-
-
Notifications
You must be signed in to change notification settings - Fork 850
/
sync.d
5915 lines (5512 loc) · 251 KB
/
sync.d
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
import std.algorithm;
import std.array: array;
import std.datetime;
import std.exception: enforce;
import std.file, std.json, std.path;
import std.regex;
import std.stdio, std.string, std.uni, std.uri;
import std.conv;
import std.encoding;
import core.time, core.thread;
import core.stdc.stdlib;
import config, itemdb, onedrive, selective, upload, util;
static import log;
// threshold after which files will be uploaded using an upload session
private long thresholdFileSize = 4 * 2^^20; // 4 MiB
// flag to set whether local files should be deleted from OneDrive
private bool noRemoteDelete = false;
// flag to set whether the local file should be deleted once it is successfully uploaded to OneDrive
private bool localDeleteAfterUpload = false;
// flag to set if we are running as uploadOnly
private bool uploadOnly = false;
// Do we configure to disable the upload validation routine
private bool disableUploadValidation = false;
private bool isItemFolder(const ref JSONValue item)
{
return ("folder" in item) != null;
}
private bool isItemFile(const ref JSONValue item)
{
return ("file" in item) != null;
}
private bool isItemDeleted(const ref JSONValue item)
{
return ("deleted" in item) != null;
}
private bool isItemRoot(const ref JSONValue item)
{
return ("root" in item) != null;
}
private bool isItemRemote(const ref JSONValue item)
{
return ("remoteItem" in item) != null;
}
private bool hasParentReference(const ref JSONValue item)
{
return ("parentReference" in item) != null;
}
private bool hasParentReferenceId(const ref JSONValue item)
{
return ("id" in item["parentReference"]) != null;
}
private bool hasParentReferencePath(const ref JSONValue item)
{
return ("path" in item["parentReference"]) != null;
}
private bool isMalware(const ref JSONValue item)
{
return ("malware" in item) != null;
}
private bool hasFileSize(const ref JSONValue item)
{
return ("size" in item) != null;
}
private bool hasId(const ref JSONValue item)
{
return ("id" in item) != null;
}
private bool hasHashes(const ref JSONValue item)
{
return ("hashes" in item["file"]) != null;
}
private bool hasQuickXorHash(const ref JSONValue item)
{
return ("quickXorHash" in item["file"]["hashes"]) != null;
}
private bool hasSha1Hash(const ref JSONValue item)
{
return ("sha1Hash" in item["file"]["hashes"]) != null;
}
private bool isDotFile(const(string) path)
{
// always allow the root
if (path == ".") return false;
auto paths = pathSplitter(buildNormalizedPath(path));
foreach(base; paths) {
if (startsWith(base, ".")){
return true;
}
}
return false;
}
// construct an Item struct from a JSON driveItem
private Item makeItem(const ref JSONValue driveItem)
{
Item item = {
id: driveItem["id"].str,
name: "name" in driveItem ? driveItem["name"].str : null, // name may be missing for deleted files in OneDrive Biz
eTag: "eTag" in driveItem ? driveItem["eTag"].str : null, // eTag is not returned for the root in OneDrive Biz
cTag: "cTag" in driveItem ? driveItem["cTag"].str : null, // cTag is missing in old files (and all folders in OneDrive Biz)
};
// OneDrive API Change: https://github.com/OneDrive/onedrive-api-docs/issues/834
// OneDrive no longer returns lastModifiedDateTime if the item is deleted by OneDrive
if(isItemDeleted(driveItem)){
// Set mtime to SysTime(0)
item.mtime = SysTime(0);
} else {
// Item is not in a deleted state
// Resolve 'Key not found: fileSystemInfo' when then item is a remote item
// https://github.com/abraunegg/onedrive/issues/11
if (isItemRemote(driveItem)) {
item.mtime = SysTime.fromISOExtString(driveItem["remoteItem"]["fileSystemInfo"]["lastModifiedDateTime"].str);
} else {
item.mtime = SysTime.fromISOExtString(driveItem["fileSystemInfo"]["lastModifiedDateTime"].str);
}
}
if (isItemFile(driveItem)) {
item.type = ItemType.file;
} else if (isItemFolder(driveItem)) {
item.type = ItemType.dir;
} else if (isItemRemote(driveItem)) {
item.type = ItemType.remote;
} else {
// do not throw exception, item will be removed in applyDifferences()
}
// root and remote items do not have parentReference
if (!isItemRoot(driveItem) && ("parentReference" in driveItem) != null) {
item.driveId = driveItem["parentReference"]["driveId"].str;
if (hasParentReferenceId(driveItem)) {
item.parentId = driveItem["parentReference"]["id"].str;
}
}
// extract the file hash
if (isItemFile(driveItem) && ("hashes" in driveItem["file"])) {
if ("crc32Hash" in driveItem["file"]["hashes"]) {
item.crc32Hash = driveItem["file"]["hashes"]["crc32Hash"].str;
} else if ("sha1Hash" in driveItem["file"]["hashes"]) {
item.sha1Hash = driveItem["file"]["hashes"]["sha1Hash"].str;
} else if ("quickXorHash" in driveItem["file"]["hashes"]) {
item.quickXorHash = driveItem["file"]["hashes"]["quickXorHash"].str;
} else {
log.vlog("The file does not have any hash");
}
}
if (isItemRemote(driveItem)) {
item.remoteDriveId = driveItem["remoteItem"]["parentReference"]["driveId"].str;
item.remoteId = driveItem["remoteItem"]["id"].str;
}
// National Cloud Deployments (US and DE) do not support /delta as a query
// Thus we need to track in the database that this item is in sync
// As we are making an item, set the syncStatus to Y
// ONLY when using a National Cloud Deployment, all the existing DB entries will get set to N
// so when processing /children, it can be identified what the 'deleted' difference is
item.syncStatus = "Y";
return item;
}
private bool testFileHash(const(string) path, const ref Item item)
{
if (item.crc32Hash) {
if (item.crc32Hash == computeCrc32(path)) return true;
} else if (item.sha1Hash) {
if (item.sha1Hash == computeSha1Hash(path)) return true;
} else if (item.quickXorHash) {
if (item.quickXorHash == computeQuickXorHash(path)) return true;
}
return false;
}
class SyncException: Exception
{
@nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line);
}
}
final class SyncEngine
{
private Config cfg;
private OneDriveApi onedrive;
private ItemDatabase itemdb;
private UploadSession session;
private SelectiveSync selectiveSync;
// list of items to skip while applying the changes
private string[] skippedItems;
// list of items to delete after the changes has been downloaded
private string[2][] idsToDelete;
// list of items we fake created when running --dry-run
private string[2][] idsFaked;
// default drive id
private string defaultDriveId;
// default root id
private string defaultRootId;
// type of OneDrive account
private string accountType;
// free space remaining at init()
private long remainingFreeSpace;
// file size limit for a new file
private long newSizeLimit;
// is file malware flag
private bool malwareDetected = false;
// download filesystem issue flag
private bool downloadFailed = false;
// upload failure - OneDrive or filesystem issue (reading data)
private bool uploadFailed = false;
// initialization has been done
private bool initDone = false;
// sync engine dryRun flag
private bool dryRun = false;
// quota details available
private bool quotaAvailable = true;
// quota details restricted
private bool quotaRestricted = false;
// sync business shared folders flag
private bool syncBusinessFolders = false;
// single directory scope flag
private bool singleDirectoryScope = false;
// is sync_list configured
private bool syncListConfigured = false;
// sync_list new folder added, trigger delta scan override
private bool oneDriveFullScanTrigger = false;
// is bypass_data_preservation set via config file
// Local data loss MAY occur in this scenario
private bool bypassDataPreservation = false;
// is National Cloud Deployments configured
private bool nationalCloudDeployment = false;
// array of all OneDrive driveId's for use with OneDrive Business Folders
private string[] driveIDsArray;
this(Config cfg, OneDriveApi onedrive, ItemDatabase itemdb, SelectiveSync selectiveSync)
{
assert(onedrive && itemdb && selectiveSync);
this.cfg = cfg;
this.onedrive = onedrive;
this.itemdb = itemdb;
this.selectiveSync = selectiveSync;
// session = UploadSession(onedrive, cfg.uploadStateFilePath);
this.dryRun = cfg.getValueBool("dry_run");
this.newSizeLimit = cfg.getValueLong("skip_size") * 2^^20;
this.newSizeLimit = (this.newSizeLimit == 0) ? long.max : this.newSizeLimit;
}
void reset()
{
initDone=false;
}
void init()
{
// Set accountType, defaultDriveId, defaultRootId & remainingFreeSpace once and reuse where possible
JSONValue oneDriveDetails;
JSONValue oneDriveRootDetails;
if (initDone) {
return;
}
session = UploadSession(onedrive, cfg.uploadStateFilePath);
// Need to catch 400 or 5xx server side errors at initialization
// Get Default Drive
try {
oneDriveDetails = onedrive.getDefaultDrive();
} catch (OneDriveException e) {
log.vdebug("oneDriveDetails = onedrive.getDefaultDrive() generated a OneDriveException");
if (e.httpStatusCode == 400) {
// OneDrive responded with 400 error: Bad Request
displayOneDriveErrorMessage(e.msg);
// Check this
if (cfg.getValueString("drive_id").length) {
log.error("\nERROR: Check your 'drive_id' entry in your configuration file as it may be incorrect\n");
}
// Must exit here
exit(-1);
}
if (e.httpStatusCode == 401) {
// HTTP request returned status code 401 (Unauthorized)
displayOneDriveErrorMessage(e.msg);
log.errorAndNotify("\nERROR: Check your configuration as your refresh_token may be empty or invalid. You may need to issue a --logout and re-authorise this client.\n");
// Must exit here
exit(-1);
}
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling init();");
init();
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// There was a HTTP 5xx Server Side Error
displayOneDriveErrorMessage(e.msg);
// Must exit here
exit(-1);
}
}
// Get Default Root
try {
oneDriveRootDetails = onedrive.getDefaultRoot();
} catch (OneDriveException e) {
log.vdebug("oneDriveRootDetails = onedrive.getDefaultRoot() generated a OneDriveException");
if (e.httpStatusCode == 400) {
// OneDrive responded with 400 error: Bad Request
displayOneDriveErrorMessage(e.msg);
// Check this
if (cfg.getValueString("drive_id").length) {
log.error("\nERROR: Check your 'drive_id' entry in your configuration file as it may be incorrect\n");
}
// Must exit here
exit(-1);
}
if (e.httpStatusCode == 401) {
// HTTP request returned status code 401 (Unauthorized)
displayOneDriveErrorMessage(e.msg);
log.errorAndNotify("\nERROR: Check your configuration as your refresh_token may be empty or invalid. You may need to issue a --logout and re-authorise this client.\n");
// Must exit here
exit(-1);
}
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling init();");
init();
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// There was a HTTP 5xx Server Side Error
displayOneDriveErrorMessage(e.msg);
// Must exit here
exit(-1);
}
}
if ((oneDriveDetails.type() == JSONType.object) && (oneDriveRootDetails.type() == JSONType.object) && (hasId(oneDriveDetails)) && (hasId(oneDriveRootDetails))) {
// JSON elements are valid
// Debug OneDrive Account details response
log.vdebug("OneDrive Account Details: ", oneDriveDetails);
log.vdebug("OneDrive Account Root Details: ", oneDriveRootDetails);
// Successfully got details from OneDrive without a server side error such as 'HTTP/1.1 500 Internal Server Error' or 'HTTP/1.1 504 Gateway Timeout'
accountType = oneDriveDetails["driveType"].str;
defaultDriveId = oneDriveDetails["id"].str;
defaultRootId = oneDriveRootDetails["id"].str;
remainingFreeSpace = oneDriveDetails["quota"]["remaining"].integer;
// Make sure that defaultDriveId is in our driveIDs array to use when checking if item is in database
// Keep the driveIDsArray with unique entries only
if (!canFind(driveIDsArray, defaultDriveId)) {
// Add this drive id to the array to search with
driveIDsArray ~= defaultDriveId;
}
// In some cases OneDrive Business configurations 'restrict' quota details thus is empty / blank / negative value / zero
if (remainingFreeSpace <= 0) {
// free space is <= 0 .. why ?
if ("remaining" in oneDriveDetails["quota"]){
// json response contained a 'remaining' value
if (accountType == "personal"){
// zero space available
log.error("ERROR: OneDrive account currently has zero space available. Please free up some space online.");
quotaAvailable = false;
} else {
// zero space available is being reported, maybe being restricted?
log.error("WARNING: OneDrive quota information is being restricted or providing a zero value. Please fix by speaking to your OneDrive / Office 365 Administrator.");
quotaRestricted = true;
}
} else {
// json response was missing a 'remaining' value
if (accountType == "personal"){
log.error("ERROR: OneDrive quota information is missing. Potentially your OneDrive account currently has zero space available. Please free up some space online.");
} else {
// quota details not available
log.error("ERROR: OneDrive quota information is being restricted. Please fix by speaking to your OneDrive / Office 365 Administrator.");
}
}
}
// Display accountType, defaultDriveId, defaultRootId & remainingFreeSpace for verbose logging purposes
log.vlog("Application version: ", strip(import("version")));
log.vlog("Account Type: ", accountType);
log.vlog("Default Drive ID: ", defaultDriveId);
log.vlog("Default Root ID: ", defaultRootId);
// What do we display here
if (remainingFreeSpace > 0) {
// Display the actual value
log.vlog("Remaining Free Space: ", remainingFreeSpace);
} else {
// zero or non-zero value or restricted
if (!quotaRestricted){
log.vlog("Remaining Free Space: 0");
} else {
log.vlog("Remaining Free Space: Not Available");
}
}
// If account type is documentLibrary - then most likely this is a SharePoint repository
// and files 'may' be modified after upload. See: https://github.com/abraunegg/onedrive/issues/205
if(accountType == "documentLibrary") {
setDisableUploadValidation();
}
// Check the local database to ensure the OneDrive Root details are in the database
checkDatabaseForOneDriveRoot();
// Check if there is an interrupted upload session
if (session.restore()) {
log.log("Continuing the upload session ...");
auto item = session.upload();
saveItem(item);
}
initDone = true;
} else {
// init failure
initDone = false;
// log why
log.error("ERROR: Unable to query OneDrive to initialize application");
// Debug OneDrive Account details response
log.vdebug("OneDrive Account Details: ", oneDriveDetails);
log.vdebug("OneDrive Account Root Details: ", oneDriveRootDetails);
// Must exit here
exit(-1);
}
}
// Configure uploadOnly if function is called
// By default, uploadOnly = false;
void setUploadOnly()
{
uploadOnly = true;
}
// Configure noRemoteDelete if function is called
// By default, noRemoteDelete = false;
// Meaning we will process local deletes to delete item on OneDrive
void setNoRemoteDelete()
{
noRemoteDelete = true;
}
// Configure localDeleteAfterUpload if function is called
// By default, localDeleteAfterUpload = false;
// Meaning we will not delete any local file after upload is successful
void setLocalDeleteAfterUpload()
{
localDeleteAfterUpload = true;
}
// set the flag that we are going to sync business shared folders
void setSyncBusinessFolders()
{
syncBusinessFolders = true;
}
// Configure singleDirectoryScope if function is called
// By default, singleDirectoryScope = false
void setSingleDirectoryScope()
{
singleDirectoryScope = true;
}
// Configure disableUploadValidation if function is called
// By default, disableUploadValidation = false;
// Meaning we will always validate our uploads
// However, when uploading a file that can contain metadata SharePoint will associate some
// metadata from the library the file is uploaded to directly in the file
// which breaks this validation. See https://github.com/abraunegg/onedrive/issues/205
void setDisableUploadValidation()
{
disableUploadValidation = true;
log.vdebug("documentLibrary account type - flagging to disable upload validation checks due to Microsoft SharePoint file modification enrichments");
}
// Issue #658 Handling
// If an existing folder is moved into a sync_list valid path (where it previously was out of scope due to sync_list),
// then set this flag to true, so that on the second 'true-up' sync, we force a rescan of the OneDrive path to capture any 'files'
void setOneDriveFullScanTrigger()
{
oneDriveFullScanTrigger = true;
log.vdebug("Setting oneDriveFullScanTrigger = true due to new folder creation request in a location that is now in-scope which may have previously out of scope");
}
// unset method
void unsetOneDriveFullScanTrigger()
{
oneDriveFullScanTrigger = false;
log.vdebug("Setting oneDriveFullScanTrigger = false");
}
// set syncListConfigured to true
void setSyncListConfigured()
{
syncListConfigured = true;
log.vdebug("Setting syncListConfigured = true");
}
// set bypassDataPreservation to true
void setBypassDataPreservation()
{
bypassDataPreservation = true;
log.vdebug("Setting bypassDataPreservation = true");
}
// set nationalCloudDeployment to true
void setNationalCloudDeployment()
{
nationalCloudDeployment = true;
log.vdebug("Setting nationalCloudDeployment = true");
}
// return the OneDrive Account Type
auto getAccountType()
{
// return account type in use
return accountType;
}
// download all new changes from OneDrive
void applyDifferences(bool performFullItemScan)
{
// Set defaults for the root folder
// Use the global's as initialised via init() rather than performing unnecessary additional HTTPS calls
string driveId = defaultDriveId;
string rootId = defaultRootId;
applyDifferences(driveId, rootId, performFullItemScan);
// Check OneDrive Personal Shared Folders
if (accountType == "personal"){
// https://github.com/OneDrive/onedrive-api-docs/issues/764
Item[] items = itemdb.selectRemoteItems();
foreach (item; items) {
// Only check path if config is != ""
if (cfg.getValueString("skip_dir") != "") {
// The path that needs to be checked needs to include the '/'
// This due to if the user has specified in skip_dir an exclusive path: '/path' - that is what must be matched
if (selectiveSync.isDirNameExcluded(item.name)) {
// This directory name is excluded
log.vlog("Skipping item - excluded by skip_dir config: ", item.name);
continue;
}
}
// Directory name is not excluded or skip_dir is not populated
log.vdebug("------------------------------------------------------------------");
if (!cfg.getValueBool("monitor")) {
log.log("Syncing this OneDrive Personal Shared Folder: ", item.name);
} else {
log.vlog("Syncing this OneDrive Personal Shared Folder: ", item.name);
}
// Check this OneDrive Personal Shared Folders
applyDifferences(item.remoteDriveId, item.remoteId, performFullItemScan);
// Keep the driveIDsArray with unique entries only
if (!canFind(driveIDsArray, item.remoteDriveId)) {
// Add this OneDrive Personal Shared Folder driveId array
driveIDsArray ~= item.remoteDriveId;
}
}
}
// Check OneDrive Business Shared Folders, if configured to do so
if (syncBusinessFolders){
// query OneDrive Business Shared Folders shared with me
log.vlog("Attempting to sync OneDrive Business Shared Folders");
JSONValue graphQuery = onedrive.getSharedWithMe();
if (graphQuery.type() == JSONType.object) {
string sharedFolderName;
foreach (searchResult; graphQuery["value"].array) {
sharedFolderName = searchResult["name"].str;
// Compare this to values in business_shared_folders
if(selectiveSync.isSharedFolderMatched(sharedFolderName)){
// Folder name matches what we are looking for
// Flags for matching
bool itemInDatabase = false;
bool itemLocalDirExists = false;
bool itemPathIsLocal = false;
// "what if" there are 2 or more folders shared with me have the "same" name?
// The folder name will be the same, but driveId will be different
// This will then cause these 'shared folders' to cross populate data, which may not be desirable
log.vdebug("Shared Folder Name: ", sharedFolderName);
log.vdebug("Parent Drive Id: ", searchResult["remoteItem"]["parentReference"]["driveId"].str);
log.vdebug("Shared Item Id: ", searchResult["remoteItem"]["id"].str);
Item databaseItem;
// for each driveid in the existing driveIDsArray
foreach (searchDriveId; driveIDsArray) {
log.vdebug("searching database for: ", searchDriveId, " ", sharedFolderName);
if (itemdb.selectByPath(sharedFolderName, searchDriveId, databaseItem)) {
log.vdebug("Found shared folder name in database");
itemInDatabase = true;
log.vdebug("databaseItem: ", databaseItem);
// Does the databaseItem.driveId == defaultDriveId?
if (databaseItem.driveId == defaultDriveId) {
itemPathIsLocal = true;
}
} else {
log.vdebug("Shared folder name not found in database");
// "what if" there is 'already' a local folder with this name
// Check if in the database
// If NOT in the database, but resides on disk, this could be a new local folder created after last sync but before this one
// However we sync 'shared folders' before checking for local changes
string localpath = expandTilde(cfg.getValueString("sync_dir")) ~ "/" ~ sharedFolderName;
if (exists(localpath)) {
// local path exists
log.vdebug("Found shared folder name in local OneDrive sync_dir");
itemLocalDirExists = true;
}
}
}
// Shared Folder Evaluation Debugging
log.vdebug("item in database: ", itemInDatabase);
log.vdebug("path exists on disk: ", itemLocalDirExists);
log.vdebug("database drive id matches defaultDriveId: ", itemPathIsLocal);
log.vdebug("database data matches search data: ", ((databaseItem.driveId == searchResult["remoteItem"]["parentReference"]["driveId"].str) && (databaseItem.id == searchResult["remoteItem"]["id"].str)));
// Additional logging
string sharedByName;
string sharedByEmail;
// Extra details for verbose logging
if ("sharedBy" in searchResult["remoteItem"]["shared"]) {
if ("displayName" in searchResult["remoteItem"]["shared"]["sharedBy"]["user"]) {
sharedByName = searchResult["remoteItem"]["shared"]["sharedBy"]["user"]["displayName"].str;
}
if ("email" in searchResult["remoteItem"]["shared"]["sharedBy"]["user"]) {
sharedByEmail = searchResult["remoteItem"]["shared"]["sharedBy"]["user"]["email"].str;
}
}
if ( ((!itemInDatabase) || (!itemLocalDirExists)) || (((databaseItem.driveId == searchResult["remoteItem"]["parentReference"]["driveId"].str) && (databaseItem.id == searchResult["remoteItem"]["id"].str)) && (!itemPathIsLocal)) ) {
// This shared folder does not exist in the database
if (!cfg.getValueBool("monitor")) {
log.log("Syncing this OneDrive Business Shared Folder: ", sharedFolderName);
} else {
log.vlog("Syncing this OneDrive Business Shared Folder: ", sharedFolderName);
}
Item businessSharedFolder = makeItem(searchResult);
// Log who shared this to assist with sync data correlation
if ((sharedByName != "") && (sharedByEmail != "")) {
log.vlog("OneDrive Business Shared Folder - Shared By: ", sharedByName, " (", sharedByEmail, ")");
} else {
if (sharedByName != "") {
log.vlog("OneDrive Business Shared Folder - Shared By: ", sharedByName);
}
}
// Do the actual sync
applyDifferences(businessSharedFolder.remoteDriveId, businessSharedFolder.remoteId, performFullItemScan);
// add this parent drive id to the array to search for, ready for next use
string newDriveID = searchResult["remoteItem"]["parentReference"]["driveId"].str;
// Keep the driveIDsArray with unique entries only
if (!canFind(driveIDsArray, newDriveID)) {
// Add this drive id to the array to search with
driveIDsArray ~= newDriveID;
}
} else {
// Shared Folder Name Conflict ...
log.log("WARNING: Skipping shared folder due to existing name conflict: ", sharedFolderName);
log.log("WARNING: Skipping changes of Path ID: ", searchResult["remoteItem"]["id"].str);
log.log("WARNING: To sync this shared folder, this shared folder needs to be renamed");
// Log who shared this to assist with conflict resolution
if ((sharedByName != "") && (sharedByEmail != "")) {
log.vlog("WARNING: Conflict Shared By: ", sharedByName, " (", sharedByEmail, ")");
} else {
if (sharedByName != "") {
log.vlog("WARNING: Conflict Shared By: ", sharedByName);
}
}
}
}
}
} else {
// Log that an invalid JSON object was returned
log.error("ERROR: onedrive.getSharedWithMe call returned an invalid JSON Object");
}
}
}
// download all new changes from a specified folder on OneDrive
void applyDifferencesSingleDirectory(const(string) path)
{
// Ensure we check the 'right' location for this directory on OneDrive
// It could come from the following places:
// 1. My OneDrive Root
// 2. My OneDrive Root as an Office 365 Shared Library
// 3. A OneDrive Business Shared Folder
// If 1 & 2, the configured default items are what we need
// If 3, we need to query OneDrive
string driveId = defaultDriveId;
string rootId = defaultRootId;
string folderId;
JSONValue onedrivePathDetails;
// Check OneDrive Business Shared Folders, if configured to do so
if (syncBusinessFolders){
log.vlog("Attempting to sync OneDrive Business Shared Folders");
// query OneDrive Business Shared Folders shared with me
JSONValue graphQuery = onedrive.getSharedWithMe();
if (graphQuery.type() == JSONType.object) {
// valid response from OneDrive
foreach (searchResult; graphQuery["value"].array) {
string sharedFolderName = searchResult["name"].str;
// Compare this to values in business_shared_folders
if(selectiveSync.isSharedFolderMatched(sharedFolderName)){
// Folder matches a user configured sync entry
string[] allowedPath;
allowedPath ~= sharedFolderName;
// But is this shared folder what we are looking for?
if (selectiveSync.isPathIncluded(path,allowedPath)) {
// Path we want to sync is on a OneDrive Business Shared Folder
// Set the correct driveId
driveId = searchResult["remoteItem"]["parentReference"]["driveId"].str;
// Keep the driveIDsArray with unique entries only
if (!canFind(driveIDsArray, driveId)) {
// Add this drive id to the array to search with
driveIDsArray ~= driveId;
}
}
}
}
} else {
// Log that an invalid JSON object was returned
log.error("ERROR: onedrive.getSharedWithMe call returned an invalid JSON Object");
}
}
// Test if the path we are going to sync from actually exists on OneDrive
log.vlog("Getting path details from OneDrive ...");
try {
onedrivePathDetails = onedrive.getPathDetailsByDriveId(driveId, path);
} catch (OneDriveException e) {
log.vdebug("onedrivePathDetails = onedrive.getPathDetails(path) generated a OneDriveException");
if (e.httpStatusCode == 404) {
// The directory was not found
log.error("ERROR: The requested single directory to sync was not found on OneDrive");
return;
}
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling applyDifferencesSingleDirectory(path);");
applyDifferencesSingleDirectory(path);
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// OneDrive returned a 'HTTP 5xx Server Side Error' - gracefully handling error - error message already logged
return;
}
}
// OK - the path on OneDrive should exist, get the driveId and rootId for this folder
// Was the response a valid JSON Object?
if (onedrivePathDetails.type() == JSONType.object) {
// OneDrive Personal Shared Folder handling
// Is this item a remote item?
if(isItemRemote(onedrivePathDetails)){
// 2 step approach:
// 1. Ensure changes for the root remote path are captured
// 2. Download changes specific to the remote path
// root remote
applyDifferences(defaultDriveId, onedrivePathDetails["id"].str, false);
// remote changes
driveId = onedrivePathDetails["remoteItem"]["parentReference"]["driveId"].str; // Should give something like 66d53be8a5056eca
folderId = onedrivePathDetails["remoteItem"]["id"].str; // Should give something like BC7D88EC1F539DCF!107
// Apply any differences found on OneDrive for this path (download data)
applyDifferences(driveId, folderId, false);
} else {
// use the item id as folderId
folderId = onedrivePathDetails["id"].str; // Should give something like 12345ABCDE1234A1!101
// Apply any differences found on OneDrive for this path (download data)
applyDifferences(defaultDriveId, folderId, false);
}
} else {
// Log that an invalid JSON object was returned
log.vdebug("onedrive.getPathDetails call returned an invalid JSON Object");
}
}
// make sure the OneDrive root is in our database
auto checkDatabaseForOneDriveRoot()
{
log.vlog("Fetching details for OneDrive Root");
JSONValue rootPathDetails = onedrive.getDefaultRoot(); // Returns a JSON Value
// validate object is a JSON value
if (rootPathDetails.type() == JSONType.object) {
// valid JSON object
Item rootPathItem = makeItem(rootPathDetails);
// configure driveId and rootId for the OneDrive Root
// Set defaults for the root folder
string driveId = rootPathDetails["parentReference"]["driveId"].str; // Should give something like 12345abcde1234a1
string rootId = rootPathDetails["id"].str; // Should give something like 12345ABCDE1234A1!101
// Query the database
if (!itemdb.selectById(driveId, rootId, rootPathItem)) {
log.vlog("OneDrive Root does not exist in the database. We need to add it.");
applyDifference(rootPathDetails, driveId, true);
log.vlog("Added OneDrive Root to the local database");
} else {
log.vlog("OneDrive Root exists in the database");
}
} else {
// Log that an invalid JSON object was returned
log.error("ERROR: Unable to query OneDrive for account details");
log.vdebug("onedrive.getDefaultRoot call returned an invalid JSON Object");
// Must exit here as we cant configure our required variables
exit(-1);
}
}
// create a directory on OneDrive without syncing
auto createDirectoryNoSync(const(string) path)
{
// Attempt to create the requested path within OneDrive without performing a sync
log.vlog("Attempting to create the requested path within OneDrive");
// Handle the remote folder creation and updating of the local database without performing a sync
uploadCreateDir(path);
}
// delete a directory on OneDrive without syncing
auto deleteDirectoryNoSync(const(string) path)
{
// Use the global's as initialised via init() rather than performing unnecessary additional HTTPS calls
const(char)[] rootId = defaultRootId;
// Attempt to delete the requested path within OneDrive without performing a sync
log.vlog("Attempting to delete the requested path within OneDrive");
// test if the path we are going to exists on OneDrive
try {
onedrive.getPathDetails(path);
} catch (OneDriveException e) {
log.vdebug("onedrive.getPathDetails(path) generated a OneDriveException");
if (e.httpStatusCode == 404) {
// The directory was not found on OneDrive - no need to delete it
log.vlog("The requested directory to delete was not found on OneDrive - skipping removing the remote directory as it doesn't exist");
return;
}
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling deleteDirectoryNoSync(path);");
deleteDirectoryNoSync(path);
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// OneDrive returned a 'HTTP 5xx Server Side Error' - gracefully handling error - error message already logged
return;
}
}
Item item;
if (!itemdb.selectByPath(path, defaultDriveId, item)) {
// this is odd .. this directory is not in the local database - just go delete it
log.vlog("The requested directory to delete was not found in the local database - pushing delete request direct to OneDrive");
uploadDeleteItem(item, path);
} else {
// the folder was in the local database
// Handle the deletion and saving any update to the local database
log.vlog("The requested directory to delete was found in the local database. Processing the deletion normally");
deleteByPath(path);
}
}
// rename a directory on OneDrive without syncing
auto renameDirectoryNoSync(string source, string destination)
{
try {
// test if the local path exists on OneDrive
onedrive.getPathDetails(source);
} catch (OneDriveException e) {
log.vdebug("onedrive.getPathDetails(source); generated a OneDriveException");
if (e.httpStatusCode == 404) {
// The directory was not found
log.vlog("The requested directory to rename was not found on OneDrive");
return;
}
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling renameDirectoryNoSync(source, destination);");
renameDirectoryNoSync(source, destination);
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// OneDrive returned a 'HTTP 5xx Server Side Error' - gracefully handling error - error message already logged
return;
}
}
// The OneDrive API returned a 200 OK status, so the folder exists
// Rename the requested directory on OneDrive without performing a sync
moveByPath(source, destination);
}
// download the new changes of a specific item
// id is the root of the drive or a shared folder
private void applyDifferences(string driveId, const(char)[] id, bool performFullItemScan)
{
log.vlog("Applying changes of Path ID: " ~ id);
// function variables
const(char)[] idToQuery;
JSONValue changes;
JSONValue changesAvailable;
JSONValue idDetails;
JSONValue currentDriveQuota;
string syncFolderName;
string syncFolderPath;
string syncFolderChildPath;
string deltaLink;
string deltaLinkAvailable;
bool nationalCloudChildrenScan = false;
// Update the quota details for this driveId, as this could have changed since we started the application - the user could have added / deleted data online, or purchased additional storage
// Quota details are ONLY available for the main default driveId, as the OneDrive API does not provide quota details for shared folders
try {
currentDriveQuota = onedrive.getDriveQuota(driveId);
} catch (OneDriveException e) {
log.vdebug("currentDriveQuota = onedrive.getDriveQuota(driveId) generated a OneDriveException");
if (e.httpStatusCode == 429) {
// HTTP request returned status code 429 (Too Many Requests). We need to leverage the response Retry-After HTTP header to ensure minimum delay until the throttle is removed.
handleOneDriveThrottleRequest();
// Retry original request by calling function again to avoid replicating any further error handling
log.vdebug("Retrying original request that generated the OneDrive HTTP 429 Response Code (Too Many Requests) - calling applyDifferences(driveId, id, performFullItemScan);");
applyDifferences(driveId, id, performFullItemScan);
// return back to original call
return;
}
if (e.httpStatusCode >= 500) {
// OneDrive returned a 'HTTP 5xx Server Side Error' - gracefully handling error - error message already logged
return;
}
}
// validate that currentDriveQuota is a JSON value
if (currentDriveQuota.type() == JSONType.object) {
// Response from API contains valid data
// If 'personal' accounts, if driveId == defaultDriveId, then we will have data
// If 'personal' accounts, if driveId != defaultDriveId, then we will not have quota data
// If 'business' accounts, if driveId == defaultDriveId, then we will have data
// If 'business' accounts, if driveId != defaultDriveId, then we will have data, but it will be 0 values
if ("quota" in currentDriveQuota){
if (driveId == defaultDriveId) {
// We potentially have updated quota remaining details available
// However in some cases OneDrive Business configurations 'restrict' quota details thus is empty / blank / negative value / zero
if ("remaining" in currentDriveQuota["quota"]){
// We have valid quota details returned for the drive id