-
Notifications
You must be signed in to change notification settings - Fork 71
/
syncy.py
2263 lines (2173 loc) · 127 KB
/
syncy.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/env python
# -*- coding:utf-8 -*-
####################################################################################################
#
# Author: WishInLife
# QQ: 57956720
# QQ Group: 59160264
# E-Mail: [email protected]
# Web Home: http://www.syncy.cn
# Update date: 2017-02-09
# VERSION: 2.6.0
# Required packages: kmod-nls-utf8, libopenssl, libcurl, python, python-curl, python-crypto
# If import python-crypto package, SyncY can support ARC4、Blowfish and AES encryption.
#
####################################################################################################
import sys
import os
import stat
import time
import re
import struct
import hashlib
from urllib import urlencode
import threading
import traceback
import json
import random
# import fcntl
# if '/usr/lib/python2.7/site-packages' not in sys.path:
# sys.path.append('/usr/lib/python2.7/site-packages')
import pycurl
import binascii
# import zlib
# import fileinput
try: # require python-crypto
from Crypto.Cipher import ARC4
from Crypto.Cipher import Blowfish
from Crypto.Cipher import AES
except ImportError, ex:
ARC4 = Blowfish = AES = None
# set config_file and pidfile for your config storage path.
if os.name == 'nt':
__CONFIG_FILE__ = './syncy'
__PIDFILE__ = './syncy.pid'
__CHARSET__ = 'GBK' # windows charset
__TMP_DIR__ = os.environ['TMP'].replace('\\', '/')
else:
__CONFIG_FILE__ = '/etc/config/syncy'
__PIDFILE__ = '/var/run/syncy.pid'
__CHARSET__ = 'UTF-8' # linux charset
__TMP_DIR__ = '/tmp'
if sys.getdefaultencoding() != __CHARSET__:
reload(sys)
sys.setdefaultencoding(__CHARSET__)
# Don't modify the following.
__VERSION__ = '2.6.0'
__DEBUG__ = False
__author__ = "WishInLife <[email protected]>"
if os.name == 'nt':
import win32con
import win32file
import pywintypes
LOCK_SH = 0
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_UN = 8
__overlapped = pywintypes.OVERLAPPED()
def flock(fd, op):
fh = win32file._get_osfhandle(fd.fileno())
if op == LOCK_UN:
return win32file.UnlockFileEx(fh, 0, 0x0fff0000, __overlapped)
else:
return win32file.LockFileEx(fh, op, 0, 0x0fff0000, __overlapped)
def lockf(fd, op, length=0, start=0, whence=0):
fh = win32file._get_osfhandle(fd.fileno())
fsize = win32file.GetFileSize(fh)
if whence == 1:
start += fd.tell()
elif whence == 2:
start += fsize
if length == 0:
length = fsize
int32 = 2 ** 32
if op == LOCK_UN:
return win32file.UnlockFile(fh, int(start % int32), int(start / int32), int(length % int32), int(length / int32))
else:
return win32file.LockFile(fh, int(start % int32), int(start / int32), int(length % int32), int(length / int32))
else:
from fcntl import LOCK_EX, LOCK_SH, LOCK_NB, LOCK_UN, flock, lockf
LogLock = threading.Lock()
def printlog(msg):
LogLock.acquire()
print(msg)
LogLock.release()
def rename(src, dst):
if os.name == 'nt' and os.path.exists(dst):
os.remove(dst)
os.rename(src, dst)
class SyncY:
synccount = 0
errorcount = 0
failcount = 0
EXLock = threading.Lock()
TaskSemaphore = None
oldSTDERR = None
oldSTDOUT = None
syncydb = None
sydb = None
sydblen = None
syncData = None
basedirlen = None
syncpath = {}
extraslice = None
encryption = None
encryptkey = ''
stop = False
config = {
'apikey' : '',
'secretkey' : '',
'syncylog' : '',
'blocksize' : 10,
'ondup' : 'rename',
'datacache' : 'on',
'excludefiles' : '',
'listnumber' : 100,
'retrytimes' : 3,
'retrydelay' : 3,
'maxsendspeed' : 0,
'maxrecvspeed' : 0,
'speedlimitperiod': '0-0',
'syncperiod' : '0-24',
'syncinterval' : 3600,
'tasknumber' : 2,
'threadnumber' : 2}
syre = {
'newname': re.compile(r'^(.*)(\.[^.]+)$'),
'pcspath': re.compile(r'^[\s\.\n].*|.*[/<>\\|\*\?:\"].*|.*[\s\.\n]$')}
syncytoken = {'synctotal': 0}
synctask = {}
def __init__(self, argv=sys.argv[1:]):
self.__argv = argv
if len(self.__argv) == 0 or self.__argv[0] in ['compress', 'convert', 'rebuild']:
if os.path.exists(__PIDFILE__):
with open(__PIDFILE__, 'r') as pidh:
mypid = pidh.read()
try:
os.kill(int(mypid), 0)
except os.error:
pass
else:
print("SyncY is running!")
sys.exit(0)
with open(__PIDFILE__, 'w') as pidh:
pidh.write(str(os.getpid()))
if not (os.path.isfile(__CONFIG_FILE__)):
sys.stderr.write('%s ERROR: Config file "%s" does not exist.\n' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), __CONFIG_FILE__))
sys.exit(2)
with open(__CONFIG_FILE__, 'r') as sycfg:
line = sycfg.readline()
section = ''
while line:
if re.findall(r'^\s*#', line) or re.findall(r'^\s*$', line):
line = sycfg.readline()
continue
line = re.sub(r'#[^\']*$', '', line)
m = re.findall(r'\s*config\s+([^\s]+).*', line)
if m:
section = m[0].strip('\'')
if section == 'syncpath':
SyncY.syncpath[str(len(SyncY.syncpath))] = {}
line = sycfg.readline()
continue
m = re.findall(r'\s*option\s+([^\s]+)\s+\'([^\']*)\'', line)
if m:
if section == 'syncy':
if m[0][0].strip('\'') in ['blocksize', 'listnumber', 'syncinterval', 'threadnumber', 'tasknumber', 'retrytimes', 'retrydelay']:
SyncY.config[m[0][0].strip('\'')] = int(m[0][1])
elif m[0][0].strip('\'') in ['maxsendspeed', 'maxrecvspeed']:
if m[0][1].upper().find('K') > -1:
idx = m[0][1].upper().find('K')
SyncY.config[m[0][0].strip('\'')] = int(m[0][1][0:idx]) * 1024
elif m[0][1].upper().find('M') > -1:
idx = m[0][1].upper().find('M')
SyncY.config[m[0][0].strip('\'')] = int(m[0][1][0:idx]) * 1024 * 1024
else:
SyncY.config[m[0][0].strip('\'')] = int(m[0][1])
else:
SyncY.config[m[0][0].strip('\'')] = m[0][1]
elif section == 'syncytoken':
if m[0][0].strip('\'') in ['expires_in', 'refresh_date', 'compress_date', 'synctotal']:
SyncY.syncytoken[m[0][0].strip('\'')] = int(m[0][1])
else:
SyncY.syncytoken[m[0][0].strip('\'')] = m[0][1]
elif section == 'syncpath':
if m[0][0].strip('\'') == 'remotepath':
if m[0][1].lower().startswith('/我的应用数据'):
SyncY.syncpath[str(len(SyncY.syncpath) - 1)]['remotepath'] = '/apps' + m[0][1][len('/我的应用数据'):]
else:
SyncY.syncpath[str(len(SyncY.syncpath) - 1)]['remotepath'] = m[0][1]
else:
SyncY.syncpath[str(len(SyncY.syncpath) - 1)][m[0][0].strip('\'')] = m[0][1].replace('\\', '/')
line = sycfg.readline()
if SyncY.config['syncylog'] != '':
if not os.path.exists(os.path.dirname(SyncY.config['syncylog'])):
os.makedirs(os.path.dirname(SyncY.config['syncylog']))
if os.path.exists(SyncY.config['syncylog']) and os.path.isdir(SyncY.config['syncylog']):
SyncY.config['syncylog'] = self.__catpath(SyncY.config['syncylog'], 'syncy.log')
self.__save_config()
if SyncY.oldSTDERR is None and SyncY.config['syncylog'] != '' and len(self.__argv) != 0 and self.__argv[0] in ['sybind', 'cpbind']:
SyncY.oldSTDERR = sys.stderr
SyncY.oldSTDOUT = sys.stdout
sys.stderr = open(SyncY.config['syncylog'], 'a', 0)
sys.stdout = sys.stderr
if SyncY.config['apikey'].strip(' ') == '':
print('%s ERROR: "apikey" must set.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
sys.exit(1)
if SyncY.config['secretkey'].strip(' ') == '':
print('%s ERROR: "secretkey" must set.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
sys.exit(1)
if 'refresh_token' not in SyncY.syncytoken or SyncY.syncytoken['refresh_token'] == '' or (len(self.__argv) != 0 and self.__argv[0] in ['sybind', 'cpbind']):
sycurl = SYCurl()
if (('device_code' not in SyncY.syncytoken or SyncY.syncytoken['device_code'] == '') and len(self.__argv) == 0) or (len(self.__argv) != 0 and self.__argv[0] == 'sybind'):
retcode, responses = sycurl.request('https://openapi.baidu.com/oauth/2.0/device/code', {}, {'client_id': SyncY.config['apikey'], 'response_type': 'device_code', 'scope': 'basic,netdisk'}, 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
print('%s ERROR(Errno:%d): Get device code failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, responses['error_msg']))
sys.exit(3)
device_code = responses['device_code']
user_code = responses['user_code']
if len(self.__argv) != 0 and self.__argv[0] == 'sybind':
with open(__TMP_DIR__ + '/syncy.bind', 'w') as sybind:
sybind.write('{"user_code":"%s","device_code":"%s","time":%d}' % (user_code, device_code, int(time.time())))
sys.exit(0)
SyncY.syncytoken['device_code'] = device_code
print('Device binding Guide:')
print(' 1. Open web browser to visit:"https://openapi.baidu.com/device" and input user code to binding your baidu account.')
print(' ')
print(' 2. User code:\033[31m %s\033[0m' % user_code)
print(' (User code valid for 30 minutes.)')
print(' ')
raw_input(' 3. After granting access to the application, come back here and press [Enter] to continue.')
print(' ')
if len(self.__argv) != 0 and self.__argv[0] == 'cpbind':
with open(__TMP_DIR__ + '/syncy.bind', 'r') as sybind:
bindinfo = sybind.read()
bindinfo = json.loads(bindinfo)
os.remove(__TMP_DIR__ + '/syncy.bind')
if 'device_code' in bindinfo:
if int(time.time()) - int(bindinfo['time']) >= 1800:
sys.exit(4)
SyncY.syncytoken['device_code'] = bindinfo['device_code']
else:
sys.exit(5)
retcode, responses = sycurl.request('https://openapi.baidu.com/oauth/2.0/token', {}, {'grant_type': 'device_token', 'code': SyncY.syncytoken['device_code'], 'client_id': SyncY.config['apikey'], 'client_secret': SyncY.config['secretkey'],}, 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
print('%s ERROR(Errno:%d): Get device token failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, responses['error_msg']))
sys.exit(6)
SyncY.syncytoken['refresh_token'] = responses['refresh_token']
SyncY.syncytoken['access_token'] = responses['access_token']
SyncY.syncytoken['expires_in'] = int(responses['expires_in'])
SyncY.syncytoken['refresh_date'] = int(time.time())
SyncY.syncytoken['compress_date'] = int(time.time())
self.__save_config()
if len(self.__argv) != 0 and self.__argv[0] == 'cpbind':
sys.exit(0)
print('%s INFO: Get device token success.\n' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.oldSTDERR is None and SyncY.config['syncylog'] != '':
print('%s INFO: Running log output to log file %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), SyncY.config['syncylog']))
SyncY.oldSTDERR = sys.stderr
SyncY.oldSTDOUT = sys.stdout
sys.stderr = open(SyncY.config['syncylog'], 'a', 0)
sys.stdout = sys.stderr
try:
if SyncY.config['blocksize'] < 1:
SyncY.config['blocksize'] = 10
print('%s WARNING: "blocksize" must great than or equal to 1(M), set to default 10(M).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['ondup'] != 'overwrite' and SyncY.config['ondup'] != 'rename':
SyncY.config['ondup'] = 'rename'
print('%s WARNING: ondup is invalid, set to default(overwrite).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['datacache'] != 'on' and SyncY.config['datacache'] != 'off':
SyncY.config['datacache'] = 'on'
print('%s WARNING: "datacache" is invalid, set to default(on).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['retrytimes'] < 0:
SyncY.config['retrytimes'] = 3
print('%s WARNING: "retrytimes" is invalid, set to default(3 times).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['retrydelay'] < 0:
SyncY.config['retrydelay'] = 3
print('%s WARNING: "retrydelay" is invalid, set to default(3 second).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['listnumber'] < 1:
SyncY.config['listnumber'] = 100
print('%s WARNING: "listnumber" must great than or equal to 1, set to default 100.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['syncinterval'] < 0:
SyncY.config['syncinterval'] = 3600
print('%s WARNING: "syncinterval" must great than or equal to 1, set to default 3600.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['maxsendspeed'] < 0:
SyncY.config['maxsendspeed'] = 0
print('%s WARNING: "maxsendspeed" must great than or equal to 0, set to default 0.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['maxrecvspeed'] < 0:
SyncY.config['maxrecvspeed'] = 0
print('%s WARNING: "maxrecvspeed" must great than or equal to 0, set to default 100.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['threadnumber'] < 1:
SyncY.config['threadnumber'] = 2
print('%s WARNING: "threadnumber" must great than or equal to 1, set to default 2.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
if SyncY.config['tasknumber'] < 1:
SyncY.config['tasknumber'] = 2
print('%s WARNING: "tasknumber" must great than or equal to 1, set to default 2.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
starthour, endhour = SyncY.config['speedlimitperiod'].split('-', 1)
if starthour == '' or endhour == '' or int(starthour) < 0 or int(starthour) > 23 or int(endhour) < 0 or int(endhour) > 24:
print('%s WARNING: "speedlimitperiod" is invalid, set to default(0-0), no limit.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
SyncY.config['speedlimitperiod'] = '0-0'
starthour, endhour = SyncY.config['syncperiod'].split('-', 1)
if starthour == '' or endhour == '' or int(starthour) < 0 or int(starthour) > 23 or int(endhour) < 0 or int(endhour) > 24 or endhour == starthour:
print('%s WARNING: "syncperiod" is invalid, set to default(0-24).' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
SyncY.config['syncperiod'] = '0-24'
except Exception, e:
print('%s ERROR: initialize parameters failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), e, traceback.format_exc()))
sys.exit(7)
self._excludefiles = SyncY.config['excludefiles'].replace('\\', '/').replace('.', '\.').replace('*', '.*').replace('?', '.?').split(';')
for i in xrange(len(self._excludefiles)):
self._excludefiles[i] = re.compile(eval('r"^' + self._excludefiles[i] + '$"'))
self._excludefiles.append(re.compile(r'^.*\.syy$'))
if (SyncY.syncytoken['refresh_date'] + SyncY.syncytoken['expires_in'] - 864000) < int(time.time()):
self.__check_expires()
SyncY.TaskSemaphore = threading.Semaphore(SyncY.config['tasknumber'])
size = 32768
while True:
try:
threading.stack_size(size)
threadtest = ThreadTest()
threadtest.start()
break
except threading.ThreadError:
threading.stack_size(0)
break
except RuntimeError:
threading.stack_size(0)
break
except ValueError:
if size < 512 * 1024:
size *= 2
else:
threading.stack_size(0)
break
def __del__(self):
if self.__class__.oldSTDERR is not None:
sys.stderr.flush()
sys.stderr.close()
sys.stderr = self.__class__.oldSTDERR
sys.stdout = self.__class__.oldSTDOUT
if os.path.exists(__PIDFILE__):
with open(__PIDFILE__, 'r') as pidh:
lckpid = pidh.read()
if os.getpid() == int(lckpid):
os.remove(__PIDFILE__)
@staticmethod
def synccount_increase():
SyncY.EXLock.acquire()
SyncY.synccount += 1
SyncY.EXLock.release()
@staticmethod
def errorcount_increase():
SyncY.EXLock.acquire()
SyncY.errorcount += 1
SyncY.EXLock.release()
@staticmethod
def failcount_increase():
SyncY.EXLock.acquire()
SyncY.failcount += 1
SyncY.EXLock.release()
@staticmethod
def reset_counter():
SyncY.EXLock.acquire()
SyncY.synccount = 0
SyncY.failcount = 0
SyncY.errorcount = 0
SyncY.EXLock.release()
@staticmethod
def __init_syncdata():
SyncY.syncData = {}
if os.path.exists(SyncY.syncydb):
with open(SyncY.syncydb, 'rb') as sydb:
flock(sydb, LOCK_SH)
sydb.seek(64)
datarec = sydb.read(64)
while datarec:
SyncY.syncData[datarec[0:16]] = datarec[16:]
datarec = sydb.read(64)
flock(sydb, LOCK_UN)
def __check_expires(self):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser', {}, {'access_token': SyncY.syncytoken['access_token']}, 'POST', SYCurl.Normal)
responses = json.loads(responses)
if 'uid' in responses:
retcode, responses = sycurl.request('https://www.syncy.cn/syserver', {}, {'method': 'get_last_version', 'edition': 'python', 'ver': __VERSION__, 'uid': responses['uid'], 'code': SyncY.syncytoken['device_code']}, 'POST', SYCurl.Normal)
if retcode == 200 and responses.find('#') > -1:
(lastver, smessage) = responses.strip('\n').split('#', 1)
if lastver > __VERSION__:
printlog('%s WARNING: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), smessage.encode(__CHARSET__)))
if (SyncY.syncytoken['refresh_date'] + SyncY.syncytoken['expires_in'] - 864000) > int(time.time()):
return
retcode, retbody = sycurl.request('https://openapi.baidu.com/oauth/2.0/token', {}, {'grant_type': 'refresh_token', 'refresh_token': SyncY.syncytoken['refresh_token'], 'client_id': SyncY.config['apikey'], 'client_secret': SyncY.config['secretkey']}, 'POST', SYCurl.Normal)
responses = json.loads(retbody)
try:
if retcode != 200:
printlog('%s ERROR(Errno:%d): Refresh access token failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, responses['error_msg']))
return 1
SyncY.syncytoken['refresh_token'] = responses['refresh_token']
SyncY.syncytoken['access_token'] = responses['access_token']
SyncY.syncytoken['expires_in'] = int(responses['expires_in'])
SyncY.syncytoken['refresh_date'] = int(time.time())
except KeyError:
printlog('%s ERROR(Errno:%d): Refresh access token failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, retbody))
return 1
self.__save_config()
printlog('%s INFO: Refresh access token success.' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
return 0
@staticmethod
def __save_config():
with open('%s.tmp' % __CONFIG_FILE__, 'w') as sycfg:
sycfg.write("\nconfig syncy\n")
for key, value in SyncY.config.items():
sycfg.write("\toption %s '%s'\n" % (key, str(value)))
sycfg.write("\nconfig syncytoken\n")
for key, value in SyncY.syncytoken.items():
sycfg.write("\toption %s '%s'\n" % (key, str(value)))
for i in range(len(SyncY.syncpath)):
sycfg.write("\nconfig syncpath\n")
for key, value in SyncY.syncpath[str(i)].items():
sycfg.write("\toption %s '%s'\n" % (key, str(value)))
sycfg.flush()
os.fsync(sycfg.fileno())
if os.path.exists('%s.tmp' % __CONFIG_FILE__):
pmeta = os.stat(__CONFIG_FILE__)
rename('%s.tmp' % __CONFIG_FILE__, __CONFIG_FILE__)
if os.name == 'posix':
os.lchown(__CONFIG_FILE__, pmeta.st_uid, pmeta.st_gid)
os.chmod(__CONFIG_FILE__, pmeta.st_mode)
@staticmethod
def __catpath(*names):
fullpath = '/'.join(names)
fullpath = re.sub(r'/+', '/', fullpath)
fullpath = re.sub(r'/$', '', fullpath)
return fullpath
@staticmethod
def __get_newname(oldname):
nowtime = str(time.strftime("%Y%m%d%H%M%S", time.localtime()))
m = SyncY.syre['newname'].findall(oldname)
if m:
newname = m[0][0] + '_old_' + nowtime + m[0][1]
else:
newname = oldname + '_old_' + nowtime
return newname
@staticmethod
def __check_pcspath(pcsdirname, pcsfilename):
if len(pcsdirname) + len(pcsfilename) + 1 >= 1000:
printlog('%s ERROR: Length of PCS path(%s/%s) must less than 1000, skip upload.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), pcsdirname, pcsfilename))
return 1
if SyncY.syre['pcspath'].findall(pcsfilename):
printlog('%s ERROR: PCS path(%s/%s) is invalid, please check whether special characters exists in the path, skip upload the file.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), pcsdirname, pcsfilename))
return 1
return 0
@staticmethod
def __get_pcs_quota():
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/quota', {'method': 'info', 'access_token': SyncY.syncytoken['access_token']}, '', 'GET', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
printlog('%s ERROR(Errno:%d): Get pcs quota failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, responses['error_msg']))
return 1
printlog('%s INFO: PCS quota is %dG,used %dG.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), responses['quota'] / 1024 / 1024 / 1024, responses['used'] / 1024 / 1024 / 1024))
return 0
@staticmethod
def __get_pcs_filelist(pcspath, startindex, endindex):
if __DEBUG__:
printlog('%s Info(%s): Start get pcs file list(%d-%d) of "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, startindex, endindex, pcspath))
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'list', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath, 'limit': '%d-%d' % (startindex, endindex), 'by': 'name', 'order': 'asc'}, '', 'GET', SYCurl.Normal)
try:
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
if responses['error_code'] == 31066:
return 31066, []
else:
printlog('%s ERROR(Errno:%d): Get PCS file list of "%s" failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, pcspath, responses['error_msg']))
return 1, []
return 0, responses['list']
except Exception, e:
printlog('%s ERROR: Get PCS file list of "%s" failed. return code: %d, response body: %s.\n%s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), pcspath, retcode, str(responses), e, traceback.format_exc()))
return 1, []
finally:
del responses
if __DEBUG__:
printlog('%s Info(%s): Complete get pcs file list(%d-%d) of "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, startindex, endindex, pcspath))
@staticmethod
def __check_create_pcsdir(pcspath):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'meta', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath}, '', 'GET', SYCurl.Normal)
try:
responses = json.loads(responses)
if retcode == 200 and responses['list'][0]['isdir'] == 1:
return 0
elif (retcode != 200 and responses['error_code'] == 31066) or (retcode == 200 and responses['list'][0]['isdir'] == 0):
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'mkdir', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath}, '', 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode == 200 and responses['path'].encode(__CHARSET__) == pcspath:
return 0
printlog('%s ERROR(Errno:%d): Create PCS directory "%s" failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, pcspath, responses['error_msg']))
return 1
except Exception, e:
printlog('%s ERROR: Create PCS directory "%s" failed. return code: %d, response body: %s.\n%s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), pcspath, retcode, str(responses), e, traceback.format_exc()))
return 1
def __rm_localfile(self, delpath, slient=False):
try:
if os.path.isfile(delpath):
os.remove(delpath)
if not slient:
printlog('%s INFO: Delete local file "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), delpath))
elif os.path.isdir(delpath):
fnlist = os.listdir(delpath)
for i in xrange(len(fnlist)):
self.__rm_localfile('%s/%s' % (delpath, fnlist[i]), slient)
os.rmdir(delpath)
if not slient:
printlog('%s INFO: Delete local directory "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), delpath))
except Exception, e:
if not slient:
printlog('%s ERROR: Delete local file "%s" failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), delpath, e, traceback.format_exc()))
return 1
return 0
@staticmethod
def __rm_pcsfile(pcspath, slient=False):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'delete', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath}, '', 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
if not slient:
printlog('%s ERROR(Errno:%d): Delete remote file or directory "%s" failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, pcspath, responses['error_msg']))
return 1
if not slient:
printlog('%s INFO: Delete remote file or directory "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), pcspath))
return 0
@staticmethod
def __mv_pcsfile(oldpcspath, newpcspath, slient=False):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'move', 'access_token': SyncY.syncytoken['access_token'], 'from': oldpcspath, 'to': newpcspath}, '', 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
if not slient:
printlog('%s ERROR(Errno:%d): Move remote file or directory "%s" to "%s" failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, oldpcspath, newpcspath, responses['error_msg']))
return 1
if not slient:
printlog('%s INFO: Move remote file or directory "%s" to "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), oldpcspath, newpcspath))
return 0
@staticmethod
def __cp_pcsfile(srcpcspath, destpcspath):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'copy', 'access_token': SyncY.syncytoken['access_token'], 'from': srcpcspath, 'to': destpcspath}, '', 'POST', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
printlog('%s ERROR(Errno:%d): Copy remote file or directory "%s" to "%s" failed: %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, srcpcspath, destpcspath, responses['error_msg']))
return 1
printlog('%s INFO: Copy remote file or directory "%s" to "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), srcpcspath, destpcspath))
return 0
@staticmethod
def __get_pcs_filemeta(pcspath):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://pcs.baidu.com/rest/2.0/pcs/file', {'method': 'meta', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath}, '', 'GET', SYCurl.Normal)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
printlog('%s ERROR(Errno:%d): Get file\'s meta failed: %s, %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, pcspath, responses['error_msg']))
return 1, {}
return 0, responses['list'][0]
@staticmethod
def __upload_file_nosync(filepath, pcspath):
sycurl = SYCurl()
retcode, responses = sycurl.request('https://c.pcs.baidu.com/rest/2.0/pcs/file', {'method': 'upload', 'access_token': SyncY.syncytoken['access_token'], 'path': pcspath, 'ondup': 'newcopy'}, '0-%d' % (os.stat(filepath).st_size - 1), 'POST', SYCurl.Upload, filepath)
responses = json.loads(responses)
if retcode != 200 or 'error_code' in responses:
printlog('%s ERROR(Errno:%d): Upload file to pcs failed: %s, %s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), retcode, filepath, responses['error_msg']))
return 1
printlog('%s INFO: Upload file "%s" completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), filepath))
return 0
def __compress_data(self, pathname, sydbnew, sydb=None, sydblen=0):
fnlist = os.listdir(pathname)
fnlist.sort()
for fnname in fnlist:
if fnname[0:1] == '.':
continue
fullpath = '%s/%s' % (pathname, fnname)
if os.path.isdir(fullpath):
if SyncY.config['datacache'] == 'on':
self.__compress_data(fullpath, sydbnew)
else:
self.__compress_data(fullpath, sydbnew, sydb, sydblen)
elif os.path.isfile(fullpath):
fnmd5 = hashlib.md5(fullpath[SyncY.basedirlen:]).digest()
fnstat = os.stat(fullpath)
fmate = struct.pack('>qq', int(fnstat.st_mtime), fnstat.st_size)
if SyncY.config['datacache'] == 'on':
if fnmd5 in SyncY.syncData and SyncY.syncData[fnmd5][0:16] == fmate:
sydbnew.write('%s%s' % (fnmd5, SyncY.syncData[fnmd5]))
del SyncY.syncData[fnmd5]
else:
if sydb.tell() == sydblen:
sydb.seek(64)
datarec = sydb.read(64)
readlen = 64
while datarec and readlen <= sydblen - 64:
if datarec[0:32] == '%s%s' % (fnmd5, fmate):
sydbnew.write(datarec)
break
if readlen == sydblen - 64:
break
if sydb.tell() == sydblen:
sydb.seek(64)
datarec = sydb.read(64)
readlen += 64
return 0
def __start_compress(self, pathname=''):
if pathname == '':
mpath = []
for i in range(len(SyncY.syncpath)):
if SyncY.syncpath[str(i)]['synctype'].lower() not in ['4', 's', 'sync']:
mpath.append(SyncY.syncpath[str(i)]['localpath'])
printlog('%s INFO: Start compress sync data.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
else:
mpath = [pathname]
for ipath in mpath:
if ipath == '':
continue
SyncY.basedirlen = len(ipath)
SyncY.syncydb = '%s/.syncy.info.db' % ipath
newdbfile = '%s/.syncy.info.dbtmp' % ipath
if os.path.exists(SyncY.syncydb):
if os.path.exists(newdbfile):
os.remove(newdbfile)
self.__check_upgrade_syncdata(newdbfile)
with open(newdbfile, 'ab') as sydbnew:
if SyncY.config['datacache'] == 'on':
self.__init_syncdata()
self.__compress_data(ipath, sydbnew)
SyncY.syncData = None
else:
sydblen = os.stat(SyncY.syncydb).st_size
with open(SyncY.syncydb, 'rb') as sydb:
self.__compress_data(ipath, sydbnew, sydb, sydblen)
sydbnew.flush()
os.fsync(sydbnew.fileno())
rename(newdbfile, SyncY.syncydb)
if pathname == '':
SyncY.syncytoken['compress_date'] = int(time.time())
SyncY.syncytoken['synctotal'] = 0
self.__save_config()
printlog('%s INFO: Sync data compress completed.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
def __check_excludefiles(self, filepath):
for reexf in self._excludefiles:
if reexf.findall(filepath):
return 1
return 0
@staticmethod
def __check_syncstatus(fmd5, fmate, rmate, rmd5):
if rmd5 != '*':
rmd5 = rmd5.decode('hex')
if SyncY.config['datacache'] == 'on':
if fmd5 not in SyncY.syncData:
return 0
if rmd5 == '*' and rmate == '*' and SyncY.syncData[fmd5][0:16] == fmate:
return 1
elif fmate == '*' and SyncY.syncData[fmd5][16:] == rmate + rmd5:
return 1
elif SyncY.syncData[fmd5] == fmate + rmate + rmd5:
return 1
else:
if SyncY.sydb.tell() == SyncY.sydblen:
SyncY.sydb.seek(64)
datarec = SyncY.sydb.read(64)
readlen = 64
while datarec and readlen <= SyncY.sydblen - 64:
if rmd5 == '*' and rmate == '*' and datarec[0:32] == fmd5 + fmate:
return 1
elif fmate == '*' and datarec[16:] == rmate + rmd5:
return 1
elif datarec == fmd5 + fmate + rmate + rmd5:
return 1
if readlen == SyncY.sydblen - 64:
break
if SyncY.sydb.tell() == SyncY.sydblen:
SyncY.sydb.seek(64)
datarec = SyncY.sydb.read(64)
readlen += 64
return 0
def __syncy_upload(self, ldir, rdir):
fnlist = os.listdir(ldir)
fnlist.sort()
for fi in xrange(len(fnlist)):
lfullpath = '%s/%s' % (ldir, fnlist[fi])
fmtime = 0
fsize = 0
try:
if fnlist[fi][0:1] == '.' or self.__check_excludefiles(lfullpath) == 1 or self.__check_pcspath(rdir, fnlist[fi]) == 1:
continue
if __DEBUG__:
printlog('%s Info(%s): Start upload "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, lfullpath))
rfullpath = '%s/%s' % (rdir, fnlist[fi])
if os.path.isdir(lfullpath):
self.__syncy_upload(lfullpath, rfullpath)
else:
fmeta = os.stat(lfullpath)
fmtime = int(fmeta.st_mtime)
fsize = fmeta.st_size
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if self.__check_syncstatus(fnmd5, struct.pack('>qq', fmtime, fsize), '*', '*') == 0:
if SyncY.config['ondup'] == 'rename':
ondup = 'newcopy'
else:
ondup = 'overwrite'
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Upload, lfullpath, int(fmeta.st_mtime), fmeta.st_size, fnmd5, rfullpath, 0, 0, '', ondup)
synctask.start()
else:
continue
except struct.error, e:
printlog('%s ERROR: Struct.pack upload file mate(mtime:%d,size:%d) of "%s" error: %s\n%s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), fmtime, fsize, lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
except Exception, e:
printlog('%s ERROR: Upload file "%s" failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
return 0
def __syncy_uploadplus(self, ldir, rdir):
startidx = 0
retcode, rfnlist = self.__get_pcs_filelist(rdir, startidx, SyncY.config['listnumber'])
if retcode != 0 and retcode != 31066:
self.errorcount_increase()
return 1
lfnlist = os.listdir(ldir)
lfnlist.sort()
while retcode == 0:
for i in xrange(len(rfnlist)):
rfullpath = rfnlist[i]['path'].encode(__CHARSET__)
fnname = os.path.basename(rfullpath)
lfullpath = '%s/%s' % (ldir, fnname)
try:
if self.__check_excludefiles(lfullpath) == 1:
continue
if os.path.exists(lfullpath):
for idx in xrange(len(lfnlist)):
if lfnlist[idx] == fnname:
del lfnlist[idx]
break
else:
continue
if __DEBUG__:
printlog('%s Info(%s): Start upload+ "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, lfullpath))
if (rfnlist[i]['isdir'] == 1 and os.path.isfile(lfullpath)) or (rfnlist[i]['isdir'] == 0 and os.path.isdir(lfullpath)):
if SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (rdir, self.__get_newname(fnname))
if len(fnnamenew) >= 1000:
printlog('%s ERROR: Rename failed, the length of PCS path "%s" must less than 1000, skip upload "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), fnnamenew, lfullpath))
self.failcount_increase()
continue
if self.__mv_pcsfile(rfullpath, fnnamenew, True) == 1:
printlog('%s ERROR: Rename "%s" failed, skip upload "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), rfullpath, lfullpath))
self.errorcount_increase()
continue
else:
self.__rm_pcsfile(rfullpath, True)
if os.path.isdir(lfullpath):
self.__syncy_uploadplus(lfullpath, rfullpath)
continue
else:
fmeta = os.stat(lfullpath)
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Upload, lfullpath, int(fmeta.st_mtime), fmeta.st_size, fnmd5, rfullpath, 0, 0, '', 'overwrite')
synctask.start()
elif rfnlist[i]['isdir'] == 1:
self.__syncy_uploadplus(lfullpath, rfullpath)
continue
else:
fmeta = os.stat(lfullpath)
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if self.__check_syncstatus(fnmd5, struct.pack('>qq', int(fmeta.st_mtime), fmeta.st_size), struct.pack('>qq', rfnlist[i]['mtime'], rfnlist[i]['size']), rfnlist[i]['md5']) == 1:
continue
if SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (rdir, self.__get_newname(fnname))
if len(fnnamenew) >= 1000:
printlog('%s ERROR: Rename failed, the length of PCS path "%s" must less than 1000, skip upload "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), fnnamenew, lfullpath))
self.failcount_increase()
continue
if self.__mv_pcsfile(rfullpath, fnnamenew, True) == 1:
printlog('%s ERROR: Rename "%s" failed, skip upload "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), rfullpath, lfullpath))
self.failcount_increase()
continue
else:
self.__rm_pcsfile(rfullpath, True)
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Upload, lfullpath, int(fmeta.st_mtime), fmeta.st_size, fnmd5, rfullpath, 0, 0, '', 'overwrite')
synctask.start()
except struct.error, e:
printlog('%s ERROR: Struct.pack file mate of "%s" error: %s\n%s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
except Exception, e:
printlog('%s ERROR: Upload file "%s" failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
if len(rfnlist) < SyncY.config['listnumber']:
break
startidx += SyncY.config['listnumber']
retcode, rfnlist = self.__get_pcs_filelist(rdir, startidx, startidx + SyncY.config['listnumber'])
if retcode != 0:
self.errorcount_increase()
return 1
for idx in xrange(len(lfnlist)):
lfullpath = '%s/%s' % (ldir, lfnlist[idx])
try:
if lfnlist[idx][0:1] == '.' or self.__check_excludefiles(lfullpath) == 1 or self.__check_pcspath(rdir, lfnlist[idx]) == 1:
continue
rfullpath = '%s/%s' % (rdir, lfnlist[idx])
if os.path.isdir(lfullpath):
self.__syncy_uploadplus(lfullpath, rfullpath)
elif os.path.isfile(lfullpath):
fmeta = os.stat(lfullpath)
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Upload, lfullpath, int(fmeta.st_mtime), fmeta.st_size, fnmd5, rfullpath, 0, 0, '', 'overwrite')
synctask.start()
except struct.error, e:
printlog('%s ERROR: Struct.pack file mate of "%s" error: %s\n%s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
except Exception, e:
printlog('%s ERROR: Upload file "%s" failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
return 0
def __syncy_download(self, ldir, rdir):
startidx = 0
retcode, rfnlist = self.__get_pcs_filelist(rdir, startidx, SyncY.config['listnumber'])
if retcode != 0:
self.errorcount_increase()
return 1
while retcode == 0:
for i in xrange(len(rfnlist)):
rfullpath = rfnlist[i]['path'].encode(__CHARSET__)
fnname = os.path.basename(rfullpath)
if self.__check_excludefiles(rfullpath) == 1:
continue
lfullpath = '%s/%s' % (ldir, fnname)
try:
if __DEBUG__:
printlog('%s Info(%s): Start download "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, rfullpath))
if rfnlist[i]['isdir'] == 1:
if os.path.exists(lfullpath) and os.path.isfile(lfullpath):
if SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (ldir, self.__get_newname(fnname))
rename(lfullpath, fnnamenew)
else:
if self.__rm_localfile(lfullpath, True) == 1:
printlog('%s ERROR: Delete local file "%s" failed, skip download "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, rfullpath))
self.errorcount_increase()
continue
if not (os.path.exists(lfullpath)):
os.mkdir(lfullpath)
if os.name == 'posix':
pmeta = os.stat(ldir)
os.lchown(lfullpath, pmeta.st_uid, pmeta.st_gid)
os.chmod(lfullpath, pmeta.st_mode)
self.__syncy_download(lfullpath, rfullpath)
else:
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if not (os.path.exists(lfullpath + '.db.syy')):
if self.__check_syncstatus(fnmd5, '*', struct.pack('>qq', rfnlist[i]['mtime'], rfnlist[i]['size']), rfnlist[i]['md5']) == 1:
continue
if os.path.exists(lfullpath) and SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (ldir, self.__get_newname(fnname))
rename(lfullpath, fnnamenew)
elif os.path.exists(lfullpath):
if self.__rm_localfile(lfullpath, True) == 1:
printlog('%s ERROR: Delete local file "%s" failed, skip download "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, rfullpath))
self.failcount_increase()
continue
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Download, lfullpath, 0, 0, fnmd5, rfullpath, rfnlist[i]['mtime'], rfnlist[i]['size'], rfnlist[i]['md5'], 'overwrite')
synctask.start()
except struct.error, e:
printlog('%s ERROR: Struct.pack file mate of "%s" error: %s\n%s.' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
except Exception, e:
printlog('%s ERROR: Download file "%s" failed. %s\n%s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, e, traceback.format_exc()))
self.errorcount_increase()
return 1
if len(rfnlist) < SyncY.config['listnumber']:
break
startidx += SyncY.config['listnumber']
retcode, rfnlist = self.__get_pcs_filelist(rdir, startidx, startidx + SyncY.config['listnumber'])
if retcode != 0:
self.errorcount_increase()
return 1
return 0
def __syncy_downloadplus(self, ldir, rdir):
startidx = 0
retcode, rfnlist = self.__get_pcs_filelist(rdir, startidx, SyncY.config['listnumber'])
if retcode != 0:
self.errorcount_increase()
return 1
while retcode == 0:
for i in xrange(0, len(rfnlist), 1):
rfullpath = rfnlist[i]['path'].encode(__CHARSET__)
fnname = os.path.basename(rfullpath)
if self.__check_excludefiles(rfullpath) == 1:
continue
lfullpath = '%s/%s' % (ldir, fnname)
try:
if __DEBUG__:
printlog('%s Info(%s): Start download+ "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), threading.currentThread().name, rfullpath))
if rfnlist[i]['isdir'] == 1:
if os.path.exists(lfullpath) and os.path.isfile(lfullpath):
if SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (ldir, self.__get_newname(fnname))
rename(lfullpath, fnnamenew)
else:
if self.__rm_localfile(lfullpath, True) == 1:
printlog('%s ERROR: Delete local file "%s" failed, skip download "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, rfullpath))
self.errorcount_increase()
continue
if not (os.path.exists(lfullpath)):
os.mkdir(lfullpath)
if os.name == 'posix':
pmeta = os.stat(ldir)
os.lchown(lfullpath, pmeta.st_uid, pmeta.st_gid)
os.chmod(lfullpath, pmeta.st_mode)
self.__syncy_downloadplus(lfullpath, rfullpath)
else:
fnmd5 = hashlib.md5(lfullpath[SyncY.basedirlen:]).digest()
if os.path.exists(lfullpath) and not (os.path.exists(lfullpath + '.db.syy')):
fmeta = os.stat(lfullpath)
if self.__check_syncstatus(fnmd5, struct.pack('>qq', int(fmeta.st_mtime), fmeta.st_size), struct.pack('>qq', rfnlist[i]['mtime'], rfnlist[i]['size']), rfnlist[i]['md5']) == 1:
continue
if SyncY.config['ondup'] == 'rename':
fnnamenew = '%s/%s' % (ldir, self.__get_newname(fnname))
rename(lfullpath, fnnamenew)
else:
if self.__rm_localfile(lfullpath, True) == 1:
printlog('%s ERROR: Delete local file "%s" failed, skip download "%s".' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), lfullpath, rfullpath))
self.failcount_increase()
continue
if SyncY.TaskSemaphore.acquire():
synctask = SYTask(SYTask.Download, lfullpath, 0, 0, fnmd5, rfullpath, rfnlist[i]['mtime'], rfnlist[i]['size'], rfnlist[i]['md5'], 'overwrite')
synctask.start()
except struct.error, e: