-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbgdrive.js
executable file
·1336 lines (1235 loc) · 41.9 KB
/
bgdrive.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
#!/usr/bin/env node
const path = require("path");
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const confdir = require("os").homedir() + "/.config/Bgdrive/";
const TOKEN_PATH = confdir + "token.json";
const { Command } = require("commander");
const program = new Command();
program.version("0.0.1");
program.option("-d, --debug", "debug");
program
.command("sheet <source...>")
.option(
"-r, --range [range]",
"For a sheet, you can specify the range. Data will be returned as json.",
""
)
.option(
"-s, --set [string]",
"set the values to a json string",
""
)
.option(
"-o, --setone [string]",
"set one value",
""
)
.option(
"-f, --file [string]",
"set the values to a json string from a file",
""
)
.option(
"-g, --getone",
"get one value",
""
)
.option(
"-l, --log [string]",
"log the result to file",
""
)
.description("Read and set values in a sheet.")
.action((source, options) => {
source = cleanUp(source);
gid = getgid(source);
runFunction(handleSheet, { sources: source, gid: gid, options: options });
});
program
.command("download <source...>")
.option(
"-f, --format [format]",
"specify the format: pdf,txt,html,docx,odt,xlsx,ods,csv,tsv,pptx,odp (separate multiple formats with comma)",
"-"
)
.option(
"-r, --range [range]",
"For a sheet, you can specify the range. Data will be returned as json.",
""
)
.description("Download gdrive file(s) in the given format(s). For sheets, if a gid is present, sheets.spreadsheets will be used.")
.action((source, options) => {
source = cleanUp(source);
gid = getgid(source);
runFunction(exportFile, { sources: source, gid: gid, options: options });
});
/*
New files: Might be easier to just stick with the browser-based ways of doing this?
program
.command('new')
*/
program
.command("move <source...>")
.option("-t, --target [id]", "specify the target folder")
.option(
"-s, --shortcut",
"Create a shortcut in the original folder of the file"
)
.description("Move gdrive file(s) to the folder with id")
.action((source, options) => {
source = cleanUp(source);
options.target = cleanUp(options.target);
runFunction(moveFiles, { sources: source, options: options });
});
program
.command("shortcut <source...>")
.option("-t, --target [id]", "specify the target folder")
.description("Create shortcuts for gdrive file(s) in the folder with id")
.action((source, options) => {
source = cleanUp(source);
options.target = cleanUp(options.target);
runFunction(createShortcuts, { sources: source, options: options });
});
program
.command("wormhole <source...>")
.option("-w, --oldnew", "prefix [old] and [new]")
.option("-m, --migrate", "prefix [old_Shared_Folder] and [new_Shared_Drive]")
.description("Create shortcuts for gdrive folders in the folders")
.action((source, options) => {
source, gid = cleanUp(source, true);
runFunction(createWormhole, { sources: source, options: options });
});
program
.command("copy <source...>")
.option("-t, --target [id]", "specify the target folder")
.option(
"-p, --prefix [string]",
'prefix the name of the copied file with "string"'
)
.option(
"-n, --name [string]",
'Name the file "string" (only makes sense for one file to be copied)'
)
.description("Copy the gdrive file(s) and move to folder with id")
.action((source, options) => {
source = cleanUp(source);
options.target = cleanUp(options.target);
runFunction(copyFiles, { sources: source, options: options });
});
program
.command("replicate")
.option(
"-t, --target [id]",
"specify the target folder")
.option(
"-s, --source [id]",
"Specify the source folder"
)
.option(
"-S, --shortcuts",
"Create shortcuts in source, so that people can easily drop files.",
false
)
.option(
"-x, --nextto",
"Create shortcuts next to the source folder. Otherwise the shortcut is placed within the folder. Requires -S.",
false
)
.option(
"-n, --name [string]",
"Add the string provided to the shortcuts. Take care to include a leading space if you want it. Requires -S.",
" (shortcut)"
)
.description("Replicate a folder structure starting with folder source to the folder target.")
.action((options) => {
source = cleanUp(options.source);
target = cleanUp(options.target);
shortcuts = options.shortcuts || false;
nextto = options.nextto;
addstring = options.name;
runFunction(replicateStructure, {
source: source,
target: target,
shortcuts: shortcuts,
nextto: nextto,
addstring: addstring
});
});
program
.command("users <source...>")
.description("List users and permissions")
.option(
"-e, --emails",
"List email addresses only.",
false
)
.action((source, options) => {
source = ensureArray(cleanUp(source));
runFunction(listUsersWithAccessToFolder, {
"folderIds": source,
"options": options
});
});
program
.command("newfolder <name...>")
.option("-t, --target [id]", "specify the target folder")
.description("Create folders on gdrive.")
.action((name, options) => {
options.target = cleanUp(options.target);
runFunction(createFolders, { names: name, options: options });
});
program
.command("upload <path...>")
.option("-t, --target [id]", "specify the target folder")
.description("Upload Files on gdrive.")
.action((path, options) => {
options.target = cleanUp(options.target);
runFunction(uploadFiles, { names: path, options: options });
});
program
.command("list")
.option("-f, --folderOnly", "Retrieve only folders")
.option("-i, --fileOnly", "Retrieve only files")
.option(
"-t, --format <format...>",
"specify the format: pdf,txt,html,docx,odt,xlsx,ods,csv,tsv,pptx,odp (separate multiple formats with comma)",
)
.option("-n, --name [string]", "Specify a string to search for in file names")
.option("-d, --driveid [string]", "Specify a drive id to search")
.option("-s, --save [string]", "Save output as json")
// .option("-p, --parent [string]", "Specify a parent folder id to search. This requires that you have generated a tree.json file.")
.description("Retrieve files from Google Drive (drive.files.list). Note that it's not possible retrive sub-folders of a folder. See option 'tree'.")
.action((options) => {
options.parent = cleanUp(options.parent)
options.driveid = cleanUp(options.driveid)
console.log(options)
runFunction(collectElements, { options: options });
});
/*
program
.command("tree")
.option("-d, --drive [id]", "specify the drive")
.description("Retrieve tree of folders from Google Drive. This is slow. Output to tree.json")
.action((options) => {
// options.parent = cleanUp(options.parent)
runFunction(getTree, { options: options });
});
*/
program
.command("name <id>")
.option("-s, --set [string]", "Set the name.")
.option("-p, --prefix [string]", "Prefix the name.", "")
.option("-a, --append [string]", "Append to the name.", "")
.description("Get or set or modify the name.")
.action((id, options) => {
id = cleanUp(id);
runFunction(nameOperation, { id: id, options: options });
});
program.parse(process.argv);
const options = program.opts();
if (options.debug) console.log(options);
function ensureArray(value) {
if (Array.isArray(value)) {
return value;
} else {
return [value];
}
}
function cleanUp(value) {
if (value === undefined) {
// console.log("no need to clean ")
return;
}
if (Array.isArray(value)) {
value = value.map((x) => cleanUpOne(x));
} else {
value = cleanUpOne(value);
}
return value;
}
function getgid(value) {
if (value === undefined) {
// console.log("no need to clean ")
return;
}
if (Array.isArray(value)) {
value = value.map((x) => getgidone(x));
} else {
value = getgidone(value);
}
return value;
}
function getgidone(value) {
gid = value.replace(/\#gid/, "");
return gid;
};
function cleanUpOne(value) {
return value
.replace(/\?.*$/i, "")
.replace(/\/(edit|view).*$/i, "")
.replace(/^.*\//, "");
}
function runFunction(callback, callbackparameters) {
// Load client secrets from a local file.
fs.readFile(confdir + "credentials.json", (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
// Authorize a client with credentials, then call the Google Docs API.
authorize(JSON.parse(content), callback, callbackparameters);
});
}
/*
function main(auth) {
fileId = "..."
exportFile(auth, fileId, type);
}
*/
async function copyFiles(auth, parameters) {
files = parameters.sources;
folderId = parameters.options.target;
prefix = parameters.options.prefix;
name = parameters.options.name;
files.forEach(async (fileId) => {
copyFile(auth, fileId, folderId, prefix);
});
}
async function copyFile(auth, fileId, folderId, prefix, name) {
var drive = google.drive({ version: "v3", auth: auth });
console.log("File Id: " + fileId);
const title = await getName(auth, fileId);
console.log("Title: " + title);
const options = {
fields: "id,name,parents", // properties sent back to you from the API
supportsAllDrives: true,
};
const metadata = {
name: name,
// Team Drives files & folders can have only 1 parent
parents: [{ id: folderId }],
// other possible fields you can supply:
// https://developers.google.com/drive/api/v2/reference/files/copy#request-body
};
const result = await drive.files.copy({
fileId: fileId,
fields: "id,name,mimeType,parents",
name: name,
parents: [folderId],
});
// console.log("TEMPORARY=" + JSON.stringify(result, null, 2))
data = result.data;
moveOneFile(auth, data.id, folderId);
renameFile(auth, data.id, name);
// moveOneFile(auth, shortcut.id, folderId);
}
async function driveFilesExport(auth, filename, param) {
var drive = google.drive({ version: "v3", auth: auth });
response = await drive.files.export(param, { responseType: "stream" });
const dest = fs.createWriteStream(filename);
response.data.pipe(dest);
await new Promise((resolve, reject) => {
dest.on("finish", resolve);
dest.on("error", reject);
});
}
async function driveFilesGet(auth, filename, param) {
var drive = google.drive({ version: "v3", auth: auth });
response = await drive.files.get(param,
{ responseType: "stream" });
const dest = fs.createWriteStream(filename);
response.data.pipe(dest);
await new Promise((resolve, reject) => {
dest.on("finish", resolve);
dest.on("error", reject);
});
}
async function sheetsSpreadsheets(auth, filename, fileId, formatMime, parametersGid, parametersRange, parametersSheetNumber) {
// console.log("SheetsSpreadsheets")
const drive = google.drive('v3');
const sheets = google.sheets({ version: 'v4', auth });
//let range = "";
if (parametersRange || parametersSheetNumber || parametersGid) {
if (parametersGid) {
} else if (parametersRange) {
console.log("SheetsSpreadsheets - range")
const sheet = await sheets.spreadsheets.get({ spreadsheetId: fileId });
// const sheetName = sheet.data.sheets[0].properties.title;
// range = `${sheetName}!A1:Z`;
console.log(`${filename}\n${fileId}\n${formatMime}\n${range}`);
const response = await sheets.spreadsheets.values.get({
spreadsheetId: fileId,
ranges: range
});
fs.writeFileSync(filename + ".json", JSON.stringify(response.data.values));
// range = parametersRange;
} else if (parametersSheetNumber) {
const sheet = await sheets.spreadsheets.get({ spreadsheetId: fileId });
const sheetX = sheet.data.sheets[parametersSheetNumber];
// Get the values in the sheet
const response = await sheets.spreadsheets.values.get({
spreadsheetId: fileId,
range: sheetX.properties.title, // use the title of the sheet as the range
});
// Convert the values to TSV
const tsv = response.data.values.map(row => row.join('\t')).join('\n');
// Write the TSV to a file
fs.writeFile('output.tsv', tsv, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
// range = `${sheetName}!A1:Z`;
};
} else {
console.log("error");
process.exit(1);
}
}
async function handleSheet(auth, parameters) {
console.log("TEMPORARY=" + JSON.stringify(parameters, null, 2));
const sheets = google.sheets({ version: 'v4', auth });
for (fileId of parameters.sources) {
console.log("SheetsSpreadsheets - range")
const sheet = await sheets.spreadsheets.get({ spreadsheetId: fileId });
filename = sheet.data.properties.title;
const range = parameters.options.range.replace(/~/g, "!");
if (!range) {
console.error('Range is not defined');
continue;
}
console.log(`${filename}\n${fileId}\n${range}`);
if (parameters.options.set || parameters.options.setone || parameters.options.file) {
// Set the values in the sheet to parameters.options.set
let value;
if (parameters.options.file) {
// read the file and set the values in the sheet to the contents of the file
const data = fs.readFileSync(parameters.options.file, 'utf8');
value = JSON.parse(data);
} else if (parameters.options.setone) {
value = [[parameters.options.setone]];
} else {
value = JSON.parse(parameters.options.set);
};
const response = await sheets.spreadsheets.values.update({
spreadsheetId: fileId,
range: range,
valueInputOption: 'USER_ENTERED', // or 'RAW'
resource: {
values: value // this should be an array of arrays representing the cell values to update
}
});
if (parameters.options.log) {
console.log(response.data);
console.log(`write response.data to ${parameters.options.log}`);
fs.writeFileSync(parameters.options.log, JSON.stringify(response.data, null, 2));
};
} else {
if (parameters.options.getone) {
const response = await sheets.spreadsheets.values.get({
spreadsheetId: fileId,
range: range
});
console.log(response.data.values[0][0]);
} else {
const response = await sheets.spreadsheets.values.get({
spreadsheetId: fileId,
range: range
});
fs.writeFileSync(filename + ".json", JSON.stringify(response.data.values));
}
}
}
}
async function exportFile(auth, parameters) {
console.log("TEMPORARY=" + JSON.stringify(parameters, null, 2));
var drive = google.drive({ version: "v3", auth: auth });
let fileIds = parameters?.sources;
const formats = parameters.options.format ? parameters.options.format.split(',') : "-";
for (const fileId of fileIds) {
const { data } = await drive.files.get({
fileId,
fields: "name, mimeType",
supportsAllDrives: true
});
const name = data.name;
let response;
// Check if the file is a Google Workspace document and a format is specified
let filename = name;
// Thisshoudl be the outermost if... otherwise media is downloaded multiple times...
if (data.mimeType.includes('google-apps')) {
console.log(`${data.mimeType}\t${name}`)
for (fmt of formats) {
const formatMime = fmt == "-" ? getMimetype(defaultFormat(data.mimeType)) : getMimetype(fmt); // Assuming format like 'application/pdf' for Google Docs, for example
const extension = fmt == "-" ? defaultFormat(data.mimeType) : fmt;
console.log(`---------- ${fmt} -> ${formatMime}`);
filename = `${name}.${extension}`;
if (data.mimeType == "application/vnd.google-apps.spreadsheet" && (parameters.gid || parameters.range)) {
// TODO: Implement this method also for slides.
await sheetsSpreadsheets(auth, filename, fileId, formatMime, parameters.gid, parameters.range, null);
} else {
console.log("Drive")
await driveFilesExport(auth, filename, {
fileId,
mimeType: formatMime,
});
};
console.log(`File "${name}.${extension}" downloaded successfully! `);
}
} else {
// For non-Google Workspace files or when no format conversion is needed
await driveFilesGet(auth, filename, {
fileId,
alt: "media",
});
console.log(`Media file "${name}" downloaded successfully! `);
// For media files, we'll have the wrong format?
}
}
}
async function createWormhole(auth, parameters) {
files = parameters.sources;
//console.log("TEMPORARY="+JSON.stringify( parameters ,null,2))
//process.exit(1)
var p1 = "";
var p2 = "";
if (parameters.options.oldnew) {
p1 = "[OBSOLETE_FOLDER] ";
p2 = "[NEW_FOLDER] ";
}
if (parameters.options.migrate) {
p1 = "[OBSOLETE_SHARED_FOLDER] ";
p2 = "[NEW_FOLDER_IN_SHARED_DRIVE] ";
}
createShortcut(auth, files[0], files[1], p1);
createShortcut(auth, files[1], files[0], p2);
}
async function createShortcuts(auth, parameters) {
files = parameters.sources;
folderId = parameters.options.target;
files.forEach(async (fileId) => {
createShortcut(auth, fileId, folderId, "");
});
}
// https://developers.google.com/drive/api/v3/reference/files/create
// https://developers.google.com/drive/api/v3/shortcuts
async function createShortcut(auth, fileId, folderId, prefix) {
var drive = google.drive({ version: "v3", auth: auth });
const title = await getName(auth, fileId);
if (!prefix) {
prefix = "";
}
// console.log('File Id: ' + fileId);
console.log("Title: " + title);
shortcutMetadata = {
name: prefix + title + " [shortcut]",
mimeType: "application/vnd.google-apps.shortcut",
shortcutDetails: {
targetId: fileId,
},
};
drive.files.create(
{
resource: shortcutMetadata,
fields: "id,name,mimeType,shortcutDetails,parents",
supportsAllDrives: true
// parents: [folderId] , // <-- doesn't work...
},
function (err, resp) {
if (err) {
// Handle error
console.error(err);
} else {
shortcut = resp.data;
// console.log("TEMPORARY="+JSON.stringify( shortcut ,null,2))
/*
console.log('Shortcut Id: ' + shortcut.id +
', Name: ' + shortcut.name +
', target Id: ' + shortcut.shortcutDetails.targetId +
', target MIME type: ' + shortcut.shortcutDetails.targetMimeType);
*/
moveOneFile(auth, shortcut.id, folderId);
// renameFile(auth, shortcut.id, title + " [shortcut]");
}
}
);
}
async function createShortcutX(drive, sourceFolderId, targetFolderId, name) {
await drive.files.create({
resource: {
name: `${name}`,
mimeType: 'application/vnd.google-apps.shortcut',
parents: [sourceFolderId],
shortcutDetails: {
targetId: targetFolderId,
targetMimeType: 'application/vnd.google-apps.folder',
},
},
fields: 'id',
supportsAllDrives: true
});
}
async function moveFiles(auth, parameters) {
// runFunction(moveFiles, { sources: source, options: options} );
files = parameters.sources;
folderId = parameters.options.target;
const makeShortCut = parameters.options.shortcut;
console.log('files: ' + files);
console.log('folderId: ' + folderId);
console.log('makeShortCut: ' + makeShortCut);
files.forEach(async (fileId) => {
moveOneFile(auth, fileId, folderId, makeShortCut);
});
}
async function getFolderStructure(drive, folderId) {
let folderStructure = {};
const res = await drive.files.list({
q: `'${folderId}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false`,
fields: 'files(id, name)',
supportsAllDrives: true
});
const folders = res.data.files;
for (const folder of folders) {
console.log(`Getting folder structure for: ${folder.name}`);
folderStructure[folder.id] = {
name: folder.name,
subfolders: await getFolderStructure(drive, folder.id),
};
}
return folderStructure;
}
async function createFoldersInDestination(drive, result_in, destinationFolderId, folderStructure, sourceFolderId, shortcuts, nextto, addstring) {
let result = result_in;
for (const folderId in folderStructure) {
const folderInfo = folderStructure[folderId];
let element = {
"folderId": folderId,
"folderInfo": folderInfo
};
// Create the folder in the destination
const res = await drive.files.create({
resource: {
name: folderInfo.name,
mimeType: 'application/vnd.google-apps.folder',
parents: [destinationFolderId]
},
fields: 'id',
supportsAllDrives: true
});
const createdFolderId = res.data.id;
element = {
...element,
"createdFolderId": createdFolderId,
"createdFolderName": folderInfo.name,
"destinationFolderId": destinationFolderId
}
if (shortcuts) {
// Create a shortcut in the source folder pointing to the new folder
if (nextto) {
// This creates the shortcut next to the original folder:
const r = await createShortcutX(drive, sourceFolderId, createdFolderId, folderInfo.name);
element = {
...element,
"shortcut": r
};
} else {
// This creates the shortcut within the original folder:
const r = await createShortcutX(drive, folderId, createdFolderId, String(folderInfo.name) + String(addstring));
element = {
...element,
"shortcut": r
};
}
}
// Recursively create subfolders
const r = await createFoldersInDestination(drive, result, createdFolderId, folderInfo.subfolders, folderId, shortcuts, nextto, addstring);
element = {
...element,
"createFoldersInDestination": r
};
result.push(element);
}
// TODO: We need to return something sensibile here.
return result;
}
async function replicateStructure(auth, parameters) {
sourceFolderId = parameters.source;
destinationFolderId = parameters.target;
shortcuts = parameters.shortcuts;
nextto = parameters.nextto;
addstring = parameters.addstring;
const drive = google.drive({ version: 'v3', auth });
console.log('Replicating folder structure...');
console.log('Getting folder structure...');
const folderStructure = await getFolderStructure(drive, sourceFolderId);
console.log('Creating folders in destination...');
const result = await createFoldersInDestination(drive, [], destinationFolderId, folderStructure, sourceFolderId, shortcuts, nextto, addstring);
console.log('Folder structure replicated and shortcuts created successfully.');
return {
"parameters": parameters,
"folderStructure": folderStructure,
"createFoldersInDestination": result
};
}
async function listUsersWithAccessToFolder(auth, params) {
const folderIds = params.folderIds;
const options = params.options;
for (folderId of folderIds) {
try {
// Initialize Google Drive API client
const drive = google.drive({ version: 'v3', auth });
// Get the permissions for the folder
const res = await drive.permissions.list({
fileId: folderId,
fields: 'permissions(id,emailAddress,type,role)',
supportsAllDrives: true
});
// Extract user details from the permissions
const users = res.data.permissions
.filter(permission => permission.type === 'user')
.map(permission => ({
id: permission.id,
email: permission.emailAddress,
role: permission.role,
}));
if (options.emails) {
console.log(users.map(user => user.email).join(', '));
} else {
console.log('Users with access:', users);
};
return users;
} catch (error) {
console.error('Error listing users with access:', error);
throw error;
}
}
}
async function moveOneFile(auth, fileId, folderId, makeShortcut) {
// https://developers.google.com/drive/api/v3/reference/files/get
// Retrieve the existing parents to remove
var drive = google.drive({ version: "v3", auth: auth });
drive.files.get(
{
fileId: fileId,
fields: "parents",
supportsAllDrives: true
},
function (err, response) {
if (err) {
// Handle error
console.error(err);
console.log("ERROR ACCESSING^^^");
} else {
file = response.data;
// console.log("TEMPORARY="+JSON.stringify( file ,null,2))
// Move the file to the new folder
var previousParents = file.parents.join(",");
if (makeShortcut) {
// console.log("TEMPORARY="+JSON.stringify( file.parents ,null,2))
createShortcut(auth, fileId, file.parents[0]);
}
drive.files.update(
{
fileId: fileId,
addParents: folderId,
removeParents: previousParents,
fields: "id, parents",
supportsAllDrives: true
},
function (err, resp) {
if (err) {
console.log("oppssss")
console.log("ERROR: " + JSON.stringify(err, null, 2));
console.log("ERROR MOVING^^^");
} else {
//console.log("Success: "+JSON.stringify( resp ,null,2))
console.log("Moved successfully.");
}
}
);
}
}
);
}
async function createFolders(auth, parameters) {
if (!parameters) process.exit(1);
names = parameters.names;
folderId = parameters.options.target;
const makeShortCut = parameters.options.shortcut;
names.forEach(async (name) => {
createFolder(auth, name, folderId);
});
}
async function uploadFiles(auth, params) {
const folderId = params.options.target;
for (const file of params.names) {
const id = await uploadFile(auth, file, folderId);
}
}
function defaultFormat(param) {
switch (param) {
case 'application/vnd.google-apps.document':
return "docx";
case 'application/vnd.google-apps.presentation': // Google Slides
return "pptx";
case 'application/vnd.google-apps.spreadsheet': // Google Sheets
return "xlsx";
default:
console.log(`Did not understand type=${param}. Defaulting to pdf`);
return "pdf";
}
};
/*
application/vnd.google-apps.audio
application/vnd.google-apps.document Google Docs
application/vnd.google-apps.drive-sdk Third-party shortcut
application/vnd.google-apps.drawing Google Drawings
application/vnd.google-apps.file Google Drive file
application/vnd.google-apps.folder Google Drive folder
application/vnd.google-apps.form Google Forms
application/vnd.google-apps.fusiontable Google Fusion Tables
application/vnd.google-apps.jam Google Jamboard
application/vnd.google-apps.mail-layout Email layout
application/vnd.google-apps.map Google My Maps
application/vnd.google-apps.photo Google Photos
application/vnd.google-apps.presentation Google Slides
application/vnd.google-apps.script Google Apps Script
application/vnd.google-apps.shortcut Shortcut
application/vnd.google-apps.site Google Sites
application/vnd.google-apps.spreadsheet Google Sheets
application/vnd.google-apps.unknown
application/vnd.google-apps.video
*/
function getMimetype(file) {
switch (file) {
case "pdf":
return "application/pdf";
case "html":
case "htm":
return "text/html";
case "txt":
return "text/plain";
case "doc":
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "odt":
return "application/vnd.oasis.opendocument.text";
case "xls":
case "xlsx":
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
case "ods":
return "application/vnd.oasis.opendocument.spreadsheet";
case "xml":
return "application/xml";
case "csv":
return "text/csv";
case "tsv":
return 'text/tab-separated-values';
case "tmpl":
return "text/plain";
case "php":
return "application/x-httpd-php";
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
case "js":
return "application/javascript";
case "swf":
return "application/x-shockwave-flash";
case "mp3":
return "audio/mpeg";
case "zip":
return "application/zip";
case "rar":
return "application/x-rar-compressed";
case "tar":
return "application/x-tar";
case "arj":
return "application/x-arj";
case "cab":
return "application/vnd.ms-cab-compressed";
default:
console.log(`Did not understand type=${file}`);
return null;
}
}
async function collectElements(auth, params) {
let query = "";
let queryArr = [];
console.log("Collecting elements from Google Drive " + JSON.stringify(params));
if (params.options.format) {
console.log("FORMAT=" + params.options.format);
let mimetypes = [];
params.options.format.forEach(async (type) => {
const mimetype = getMimetype(type);
if (!mimetype) return;
mimetypes.push(mimetype);
});
if (mimetypes.length != 0) {
let qArr = []
for (const mimetype of mimetypes) {
qArr.push("mimeType='" + mimetype + "'");
}
query = query.slice(0, -4);
query = "( " + qArr.join("or") + ")";
}
queryArr.push(query);
}
if (params.options.fileOnly && !params.options.folderOnly)
queryArr.push("(mimeType!='application/vnd.google-apps.folder')");
else if (!params.options.fileOnly && params.options.folderOnly)
queryArr.push("(mimeType='application/vnd.google-apps.folder')");
if (params.options.name)
queryArr.push("(name contains '" + params.options.name + "')");
// Doesn't work:
//if (params.options.parent)
// queryArr.push("('" + params.options.parent + "' in parents)");
query = queryArr.join(" and ");
console.log(query);
const drive = google.drive({ version: "v3", auth });
const files = [];
const data = [];
let jsonData = [];
let pageToken = null;
// console.log("q: ", query);
// fields: "nextPageToken, files(id, name, mimeType, description, starred, trashed, parents, webViewLink, iconLink, hasThumbnail, thumbnailLink, createdTime, modifiedTime, size, version, owners, lastModifyingUser, shared, permissions, folderColorRgb, originalFilename, fullFileExtension, fileExtension)",
let listParam = {
q: query,
fields: "nextPageToken, files(id, name, mimeType, starred, trashed, createdTime, modifiedTime, version, parents, fullFileExtension, fileExtension)",
spaces: "drive",
pageToken: pageToken,
supportsAllDrives: true
}
if (params.options.driveid) {
listParam = {
...listParam,
corpora: 'drive',
driveId: params.options.driveid,
includeItemsFromAllDrives: true,
orderBy: 'folder,name'
}
}
// console.log(listParam)
do {
try {
const res = await drive.files.list(listParam);
console.log("TEMPORARY=" + JSON.stringify(res, null, 2))
Array.prototype.push.apply(files, res.data.files);
res.data.files.forEach(function (file) {
// console.log('Found file:', file.name, file.id);
data.push([shortenFileName(file), file.id]);
jsonData.push(file);
});
pageToken = res.data.nextPageToken;
} catch (err) {
// TODO (developer) - Handle error
throw err;