-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
gdrive.js
105 lines (75 loc) · 2.76 KB
/
gdrive.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const MIME_GZIP = "application/gzip"
const MIME_JSON = "application/json"
export async function do_gdrive_backup(data) {
console.log("Requesting oauth token");
const {token} = await chrome.identity.getAuthToken({ interactive: true });
if (!token) {
console.log("OAuth failed");
return;
}
console.log("Check for file ID.");
var {gdrive_id} = await chrome.storage.local.get(["gdrive_id"]);
if(!gdrive_id) {
console.log("Not Found!");
const filename = `odinochka-${self.crypto.randomUUID()}.json.gz`;
const reponse = await uploadBlankFileToDrive(filename, token);
gdrive_id = reponse.id;
console.log(`Creted ID: ${gdrive_id}`);
await chrome.storage.local.set({"gdrive_id":gdrive_id});
}
const content = await gzip(data);
updateFile(token, gdrive_id, content, MIME_GZIP);
}
async function gzip(data) {
// h/t https://dev.to/ternentdotdev/json-compression-in-the-browser-with-gzip-and-the-compression-streams-api-4135
const inblob = new Blob([JSON.stringify(data)])
const compressedReadableStream = inblob.stream().pipeThrough(
new CompressionStream("gzip"),
);
const compressedResponse =
await new Response(compressedReadableStream);
// Get response Blob
const outblob = await compressedResponse.blob()
return outblob.arrayBuffer();
}
// Below generated by ChatGPT. Don't sue me bro!
async function uploadBlankFileToDrive(fileName, authToken) {
console.log("Creating blank file.");
const metadata = {
name: fileName,
};
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: MIME_JSON }));
form.append('file', new Blob([], { type: MIME_GZIP}));
const response = await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + authToken
},
body: form
})
return response.json()
}
// *************************************************************
function updateFile(authToken, fileId, newFileContent, mimeType) {
const metadata = {
mimeType: mimeType
};
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: MIME_JSON }));
form.append('file', new Blob([newFileContent], { type: mimeType }));
fetch(`https://www.googleapis.com/upload/drive/v3/files/${fileId}?uploadType=multipart`, {
method: 'PATCH',
headers: {
'Authorization': 'Bearer ' + authToken
},
body: form
})
.then(response => response.json())
.then(result => {
console.log('File updated successfully, new revision created:', result);
})
.catch(error => {
console.error('Error updating file', error);
});
}