-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
executable file
·599 lines (511 loc) · 11.4 KB
/
Code.gs
File metadata and controls
executable file
·599 lines (511 loc) · 11.4 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
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
var userProperties = PropertiesService.getUserProperties();
var internalStates = {
bare: {
previous: null,
val: 0,
text: 'bare',
next: 'analysed'
},
analysed: {
previous: null,
val: 1,
text: 'analysed',
next: 'prepared'
},
prepared: {
previous: 'bare',
val: 2,
text: 'prepared',
next: 'copyInProgress'
},
copyInProgress: {
previous: 'bare',
val: 3,
text: 'copyInProgress',
next: 'finished'
},
finished: {
previous: 'bare',
val: 4,
text: 'finished',
next: null
}
}
var frontendStates = {
analyse: {
val: 0,
text: 'Analyse',
next: 'analyseRunning',
back: null,
disabled: false
},
analyseRunning: {
val: 1,
text: 'Analysing...',
next: 'prepare',
back: 'analyse',
disabled: true
},
prepare: {
val: 2,
text: 'Prepare',
next: 'prepareRunning',
back: 'analyseRunning',
disabled: false
},
prepareRunning: {
val: 3,
text: 'Preparing...',
next: 'copy',
back: 'prepare',
disabled: true
},
copy: {
val: 4,
text: 'Copy',
next: 'copyRunning',
back: 'prepareRunning',
disabled: false
},
copyRunning: {
val: 5,
text: 'Copying...',
next: 'finished',
back: 'copy',
disabled: true
},
finished: {
val: 6,
text: 'Finished',
next: null,
back: 'copyRunning',
disabled: false
}
}
/**
* Init
*/
function init()
{
try {
initState_();
var currentState = getFrontendState_();
if (
(currentState.val == internalStates.prepared.val || currentState.val == internalStates.copyInProgress.val || currentState.val == internalStates.finished.val)
&&
!healthCheck_()
) {
reset();
}
setSourceDir_();
return getCurrentStatus_('Everything is set to go...');
} catch (e) {
reset();
throw getErrorMessage_(4);
}
}
function healthCheck_()
{
var destinationDir = getDestinationDir_();
Logger.log('Destination dir: '+destinationDir)
return !(destinationDir == null || destinationDir.isTrashed())
}
function getCurrentStatus_(message)
{
return {
'states': frontendStates,
'analysis': getAnalysis_(),
'currentState': getFrontendState_(),
'message': message
}
}
/**
* State Machine
*/
function initState_()
{
Logger.log(internalStates[getProperty_('currentState')]);
if (getCurrentState_() == null) {
setNewState_(internalStates.bare);
}
}
function nextState_()
{
var currentState = getCurrentState_();
if (currentState.next != null) {
setNewState_(internalStates[currentState.next]);
}
}
function resetState_()
{
initState_();
var currentState = getCurrentState_();
}
function getCurrentState_()
{
var currentState = getProperty_('currentState');
if (currentState != null) {
currentState = internalStates[getProperty_('currentState')];
}
return currentState;
}
function setNewState_(newState)
{
setProperty_('currentState', newState.text);
}
function getFrontendState_()
{
return mapInternalStateToFrontendStates_();
}
function mapInternalStateToFrontendStates_()
{
var currentState = getCurrentState_();
if (currentState.val == internalStates.bare.val) {
return 'analyse';
} else if (currentState.val == internalStates.analysed.val) {
return 'prepare';
} else if (currentState.val == internalStates.prepared.val || currentState.val == internalStates.copyInProgress.val) {
return 'copy';
} else {
return 'finished';
}
}
/**
* Reset Everything
*/
function reset()
{
try {
var destinationDir = getDestinationDir_();
if (destinationDir != null) {
destinationDir.setTrashed(true);
}
} catch(e) {
// NOTHING TO THROW HERE...
}
deleteAllProperties_();
resetState_();
setSourceDir_();
return getCurrentStatus_('Reset done. You can now start from scratch...');
}
/**
* Analyse
*/
function analyse()
{
var analysis = analyseDir_(getSourceDir_());
nextState_();
setAnalysis_(analysis);
return getSuccessMessage_(analysis, 'Analysis finished.');
}
function analyseDir_(sourceDir)
{
var totalDirs = 0;
var totalFiles = totalFilesInDir_(sourceDir);
var dirs = sourceDir.getFolders();
while(dirs.hasNext()) {
var dir = dirs.next();
var data = analyseDir_(dir);
totalDirs++;
totalFiles += data.totalFiles;
totalDirs += data.totalDirs;
}
return {
totalFiles: totalFiles,
totalDirs: totalDirs
}
}
function totalFilesInDir_(sourceDir)
{
var files = sourceDir.getFiles();
var totalFiles = 0;
while(files.hasNext()) {
totalFiles++;
files.next();
}
return totalFiles;
}
function getAnalysis_()
{
return {
totalFiles: Math.round(getProperty_('totalFiles')),
totalDirs: Math.round(getProperty_('totalDirs'))
};
}
function setAnalysis_(analysis)
{
setProperty_('totalFiles', analysis.totalFiles);
setProperty_('totalDirs', analysis.totalDirs);
}
/**
* Prepare destination dir
*/
function prepare()
{
setSourceDir_();
setDestinationDir_();
nextState_();
return getSuccessMessage_({}, 'Analysis finished.');
}
/**
* Copy everything
*/
function copy()
{
initFilesCopied_();
if (folderIsNotFullyCopied_(getSourceDir_())) {
try {
copyAll_(getSourceDir_(), getDestinationDir_())
} catch (e) {
Logger.log("Ups!!! Something went wrong...");
throw e;
}
Logger.log("Finally you backup is finished!");
nextState_();
}
return getCurrentStatus_('Copy finished!!! YAY!!! :D');
}
function copyAll_(sourceDir, destinationDir)
{
try {
copyFiles_(sourceDir, destinationDir);
copyFolders_(sourceDir, destinationDir);
} catch (e) {
throw (getErrorMessage_(2));
}
markFolderAsFullyCopied_(sourceDir);
}
function copyFiles_(sourceDir, destinationDir)
{
var files = sourceDir.getFiles();
while(files.hasNext()) {
var file = files.next();
if (fileIsNotCopied_(file)) {
copySingleFile_(file, destinationDir);
Utilities.sleep(2000);
}
}
}
function copySingleFile_(file, destinationDir)
{
try {
file.makeCopy(file.getName(), destinationDir);
} catch(e) {
Logger.log("Failed to copy '"+ file.getName() +"'. Error: '" + e.toString() + "'");
throw e;
}
markFileAsCopied_(file);
}
function fileIsNotCopied_(file)
{
return (getFile_(file.getId()) == null)
}
function markFileAsCopied_(file)
{
try {
incrementFilesCopied_();
setFile_(file.getId(), true);
} catch(e) {
Logger.log("Error marking dir as visited. Error: " + e.toString());
throw e;
}
}
function copyFolders_(sourceDir, destinationDir)
{
var folders = sourceDir.getFolders();
while(folders.hasNext()) {
var childSourceDir = folders.next();
var childDestinationDir = null;
if (folderIsNotFullyCopied_(childSourceDir)) {
try {
childDestinationDir = createDestinationFolder_(sourceDir, destinationDir, childSourceDir);
incrementFilesCopied_();
} catch(e) {
Logger.log("Error duplicating folder '" + childSourceDir.getName() + "'. Error: " + e.toString());
throw e;
}
try {
copyAll_(childSourceDir, childDestinationDir);
} catch (e) {
Logger.log("Error copying folder '" + childSourceDir.getName() + "'" )
throw e;
}
}
}
}
function createDestinationFolder_(sourceDir, destinationDir, folderToCopy)
{
var copiedFolderId = getMappedFolder_(folderToCopy.getId());
if (copiedFolderId != null) {
return DriveApp.getFolderById(copiedFolderId);
} else {
var copiedFolder = destinationDir.createFolder(folderToCopy.getName());
setMappedFolder_(folderToCopy.getId(), copiedFolder.getId());
return copiedFolder;
}
}
function folderIsNotFullyCopied_(folder)
{
return (getFolder_('fc_'+folder.getId()) == null);
}
function markFolderAsFullyCopied_(folder)
{
try {
setFolder_('fc_'+folder.getId(), true);
} catch(e) {
Logger.log("Error marking dir as visited. Error: " + e.toString());
throw e;
}
}
function getMappedFolder_(sourceFolderId)
{
return getFolder_(sourceFolderId);
}
function setMappedFolder_(sourceFolderId, destinationFolderId)
{
setFolder_(sourceFolderId, destinationFolderId);
}
/**
* Count total files copied
*/
function getFilesCopiedKey_()
{
return 'files_copied';
}
function initFilesCopied_()
{
var filesCopied = getTotalFilesCopied_();
if (filesCopied == null) {
setProperty_(getFilesCopiedKey_(), 0);
}
}
function incrementFilesCopied_()
{
var filesCopied = getTotalFilesCopied_();
if (filesCopied == null) {
setProperty_(getFilesCopiedKey_(), 0);
} else {
setProperty_(getFilesCopiedKey_(), filesCopied+1);
}
}
function getTotalFilesCopied_()
{
return Math.round(getProperty_(getFilesCopiedKey_()));
}
/**
* Utils
*/
function getSourceDirName_()
{
return 'ponteiro-drive-migration-source';
}
function getDestinationDirName_()
{
return 'ponteiro-drive-migration-destination';
}
function getSourceDir_()
{
return DriveApp.getFolderById(getProperty_('source_dir_id'));
}
function setSourceDir_()
{
var sourceDir = DriveApp.getFoldersByName(getSourceDirName_());
if (sourceDir.hasNext()) {
setProperty_('source_dir_id', sourceDir.next().getId());
} else {
throw (getErrorMessage_(0));
}
}
function getDestinationDir_()
{
var destinationDir = getProperty_('destination_dir_id');
if (destinationDir != null) {
destinationDir = DriveApp.getFolderById(getProperty_('destination_dir_id'));
}
return destinationDir;
}
function setDestinationDir_()
{
var destinationDir = DriveApp.getRootFolder().createFolder(getDestinationDirName_());
setProperty_('destination_dir_id', destinationDir.getId());
}
function getFolderPrefix_()
{
return 'd_';
}
function getFolder_(key)
{
return getProperty_(getFolderPrefix_()+key);
}
function setFolder_(key, value)
{
setProperty_(getFolderPrefix_()+key, value);
}
function getFilePrefix_()
{
return 'f_';
}
function getFile_(key)
{
return getProperty_(getFilePrefix_()+key)
}
function setFile_(key, value)
{
setProperty_(getFilePrefix_()+key, value)
}
/**
* Property Operations
*/
function hasProperty_(key)
{
return getProperty_(key) != null;
}
function getProperty_(key)
{
return userProperties.getProperty(key);
}
function setProperty_(key, value)
{
userProperties.setProperty(key, value);
}
function deleteProperty_(key)
{
userProperties.deleteProperty(key);
}
function deleteAllProperties_()
{
userProperties.deleteAllProperties();
}
/**
* Error Messages
*/
var errorCodes = {
0: "Source dir not found! Please create a folder with the name '" + getSourceDirName_() + "'",
1: "Destination dir not found!",
2: "Copy failed...",
4: "Initialization failed, reset forced... Refresh the page to restart the process."
}
function getErrorMessage_(key)
{
return '{"state": "' + getFrontendState_() + '","error":"' + errorCodes[key] + '"}';
}
/**
* Success Messages
*/
function getSuccessMessage_(data, message)
{
return {state: getFrontendState_(), data: data, message: message};
}
/**
* Render UI
*/
function doGet()
{
var template = HtmlService.createTemplateFromFile('index');
template.sourceDirName = getSourceDirName_();
return template.evaluate().setTitle('Google Drive Migration').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function include(filename)
{
return HtmlService.createHtmlOutputFromFile(filename).setSandboxMode(HtmlService.SandboxMode.IFRAME).getContent();
}