-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrive
More file actions
1625 lines (1517 loc) · 79.3 KB
/
grive
File metadata and controls
1625 lines (1517 loc) · 79.3 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
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/python3
# Author: https://github.com/john4smith
#
# Grive
#
### BEGIN LICENSE
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import logging, gi, os, mimetypes, io, sys, threading, subprocess, shutil, time, datetime, pyinotify, fcntl, json, re, hashlib, traceback, webbrowser
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, Gio, GLib, AppIndicator3, GdkPixbuf
# Google API/OAuth2
from apiclient.discovery import build
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
from oauth2client.client import OAuth2WebServerFlow as flow_setup
from oauth2client.client import OAuth2Credentials as flow_load
from oauth2client.client import HttpAccessTokenRefreshError as flow_token_error
from oauth2client.file import Storage as flow_storage
from oauth2client.tools import run_flow as flow_auth
from httplib2 import ServerNotFoundError as flow_server_offline
# https://developers.google.com/drive/api/v3/about-sdk
# https://developers.google.com/drive/api/v3/reference
# https://developers.google.com/drive/api/v3/mime-types
# https://developers.google.com/drive/api/v3/manage-downloads
# https://developers.google.com/drive/api/v3/manage-uploads
GOOGLE_MIME_TYPES = {
'application/vnd.google-apps.document': ['application/vnd.oasis.opendocument.text', '.odt'],
'application/vnd.google-apps.spreadsheet': ['application/x-vnd.oasis.opendocument.spreadsheet', '.ods'],
'application/vnd.google-apps.presentation': ['application/vnd.oasis.opendocument.presentation', '.odp'],
'application/vnd.google-apps.drawing': ['image/svg+xml', '.svg']
}
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
if AutoSyncState == True:
fullname = os.path.join(event.path, event.name)
if valid_fullpath(fullname) and not check_running_thread('sync'):
logging.debug('Create: %s' % fullname)
eventLoop()
def process_IN_DELETE(self, event):
if AutoSyncState == True:
fullname = os.path.join(event.path, event.name)
if valid_fullpath(fullname) and not check_running_thread('sync'):
logging.debug('Remove: %s' % fullname)
eventLoop()
def process_IN_MODIFY(self, event):
if AutoSyncState == True:
fullname = os.path.join(event.path, event.name)
if valid_fullpath(fullname) and not check_running_thread('sync'):
logging.debug('Modify: %s' % fullname)
eventLoop()
def process_IN_MOVED_FROM(self, event):
if AutoSyncState == True:
fullname = os.path.join(event.path, event.name)
if valid_fullpath(fullname) and not check_running_thread('sync'):
logging.debug('Move From: %s' % fullname)
eventLoop()
def process_IN_MOVED_TO(self, event):
if AutoSyncState == True:
fullname = os.path.join(event.path, event.name)
if valid_fullpath(fullname) and not check_running_thread('sync'):
logging.debug('Move To: %s' % fullname)
eventLoop()
class GoogleCredentials(object):
def __init__(self, config_file, client_file):
self.config_file = config_file
self.client_file = client_file
self.config = {}
self.client = {}
def _load_client_file(self):
try:
self.client = json.loads(open(self.client_file).read())
except:
logging.warning('Failed to load: ' + self.client_file)
def _load_credentials(self):
try:
self.config = json.loads(open(self.config_file).read())
except:
logging.warning('Failed to load: ' + self.config_file)
def _save_credentials(self):
fd = open(self.config_file, 'w')
fd.write(json.dumps(self.config))
def _get_credentials(self):
self._load_client_file()
# grive client id and secret
CLIENT_ID = self.client.get('client_id')
if CLIENT_ID == None:
raise Exception('ERROR: Can not load "client_id"')
CLIENT_SECRET = self.client.get('client_secret')
if CLIENT_SECRET == None:
raise Exception('ERROR: Can not load "client_secret"')
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
flow = flow_setup(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE)
store = flow_storage(self.config_file)
credentials = flow_auth(flow=flow, storage=store)
return credentials
def get_service(self):
self._load_credentials()
credentials_json = self.config.get('credentials')
if credentials_json == None:
logging.warning('Credentials not found, begin the Oauth process...')
credentials = self._get_credentials()
self.config = {}
self.config['credentials'] = credentials.to_json()
self._save_credentials()
os.chmod(self.config_file, 0o600)
else:
credentials = flow_load.from_json(credentials_json)
service = build('drive', 'v3', credentials=credentials, cache_discovery=False)
return service
def setup_google_service_thread():
global cloudService
global cloudServiceSetup
global timerServiceSetup
try:
cloudService = GoogleCredentials(cloudConfigFile, cloudClientFileUser).get_service()
update_cloud_info()
cloudServiceSetup = True
# Stop timerService
timerServiceSetup = 0
except flow_token_error:
menu_cloud_info.set_label('Info: Get Cloud Service...')
logging.warning('HttpAccessTokenRefreshError, reauth...')
sendmessage(cloudName + ' (OAuth2)', 'Failed, set up Service again...')
delete_local_erase(cloudConfigFile)
cloudServiceSetup = False
except flow_server_offline:
menu_cloud_info.set_label('Info: Are you offline?...')
logging.debug('Setup Service failed, are you offline?...')
cloudServiceSetup = False
except Exception:
logging.debug(traceback.format_exc())
cloudServiceSetup = False
def setup_google_service_helper():
# icon set up with thread, not working!
if timerServiceSetup == 0:
# Try to keep Sync Icon, if you sync now
if ind.get_icon() != icon_path_sync:
ind.set_icon_full(icon_path, 'finished')
# Stop timerService
return False
# check last thread
if check_running_thread('init'):
# Try it next time...
return True
# start a new Thread
ind.set_icon_full(icon_path_failed, 'failed')
t = threading.Thread(name='init', target=setup_google_service_thread)
t.start()
return True
def setup_google_service():
global cloudServiceSetup
global timerServiceSetup
if timerServiceSetup == 0:
logging.debug('Start to setup Service...')
cloudServiceSetup = False
timerServiceSetup = GLib.timeout_add_seconds(5, setup_google_service_helper)
# trigger it now
setup_google_service_helper()
def humanbytes(B):
# Return the given bytes as a human friendly KB, MB, GB, or TB string
B = float(B)
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) # 1,073,741,824
TB = float(KB ** 4) # 1,099,511,627,776
if B < KB:
return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')
elif KB <= B < MB:
return '{0:.2f} KB'.format(B/KB)
elif MB <= B < GB:
return '{0:.2f} MB'.format(B/MB)
elif GB <= B < TB:
return '{0:.2f} GB'.format(B/GB)
elif TB <= B:
return '{0:.2f} TB'.format(B/TB)
def valid_filename(filename):
filename = os.path.basename(filename)
return not any((filename.startswith('.'), # hidden file
filename.startswith('@'), # temporary file
filename.endswith('~'), # temporary file
filename.endswith('.pyc'), # generated Python file
filename.endswith('.pyo'), # generated Python file
filename.endswith('.bkup'))) # Cryptomator Backup file
def valid_fullpath(fullname):
for name in fullname.split('/'):
if not valid_filename(name):
return False
return True
def walk_tree_list_remote(items, parent_id, name):
global tree_list
for item in items:
if 'parents' in item:
if item['parents'][0] == parent_id:
if valid_filename(item['name']):
item_tmp = {}
item_tmp['id'] = item['id']
item_tmp['mimeType'] = item['mimeType']
item_tmp['parent'] = parent_id
# fix name for exporting media
if item['mimeType'] in GOOGLE_MIME_TYPES.keys():
item_tmp['name'] = name + item['name'] + GOOGLE_MIME_TYPES[item['mimeType']][1]
else:
item_tmp['name'] = name + item['name']
# check for dubbel names
if dict_search_name(tree_list, item_tmp['name']) == None:
if item['mimeType'] == 'application/vnd.google-apps.folder': # if folder
tree_list.append(item_tmp)
walk_tree_list_remote(items, item['id'], item_tmp['name'] + '/')
elif not item['mimeType'].startswith('application/vnd.google-apps.'):
item_tmp['md5Checksum'] = item['md5Checksum']
item_tmp['modifiedEpoch'] = time.mktime(time.strptime(item['modifiedTime'], '%Y-%m-%dT%H:%M:%S.%fZ'))
tree_list.append(item_tmp)
elif item['mimeType'] in GOOGLE_MIME_TYPES.keys():
item_tmp['modifiedEpoch'] = time.mktime(time.strptime(item['modifiedTime'], '%Y-%m-%dT%H:%M:%S.%fZ'))
tree_list.append(item_tmp)
else:
logging.debug('Skip unsupported Google File...')
else:
logging.debug('Skipp dubbel adding item "' + item_tmp['name'] + '" to remote List...')
sendmessage(cloudName + ' (WARNING, DUBBELD ITEM!)', 'Skipping: ' + item_tmp['name'])
def get_tree_list_remote():
global tree_list
root_id = None
items = []
tree_list = []
try:
results = cloudService.files().list(q='"root" in parents and trashed = false', spaces='drive', pageSize=1, pageToken=None, fields="files(parents), incompleteSearch").execute()
if results.get('incompleteSearch') == True:
raise Exception('Error: Listing remote Files (Incomplete Search)...')
for item in results.get('files'):
root_id = item['parents'][0]
if root_id == None:
logging.debug('No remote Files...')
return tree_list
except:
raise Exception('Error: Listing remote Files...')
page_token = ''
while page_token is not None:
try:
param = {}
results = cloudService.files().list(q='trashed = false', spaces='drive', pageSize=1000, pageToken=page_token, fields="nextPageToken, files(id, name, modifiedTime, mimeType, md5Checksum, parents), incompleteSearch").execute()
if results.get('incompleteSearch') == True:
raise Exception('Error: Listing remote Files (Incomplete Search)...')
items.extend(results.get('files'))
page_token = results.get('nextPageToken')
except:
raise Exception('Error: Listing remote Files...')
walk_tree_list_remote(items, root_id, '/')
return tree_list
def get_tree_list_local():
tree_list_local = []
if os.path.exists(os.path.join(cloudFolder)):
foldername = os.path.join(cloudFolder)
if foldername.endswith('/'):
foldername = foldername[:-1]
for root, dirs, files in os.walk(foldername, topdown = True):
if valid_fullpath(root):
for name in files:
if valid_filename(name):
item = {}
item['name'] = re.sub(r'^' + foldername, '', root + '/' + name)
item['modifiedEpoch'] = time.mktime(time.localtime(os.path.getmtime(root + '/' + name)))
item['md5Checksum'] = hashlib.md5(open(os.path.join(root + '/' + name), 'rb').read()).hexdigest()
tree_list_local.append(item)
for name in dirs:
if valid_filename(name):
item = {}
item['name'] = re.sub(r'^' + foldername, '', root + '/' + name)
item['mimeType'] = 'application/vnd.google-apps.folder'
tree_list_local.append(item)
return tree_list_local
else:
raise Exception('Error: Listing local Files...')
def get_tree_list_trash():
tree_list_trash = []
if os.path.exists(os.path.join(cloudTrashFolder)):
foldername = os.path.join(cloudTrashFolder)
if foldername.endswith('/'):
foldername = foldername[:-1]
for root, dirs, files in os.walk(foldername, topdown = True):
for name in files:
item = {}
item['name'] = re.sub(r'^' + foldername, '', root + '/' + name)
item['md5Checksum'] = hashlib.md5(open(os.path.join(root + '/' + name), 'rb').read()).hexdigest()
tree_list_trash.append(item)
return tree_list_trash
def write_items_json_file(items, file):
f = open(os.path.join(file), 'w')
f.write(json.dumps(items))
f.close()
def read_items_json_file(file):
with open(os.path.join(file)) as f:
items = json.loads(f.read())
f.close()
return items
def create_local_folder(foldername):
if not os.path.exists(os.path.join(foldername)):
os.makedirs(os.path.join(foldername))
def create_remote_folder(foldername, parent_id):
body = {'name': foldername, 'parents': [ parent_id ], 'mimeType': 'application/vnd.google-apps.folder'}
request = cloudService.files().create(body=body, fields="name, id, mimeType, modifiedTime").execute()
return request
def delete_local_trash(time, filename):
folderTrashTime = os.path.join(cloudTrashFolder, time)
filenameLocal = os.path.join(cloudFolder + filename)
filenameTrash = os.path.join(folderTrashTime + filename)
create_local_folder(os.path.dirname(filenameTrash))
number = 0
while True:
if os.path.exists(filenameTrash):
number += 1
filenameTrash = os.path.join(folderTrashTime + filename + '_' + number)
else:
logging.debug('Trash: Move "' + filenameLocal + '" to "' + filenameTrash + '"')
os.rename(filenameLocal, filenameTrash)
return
def delete_local_erase(filename):
if os.path.isfile(os.path.join(filename)):
os.remove(os.path.join(filename))
elif os.path.isdir(os.path.join(filename)):
shutil.rmtree(os.path.join(filename), ignore_errors=True)
def delete_remote_trash(file_id):
body = {'trashed': 'true'}
request = cloudService.files().update(fileId=file_id, body=body).execute()
return request
def delete_remote_erase(file_id):
try:
cloudService.files().delete(fileId=file_id).execute()
except:
logging.warning('Delete remote File failed!')
def empty_remote_trash():
try:
logging.debug('Empty remote Trash...')
cloudService.files().emptyTrash().execute()
ind.set_icon_full(icon_path, 'finished')
except:
logging.warning('Empty remote Trash, failed!')
ind.set_icon_full(icon_path_failed, 'failed')
def upload_file(filename, parent_id):
modifiedTime = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(filename))).isoformat() + 'Z'
body = {'name': os.path.basename(filename), 'modifiedTime': modifiedTime, 'parents': [ parent_id ]}
# check if the file is bigger then 5MB (1024*1024*5)
if os.path.getsize(os.path.join(filename)) >= 5242880:
media_body = MediaFileUpload(filename=os.path.join(filename), resumable=True)
# Fix for small files with no MimeType, must be uploaded with "resumable=True"
elif os.path.getsize(os.path.join(filename)) > 0 and mimetypes.MimeTypes().guess_type(os.path.join(filename))[0] == None:
media_body = MediaFileUpload(filename=os.path.join(filename), resumable=True)
else:
media_body = MediaFileUpload(filename=os.path.join(filename))
request = cloudService.files().create(body=body, media_body=media_body, fields="name, id, modifiedTime, mimeType, md5Checksum").execute()
if request['md5Checksum'] != hashlib.md5(open(os.path.join(filename), 'rb').read()).hexdigest():
logging.warning('Upload File (MD5SUM) failed!')
delete_remote_erase(request['id'])
return None
return request
def upload_file_replace(filename, item_id):
modifiedTime = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(filename))).isoformat() + 'Z'
body = {'name': os.path.basename(filename), 'modifiedTime': modifiedTime}
# check if the file is bigger then 5MB (1024*1024*5)
if os.path.getsize(os.path.join(filename)) >= 5242880:
media_body = MediaFileUpload(filename=os.path.join(filename), resumable=True)
# Fix for small files with no MimeType, must be uploaded with "resumable=True"
elif os.path.getsize(os.path.join(filename)) > 0 and mimetypes.MimeTypes().guess_type(os.path.join(filename))[0] == None:
media_body = MediaFileUpload(filename=os.path.join(filename), resumable=True)
else:
media_body = MediaFileUpload(filename=os.path.join(filename))
request = cloudService.files().update(fileId=item_id, body=body, media_body=media_body, fields="name, id, modifiedTime, mimeType, md5Checksum").execute()
if request['md5Checksum'] != hashlib.md5(open(os.path.join(filename), 'rb').read()).hexdigest():
logging.warning('Upload File (MD5SUM) failed!')
request_trash = delete_remote_trash(request['id'])
if request_trash == None:
delete_remote_erase(request['id'])
return None
return request
def download_file_export(filename, file_id):
# Export only supports Google Docs.
request = cloudService.files().get(fileId=file_id, fields="name, id, modifiedTime, mimeType").execute()
if request['mimeType'] in GOOGLE_MIME_TYPES.keys():
mimeTypeExport = GOOGLE_MIME_TYPES[request['mimeType']][0]
# Try to export it (can not export empty files and max 10MB [1024*1024*10]!)
try:
request_media = cloudService.files().export_media(fileId=file_id, mimeType=mimeTypeExport)
downloader = MediaIoBaseDownload(io.FileIO(os.path.join(filename), 'wb'), request_media)
done = False
while done is False:
status, done = downloader.next_chunk()
logging.debug('Download %d%%' % int(status.progress() * 100))
except:
# only touch the file (export failed!)
logging.log(40, 'Fail: Export Google File "' + filename + '" (make a dummy file)...')
open(os.path.join(filename), 'a').close()
# Update Modified Time for the local File
file_epoche = time.mktime(time.strptime(request['modifiedTime'], '%Y-%m-%dT%H:%M:%S.%fZ'))
os.utime(filename, (file_epoche, file_epoche))
return request
else:
logging.warning('Error: Failed to export Google File!')
return None
def download_file(filename, file_id):
request = cloudService.files().get(fileId=file_id, fields="name, id, modifiedTime, mimeType, md5Checksum, size").execute()
# check if it is downloadable (can not download empty files!)
if int(request['size']) > 0:
request_media = cloudService.files().get_media(fileId=file_id)
downloader = MediaIoBaseDownload(io.FileIO(os.path.join(filename), 'wb'), request_media)
done = False
while done is False:
status, done = downloader.next_chunk()
logging.debug('Download %d%%' % int(status.progress() * 100))
else:
# only touch the file
open(os.path.join(filename), 'a').close()
if request['md5Checksum'] != hashlib.md5(open(os.path.join(filename), 'rb').read()).hexdigest():
logging.warning('Error: Download File (MD5SUM) failed!')
return None
# Update Modified Time for the local File
file_epoche = time.mktime(time.strptime(request['modifiedTime'], '%Y-%m-%dT%H:%M:%S.%fZ'))
os.utime(filename, (file_epoche, file_epoche))
return request
def remote_copy_file(file_id, filename, parent):
body = {'name': os.path.basename(filename), 'parents': [parent]}
request = cloudService.files().copy(fileId=file_id, body=body, fields="name, id, modifiedTime, mimeType, md5Checksum").execute()
return request
def remote_move_file(file_id, filename, modifiedEpoch, parent_add, parend_remove):
modifiedTime = datetime.datetime.fromtimestamp(modifiedEpoch).isoformat() + 'Z'
body = {'name': os.path.basename(filename), 'modifiedTime': modifiedTime}
if parent_add == parend_remove:
request = cloudService.files().update(fileId=file_id, body=body, fields="name, id, modifiedTime, mimeType, md5Checksum").execute()
else:
request = cloudService.files().update(fileId=file_id, body=body, addParents=parent_add, removeParents=parend_remove, fields="name, id, modifiedTime, mimeType, md5Checksum").execute()
return request
def get_remote_info_by_id(id):
return cloudService.files().get(fileId=id, fields="name, modifiedTime, mimeType, md5Checksum, parents").execute()
def check_remote_trashed_by_id(file_id):
# Search for a File in Google Drive by ID
request = cloudService.files().get(fileId=file_id, fields="trashed").execute()
return request.get('trashed')
def update_cloud_info():
cloudInfo = get_drive_info()
cloudLabel = cloudInfo['user']['displayName'] + ': ' + humanbytes(cloudInfo['storageQuota']['usage']) + ' / ' + humanbytes(cloudInfo['storageQuota']['limit'])
menu_cloud_info.set_label(cloudLabel)
logging.debug('CloudInfo: [ ' + cloudLabel + ' ]')
def check_running_thread(name):
# check if a thread is running
for t in threading.enumerate():
if t.getName() == name and hasattr(t, 'isAlive'):
try:
if t.isAlive():
return True
except:
logging.warning('Failed to check thread: ' + name)
return False
return False
def join_running_thread(name):
# join a thread is running
for t in threading.enumerate():
if t.getName() == name and hasattr(t, 'join'):
try:
t.join()
except:
logging.warning('Failed to join thread: ' + name)
def get_drive_info():
request = cloudService.about().get(fields="kind,maxUploadSize,user(displayName,emailAddress), storageQuota(usage,limit)").execute()
return request
def compare_lists(list_static, list_remote, list_local):
# build items_all and items_return
items_all = []
items_return = []
# append all items from list_remote to items_all
for item in list_remote:
item_tmp = {}
item_tmp = item
item_tmp['found_in_remote'] = True
items_all.append(item_tmp)
# append all items from list_static to items_all
for item in list_static:
item_tmp = {}
item_search = dict_search_name(items_all, item['name'])
if item_search != None:
item_tmp = item_search
item_tmp['found_in_static'] = True
items_all.remove(item_search)
items_all.append(item_tmp)
else:
item_tmp = item
item_tmp['found_in_static'] = True
items_all.append(item_tmp)
# append all items from list_local to items_all
for item in list_local:
item_tmp = {}
item_search = dict_search_name(items_all, item['name'])
if item_search != None:
item_tmp = item_search
item_tmp['found_in_local'] = True
items_all.remove(item_search)
items_all.append(item_tmp)
else:
item_tmp = item
item_tmp['found_in_local'] = True
items_all.append(item_tmp)
# build items_return with todo for all items in items_all
for item in items_all:
if item.get('found_in_static') != True and item.get('found_in_remote') == True and item.get('found_in_local') != True:
item['todo'] = 'DOWNLOAD'
if item.get('found_in_static') != True and item.get('found_in_remote') != True and item.get('found_in_local') == True:
item['todo'] = 'UPLOAD'
if item.get('found_in_static') == True and item.get('found_in_remote') == True and item.get('found_in_local') != True:
item['todo'] = 'REMOVE_REMOTE'
if item.get('found_in_static') == True and item.get('found_in_remote') != True and item.get('found_in_local') == True:
item['todo'] = 'REMOVE_LOCAL'
if item.get('found_in_static') != True and item.get('found_in_remote') == True and item.get('found_in_local') == True:
item['todo'] = 'CHECK_DB_ERROR'
if item.get('found_in_static') == True and item.get('found_in_remote') == True and item.get('found_in_local') == True:
item['todo'] = 'CHECK_FILE'
if item.get('todo') != None:
items_return.append(item)
# return a todo list
return items_return
def dict_search_name(list, name):
for item in list:
if item['name'] == name:
return item
return None
def dict_search_name_by_todo(list, name, todo):
for item in list:
if item['name'] == name and item['todo'] == todo:
return item
return None
def dict_search_checksum(list, md5Checksum):
for item in list:
if item.get('md5Checksum') == md5Checksum:
return item
return None
def check_save_item(item):
item_new = {}
item_new['id'] = item['id']
item_new['name'] = item['name']
item_new['mimeType'] = item['mimeType']
# check if it is a Folder
if item_new['mimeType'] == 'application/vnd.google-apps.folder':
return item_new
# check if it is a Google Export File
elif item_new['mimeType'] in GOOGLE_MIME_TYPES.keys():
item_new['modifiedEpoch'] = item['modifiedEpoch']
return item_new
else:
item_new['modifiedEpoch'] = item['modifiedEpoch']
item_new['md5Checksum'] = item['md5Checksum']
return item_new
def check_load_item(item):
# check ID and Name
if item.get('id') != None and item.get('name') != None:
# check if it is a Folder
if item.get('mimeType') == 'application/vnd.google-apps.folder':
return True
# check if it is a Google Export File
if item.get('mimeType') in GOOGLE_MIME_TYPES.keys():
if item.get('modifiedEpoch') != None:
return True
# check not Google Export Files
if item.get('modifiedEpoch') != None and item.get('md5Checksum') != None:
return True
# Bad File!
return False
def syncThread():
global cloudServiceSetup
global threadExitCodeSync
run_loop = True
threadExitCodeSync = False
sync_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
try:
list_static = read_items_json_file(cloudStatusFile)
# check every item in list_static
for item in list_static:
if check_load_item(item) != True:
logging.warning('Failed to load Status File (database is broken)...')
sendmessage(cloudName + ' (synchronizing)', 'Failed to load Status File (database is broken)...')
return
except:
logging.warning('Failed to load Status File...')
sendmessage(cloudName + ' (synchronizing)', 'Failed to load Status File...')
return
while run_loop:
try:
logging.debug('Start Sync...')
list_remote = get_tree_list_remote()
list_local = get_tree_list_local()
list_trash = get_tree_list_trash()
list_todo = compare_lists(list_static, list_remote, list_local)
if list_todo:
# create a list for remove later items from list_todo, befor run all todo_remove
remove_todo_files = []
# first, run all todo's for Folders (but remove at the end!)
for item in list_todo:
if item.get('mimeType') == 'application/vnd.google-apps.folder':
if item['todo'] == 'CHECK_DB_ERROR':
try:
# Try to remove item from list_static
item_old = dict_search_name(list_static, item['name'])
if item_old:
list_static.remove(item_old)
if not os.path.exists(os.path.join(cloudFolder + item['name'])):
logging.log(40, 'Fix DB: Create local Folder: ' + item['name'])
sendmessage(cloudName + ' (Handle DB Error, create local Folder!)', item['name'])
create_local_folder(cloudFolder + item['name'])
else:
# do not run sendmessage, can crash the pc!
logging.log(40, 'Fix DB: Add Dir to DB: ' + item['name'])
item_remote = dict_search_name(list_remote, item['name'])
list_static.append(check_save_item(item_remote))
except Exception:
logging.debug(traceback.format_exc())
delete_local_trash(sync_time, item['name'])
logging.warning('Create local Dir (replace) failed!')
return
if item['todo'] == 'DOWNLOAD':
try:
logging.log(40, 'Create (local/folder): ' + item['name'])
sendmessage(cloudName + ' (create local Folder)', item['name'])
create_local_folder(cloudFolder + item['name'])
item_remote = dict_search_name(list_remote, item['name'])
list_static.append(check_save_item(item_remote))
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Create local Folder failed!')
return
if item['todo'] == 'UPLOAD':
try:
logging.log(40, 'Create (remote/folder): ' + item['name'])
sendmessage(cloudName + ' (create remote Folder)', item['name'])
# search for parend dir id
parent_dir = os.path.dirname(item['name'])
if parent_dir == '/':
parent_id = 'root'
else:
parent_id = dict_search_name(list_static, parent_dir)['id']
request = create_remote_folder(os.path.basename(item['name']), parent_id)
if request != None:
item['id'] = request['id']
item['mimeType'] = request['mimeType']
list_static.append(check_save_item(item))
else:
delete_local_erase(cloudFolder + item['name'])
logging.warning('Create remote Folder failed!')
return
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Create remote Folder failed!')
return
# first, run all todo's for Files (but remove at the end!)
for item in list_todo:
if item.get('mimeType') != 'application/vnd.google-apps.folder':
item_remote = dict_search_name(list_remote, item['name'])
item_local = dict_search_name(list_local, item['name'])
if item.get('mimeType') in GOOGLE_MIME_TYPES.keys():
if item['todo'] == 'CHECK_FILE':
item_static = dict_search_name(list_static, item['name'])
if item_remote['id'] != item_static['id']:
item['todo'] = 'DOWNLOAD_REPLACE'
if item_remote['modifiedEpoch'] != item_local['modifiedEpoch']:
item['todo'] = 'DOWNLOAD_REPLACE'
if item['todo'] == 'CHECK_DB_ERROR':
if item_remote['modifiedEpoch'] != item_local['modifiedEpoch']:
item['todo'] = 'DOWNLOAD_REPLACE'
else:
# do not run sendmessage, can crash the pc!
logging.log(40, 'Fix DB: Add (exported) File to DB: ' + item['name'])
list_static.append(check_save_item(item_remote))
else:
if item['todo'] == 'CHECK_FILE':
item_static = dict_search_name(list_static, item['name'])
if item_remote['id'] != item_static['id']:
item['todo'] = 'DOWNLOAD_REPLACE'
else:
if item_remote['md5Checksum'] != item_local['md5Checksum']:
if item_remote['modifiedEpoch'] > item_local['modifiedEpoch']:
item['todo'] = 'DOWNLOAD_REPLACE'
elif item_remote['modifiedEpoch'] < item_local['modifiedEpoch']:
item['todo'] = 'UPLOAD_REPLACE'
elif item_remote['modifiedEpoch'] != item_local['modifiedEpoch']:
try:
logging.log(40, 'Update modified Time (local/file): ' + item['name'])
sendmessage(cloudName + ' (update modified Time for File)', item['name'])
os.utime(cloudFolder + item['name'], (item_remote['modifiedEpoch'], item_remote['modifiedEpoch']))
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Update modified Time for File failed!')
return
if item['todo'] == 'CHECK_DB_ERROR':
if item_remote['md5Checksum'] != item_local['md5Checksum'] or item_remote['modifiedEpoch'] != item_local['modifiedEpoch']:
item['todo'] = 'DOWNLOAD_REPLACE'
else:
# do not run sendmessage, can crash the pc!
logging.log(40, 'Fix DB: Add File to DB: ' + item['name'])
list_static.append(check_save_item(item_remote))
# Dummy DOWNLOAD, for detect allready downloaded Files
if item['todo'] == 'DOWNLOAD':
try:
if not item['mimeType'] in GOOGLE_MIME_TYPES.keys():
# Try to find a local File with the same MD5 (allready downloaded?)
item_search_local = dict_search_checksum(list_local, item_remote['md5Checksum'])
if item_search_local != None:
# try to find out if the file is moved?
item_search_remove = dict_search_name_by_todo(list_todo, item_search_local['name'], 'REMOVE_LOCAL')
if item_search_remove != None:
logging.log(40, 'Move (local/file): From "' + item_search_local['name'] + '" to "' + item['name'] + '"')
sendmessage(cloudName + ' (move/rename file)', item['name'])
shutil.move(cloudFolder + item_search_local['name'], cloudFolder + item['name'])
os.utime(cloudFolder + item['name'], (item_remote['modifiedEpoch'], item_remote['modifiedEpoch']))
copyfile_checksum = hashlib.md5(open(cloudFolder + item['name'], 'rb').read()).hexdigest()
if item_remote['md5Checksum'] == copyfile_checksum:
# remove later item_search_remove from list_todo
remove_todo_files.append(item_search_remove)
list_static.remove(dict_search_name(list_static, item_search_remove['name']))
list_static.append(check_save_item(item_remote))
# skip the real DOWNLOAD!
continue
else:
delete_local_trash(cloudFolder + item['name'])
logging.warning('Move File (try to download) failed!')
else:
logging.log(40, 'Copy (local/file): From "' + item_search_local['name'] + '" to "' + item['name'] + '"')
sendmessage(cloudName + ' (copy file)', item['name'])
shutil.copyfile(cloudFolder + item_search_local['name'], cloudFolder + item['name'])
os.utime(cloudFolder + item['name'], (item_remote['modifiedEpoch'], item_remote['modifiedEpoch']))
copyfile_checksum = hashlib.md5(open(cloudFolder + item['name'], 'rb').read()).hexdigest()
if item_remote['md5Checksum'] == copyfile_checksum:
list_static.append(check_save_item(item_remote))
# skip the real DOWNLOAD!
continue
else:
delete_local_erase(cloudFolder + item['name'])
logging.warning('Copy File (try to download) failed!')
# Try to find a local File in Trash with the same MD5 (allready downloaded?)
item_search_trash = dict_search_checksum(list_trash, item_remote['md5Checksum'])
if item_search_trash != None:
logging.log(40, 'Restore (local/file): From "' + item_search_trash['name'] + '" to "' + item['name'] + '"')
sendmessage(cloudName + ' (restore file)', item['name'])
shutil.move(cloudTrashFolder + item_search_trash['name'], cloudFolder + item['name'])
os.utime(cloudFolder + item['name'], (item_remote['modifiedEpoch'], item_remote['modifiedEpoch']))
copyfile_checksum = hashlib.md5(open(cloudFolder + item['name'], 'rb').read()).hexdigest()
if item_remote['md5Checksum'] == copyfile_checksum:
list_static.append(check_save_item(item_remote))
# skip the real DOWNLOAD!
continue
else:
delete_local_trash(cloudFolder + item['name'])
logging.warning('Restore File (try to download) failed!')
except Exception:
logging.debug(traceback.format_exc())
delete_local_erase(cloudFolder + item['name'])
logging.warning('Copy File failed!')
return
if item['todo'] == 'DOWNLOAD':
try:
if item['mimeType'] in GOOGLE_MIME_TYPES.keys():
logging.log(40, 'Download (remote/export): ' + item['name'])
sendmessage(cloudName + ' (downloading)', 'Export: ' + item['name'])
request = download_file_export(cloudFolder + item['name'], item_remote['id'])
else:
logging.log(40, 'Download (remote/file): ' + item['name'])
sendmessage(cloudName + ' (downloading)', item['name'])
request = download_file(cloudFolder + item['name'], item_remote['id'])
if request != None:
list_static.append(check_save_item(item_remote))
else:
delete_local_erase(cloudFolder + item['name'])
logging.warning('Downloading File failed!')
return
except Exception:
logging.debug(traceback.format_exc())
delete_local_erase(cloudFolder + item['name'])
logging.warning('Downloading File failed!')
return
if item['todo'] == 'DOWNLOAD_REPLACE':
try:
if item['mimeType'] in GOOGLE_MIME_TYPES.keys():
logging.log(40, 'Download changes (remote/export): ' + item['name'])
sendmessage(cloudName + ' (downloading changes)', 'Export: ' + item['name'])
delete_local_trash(sync_time, item['name'])
request = download_file_export(cloudFolder + item['name'], item_remote['id'])
else:
logging.log(40, 'Download changes (remote/file): ' + item['name'])
sendmessage(cloudName + ' (downloading changes)', item['name'])
delete_local_trash(sync_time, item['name'])
request = download_file(cloudFolder + item['name'], item_remote['id'])
# Try to remove item from list_static
item_old = dict_search_name(list_static, item['name'])
if item_old:
list_static.remove(item_old)
if request != None:
list_static.append(check_save_item(item_remote))
else:
delete_local_erase(cloudFolder + item['name'])
logging.warning('Downloading File (replace) failed!')
return
except Exception:
logging.debug(traceback.format_exc())
delete_local_erase(cloudFolder + item['name'])
logging.warning('Downloading File (replace) failed!')
return
# Dummy UPLOAD, for detect allready uploaded Files
if item['todo'] == 'UPLOAD':
try:
# Try to find a remote File with the same MD5 (allready uploaded?)
item_search_remote = dict_search_checksum(list_remote, item_local['md5Checksum'])
if item_search_remote != None:
# try to find out if the file is moved?
item_search_remove = dict_search_name_by_todo(list_todo, item_search_remote['name'], 'REMOVE_REMOTE')
if item_search_remove != None:
logging.log(40, 'Move (remote/file): From "' + item_search_remote['name'] + '" to "' + item['name'] + '"')
sendmessage(cloudName + ' (remote move/rename file)', item['name'])
# search for parend dir id
parent_dir_add = os.path.dirname(item['name'])
if parent_dir_add == '/':
parent_add = 'root'
else:
parent_add = dict_search_name(list_static, parent_dir_add)['id']
# search for parend dir id
parent_dir_remove = os.path.dirname(item_search_remote['name'])
if parent_dir_remove == '/':
parend_remove = 'root'
else:
parend_remove = dict_search_name(list_static, parent_dir_remove)['id']
request = remote_move_file(item_search_remote['id'], item['name'], item_local['modifiedEpoch'] , parent_add, parend_remove)
if request != None:
# check request['md5Checksum'] !!!
item['id'] = request['id']
item['mimeType'] = request['mimeType']
item['modifiedEpoch'] = item_local['modifiedEpoch']
item['md5Checksum'] = item_local['md5Checksum']
# remove later item_search_remove from list_todo
remove_todo_files.append(item_search_remove)
list_static.remove(dict_search_name(list_static, item_search_remove['name']))
list_static.append(check_save_item(item))
# skip the real UPLOAD!
continue
else:
logging.warning('Remote move File (try to upload) failed!')
else:
logging.log(40, 'Copy (remote/file): From "' + item_search_remote['name'] + '" to "' + item['name'] + '"')
sendmessage(cloudName + ' (remote copy file)', item['name'])
# search for parend dir id
parent_dir = os.path.dirname(item['name'])
if parent_dir == '/':
parent_id = 'root'
else:
parent_id = dict_search_name(list_static, parent_dir)['id']
request = remote_copy_file(item_search_remote['id'], item['name'], parent_id)
if request != None:
# check request['md5Checksum'] !!!
item['id'] = request['id']
item['mimeType'] = request['mimeType']
item['modifiedEpoch'] = item_local['modifiedEpoch']
item['md5Checksum'] = item_local['md5Checksum']
list_static.append(check_save_item(item))
# skip the real UPLOAD!
continue
else:
logging.warning('Remote copy File (try to upload) failed!')
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Remote copy File failed!')
return
if item['todo'] == 'UPLOAD':
try:
logging.log(40, 'Upload (local/file): ' + item['name'])
sendmessage(cloudName + ' (uploading)', item['name'])
# search for parend dir id
parent_dir = os.path.dirname(item['name'])
if parent_dir == '/':
parent_id = 'root'
else:
parent_id = dict_search_name(list_static, parent_dir)['id']
request = upload_file(cloudFolder + item['name'], parent_id)
if request != None:
item['id'] = request['id']
item['mimeType'] = request['mimeType']
item['modifiedEpoch'] = item_local['modifiedEpoch']
item['md5Checksum'] = item_local['md5Checksum']
list_static.append(check_save_item(item))
else:
logging.warning('Uploading File failed!')
return
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Uploading File failed!')
return
if item['todo'] == 'UPLOAD_REPLACE':
try:
logging.log(40, 'Upload changes (local/file): ' + item['name'])
sendmessage(cloudName + ' (uploading changes)', item['name'])
request = upload_file_replace(cloudFolder + item['name'], item['id'])
if request != None:
item['modifiedEpoch'] = item_local['modifiedEpoch']
item['md5Checksum'] = item_local['md5Checksum']
list_static.remove(dict_search_name(list_static, item['name']))
list_static.append(check_save_item(item))
else:
list_static.remove(dict_search_name(list_static, item['name']))
logging.warning('Uploading File (replace) failed!')
return
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Uploading File (replace) failed!')
return
# Search for unnessesary todo's (in to remove Folders)
items_remove = []
for item in list_todo:
if item.get('mimeType') == 'application/vnd.google-apps.folder':
if item['todo'] == 'REMOVE_REMOTE' or item['todo'] == 'REMOVE_LOCAL':
items_remove.extend([i for i in list_todo if i['name'].startswith(item['name'] + '/')])
list_todo_folder = [i for i in list_todo if i not in items_remove]
# at the end, run all todo's for Folders (only remove!)
for item in list_todo_folder:
if item.get('mimeType') == 'application/vnd.google-apps.folder':
if item['todo'] == 'REMOVE_REMOTE':
try:
logging.log(40, 'Trash (remote/folder): ' + item['name'])
sendmessage(cloudName + ' (trash remote Folder)', item['name'])
delete_remote_trash(item['id'])
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Remove remote Folder failed!')
return
if item['todo'] == 'REMOVE_LOCAL':
try:
logging.log(40, 'Trash (local/folder): ' + item['name'])
sendmessage(cloudName + ' (trash local Folder)', item['name'])
delete_local_trash(sync_time, item['name'])
except Exception:
logging.debug(traceback.format_exc())
logging.warning('Remove local Folder failed!')
return
if item['todo'] == 'REMOVE_LOCAL' or item['todo'] == 'REMOVE_REMOTE':
# remove recursive all files and folders in list_static and items_todo for the item name
list_static.remove(dict_search_name(list_static, item['name']))
remove_todo_files.extend([i for i in list_todo if i['name'].startswith(item['name'] + '/')])