-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle-drive-api.js
More file actions
75 lines (63 loc) · 1.91 KB
/
google-drive-api.js
File metadata and controls
75 lines (63 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function getAuthToken() {
return new Promise((resolve, reject) => {
chrome.identity.getAuthToken({ interactive: true }, function (token) {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(token);
}
});
});
}
async function uploadToDrive(token, fileName, content) {
const metadata = {
name: fileName,
mimeType: 'application/json',
};
const form = new FormData();
form.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
form.append('file', new Blob([content], { type: 'application/json' }));
const response = await fetch(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,webViewLink',
{
method: 'POST',
headers: new Headers({ Authorization: 'Bearer ' + token }),
body: form,
}
);
if (!response.ok) {
throw new Error('Failed to upload file to Google Drive');
}
return await response.json();
}
async function downloadFromDrive(token, fileName) {
// First, search for the file
const searchResponse = await fetch(
`https://www.googleapis.com/drive/v3/files?q=name='${fileName}'`,
{
headers: new Headers({ Authorization: 'Bearer ' + token }),
}
);
if (!searchResponse.ok) {
throw new Error('Failed to search for file in Google Drive');
}
const searchResult = await searchResponse.json();
if (searchResult.files.length === 0) {
throw new Error('File not found in Google Drive');
}
const fileId = searchResult.files[0].id;
// Now, download the file
const downloadResponse = await fetch(
`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`,
{
headers: new Headers({ Authorization: 'Bearer ' + token }),
}
);
if (!downloadResponse.ok) {
throw new Error('Failed to download file from Google Drive');
}
return await downloadResponse.text();
}