-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOneDriveSync.py
1331 lines (1087 loc) · 32.6 KB
/
OneDriveSync.py
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/python
# -*- coding: utf_8 -*-
'''
OneDriveSync
Sync files in local directory to a One Drive directory.
'''
import json
import math
import fnmatch
import sys
import os
import shutil
import logging
import datetime
import traceback
import pytz, tzlocal
import unicodedata
import threading
import time
import types
import urllib
import webbrowser
import FileLock
try:
from ConfigParser import ConfigParser
except Exception:
from configparser import ConfigParser
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
LTZ = tzlocal.get_localzone()
SENC = sys.getdefaultencoding()
FENC = sys.getfilesystemencoding()
DT1970 = datetime.datetime.fromtimestamp(0)
SMALL = 2 * 1024 * 1024
LOG = None
if sys.version_info >= (3, 0):
def unicode(s):
return str(s)
def raw_input(s):
return input(s)
def quote(s):
return urllib.parse.quote(s)
else:
def quote(s):
return urllib.quote(s)
def normpath(s):
return unicodedata.normalize('NFC', s)
LOCK = threading.Lock()
def uprint(s):
with LOCK:
try:
print(s)
except Exception:
try:
print(s.encode(SENC))
except Exception:
print(s.encode('utf-8'))
def tprint(i, s):
n = datetime.datetime.now().strftime('%H:%M:%S ')
uprint(u'%s %s %s' % (i, n, s))
def udebug(s):
return
tprint('-', s)
if LOG:
LOG.debug(s)
def uinfo(s):
tprint('>', s)
if LOG:
LOG.info(s)
def uwarn(s):
tprint('+', s)
if LOG:
LOG.warn(s)
def uerror(s):
tprint('!', s)
if LOG:
LOG.error(s)
def uexception(ex):
traceback.print_exc()
if LOG:
LOG.exception(ex)
def szstr(n):
return "{:,}".format(n)
def tmstr(t):
return t.strftime('%Y-%m-%d %H:%M:%S')
def mtstr(t):
return t.replace(tzinfo=LTZ).astimezone(pytz.utc).strftime('%Y-%m-%dT%H:%M:%S.000Z')
def mtime(p):
return datetime.datetime.fromtimestamp(os.path.getmtime(p)).replace(microsecond=0)
def ftime(dt):
return tseconds(dt - DT1970)
def tseconds(td):
return (td.seconds + td.days * 24 * 3600)
def touch(p, d = None):
atime = ftime(datetime.datetime.now())
mtime = atime if d is None else ftime(d)
os.utime(p, ( atime, mtime ))
def mkpdirs(p):
d = os.path.dirname(p)
if not os.path.exists(d):
os.makedirs(d)
def trimdir(p):
if p == '':
return p
if p[-1] == os.path.sep:
p = p[:-1]
return unicode(p)
class Config:
"""Singleton style/static initialisation wrapper thing"""
def __init__(self):
self.dict = ConfigParser()
paths = (os.path.abspath('.onedrivesync.ini'), os.path.expanduser('~/.onedrivesync.ini'))
for filename in paths:
if os.path.exists(filename):
uprint('using onedrivesync.ini file "%s"' % os.path.abspath(filename))
self.dict.read(filename, 'utf-8')
break
# debug
self.debug_log = self.get('debug_log', '')
# error
self.error_log = self.get('error_log', '')
# Location
self.root_dir = trimdir(os.path.abspath(self.get('root_dir', '.')))
# self.get('trash_dir', self.root_dir + '/.trash')
self.trash_dir = self.get('trash_dir', '')
if self.trash_dir:
self.trash_dir = trimdir(os.path.abspath(self.trash_dir))
# user webbrowser
self.webbrowser = True if self.get('webbrowser', 'true') == 'true' else False
# max_file_size (100MB)
self.max_file_size = int(self.get('max_file_size', '104857600'))
# max retry
self.max_retry = int(self.get('max_retry', '3'))
# Threads
self.max_threads = int(self.get('num_threads', '4'))
# includes
self.includes = json.loads(self.get('includes', '[]'))
self.excludes = json.loads(self.get('excludes', '[]'))
# GDrive API
self.API_BASE_URL = "https://api.onedrive.com/v1.0/"
self.OAUTH_SCOPE = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
self.REDIRECT_URI = 'http://localhost:8080'
self.client_id = self.get('client_id', '19f839f9-69d9-4e6d-b841-bc39d0c241d8')
self.client_secret = self.get('client_secret', '2U0NhMmsKo1iw1RW7fJpjgq')
self.token_file = self.get('token_file', '.onedrivesync.token')
if os.path.exists(self.token_file):
self.last_sync = mtime(self.token_file)
else:
self.last_sync = DT1970
def get(self, configparam, default=None):
"""get the value from the ini file's default section."""
defaults = self.dict.defaults()
if configparam in defaults:
return defaults[configparam]
if not default is None:
return default
raise KeyError(configparam)
# global config
config = Config()
class OneDriveSession(onedrivesdk.session.SessionBase):
def __init__(self,
token_type,
expires_in,
scope_string,
access_token,
client_id,
auth_server_url,
redirect_uri,
refresh_token=None,
client_secret=None):
self.token_type = token_type
self.expires_at = time.time() + int(expires_in)
self.scope = scope_string.split(" ")
self.access_token = access_token
self.client_id = client_id
self.auth_server_url = auth_server_url
self.redirect_uri = redirect_uri
self.refresh_token = refresh_token
self.client_secret = client_secret
def is_expired(self):
"""Whether or not the session has expired
Returns:
bool: True if the session has expired, otherwise false
"""
# Add a 60 second buffer in case the token is just about to expire
return self.expires_at < time.time() - 60
def refresh_session(self, expires_in, scope_string, access_token, refresh_token):
self.expires_at = time.time() + int(expires_in)
self.scope = scope_string.split(" ")
self.access_token = access_token
self.refresh_token = refresh_token
def save_session(self, **save_session_kwargs):
path = save_session_kwargs["path"]
with open(path, "w") as f:
s = { "token_type": self.token_type,
"expires_at": self.expires_at,
"scope": ' '.join(self.scope),
"access_token": self.access_token,
"client_id": self.client_id,
"auth_server_url": self.auth_server_url,
"redirect_uri": self.redirect_uri,
"refresh_token": self.refresh_token,
"client_secret": self.client_secret }
f.write(json.dumps(s))
@staticmethod
def load_session(**load_session_kwargs):
path = load_session_kwargs["path"]
with open(path) as f:
c = json.loads(f.read())
s = OneDriveSession(c["token_type"],
0,
c["scope"],
c["access_token"],
c["client_id"],
c["auth_server_url"],
c["redirect_uri"],
c["refresh_token"],
c["client_secret"])
s.expires_at = c["expires_at"]
return s
class OneDriveCredentials(object):
def __init__(self):
self.path = os.path.abspath(config.token_file)
self.lock = None
def _load_credentials(self, client):
if os.path.exists(self.path):
client.auth_provider.load_session(path=self.path)
client.item(drive="me", id="root").get()
return
raise Exception('Token file %s not found' % self.path)
def _save_credentials(self, client):
client.auth_provider.save_session(path=self.path)
touch(self.path, config.last_sync)
def _lock_credentials(self):
FileLock.lock(open(self.path))
def _authenticate(self, client):
auth_url = client.auth_provider.get_auth_url(config.REDIRECT_URI)
# Ask for the code
uprint('Paste this URL into your browser, approve the app\'s access.')
uprint('Copy everything in the address bar after "code=", and paste it below.')
uprint(auth_url)
if config.webbrowser:
webbrowser.open(auth_url)
code = raw_input('Paste code here: ')
client.auth_provider.authenticate(code, config.REDIRECT_URI, config.client_secret)
def get_service(self):
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider=http_provider,
session_type=OneDriveSession,
client_id=config.client_id,
scopes=config.OAUTH_SCOPE)
client = onedrivesdk.OneDriveClient(config.API_BASE_URL, auth_provider, http_provider)
try:
self._load_credentials(client)
except Exception as e:
uinfo("Failed to load credentials, begin the OAuth process.")
self._authenticate(client)
self._save_credentials(client)
try:
self._lock_credentials()
except Exception as e:
uerror(str(e))
raise Exception('Failed to lock %s' % self.path)
return client
class OFile:
def __init__(self, r = None, root = False):
self.path = None
self.parent = None
self.action = None
self.reason = ''
if r:
self.id = r.id
self.mdate = self.to_date(r.file_system_info._prop_dict)
self.name = r.name
self.folder = r.folder
if self.folder:
self.size = 0
self.url = None
else:
self.folder = False
self.size = r.size
self.url = r.web_url
if r.parent_reference:
if not root:
self.parent = r.parent_reference.id
else:
self.parent = 'UNKNOWN'
def to_date(self, d):
if "lastModifiedDateTime" in d:
t = d["lastModifiedDateTime"].replace("Z", "")
s = t.find('.')
if s > 0:
t = t[0:s]
md = datetime.datetime.strptime(t, "%Y-%m-%dT%H:%M:%S")
return md.replace(tzinfo=pytz.utc).astimezone(LTZ).replace(tzinfo=None)
else:
return None
class Obj:
pass
class OneDriveSync:
def __init__(self, service):
'''
:param service: The service of get_service by OneDriveCredentials.
:param target: The target folder to sync.
'''
self.service = service
self.rfiles = {}
self.rpaths = {}
self.skips = []
def exea(self, api, msg):
auth = False
cnt = 0
while True:
try:
cnt += 1
if auth:
self.service.auth_provider.refresh_token()
auth = True
return api.execute()
except Exception as e:
if cnt <= config.max_retry:
err = str(e)
if "unauthenticated" in err:
auth = True
uwarn(err)
uwarn("Failed to %s, retry %d" % (msg, cnt))
time.sleep(3)
else:
uerror("Failed to %s" % msg)
uexception(e)
raise
def print_files(self, paths):
uprint("--------------------------------------------------------------------------------")
tz = 0
lp = ''
ks = list(paths.keys())
ks.sort()
for n in ks:
f = paths[n]
tp = os.path.dirname(f.path)
if tp != lp:
lp = tp
tz += f.size
if f.folder:
uprint(u"== %s ==" % (f.path))
elif f.parent and f.parent != '/' and f.path[0] != '?':
uprint(u" %-40s [%11s] (%s)" % (f.name, szstr(f.size), tmstr(f.mdate)))
else:
uprint(u"%-44s [%11s] (%s)" % (f.path, szstr(f.size), tmstr(f.mdate)))
uprint("--------------------------------------------------------------------------------")
uprint("Total %s items [%s]" % (szstr(len(paths)), szstr(tz)))
def print_updates(self, files):
if files:
for f in files:
uprint(u"%s: %s [%s] (%s) %s" % (f.action, f.path, szstr(f.size), tmstr(f.mdate), f.reason))
def print_skips(self, files):
if files:
uprint("--------------------------------------------------------------------------------")
uprint("Skipped files:")
for f in files:
uprint(u"%s: %s [%s] (%s) %s" % (f.action, f.path, szstr(f.size), tmstr(f.mdate), f.reason))
def unknown_files(self, unknowns):
uprint("--------------------------------------------------------------------------------")
tz = 0
for f in unknowns.values():
tz += f.size
uprint(u"%s %s [%s] (%s)" % ('=' if f.folder else ' ', f.name, szstr(f.size), tmstr(f.mdate)))
uprint("--------------------------------------------------------------------------------")
uprint("Unknown %s items [%s]" % (szstr(len(unknowns)), szstr(tz)))
def get(self, fid):
r = self.service.item(drive="me", id=fid)
uprint(str(r))
def tree(self, verb = False):
uinfo('Get remote folders ...')
return self._list(True, verb)
def list(self, verb = False, unknown = False):
uinfo('Get remote files ...')
return self._list(False, verb, unknown)
def _alist(self, fid):
def exef(a):
return self.service.item(drive="me", id=fid).children.request(top=1000).get()
items = []
a = Obj()
a.execute = types.MethodType(exef, a)
r = self.exea(a, "children.get");
items.extend(r)
self._anext(r, items)
return items
def _anext(self, c, items):
if not hasattr(c, "_next_page_link"):
return
sys.stdout.write(" .")
sys.stdout.flush()
def exef(a):
return onedrivesdk.ChildrenCollectionRequest.get_next_page_request(c, self.service).get();
a = Obj()
a.execute = types.MethodType(exef, a)
r = self.exea(a, "children.next");
if r:
items.extend(r)
self._anext(r, items)
def _rlist(self, files, unknowns, fid, path, lvl):
if not self.accept_path(path):
return
sys.stdout.write("\r> " + path.ljust(78))
sys.stdout.flush()
items = self._alist(fid)
for r in items:
# uprint("-------------")
# uprint(str(r))
f = OFile(r, True if lvl == 0 else False)
# ignore unarchived SHARED files
if f.parent == 'UNKNOWN':
unknowns[f.id] = f
continue
# ignore online docs
if not f.folder and not f.url:
unknowns[f.id] = f
continue
files[f.id] = f
if f.folder:
self._rlist(files, unknowns, f.id, path + '/' + f.name, lvl+1)
if lvl == 0:
sys.stdout.write("\n")
def _list(self, folder, verb, unknown = False):
files = {}
unknowns = {}
self._rlist(files, unknowns, "root", "", 0)
# for f in files.itervalues():
# if verb:
# uprint("%s %s %s" % (f.id, f.name, f.parent))
self.rfiles = {}
self.rpaths = {}
if files:
for k,f in files.items():
if folder and not f.folder:
continue
p = self.get_path(files, f)
if p[0] == '?':
unknowns[f.id] = f
continue
if not self.accept_path(p):
continue
self.rfiles[f.id] = f
self.rpaths[p] = f
if verb:
self.print_files(self.rpaths)
if verb and unknown and unknowns:
self.unknown_files(unknowns)
def get_path(self, files, f):
p = u'/' + f.name
i = f
while i.parent:
i = files.get(i.parent)
if i is None:
p = u'?' + p
break
p = u'/' + i.name + p
f.path = p
f.npath = os.path.abspath(config.root_dir + p)
return p
def accept_path(self, path):
"""
Return if name matches any of the ignore patterns.
"""
if not path:
return True
if config.excludes:
for pat in config.excludes:
if fnmatch.fnmatch(path, pat):
return False
if config.includes:
for pat in config.includes:
if fnmatch.fnmatch(path, pat):
return True
return False
return True
"""
get all files in folders and subfolders
"""
def scan(self, verbose = False):
rootdir = config.root_dir
uinfo('Scan local files %s ...' % rootdir)
lpaths = {}
for dirpath, dirnames, filenames in os.walk(rootdir, topdown=True, followlinks=True):
# do not walk into unacceptable directory
dirnames[:] = [d for d in dirnames if self.accept_path(os.path.normpath(os.path.join(dirpath, d))[len(rootdir):].replace('\\', '/'))]
for d in dirnames:
np = os.path.normpath(os.path.join(dirpath, d))
rp = np[len(rootdir):].replace('\\', '/')
if not self.accept_path(rp):
continue
of = OFile()
of.folder = True
of.name = d
of.parent = os.path.dirname(rp)
of.npath = np
of.path = normpath(rp)
of.size = 0
of.mdate = mtime(np)
lpaths[of.path] = of
for f in filenames:
np = os.path.normpath(os.path.join(dirpath, f))
rp = np[len(rootdir):].replace('\\', '/')
if not self.accept_path(rp):
continue
of = OFile()
of.folder = False
of.name = f
of.parent = os.path.dirname(rp)
of.npath = np
of.path = normpath(rp)
of.size = os.path.getsize(np)
of.mdate = mtime(np)
ext = os.path.splitext(f)[1]
lpaths[of.path] = of
self.lpaths = lpaths
if verbose:
self.print_files(lpaths)
"""
find remote patch files
"""
def find_remote_patches(self):
lps = []
for lp,lf in self.lpaths.items():
if lf.folder:
continue
# check patchable
rf = self.rpaths.get(lp)
if rf and lf.size == rf.size and math.fabs(tseconds(lf.mdate - rf.mdate)) > 2:
lf.action = '^~'
lf.reason = '| <> R:[' + szstr(rf.size) + '] ' + tmstr(rf.mdate)
lps.append(lp)
lps.sort()
ufiles = [ ]
for lp in lps:
ufiles.append(self.lpaths[lp])
return ufiles
"""
find local touch files
"""
def find_local_touches(self):
rps = []
for rp,rf in self.rpaths.items():
if rf.folder:
continue
# check touchable
lf = self.lpaths.get(rp)
if lf and lf.size == rf.size and math.fabs(tseconds(rf.mdate - lf.mdate)) > 2:
rf.action = '>~'
rf.reason = '| <> L:[' + szstr(lf.size) + '] ' + tmstr(lf.mdate)
rps.append(rp)
rps.sort()
ufiles = [ ]
for rp in rps:
ufiles.append(self.rpaths[rp])
return ufiles
"""
find local updated files
"""
def find_local_updates(self, lastsync = None, force = False):
lps = []
for lp,lf in self.lpaths.items():
if lf.folder:
# skip for SYNC
if lastsync:
continue
# check remote dir exists
rf = self.rpaths.get(lp)
if rf:
continue
lf.action = '^/'
else:
# check updateable
rf = self.rpaths.get(lp)
if rf:
if tseconds(lf.mdate - rf.mdate) <= 2:
if not force or lf.size == rf.size:
continue
lf.action = '^*'
lf.reason = '| > R:[' + szstr(rf.size) + '] ' + tmstr(rf.mdate)
elif lastsync:
if tseconds(lf.mdate - lastsync) > 2:
lf.action = '^+'
else:
lf.action = '>-'
else:
lf.action = '^+'
lps.append(lp)
lps.sort()
ufiles = [ ]
for lp in lps:
ufiles.append(self.lpaths[lp])
# force to trash remote items that does not exist in local
if force:
# trash remote files
for rp,rf in self.rpaths.items():
if not rf.folder and not rp in self.lpaths:
rf.action = '^-'
ufiles.append(rf)
# trash remote folders
rps = []
for rp,rf in self.rpaths.items():
if rf.folder and not rp in self.lpaths:
rf.action = '^-'
rps.append(rp)
rps.sort(reverse=True)
for rp in rps:
ufiles.append(self.rpaths[rp])
return ufiles
"""
find remote updated files
"""
def find_remote_updates(self, lastsync = None, force = False):
rps = []
for rp,rf in self.rpaths.items():
if rf.folder:
# skip for SYNC
if lastsync:
continue
# check local dir exists
lf = self.lpaths.get(rp)
if lf:
continue
rf.action = '>/'
else:
# check updateable
lf = self.lpaths.get(rp)
if lf:
if tseconds(rf.mdate - lf.mdate) <= 2:
if not force or lf.size == rf.size:
continue
rf.action = '>*'
rf.reason = '| > L:[' + szstr(lf.size) + '] ' + tmstr(lf.mdate)
elif lastsync:
if tseconds(rf.mdate - lastsync) > 2:
rf.action = '>+'
else:
rf.action = '^-'
else:
rf.action = '>+'
rps.append(rp)
rps.sort()
ufiles = [ ]
for rp in rps:
ufiles.append(self.rpaths[rp])
# force to trash local items that does not exist in remote
if force:
# trash local files
for lp,lf in self.lpaths.items():
if not lf.folder and not lp in self.rpaths:
lf.action = '>-'
ufiles.append(lf)
# delete local folders
lps = []
for lp,lf in self.lpaths.items():
if lf.folder and not lp in self.rpaths:
lf.action = '>!'
lps.append(lp)
lps.sort(reverse=True)
for lp in lps:
ufiles.append(self.lpaths[lp])
return ufiles
"""
find synchronizeable files
"""
def find_sync_files(self):
lfiles = self.find_local_updates(config.last_sync)
rfiles = self.find_remote_updates(config.last_sync)
sfiles = lfiles + rfiles
spaths = {}
for sf in sfiles:
if sf.path in spaths:
raise Exception('Duplicated sync file: %s' % sf.path)
spaths[sf.path] = sf
return sfiles
def sync_files(self, sfiles):
i = 0
t = len(sfiles)
for sf in sfiles:
i += 1
self.prog = '[%d/%d]' % (i, t)
if sf.action == '^-':
self.trash_remote_file(sf)
elif sf.action == '^*':
rf = self.rpaths[sf.path]
self.update_remote_file(rf, sf)
elif sf.action == '^+':
pf = self.make_remote_dirs(os.path.dirname(sf.path))
self.insert_remote_file(pf, sf)
elif sf.action == '^/':
self.make_remote_dirs(sf.path)
elif sf.action == '^~':
rf = self.rpaths[sf.path]
self.patch_remote_file(rf, sf.mdate)
elif sf.action in ('>*', '>+'):
self.download_remote_file(sf)
elif sf.action == '>/':
self.create_local_dirs(sf)
elif sf.action == '>-':
self.trash_local_file(sf)
elif sf.action == '>!':
self.remove_local_file(sf)
elif sf.action == '>~':
lf = self.lpaths[sf.path]
self.touch_local_file(lf, sf.mdate)
self.print_skips(self.skips)
def upload_files(self, lfiles):
self.sync_files(lfiles)
def dnload_files(self, rfiles):
self.sync_files(rfiles)
def touch_files(self, pfiles):
self.sync_files(pfiles)
def patch_files(self, pfiles):
self.sync_files(pfiles)
def patch(self, noprompt):
# get remote files
self.list()
# scan local files
self.scan()
pfiles = self.find_remote_patches()
if pfiles:
uprint("--------------------------------------------------------------------------------")
uinfo("Files to be synchronized:")
self.print_updates(pfiles)
if not noprompt:
uprint("--------------------------------------------------------------------------------")
ans = raw_input("Are you sure to patch %d remote files? (Y/N): " % (len(pfiles)))
if ans.lower() != "y":
return
self.patch_files(pfiles)
uprint("--------------------------------------------------------------------------------")
uinfo("PATCH Completed!")
else:
uinfo('No files need to be patched.')
def touch(self, noprompt):
# get remote files
self.list()
# scan local files
self.scan()
pfiles = self.find_local_touches()
if pfiles:
uprint("--------------------------------------------------------------------------------")
uinfo("Files to be synchronized:")
self.print_updates(pfiles)
if not noprompt:
uprint("--------------------------------------------------------------------------------")
ans = raw_input("Are you sure to touch %d local files? (Y/N): " % (len(pfiles)))
if ans.lower() != "y":
return
self.touch_files(pfiles)
uprint("--------------------------------------------------------------------------------")
uinfo("TOUCH Completed!")
else:
uinfo('No files need to be touched.')
def push(self, force = False, noprompt = False):
# get remote files
self.list()
# scan local files
self.scan()
# find files that are in folders and not in remote
ufiles = self.find_local_updates(None, force)
if ufiles:
uprint("--------------------------------------------------------------------------------")
uinfo("Files to be synchronized:")
self.print_updates(ufiles)
if not noprompt:
uprint("--------------------------------------------------------------------------------")
ans = raw_input("Are you sure to push %d files to One Drive? (Y/N): " % len(ufiles))
if ans.lower() != "y":
return
self.upload_files(ufiles)
if force:
self.up_to_date()
uprint("--------------------------------------------------------------------------------")
uinfo("PUSH %s Completed!" % ('(FORCE)' if force else ''))
else:
uprint("--------------------------------------------------------------------------------")
uinfo('No files need to be uploaded to remote server.')
def pull(self, force = False, noprompt = False):
# get remote files
self.list()
# scan local files
self.scan()
# find files that are in folders and not in remote
dfiles = self.find_remote_updates(None, force)
if dfiles:
uprint("--------------------------------------------------------------------------------")
uinfo("Files to be synchronized:")
self.print_updates(dfiles)
if not noprompt:
uprint("--------------------------------------------------------------------------------")
ans = raw_input("Are you sure to pull %d files to local? (Y/N): " % len(dfiles))
if ans.lower() != "y":
return
self.dnload_files(dfiles)
if force:
self.up_to_date()
uprint("--------------------------------------------------------------------------------")
uinfo("PULL %s Completed!" % ('(FORCE)' if force else ''))
else:
uprint("--------------------------------------------------------------------------------")
uinfo('No files need to be downloaded to local.')
def sync(self, noprompt):
# get remote files
self.list()
# scan local files
self.scan()
# find files that are need to be sync
sfiles = self.find_sync_files()
if sfiles:
uprint("--------------------------------------------------------------------------------")
uinfo("Files to be synchronized:")
self.print_updates(sfiles)
if not noprompt:
uprint("--------------------------------------------------------------------------------")
ans = raw_input("Are you sure to sync %d files? (Y/N): " % len(sfiles))
if ans.lower() != "y":
return
self.sync_files(sfiles)
self.up_to_date()