-
Notifications
You must be signed in to change notification settings - Fork 252
/
index_beta.js
1954 lines (1842 loc) · 66.9 KB
/
index_beta.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const authConfig = {
"siteName": "GoIndex Extended", // WebSite Name
"siteIcon": "https://raw.githubusercontent.com/cheems/goindex-extended/master/images/favicon-x.png", //or fevicon-x-light.png
"version": "1.4.1", // VersionControl, do not modify manually
// client_id & client_secret - PLEASE USE YOUR OWN!
"client_id": "", // Client ID
"client_secret": "", // Client Secret
"refresh_token": "", // Refresh Token
"folder_list_url": "", // Folder Id List(Only if you have any folders in roots) - Sample: https://cdn.jsdelivr.net/gh/cheems/goindex-extended@master/sample-files/sample-folder-id-list.txt
// Crypt Secret must be 32 characters long - Sample: "1234567890123456abcdefghIJKLMN!*" | don't use these characters (\,/,",')
"crypt_secret": "", // Crypt Secret (Required)* This is used to encrypt file ids
/**
* Set up multiple Drives to be displayed; add multiples by format
* [id]: It can be team folder id, subfolder id, or "root" (representing the root directory of personal disk);
* [name]: the displayed name
* [auth]: {'username_1' : 'password_1', 'username_2' : 'password_2'}
* [protect_file_link]: Whether Basic Auth is used to protect the file link, the default value (when not set) is false, that is, the file link is not protected (convenient for straight chain download / external playback, etc.)
* Basic Auth of each folder can be set separately. Basic Auth protects all folders / subfolders in the disk by default
* [Note] By default, the file link is not protected, which can facilitate straight-chain download / external playback;
* If you want to protect the file link, you need to set protect_file_link to true. At this time, if you want to perform external playback and other operations, you need to replace host with user: pass @ host
* No need for Basic Auth folder, just keep user and pass empty at the same time. (No need to set it directly)
* [Note] For the folder whose id is set to the subfolder id, the search function will not be supported (it does not affect other disks).
*/
// =================== ROOTS ===================
"roots": [
{
id: "root", //you can use folderid other than root but then search wont work
name: "Personal Drive",
/* provide 'username':'password' combinations seperated by commas.
* If you add empty values like this => auth":{"":""} then the site will still ask for authentication but user can enter without entering any data by clicking submit
*/
// To enable password protection, uncomment the below code line(remove "//" in the front of the below code line)
// auth: {'username_1' : 'password_1', 'username_2' : 'password_2'},
protect_file_link: false //true or false
},
{
id: "drive_id",
name: "Personal Drive II",
// To enable password protection, uncomment the below line
// auth: {'username_1' : 'password_1', 'username_2' : 'password_2'},
protect_file_link: false
},
// You can add more drives like above
/*{
id: "drive_id",
name: "Personal Drive II",
// To enable password protection, uncomment the below line
// auth: {'username_1' : 'password_1', 'username_2' : 'password_2'},
protect_file_link: false
}, */
],
// =================== END OF ROOTS =================== <-- DON'T REMOVE THIS LINE
//Set this to true if you need to let users download files which Google Drive has flagged as a virus
"enable_virus_infected_file_down": false,
//Set this to true if you want to sort the list by modified time
"sort_by_modified_time": false,
//Set this to true if you need to let users download deleted files from the current drive
"include_trashed_files": false, // Then files will be visible at where they were before moving to the trash bin
//Set this to true if you want to force directories to load. This may cause you to exceed API rate limits
"force_list_to_load": true,
/**
* The number displayed on each page of the file list page. [Recommended setting value is between 100 and 1000];
* If the setting is greater than 1000, it will cause an error when requesting drive api;
* If the set value is too small, the incremental loading (page loading) of the scroll bar of the file list page will be invalid
* Another effect of this value is that if the number of files in the directory is greater than this setting (that is, multiple pages need to be displayed), the results of the first listing directory will be cached.
*/
"files_list_page_size": 500,
/**
* The number displayed on each page of the search results page. [Recommended setting value is between 50 and 1000];
* If the setting is greater than 1000, it will cause an error when requesting drive api;
* If the set value is too small, it will cause the incremental loading (page loading) of the scroll bar of the search results page to fail;
* The size of this value affects the response speed of the search operation
*/
"search_result_list_page_size": 50,
// Confirm that cors can be opened
"enable_cors_file_down": false,
/**
* The above basic auth already contains the function of global protection in the disk. So by default, the password in the .password file is no longer authenticated;
* If you still need to verify the password in the .password file for certain directories based on global authentication, set this option to true;
* [Note] If the password verification of the .password file is enabled, the overhead of querying whether the .password file in the directory will be added each time the directory is listed.
*/
"enable_password_file_verify": false
};
/**
* web ui
*/
const uiConfig = {
"theme": "material", // DO NOT set it to classic
"dark_mode": true, // true or false
"title_include_drive_name": false, // Set this to true if you need to add drive name to the page title which will be displayed in browser tab name area (ex: Goindex Extented - Disk 01)
"title_include_path": "", // full-path | current-directory | or leave it empty
// set title_include_path to "full-path" if you want to add full path of the current directory to title (ex: Goindex Extented - /Multimedia/images/) or (ex: Goindex Extented - Disk 01 - /Multimedia/images)
// set title_include_path to "current-directory" to add current directory to title (ex: Goindex Extented - /images/)
// If you need to remove path from page title, leave it empty as it is
"hide_actions_tab": false, // Set this to true if you want to hide the actions tab which contains direct dowload, copy link, open in a new tab button
"hide_head_md": false, // Set this to true if you need to disable rendering HEAD.md
"hide_readme_md": false, // Set this to true if you need to disable rendering README.md
"helpURL": "", // Provide the URL of the help page(instructions for using the index). Leave this empty if you want to hide the help icon. Providing a URL will open the help page in a new tab. (You can use telegra.ph to write instructions)
"footer_text": "Made with <3", // Provide the footer text. Leave this empty if you want to hide it.
"credits": true, // Set this to true if you like to give credits. Otherwise you can set it to false. (NO BIG DEAL:3)
"main_color": "blue-grey", // blue-grey | red | pink | purple | deep-purple | indigo | blue | light-blue | cyan | teal | green | light-green | lime | yellow | amber | orange | deep-orange | brown | grey
"accent_color": "blue" // red | pink | purple | deep-purple | indigo | blue | light-blue | cyan | teal | green | light-green | lime | yellow | amber | orange | deep-orange
// blue-grey and blue suit with both light and dark themes
};
/**
* Player Configuration
*/
const playerConfig = {
"autoplay": true,
"loop": true,
"player_dp": "|m3u8|flv|",
"thumbnails": [
{
name: "dplayer",
url: "Thumbnail/dplayer.jpg"
},
{
name: "plyr",
url: "Thumbnail/plyr.vtt"
}
],
"video_cover": "${fileName}.${ext}",
"video_subtitle": "${fileName}.${ext}",
};
/**
* Google Workspace Apps Export config
*
* Set preferred extensions that workspace files need to be downloaded.
* Use one of available extensions mentioned next to each value.
* Don't change the current values if you need to use the default extensions which Google drive uses.
*/
const exportConfig = {
"documents": "docx", // docx | odt | rtf | pdf | txt | html | html/zipped | epub
"spreadsheets": "xlsx", // xlsx | ods | csv | pdf | html/zipped
"slides": "pptx", // pptx | odp | pdf | txt
"drawings": "jpg", // pdf | jpg | png | svg
"jamboard": "pdf", // pdf
"forms": "html/zipped" // html/zipped
};
const exportExtensions = {
"application/vnd.google-apps.document": exportConfig.documents,
"application/vnd.google-apps.spreadsheet": exportConfig.spreadsheets,
"application/vnd.google-apps.presentation": exportConfig.slides,
"application/vnd.google-apps.drawing": exportConfig.drawings,
"application/vnd.google-apps.jam": exportConfig.jamboard,
"application/vnd.google-apps.form": exportConfig.forms
};
const workspaceExportMimeTypes = {
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"odt": "application/vnd.oasis.opendocument.text",
"rtf": "application/rtf",
"pdf": "application/pdf",
"txt": "text/plain",
"html": "text/html",
"html/zipped": "application/zip",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ods": "application/x-vnd.oasis.opendocument.spreadsheet",
"csv": "text/csv",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"odp": "application/vnd.oasis.opendocument.presentation",
"jpg": "image/jpeg",
"png": "image/png",
"svg": "image/svg+xml"
};
/**
* global functions
*/
const FUNCS = {
formatSearchKeyword: function (keyword) {
let nothing = "";
let space = " ";
if (!keyword) return nothing;
return keyword.replace(/(!=)|['"=<>/\\:]/g, nothing)
.replace(/[,,|(){}]/g, space)
.trim()
}
};
/**
* global consts
* @type {{folder_mime_type: string, default_file_fields: string, gd_root_type: {share_drive: number, user_drive: number, sub_folder: number}}}
*/
const CONSTS = new (class {
default_file_fields = 'parents,id,name,mimeType,modifiedTime,createdTime,fileExtension,size';
gd_root_type = {
user_drive: 0,
share_drive: 1,
sub_folder: 2
};
folder_mime_type = 'application/vnd.google-apps.folder';
})();
// gd instances
var gds = [];
function html(current_drive_order = 0, model = {}) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
<title>${authConfig.siteName}</title>
<link rel="shortcut icon" href="${authConfig.siteIcon}" type="image/x-icon" />
<script>
window.drive_names = JSON.parse('${JSON.stringify(authConfig.roots.map(it => it.name))}');
window.MODEL = JSON.parse('${JSON.stringify(model)}');
window.current_drive_order = ${current_drive_order};
window.UI = JSON.parse('${JSON.stringify(uiConfig)}');
window.PLYR = JSON.parse('${JSON.stringify(playerConfig)}');
</script>
<script src="//cdn.jsdelivr.net/gh/cheems/goindex-extended@4d1427558a21603e7c7e7dc986a154a9560f4835/app_beta.js"></script>
</head>
<body>
</body>
</html>
`;
};
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
function id2crc32(r) {
for (var a, o = [], c = 0; c < 256; c++) {
a = c;
for (var f = 0; f < 8; f++) a = 1 & a ? 3988292384 ^ a >>> 1 : a >>> 1;
o[c] = a
}
for (var n = -1, t = 0; t < r.length; t++) n = n >>> 8 ^ o[255 & (n ^ r.charCodeAt(t))]
;
return (-1 ^ n) >>> 0
};
function getIV(ParsedString) {
let iv = ParsedString.clone();
iv.sigBytes = 16;
iv.clamp();
return iv
}
function encryptAES(RawText, Key) {
let plainText = RawText;
let key = CryptoJS.enc.Utf8.parse(Key);
let iv = getIV(CryptoJS.enc.Utf8.parse(plainText));
let failSafe = "a a a a a a a a ";
let encrypted = CryptoJS.AES.encrypt(failSafe + plainText, key, {
iv: iv,
mode: CryptoJS.mode.CFB
});
return encrypted.toString()
}
function decryptAES(EncryptedString, Key) {
if (Key.length < 32 || !Key) {
Key = authConfig.refresh_token.substring(3, 35)
} else if (Key.length > 32) {
Key = Key.substring(0, 32)
}
let cipherText = CryptoJS.enc.Base64.parse(EncryptedString);
let key = CryptoJS.enc.Utf8.parse(Key);
let iv = getIV(cipherText);
cipherText.words.splice(0, 4);
cipherText.sigBytes -= 16;
decrypted = CryptoJS.AES.decrypt({ ciphertext: cipherText }, key, {
iv: iv,
mode: CryptoJS.mode.CFB
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
async function getFolderIdList() {
var encryptedIdList = await fetch(authConfig.folder_list_url);
var encryptedIdList = await encryptedIdList.text();
var idListString = decryptAES(encryptedIdList, authConfig.crypt_secret)
var idList = JSON.parse(idListString);
return idList
}
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
if (gds.length === 0) {
for (let i = 0; i < authConfig.roots.length; i++) {
const gd = new googleDrive(authConfig, i);
await gd.init();
gds.push(gd)
}
// This operation is parallel to improve efficiency
let tasks = [];
gds.forEach(gd => {
tasks.push(gd.initRootType());
});
for (let task of tasks) {
await task;
}
}
// Extract drive order from path
// And get the corresponding gd instance according to drive order
let gd;
let url = new URL(request.url);
let path = url.pathname;
/**
* Redirect to start page
* @returns {Response}
*/
function redirectToIndexPage() {
return new Response('', { status: 301, headers: { 'Location': `${url.origin}/0:/` } });
}
if (path == '/') return redirectToIndexPage();
if (path.toLowerCase() == '/favicon.ico') {
// You can find a favicon later
return new Response('', { status: 404 })
}
// Special command format
const command_reg = /^\/(?<num>\d+):(?<command>[a-zA-Z0-9]+)$/g;
const match = command_reg.exec(path);
if (match) {
const num = match.groups.num;
const order = Number(num);
if (order >= 0 && order < gds.length) {
gd = gds[order];
} else {
return redirectToIndexPage()
}
// basic auth
for (const r = gd.basicAuthResponse(request); r;) return r;
const command = match.groups.command;
// search for
if (command === 'search') {
if (request.method === 'POST') {
// search results
return handleSearch(request, gd);
} else {
const params = url.searchParams;
// Search page
return new Response(html(gd.order, {
q: params.get("q") || '',
is_search_page: true,
root_type: gd.root_type
}),
{
status: 200,
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}
} else if (command === 'id2path' && request.method === 'POST') {
return handleId2Path(request, gd)
}
}
// Expected path format
const common_reg = /^\/\d+:\/.*$/g;
try {
if (!path.match(common_reg)) {
return redirectToIndexPage();
}
let split = path.split("/");
let order = Number(split[1].slice(0, -1));
if (order >= 0 && order < gds.length) {
gd = gds[order];
} else {
return redirectToIndexPage()
}
} catch (e) {
return redirectToIndexPage()
}
// basic auth
// for (const r = gd.basicAuthResponse(request); r;) return r;
const basic_auth_res = gd.basicAuthResponse(request);
path = path.replace(gd.url_path_prefix, '') || '/';
if (request.method == 'POST') {
return basic_auth_res || apiRequest(request, gd);
}
let action = url.searchParams.get('a');
if (path.substr(-1) == '/' || action != null) {
return basic_auth_res || new Response(html(gd.order, { root_type: gd.root_type }), {
status: 200,
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
} else {
if (path.split('/').pop().toLowerCase() == ".password") {
return basic_auth_res || new Response("", { status: 404 });
}
let file = await gd.file(path);
let range = request.headers.get('Range');
const inline_down = 'true' === url.searchParams.get('inline');
if (gd.root.protect_file_link && basic_auth_res) return basic_auth_res;
return gd.down(file.id, file.mimeType, range, inline_down);
}
}
async function apiRequest(request, gd) {
let url = new URL(request.url);
let path = url.pathname;
path = path.replace(gd.url_path_prefix, '') || '/';
let option = { status: 200, headers: { 'Access-Control-Allow-Origin': '*' } }
if (path.substr(-1) == '/') {
let form = await request.formData();
// This can increase the speed when listing the directory for the first time. The disadvantage is that if password verification fails, the overhead of listing directories will still be incurred
let deferred_list_result = gd.list(path, form.get('page_token'), Number(form.get('page_index')));
// check .password file, if `enable_password_file_verify` is true
if (authConfig['enable_password_file_verify']) {
let password = await gd.password(path);
// console.log("dir password", password);
if (password && password.replace("\n", "") !== form.get('password')) {
let html = `{"error": {"code": 401,"message": "password error."}}`;
return new Response(html, option);
}
}
let list_result = await deferred_list_result;
return new Response(JSON.stringify(list_result), option);
} else {
let file = await gd.file(path);
let range = request.headers.get('Range');
return new Response(JSON.stringify(file));
}
}
// Processing search
async function handleSearch(request, gd) {
const option = { status: 200, headers: { 'Access-Control-Allow-Origin': '*' } };
let form = await request.formData();
let search_result = await
gd.search(form.get('q') || '', form.get('page_token'), Number(form.get('page_index')));
return new Response(JSON.stringify(search_result), option);
}
/**
* Handle id2path
* @param request 需要 id 参数
* @param gd
* @returns {Promise<Response>} [Note] If the item represented by the id received from the front desk is not under the target gd disk, the response will return an empty string to the front desk""
*/
async function handleId2Path(request, gd) {
const option = { status: 200, headers: { 'Access-Control-Allow-Origin': '*' } };
let form = await request.formData();
let path = await gd.findPathById(decryptAES(form.get('id'), authConfig.crypt_secret));
return new Response(path || '', option);
}
class googleDrive {
constructor(authConfig, order) {
// Each disk corresponds to an order, corresponding to a gd instance
this.order = order;
this.root = authConfig.roots[order];
this.root.protect_file_link = this.root.protect_file_link || false;
this.url_path_prefix = `/${order}:`;
this.authConfig = authConfig;
// TODO: These cache invalidation refresh strategies can be formulated later
// path id
this.paths = [];
// path file
this.files = [];
// path pass
this.passwords = [];
// id <-> path
this.id_path_cache = {};
this.id_path_cache[this.root['id']] = '/';
this.paths["/"] = this.root['id'];
/*if (this.root['pass'] != "") {
this.passwords['/'] = this.root['pass'];
}*/
// this.init();
}
/**
* Initial authorization; then obtain user_drive_real_root_id
* @returns {Promise<void>}
*/
async init() {
await this.accessToken();
/*await (async () => {
// Only get 1 time
if (authConfig.user_drive_real_root_id) return;
const root_obj = await (gds[0] || this).findItemById('root');
if (root_obj && root_obj.id) {
authConfig.user_drive_real_root_id = root_obj.id
}
})();*/
// Wait for user_drive_real_root_id, only get 1 time
if (authConfig.user_drive_real_root_id) return;
const root_obj = await (gds[0] || this).findItemById('root');
if (root_obj && root_obj.id) {
authConfig.user_drive_real_root_id = root_obj.id
}
}
/**
* Get the root directory type, set to root_type
* @returns {Promise<void>}
*/
async initRootType() {
const root_id = this.root['id'];
const types = CONSTS.gd_root_type;
if (root_id === 'root' || root_id === authConfig.user_drive_real_root_id) {
this.root_type = types.user_drive;
} else {
const obj = await this.getShareDriveObjById(root_id);
this.root_type = obj ? types.share_drive : types.sub_folder;
}
}
/**
* Returns a response that requires authorization, or null
* @param request
* @returns {Response|null}
*/
basicAuthResponse(request) {
const auth = this.root.auth || '',
_401 = new Response('unauthorized', {
headers: {
'WWW-Authenticate': `Basic realm="goindex:drive:${this.order}"`,
'content-type': 'text/html;charset=UTF-8'
},
status: 401
});
if (auth) {
const _auth = request.headers.get('Authorization')
if (_auth) {
try {
const [received_user, received_pass] = atob(_auth.split(' ').pop()).split(':');
if (auth.hasOwnProperty(received_user)) {
if (auth[received_user] == received_pass) {
return null;
} else return _401;
} else return _401;
} catch (e) { }
}
} else return null;
return _401;
}
async down(id, mimeType, range = '', inline = false) {
let exportExtension = exportExtensions[mimeType];
let exportMimeType = workspaceExportMimeTypes[exportExtension];
let url;
if (exportExtensions.hasOwnProperty(mimeType)) {
url = `https://www.googleapis.com/drive/v3/files/${id}/export?alt=media&mimeType=${exportMimeType}`;
} else if (mimeType === "application/vnd.google-apps.script") {
url = `https://script.google.com/feeds/download/export?id=${id}&format=json`;
} else {
url = `https://www.googleapis.com/drive/v3/files/${id}?alt=media`;
}
let requestOption = await this.requestOption();
requestOption.headers['Range'] = range;
let res = await fetch(url, requestOption);
if (this.authConfig.enable_virus_infected_file_down) {
if (res.status === 403) {
url += '&acknowledgeAbuse=true';
res = await this.fetch200(url, requestOption);
}
}
const { headers } = res = new Response(res.body, res)
this.authConfig.enable_cors_file_down && headers.append('Access-Control-Allow-Origin', '*');
inline === true && headers.set('Content-Disposition', 'inline');
return res;
}
async file(path) {
if (typeof this.files[path] == 'undefined') {
this.files[path] = await this._file(path);
}
return this.files[path];
}
async _file(path) {
let arr = path.split('/');
let name = arr.pop();
let _temp_name = name;
name = decodeURIComponent(name).replace(/\'/g, "\\'");
let dupID;
if (/\(dupID: \d+\)/.test(name.substring(name.search(/\(dupID: \d+\)/)))) {
dupID = name.substring(0, name.length - 1).substring(name.search(/\(dupID: \d+/) + 8);
name = name.substring(0, name.search(/\(dupID: \d+\)/) - 1);
}
let dir = arr.join('/') + '/';
// console.log(name, dir);
let parent = await this.findPathId(dir);
// console.log(parent);
let url = 'https://www.googleapis.com/drive/v3/files';
let params = { 'includeItemsFromAllDrives': true, 'supportsAllDrives': true };
params.q = `'${parent}' in parents and name = '${name}'`;
if (!this.authConfig.include_trashed_files) {
params.q += ' and trashed = false';
}
params.fields = "files(id, name, mimeType, size ,createdTime, modifiedTime, iconLink, thumbnailLink, shortcutDetails)";
url += '?' + this.enQuery(params);
let requestOption = await this.requestOption();
let response = await fetch(url, requestOption);
if (this.authConfig.force_list_to_load) {
if (response.status !== 200) {
response = await this.fetch200(url, requestOption);
}
}
let obj = await response.json();
if (!obj.files[0]) {
return null
} else if (obj.files.length > 1) {
if (dupID) {
let correct_file_item;
obj.files.map(function (item) {
if (id2crc32(item.id).toString() === dupID) {
correct_file_item = item;
}
})
obj.files = [];
obj.files.push(correct_file_item);
}
}
if (obj.files && obj.files[0] && obj.files[0].mimeType == 'application/vnd.google-apps.shortcut') {
obj.files[0].id = obj.files[0].shortcutDetails.targetId;
obj.files[0].mimeType = obj.files[0].shortcutDetails.targetMimeType;
}
// console.log(obj);
if (_temp_name.includes("%5C%5C")) {
name = _temp_name.replaceAll("%5C%5C", "%5C");
name = decodeURIComponent(name);
}
const same_name = obj.files.find(v => v.name === name)
if (!same_name) {
return obj.files[0];
}
return same_name;
// return obj.files[0];
}
// Cache through reqeust cache
async list(path, page_token = null, page_index = 0) {
if (this.path_children_cache == undefined) {
// { <path> :[ {nextPageToken:'',data:{}}, {nextPageToken:'',data:{}} ...], ...}
this.path_children_cache = {};
}
if (this.path_children_cache[path]
&& this.path_children_cache[path][page_index]
&& this.path_children_cache[path][page_index].data
) {
let child_obj = this.path_children_cache[path][page_index];
return {
nextPageToken: child_obj.nextPageToken || null,
curPageIndex: page_index,
data: child_obj.data
};
}
let id = await this.findPathId(path);
let result = await this._ls(id, page_token, page_index);
let data = result.data;
// Cache for multiple pages
if (result.nextPageToken && data.files) {
if (!Array.isArray(this.path_children_cache[path])) {
this.path_children_cache[path] = []
}
this.path_children_cache[path][Number(result.curPageIndex)] = {
nextPageToken: result.nextPageToken,
data: data
};
}
return result
}
async _ls(parent, page_token = null, page_index = 0) {
// console.log("_ls", parent);
if (parent == undefined) {
return null;
}
let obj;
let params = { 'includeItemsFromAllDrives': true, 'supportsAllDrives': true };
params.q = `'${parent}' in parents AND name !='.password'`;
if (!this.authConfig.include_trashed_files) {
params.q += ' and trashed = false';
}
if (this.authConfig.sort_by_modified_time) {
params.orderBy = 'folder,modifiedTime desc,name';
} else {
params.orderBy = 'folder,name,modifiedTime desc';
}
params.fields = "nextPageToken, files(id, name, mimeType, size , modifiedTime, shortcutDetails)";
params.pageSize = this.authConfig.files_list_page_size;
if (page_token) {
params.pageToken = page_token;
}
let url = 'https://www.googleapis.com/drive/v3/files';
url += '?' + this.enQuery(params);
let requestOption = await this.requestOption();
let response = await fetch(url, requestOption);
if (this.authConfig.force_list_to_load) {
if (response.status !== 200) {
response = await this.fetch200(url, requestOption);
}
}
obj = await response.json();
let temp_names = [];
let duplicate_names = [];
obj.files.map(function (item) {
if (!temp_names.includes(item.name)) {
temp_names.push(item.name)
} else {
if (!duplicate_names.includes(item.name)) {
duplicate_names.push(item.name)
}
}
})
obj.files.map(function (item) {
if (duplicate_names.includes(item.name)) {
item.name = item.name + " (dupID: " + id2crc32(item.id) + ")"
}
})
obj.files.forEach(file => {
if (file && file.mimeType == 'application/vnd.google-apps.shortcut') {
file.id = file.shortcutDetails.targetId;
file.mimeType = file.shortcutDetails.targetMimeType;
}
});
if (obj.files.length != 0) {
obj.files.map(function (item) {
item.id = encryptAES(item.id, authConfig.crypt_secret)
})
}
return {
nextPageToken: obj.nextPageToken || null,
curPageIndex: page_index,
data: obj
};
/*do {
if (pageToken) {
params.pageToken = pageToken;
}
let url = 'https://www.googleapis.com/drive/v3/files';
url += '?' + this.enQuery(params);
let requestOption = await this.requestOption();
let response = await fetch(url, requestOption);
obj = await response.json();
files.push(...obj.files);
pageToken = obj.nextPageToken;
} while (pageToken);*/
}
async password(path) {
if (this.passwords[path] !== undefined) {
return this.passwords[path];
}
// console.log("load", path, ".password", this.passwords[path]);
let file = await this.file(path + '.password');
if (file == undefined) {
this.passwords[path] = null;
} else {
let url = `https://www.googleapis.com/drive/v3/files/${file.id}?alt=media`;
let requestOption = await this.requestOption();
let response = await this.fetch200(url, requestOption);
this.passwords[path] = await response.text();
}
return this.passwords[path];
}
/**
* Get share drive information by id
* @param any_id
* @returns {Promise<null|{id}|any>} Any abnormal situation returns null
*/
async getShareDriveObjById(any_id) {
if (!any_id) return null;
if ('string' !== typeof any_id) return null;
let url = `https://www.googleapis.com/drive/v3/drives/${any_id}`;
let requestOption = await this.requestOption();
let res = await fetch(url, requestOption);
if (res.status !== 200) {
res = await this.fetch200(url, requestOption);
}
let obj = await res.json();
if (obj && obj.id) return obj;
return null
}
/**
* search for
* @returns {Promise<{data: null, nextPageToken: null, curPageIndex: number}>}
*/
async search(origin_keyword, page_token = null, page_index = 0) {
const types = CONSTS.gd_root_type;
const is_user_drive = this.root_type === types.user_drive;
const is_share_drive = this.root_type === types.share_drive;
const is_sub_folder = this.root_type === types.sub_folder;
const empty_result = {
nextPageToken: null,
curPageIndex: page_index,
data: null
};
// if (!is_user_drive && !is_share_drive) {
// return empty_result;
// }
let keyword = FUNCS.formatSearchKeyword(origin_keyword);
if (!keyword) {
// Keyword is empty, return
return empty_result;
}
let words = keyword.split(/\s+/);
let name_search_str = `name contains '${words.join("' AND name contains '")}'`;
// For corpora, user is a personal disk, and drive is a team disk. Match driveId
let params = {};
if (is_user_drive) {
params.corpora = 'user'
}
if (is_share_drive) {
params.corpora = 'drive';
params.driveId = this.root.id;
// This parameter will only be effective until June 1, 2020. Afterwards shared drive items will be included in the results.
params.includeItemsFromAllDrives = true;
params.supportsAllDrives = true;
}
if (page_token) {
params.pageToken = page_token;
}
params.q = `name !='.password' AND (${name_search_str})`;
if (!this.authConfig.include_trashed_files) {
params.q += ' and trashed = false';
}
params.fields = "nextPageToken, files(id, name, mimeType, size , modifiedTime)";
params.pageSize = this.authConfig.search_result_list_page_size;
// params.orderBy = 'folder,name,modifiedTime desc';
let search_q_ids, huge_folder_list;
if (is_sub_folder) {
params.corpora = 'allDrives';
params.supportsAllDrives = true;
params.includeItemsFromAllDrives = true;
if (authConfig.folder_list_url) {
let folder_list = await getFolderIdList();
let target_folder = folder_list[this.root.id];
if (target_folder.length > 1) {
console.log("hehe");
var temp_id_list = [];
target_folder.map(function (item) {
Array.prototype.push.apply(temp_id_list, item);
})
search_q_ids = temp_id_list;
huge_folder_list = true,
params.pageSize = 200;
params.fields = "nextPageToken, files(id, name, mimeType, size , modifiedTime, parents)";
} else {
search_q_ids = "('" + target_folder[0].join("' in parents or '") + "' in parents)";
params.q += `AND ${search_q_ids}`;
}
} else {
params.q += `AND '${this.root.id}' in parents`;
}
}
let url = 'https://www.googleapis.com/drive/v3/files';
url += '?' + this.enQuery(params);
// console.log(params)
let requestOption = await this.requestOption();
let response = await this.fetch200(url, requestOption);
let res_obj = await response.json();
while (response.status != 200 || (res_obj.nextPageToken && res_obj.files.length == 0)) {
if (response.status != 200) {
param.pageToken = null;
} else {
params.pageToken = res_obj.nextPageToken;
}
url = 'https://www.googleapis.com/drive/v3/files';
url += '?' + this.enQuery(params);
requestOption = await this.requestOption();
response = await this.fetch200(url, requestOption);
res_obj = await response.json();
}
let repeat_until_fetch_enough;
if (!page_token) {
repeat_until_fetch_enough = true;
}
if (huge_folder_list) {
let temp_files = [];
if (res_obj.files.length != 0) {
res_obj.files.map(function (item) {
if (item.parents) {
if (search_q_ids.includes(item.parents[0])) {
item.parents[0] = encryptAES(item.parents[0], authConfig.crypt_secret)
temp_files.push(item)
}
}
})
}
if (repeat_until_fetch_enough) {
while (response.status != 200 || (res_obj.nextPageToken && temp_files.length < 10)) {
if (response.status != 200) {
param.pageToken = null;
} else {
params.pageToken = res_obj.nextPageToken;
}
url = 'https://www.googleapis.com/drive/v3/files';
url += '?' + this.enQuery(params);
requestOption = await this.requestOption();
response = await this.fetch200(url, requestOption);
res_obj = await response.json();
if (res_obj.files.length !== undefined && res_obj.files.length != 0) {
res_obj.files.map(function (item) {
if (item.parents) {
if (search_q_ids.includes(item.parents[0])) {
item.parents[0] = encryptAES(item.parents[0], authConfig.crypt_secret)
temp_files.push(item)
}
}
})
}
}
}
res_obj.files = temp_files;
}
if (res_obj.files.length != 0) {
res_obj.files.map(function (item) {
item.id = encryptAES(item.id, authConfig.crypt_secret)
})
}
return {
nextPageToken: res_obj.nextPageToken || null,
curPageIndex: page_index,
data: res_obj
};
}
/**
* Get the file object of the parent folder of this file or folder one by one upwards. Note: it will be slow! ! !
* Find up to the root directory of the current gd object (root id)
* Only consider a single upward chain.
* [Note] If the item represented by this id is not in the target gd disk, then this function will return null
*
* @param child_id
* @param contain_myself
* @returns {Promise<[]>}
*/
async findParentFilesRecursion(child_id, contain_myself = true) {
const gd = this;
const gd_root_id = gd.root.id;
const user_drive_real_root_id = authConfig.user_drive_real_root_id;
const is_user_drive = gd.root_type === CONSTS.gd_root_type.user_drive;
// End goal id for bottom-up query
const target_top_id = is_user_drive ? user_drive_real_root_id : gd_root_id;
const fields = CONSTS.default_file_fields;
// [{},{},...]
const parent_files = [];
let meet_top = false;
async function addItsFirstParent(file_obj) {
if (!file_obj) return;
if (!file_obj.parents) return;
if (file_obj.parents.length < 1) return;
// ['','',...]
let p_ids = file_obj.parents;