-
Notifications
You must be signed in to change notification settings - Fork 13
/
gdrive.js
236 lines (198 loc) · 7.75 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
var authConfig = {
"client_id": "202264815644.apps.googleusercontent.com", // RClone client_id
"client_secret": "X4Z3ca8xfWDb1Voo-F9a7ZxJ", // RClone client_secret
"refresh_token": "", // unique
"root": "allDrives"
};
let gd;
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
let linksHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Links</title></head>
<body>
SEARCH_RESULT_PLACEHOLDER
</body>
</html>
`;
if (gd === undefined) {
gd = new googleDrive(authConfig);
}
let url = new URL(request.url);
let path = url.pathname;
let action = url.searchParams.get('a');
if (path.substr(-1) === '/' || action != null) {
return new Response(linksHtml, {status: 200, headers: {'Content-Type': 'text/html; charset=utf-8'}});
} else {
let baseUrl = url.toString().replace(path, "/");
// If client requests a search
if (path.startsWith("/search/")) {
let file = await gd.getFilesCached(path);
if (file !== undefined) {
file.forEach(function (f) {
let link = baseUrl + encodeURIComponent(f.name);
linksHtml = linksHtml.replace("SEARCH_RESULT_PLACEHOLDER", `<a href="${link}">${f.name} ${f.size}</a><br><br>\nSEARCH_RESULT_PLACEHOLDER`);
});
} else {
return new Response("Could not load the search results", {
status: 500,
headers: {'Content-Type': 'text/html; charset=utf-8'}
});
}
linksHtml = linksHtml.replace("SEARCH_RESULT_PLACEHOLDER", "");
return new Response(linksHtml, {status: 200, headers: {'Content-Type': 'text/html; charset=utf-8'}});
} else if (path.startsWith("/searchjson/")) {
const response = [];
let file = await gd.getFilesCached(path);
if (file !== undefined) {
file.forEach(function (f) {
let link = baseUrl + encodeURIComponent(f.name);
let size = Math.round(f.size / 2 ** 30 * 100) / 100;
let result = {"link": link, "size_gb": size, "file_id": f.id, "drive_id": f.driveId};
response.push(result);
});
}
console.log(response)
return new Response(JSON.stringify(response), {status: 200, headers: {'Content-Type': 'application/json'}});
} else {
// If client requests a file
let file = await gd.getFilesCached(path);
file = file[0];
console.log(file);
let range = request.headers.get('Range');
return gd.down(file.id, range);
}
}
}
class googleDrive {
constructor(authConfig) {
this.authConfig = authConfig;
this.paths = [];
this.files = [];
this.paths["/"] = authConfig.root;
this.accessToken();
}
async fetchAndRetryOnError(url, requestOption, maxRetries = 3) {
let response = await fetch(url, requestOption);
let retries = 0
while (!response.ok && response.status != 400 && retries < maxRetries) {
console.log(response.status);
await sleep(1000 + 1000 * 2 ** retries)
retries += 1
response = await fetch(url, requestOption);
console.log(`Retry nr. ${retries} result: ${response.ok}`)
}
return response
}
async down(id, range = '') {
let url = `https://www.googleapis.com/drive/v3/files/${id}?alt=media`;
let requestOption = await this.requestOption();
requestOption.headers['Range'] = range;
return await this.fetchAndRetryOnError(url, requestOption);
}
async getFilesCached(path) {
if (typeof this.files[path] == 'undefined') {
let files = await this.getFiles(path)
if (files !== "FAILED") {
this.files[path] = files;
}
}
return this.files[path];
}
getSearchScopeParams() {
let params = {'spaces': 'drive'};
if (authConfig.root === "allDrives") {
params = {
'corpora': 'allDrives',
'includeItemsFromAllDrives': true,
'supportsAllDrives': true,
'pageSize': 1000
};
} else if (authConfig.root !== "") {
params = {
'spaces': 'drive',
'corpora': 'drive',
'includeItemsFromAllDrives': true,
'supportsAllDrives': true,
'driveId': authConfig.root
};
}
return params
}
async getFiles(path) {
let arr = path.split('/');
let name = arr.pop();
name = decodeURIComponent(name).replace(/'/g, "\\'");
console.log(name);
let url = 'https://www.googleapis.com/drive/v3/files';
let params = this.getSearchScopeParams()
params.q = `fullText contains '${name}' and (mimeType contains 'application/octet-stream' or mimeType contains 'video/') and (name contains 'mkv' or name contains 'mp4' or name contains 'avi') `;
params.fields = "files(id, name, size, driveId)";
url += '?' + this.enQuery(params);
let requestOption = await this.requestOption();
let response = await this.fetchAndRetryOnError(url, requestOption);
let obj = await response.json();
console.log(obj);
console.log(obj.files);
if (response.ok) {
return obj.files;
} else {
return "FAILED"
}
}
async accessToken() {
console.log("accessToken");
if (this.authConfig.expires === undefined || this.authConfig.expires < Date.now()) {
const obj = await this.fetchAccessToken();
if (obj.access_token !== undefined) {
this.authConfig.accessToken = obj.access_token;
this.authConfig.expires = Date.now() + 3500 * 1000;
}
}
return this.authConfig.accessToken;
}
async fetchAccessToken() {
console.log("fetchAccessToken");
const url = "https://www.googleapis.com/oauth2/v4/token";
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const post_data = {
'client_id': this.authConfig.client_id,
'client_secret': this.authConfig.client_secret,
'refresh_token': this.authConfig.refresh_token,
'grant_type': 'refresh_token'
};
let requestOption = {
'method': 'POST',
'headers': headers,
'body': this.enQuery(post_data)
};
const response = await this.fetchAndRetryOnError(url, requestOption);
return await response.json();
}
async requestOption(headers = {}, method = 'GET') {
const accessToken = await this.accessToken();
headers['authorization'] = 'Bearer ' + accessToken;
return {'method': method, 'headers': headers};
}
enQuery(data) {
const ret = [];
for (let d in data) {
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
}
ret.push(encodeURIComponent("acknowledgeAbuse") + '=' + encodeURIComponent("true"));
return ret.join('&');
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}