forked from yadayada/acd_cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
acd_cli.py
executable file
·1696 lines (1323 loc) · 59.2 KB
/
acd_cli.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 python3
import sys
import os
import json
import argparse
import logging
import logging.handlers
import signal
import time
import re
import appdirs
from collections import namedtuple
from configparser import ConfigParser
from functools import partial
from multiprocessing import Event
from pkgutil import walk_packages
from pkg_resources import iter_entry_points
import acdcli
from acdcli.api import client
from acdcli.api.common import RequestError, is_valid_id
from acdcli.cache import format, db
from acdcli.utils import hashing, progress
from acdcli.utils.conf import get_conf
from acdcli.utils.threading import QueuedLoader
from acdcli.utils.time import *
# load local plugin modules (default ones, for developers)
from acdcli import plugins
for importer, modname, ispkg in walk_packages(path=plugins.__path__, prefix=plugins.__name__ + '.',
onerror=lambda x: None):
if not ispkg:
__import__(modname)
# load additional plugins from entry point
for plug_mod in iter_entry_points(group='acdcli.plugins', name=None):
__import__(plug_mod.module_name)
_app_name = 'acd_cli'
logger = logging.getLogger(_app_name)
# path settings
cp = os.environ.get('ACD_CLI_CACHE_PATH')
sp = os.environ.get('ACD_CLI_SETTINGS_PATH')
CACHE_PATH = cp if cp else appdirs.user_cache_dir(_app_name)
SETTINGS_PATH = sp if sp else appdirs.user_config_dir(_app_name)
_SETTINGS_FILENAME = _app_name + '.ini'
paths = {CACHE_PATH: True, SETTINGS_PATH: False} # path:str : critical:bool
for path in paths:
if not os.path.isdir(path):
try:
os.makedirs(path, mode=0o0700) # private data
except OSError:
err_msg = 'Error creating directory "%s".'
if paths[path]:
logger.critical(err_msg % path)
sys.exit(1)
else:
logger.warning(err_msg % path)
def_conf = ConfigParser()
def_conf['download'] = dict(keep_corrupt=False, keep_incomplete=True)
def_conf['upload'] = dict(timeout_wait=10)
conf = None
# consts
MIN_SYNC_INTERVAL = 300
MAX_LOG_SIZE = 10 * 2 ** 20
MAX_LOG_FILES = 5
TIMESTAMP_FORMAT = "%Y-%m-%d_%H:%M:%S"
# return values
ERROR_RETVAL = 1
INVALID_ARG_RETVAL = 2 # doubles as flag
INIT_FAILED_RETVAL = 3
KEYB_INTERR_RETVAL = 4
# additional retval flags
UL_DL_FAILED = 8
UL_TIMEOUT = 16
HASH_MISMATCH = 32
ERR_CR_FOLDER = 64
SIZE_MISMATCH = 128
CACHE_ASYNC = 256
DUPLICATE = 512
DUPLICATE_DIR = 1024
NAME_COLLISION = 2048
ERR_DEL_FILE = 4096
def signal_handler(signal_, frame):
sys.exit(KEYB_INTERR_RETVAL)
signal.signal(signal.SIGINT, signal_handler)
if hasattr(signal, 'SIGPIPE'):
signal.signal(signal.SIGPIPE, signal_handler)
def pprint(d: dict):
print(json.dumps(d, indent=4, sort_keys=True))
acd_client = None
cache = None
#
# Glue functions (API, cache)
#
class CacheConsts(object):
CHECKPOINT_KEY = 'checkpoint'
LAST_SYNC_KEY = 'last_sync'
MAX_AGE = 30
def sync_node_list(full=False, to_file=None, from_file=None) -> 'Union[int, None]':
global cache
cp_ = cache.KeyValueStorage.get(CacheConsts.CHECKPOINT_KEY) if not full else None
lst = cache.KeyValueStorage.get(CacheConsts.LAST_SYNC_KEY)
lst = float(lst) if lst else 0
wt = min(lst + MIN_SYNC_INTERVAL - time.time(), MIN_SYNC_INTERVAL)
if lst and wt > 0:
print('Last sync was very recent or has invalid date. Waiting %im %is.'
% (wt / 60, wt % 60))
time.sleep(wt)
print('Getting changes', end='', flush=True)
if from_file:
f = open(from_file, 'rb')
else:
f = acd_client.get_changes(checkpoint=cp_, include_purged=bool(cp_), silent=False,
file=to_file if to_file else None)
if to_file:
f.close()
return
try:
first = True
for changeset in acd_client._iter_changes_lines(f):
if to_file:
if first:
out = open(to_file, 'wb')
out.write(b'%s\n' % str(changeset))
continue
if changeset.reset or (full and first):
cache.drop_all()
cache.init()
full = True
else:
cache.remove_purged(changeset.purged_nodes)
if first:
print('Inserting nodes', end='', flush=True)
if len(changeset.nodes) > 0:
cache.insert_nodes(changeset.nodes, partial=not full)
cache.KeyValueStorage.update({CacheConsts.LAST_SYNC_KEY: time.time()})
if len(changeset.nodes) > 0 or len(changeset.purged_nodes) > 0:
cache.KeyValueStorage.update({CacheConsts.CHECKPOINT_KEY: changeset.checkpoint})
print('.', end='', flush=True)
first = False
except RequestError as e:
print(e)
if e.CODE == RequestError.CODE.INCOMPLETE_RESULT:
logger.warning('Sync incomplete.')
else:
logger.critical('Sync failed.')
return ERROR_RETVAL
finally:
if not first:
print()
if to_file:
out.close()
def old_sync() -> 'Union[int, None]':
global cache
cache.drop_all()
cache = db.NodeCache(CACHE_PATH)
try:
folders = acd_client.get_folder_list()
folders.extend(acd_client.get_trashed_folders())
files = acd_client.get_file_list()
files.extend(acd_client.get_trashed_files())
except RequestError as e:
logger.error(e)
logger.critical('Sync failed.')
return ERROR_RETVAL
cache.insert_nodes(files + folders, partial=False)
cache.KeyValueStorage['sync_date'] = time.time()
def partial_sync(path: str, recursive: bool) -> 'Union[int|None]':
path = '/' + '/'.join(list(filter(bool, path.split('/'))))
n = cache.resolve(path, trash=False)
fid = None
if n:
fid = n.id
n = acd_client.get_metadata(fid)
cache.insert_node(n)
else:
exc = None
try:
folder_chain = acd_client.resolve_folder_path(path)
except RequestError as e:
exc = e
if not folder_chain or exc:
if exc:
logger.error(e)
logger.critical('Could not resolve path "%s".' % path)
return INVALID_ARG_RETVAL
cache.insert_nodes(folder_chain)
fid = folder_chain[-1]['id']
try:
children = acd_client.list_children(fid)
if recursive:
recursive_insert(children)
else:
cache.insert_nodes(children)
except RequestError as e:
logger.error("Sync failed: %s" % e)
return ERROR_RETVAL
def recursive_insert(nodes: 'List[dict]'):
cache.insert_nodes(nodes)
for n in nodes:
if n['kind'] == 'FOLDER':
recursive_insert(acd_client.list_children(n['id']))
def autosync(interval: int, stop: Event = None):
"""Periodically syncs the node cache each *interval* seconds.
:param stop: Event that may be triggered to end syncing."""
if not interval:
return
interval = max(MIN_SYNC_INTERVAL, interval)
while True:
if stop.is_set():
break
try:
sync_node_list(full=False)
except:
import traceback
logger.error(traceback.format_exc())
time.sleep(interval)
#
# File transfer
#
RetryRetVal = namedtuple('RetryRetVal', ['ret_val', 'retry'])
STD_RETRY_RETVALS = [UL_DL_FAILED]
DL_RETRY_RETVALS = [UL_DL_FAILED, HASH_MISMATCH]
def retry_on(ret_vals: 'List[int]'):
"""Retry decorator that sets the wrapped function's progress handler argument according to its
return value and wraps the return value in RetryRetVal object.
:param ret_vals: list of retry values on which execution should be repeated"""
def wrap(f: 'Callable'):
def wrapped(*args, **kwargs) -> RetryRetVal:
ret_val = ERROR_RETVAL
try:
ret_val = f(*args, **kwargs)
except:
import traceback
logger.error(traceback.format_exc())
h = kwargs.get('pg_handler')
h.status = ret_val
retry = ret_val in ret_vals
if retry:
h.reset()
return RetryRetVal(ret_val, ret_val in ret_vals)
return wrapped
return wrap
#
# things to do on successful transfer
#
def compare_hashes(hash1: str, hash2: str, file_name: str) -> int:
if hash1 != hash2:
logger.error('Hash mismatch between local and remote file for "%s".' % file_name)
return HASH_MISMATCH
logger.debug('Local and remote hashes match for "%s".' % file_name)
return 0
def compare_sizes(size1: int, size2: int, file_name: str) -> int:
if size1 != size2:
logger.error('Size mismatch between local and remote file for "%s".' % file_name)
return SIZE_MISMATCH
logger.debug('Local and remote sizes match for "%s".' % file_name)
return 0
def remove_file(path: str) -> int:
try:
os.remove(path)
except OSError:
logger.error('Removing file "%s" failed.' % path)
return ERR_DEL_FILE
logger.debug('Deleted "%s".' % path)
return 0
def upload_complete(node: dict, path: str, hash_: str, size_: int, rsf: bool) -> int:
cache.insert_node(node)
node = cache.get_node(node['id'])
match = (compare_hashes(hash_, node.md5, path) |
compare_sizes(size_, node.size, path) if size_ is not None else 0)
if match != 0:
return match
if rsf:
return remove_file(path)
return 0
def upload_timeout(parent_id: str, path: str, hash_: str, size_: int, rsf: bool) -> int:
minutes = conf.getint('upload', 'timeout_wait')
while minutes > 0:
time.sleep(60)
minutes -= 1
l = acd_client.list_children(parent_id)
for n in l:
if os.path.basename(path) == n['name']:
return upload_complete(n, path, hash_, size_, rsf)
logger.warning('Timeout while uploading "%s".' % path)
return UL_TIMEOUT
def overwrite_timeout(initial_node: dict, path: str, hash_: str, size_: int, rsf: bool) -> int:
minutes = conf.getint('upload', 'timeout_wait')
while minutes > 0:
time.sleep(60)
minutes -= 1
n = acd_client.get_metadata(initial_node['id'])
if n['version'] > initial_node['version']:
return upload_complete(n, path, hash_, size_, rsf)
logger.warning('Timeout while overwriting "%s".' % path)
return UL_TIMEOUT
def download_complete(node: 'Node', path: str, hash_: str, rsf: bool):
md5_match = compare_hashes(node.md5, hash_, node.name)
if md5_match != 0:
if not conf.getboolean('download', 'keep_corrupt'):
return md5_match | remove_file(path)
else:
os.rename(path, '%s_%s' % (path, datetime.now().strftime(TIMESTAMP_FORMAT)))
return md5_match
size_match = compare_sizes(node.size, os.path.getsize(path), path)
if size_match != 0:
return size_match
if rsf:
try:
r = acd_client.move_to_trash(node.id)
cache.insert_node(r)
except RequestError as e:
print(e)
return ERROR_RETVAL
return 0
#
# Transfer job creation and actual transfer
#
def create_upload_jobs(dirs: list, path: str, parent_id: str, overwr: bool, force: bool,
dedup: bool, rsf: bool, exclude: list, exclude_paths: list, jobs: list) \
-> int:
"""Creates upload job if passed path is a file, delegates directory traversal otherwise.
Detects soft links that link to an already queued directory.
:param dirs: list of directories' inodes traversed so far
:param rsf: remove source files
:param exclude: list of file exclusion patterns
:param exclude_paths: list of paths for file or directory exclusion"""
if os.path.realpath(path) in [os.path.realpath(p) for p in exclude_paths]:
logger.info('Skipping upload of path "%s".' % path)
return 0
if not os.access(path, os.R_OK):
logger.error('Path "%s" is not accessible.' % path)
return INVALID_ARG_RETVAL
if os.path.isdir(path):
ino = os.stat(path).st_ino
if ino in dirs:
logger.warning('Duplicate directory detected: "%s".' % path)
return DUPLICATE_DIR
dirs.append(ino)
return traverse_ul_dir(dirs, path, parent_id, overwr, force, dedup,
rsf, exclude, exclude_paths, jobs)
elif os.path.isfile(path):
short_nm = os.path.basename(path)
for reg in exclude:
if re.match(reg, short_nm):
logger.info('Skipping upload of "%s" because of exclusion pattern.' % short_nm)
return 0
prog = progress.FileProgress(os.path.getsize(path))
fo = partial(upload_file, path, parent_id, overwr, force, dedup, rsf, pg_handler=prog)
jobs.append(fo)
return 0
else:
logger.warning('Skipping upload of "%s", possibly because it is a broken symlink.' % path)
return INVALID_ARG_RETVAL
def traverse_ul_dir(dirs: list, directory: str, parent_id: str, overwr: bool, force: bool,
dedup: bool, rsf: bool, exclude: list, exclude_paths: list, jobs: list) -> int:
"""Duplicates local directory structure."""
if parent_id is None:
parent_id = cache.get_root_id()
parent = cache.get_node(parent_id)
real_path = os.path.realpath(directory)
short_nm = os.path.basename(real_path)
curr_node = cache.get_child(parent_id, short_nm)
if not curr_node or not curr_node.is_available or not parent.is_available:
try:
r = acd_client.create_folder(short_nm, parent_id)
logger.info('Created folder "%s"' % (cache.first_path(parent.id) + short_nm))
cache.insert_node(r)
curr_node = cache.get_node(r['id'])
except RequestError as e:
if e.status_code == 409:
logger.error('Folder "%s" already exists. Please sync.' % short_nm)
else:
logger.error('Error creating remote folder "%s": %s.' % (short_nm, e))
return ERR_CR_FOLDER
elif curr_node.is_file:
logger.error('Cannot create remote folder "%s", '
'because a file of the same name already exists.' % short_nm)
return ERR_CR_FOLDER
try:
entries = sorted(os.listdir(directory))
except OSError as e:
logger.error('Skipping directory %s because of an error.' % directory)
logger.info(e)
return ERROR_RETVAL
ret_val = 0
for entry in entries:
full_path = os.path.join(real_path, entry)
ret_val |= create_upload_jobs(dirs, full_path, curr_node.id,
overwr, force, dedup, rsf, exclude, exclude_paths, jobs)
return ret_val
@retry_on(STD_RETRY_RETVALS)
def upload_file(path: str, parent_id: str, overwr: bool, force: bool, dedup: bool, rsf: bool,
pg_handler: progress.FileProgress = None) -> RetryRetVal:
short_nm = os.path.basename(path)
if dedup and cache.file_size_exists(os.path.getsize(path)):
nodes = cache.find_by_md5(hashing.hash_file(path))
nodes = [n for n in cache.path_format(nodes)]
if len(nodes) > 0:
logger.info('Skipping upload of duplicate file "%s". Location of duplicates: %s' % (short_nm, nodes))
pg_handler.done()
if rsf:
return remove_file(path)
return DUPLICATE
conflicting_node = cache.get_conflicting_node(short_nm, parent_id)
file_id = None
if conflicting_node:
if conflicting_node.name != short_nm:
logger.error('File name "%s" collides with remote node "%s".'
% (short_nm, conflicting_node.name))
return NAME_COLLISION
if conflicting_node.is_folder:
logger.error('Name collision with existing folder '
'in the same location: "%s".' % short_nm)
return NAME_COLLISION
file_id = conflicting_node.id
if not file_id:
logger.info('Uploading %s' % path)
hasher = hashing.IncrementalHasher()
local_size = os.path.getsize(path)
try:
r = acd_client.upload_file(path, parent_id,
read_callbacks=[hasher.update, pg_handler.update],
deduplication=dedup)
except RequestError as e:
if e.status_code == 409: # might happen if cache is outdated
if not dedup:
logger.error('Uploading "%s" failed. Name collision with non-cached file. '
'If you want to overwrite, please sync and try again.' % short_nm)
else:
logger.error(
'Uploading "%s" failed. '
'Name or hash collision with non-cached file.' % short_nm)
logger.info(e)
# colliding node ID is returned in error message -> could be used to continue
return CACHE_ASYNC
elif e.status_code == 504 or e.status_code == 408: # proxy timeout / request timeout
return upload_timeout(parent_id, path, hasher.get_result(), local_size, rsf)
else:
logger.error('Uploading "%s" failed. %s.' % (short_nm, str(e)))
return UL_DL_FAILED
else:
return upload_complete(r, path, hasher.get_result(), local_size, rsf)
# else: file exists
rmod = datetime_to_timestamp(conflicting_node.modified)
rmod = datetime.utcfromtimestamp(rmod)
lmod = datetime.utcfromtimestamp(os.path.getmtime(path))
lcre = datetime.utcfromtimestamp(os.path.getctime(path))
logger.debug('Remote mtime: %s, local mtime: %s, local ctime: %s' % (rmod, lmod, lcre))
if not overwr and not force:
logger.info('Skipping upload of existing file "%s".' % short_nm)
pg_handler.done()
if not rsf:
return 0
if not compare_sizes(os.path.getsize(path), conflicting_node.size, short_nm):
return remove_file(path)
logger.info('Keeping "%s" because of remote size mismatch.' % path)
return 0
# ctime is checked because files can be overwritten by files with older mtime
if rmod < lmod or (rmod < lcre and conflicting_node.size != os.path.getsize(path)) \
or force:
return overwrite(file_id, path, dedup=dedup, rsf=rsf, pg_handler=pg_handler).ret_val
elif not force:
logger.info('Skipping upload of "%s" because of mtime or ctime and size.' % short_nm)
pg_handler.done()
return 0
@retry_on(STD_RETRY_RETVALS)
def overwrite(node_id: str, local_file: str, dedup=False, rsf=False,
pg_handler: progress.FileProgress = None) -> RetryRetVal:
hasher = hashing.IncrementalHasher()
local_size = os.path.getsize(local_file)
initial_node = acd_client.get_metadata(node_id)
logger.info('Overwriting "%s" with "%s".' % (node_id, local_file))
try:
r = acd_client.overwrite_file(node_id, local_file,
read_callbacks=[hasher.update, pg_handler.update],
deduplication=dedup)
except RequestError as e:
if e.status_code == 504 or e.status_code == 408: # proxy timeout / request timeout
return overwrite_timeout(initial_node, local_file, hasher.get_result(), local_size, rsf)
logger.error('Error overwriting "%s". %s' % (node_id, str(e)))
return UL_DL_FAILED
else:
return upload_complete(r, local_file, hasher.get_result(), local_size, rsf)
@retry_on([])
def upload_stream(stream, file_name, parent_id, overwr=False, dedup=False,
pg_handler: progress.FileProgress = None) -> RetryRetVal:
hasher = hashing.IncrementalHasher()
child = cache.get_child(parent_id, file_name)
log_fname = 'stream/' + file_name
if child and not overwr:
logger.warning('Skipping streamed upload because file "%s" exists.' % file_name)
return 0
try:
if child:
initial_node = acd_client.get_metadata(child.id)
r = acd_client.overwrite_stream(stream, child.id,
read_callbacks=[hasher.update, pg_handler.update])
else:
r = acd_client.upload_stream(stream, file_name, parent_id,
read_callbacks=[hasher.update, pg_handler.update],
deduplication=dedup)
except RequestError as e:
if e.status_code == 504 or e.status_code == 408: # proxy timeout / request timeout
if child:
return overwrite_timeout(initial_node, log_fname, hasher.get_result(), None, False)
else:
return upload_timeout(parent_id, log_fname, hasher.get_result(), None, False)
logger.error('Error uploading stream. %s' % str(e))
return UL_DL_FAILED
else:
return upload_complete(r, log_fname, hasher.get_result(), None, False)
def create_dl_jobs(node_id: str, local_path: str, preserve_mtime: bool, rsf: bool,
exclude: 'List[re._pattern_type]', jobs: list) -> int:
"""Appends download partials for folder/file node pointed to by *node_id*
to the **jobs** list."""
local_path = local_path if local_path else ''
node = cache.get_node(node_id)
if not node.is_available:
return 0
if node.is_folder:
return traverse_dl_folder(node, local_path, preserve_mtime, rsf, exclude, jobs)
loc_name = node.name
for reg in exclude:
if re.match(reg, loc_name):
logger.info('Skipping download of "%s" because of exclusion pattern.' % loc_name)
return 0
flp = os.path.join(local_path, loc_name)
if os.path.isfile(flp):
logger.info('Skipping download of existing file "%s"' % loc_name)
if os.path.getsize(flp) != node.size:
logger.info('Skipped file "%s" has different size than local file.' % loc_name)
return SIZE_MISMATCH
return 0
prog = progress.FileProgress(node.size)
fo = partial(download_file, node_id, local_path, preserve_mtime, rsf, pg_handler=prog)
jobs.append(fo)
return 0
def traverse_dl_folder(node: 'Node', local_path: str, preserve_mtime: bool, rsf: bool,
exclude: 'List[re._pattern_type', jobs: list) -> int:
"""Duplicates remote folder structure."""
if not local_path:
local_path = os.getcwd()
if node.name is None:
curr_path = os.path.join(local_path, 'acd')
else:
curr_path = os.path.join(local_path, node.name)
try:
os.makedirs(curr_path, exist_ok=True)
except OSError:
logger.error('Error creating directory "%s".' % curr_path)
return ERR_CR_FOLDER
ret_val = 0
folders, files = cache.list_children(node.id)
folders, files = sorted(folders), sorted(files)
for file in files:
ret_val |= create_dl_jobs(file.id, curr_path, preserve_mtime, rsf, exclude, jobs)
for folder in folders:
ret_val |= traverse_dl_folder(folder, curr_path, preserve_mtime, rsf, exclude, jobs)
return ret_val
@retry_on(DL_RETRY_RETVALS)
def download_file(node_id: str, local_path: str, preserve_mtime: bool, rsf: bool,
pg_handler: progress.FileProgress = None) -> RetryRetVal:
node = cache.get_node(node_id)
name, md5, size = node.name, node.md5, node.size
logger.info('Downloading "%s".' % name)
hasher = hashing.IncrementalHasher()
try:
acd_client.download_file(node_id, name, local_path, length=size,
write_callbacks=[hasher.update, pg_handler.update])
except RequestError as e:
logger.error('Downloading "%s" failed. %s' % (name, str(e)))
return UL_DL_FAILED
else:
if preserve_mtime:
mtime = datetime_to_timestamp(node.modified)
os.utime(os.path.join(local_path, name), (mtime, mtime))
return download_complete(node, os.path.join(local_path, name), hasher.get_result(), rsf)
#
# Subparser actions. Return value Union[None, int] will be used as sys exit status.
#
# decorators
nocache_actions = []
offline_actions = []
no_autores_trash_actions = []
def nocache_action(func):
"""Decorator for actions that do not need to read from cache or autoresolve."""
nocache_actions.append(func)
return func
def offline_action(func):
"""Decorator for actions that can be performed without API calls."""
offline_actions.append(func)
return func
def no_autores_trash_action(func):
"""Decorator for actions that should not have trash paths auto-resolved."""
no_autores_trash_actions.append(func)
return func
# actual actions
def sync_action(args: argparse.Namespace):
ret = sync_node_list(args.full, args.to_file, args.from_file)
if cache.get_root_node() or args.to_file:
return ret
logger.error("Root node not found. Sync may have been incomplete.")
return ret if ret else 0 | ERROR_RETVAL
def old_sync_action(args: argparse.Namespace):
print('Syncing...')
r = old_sync()
if not r:
print('Done.')
return r
def partial_sync_action(args: argparse.Namespace):
print('Syncing...')
r = partial_sync(args.path, args.recursive)
if not r:
print('Done.')
return r
@nocache_action
@offline_action
def delete_everything_action(args: argparse.Namespace):
from distutils.util import strtobool
from shutil import rmtree
a = input('Do you really want to delete %s? [y/n] ' % CACHE_PATH)
try:
if strtobool(a):
rmtree(CACHE_PATH)
except ValueError:
pass
except OSError as e:
print(e)
print('Deleting directory failed.')
@nocache_action
@offline_action
def clear_action(args: argparse.Namespace):
if not db.NodeCache.remove_db_file(CACHE_PATH, SETTINGS_PATH):
return ERROR_RETVAL
@nocache_action
@offline_action
def print_version_action(args: argparse.Namespace):
print('%s %s, api %s ' % (_app_name, acdcli.__version__, acdcli.api.__version__))
@offline_action
def tree_action(args: argparse.Namespace):
node = cache.get_node(args.node)
if not node or not node.is_folder:
logger.critical('Invalid folder.')
return INVALID_ARG_RETVAL
for line in cache.tree_format(node, args.node_path, trash=args.include_trash,
dir_only=args.dir_only, max_depth=args.max_depth):
print(line)
@nocache_action
def usage_action(args: argparse.Namespace):
r = acd_client.get_account_usage()
print(r, end='')
@nocache_action
def quota_action(args: argparse.Namespace):
r = acd_client.get_quota()
pprint(r)
def regex_helper(args: argparse.Namespace) -> 'List[re._pattern_type]':
"""Pre-compiles regexes from strings in args namespace."""
excl_re = []
for re_ in args.exclude_re:
try:
excl_re.append(re.compile(re_, flags=re.IGNORECASE))
except re.error as e:
logger.critical('Invalid regular expression: %s. %s' % (re_, e))
sys.exit(INVALID_ARG_RETVAL)
for ending in args.exclude_fe:
excl_re.append(re.compile('^.*\.' + re.escape(ending) + '$', flags=re.IGNORECASE))
return excl_re
@no_autores_trash_action
def upload_action(args: argparse.Namespace) -> int:
if not cache.get_node(args.parent):
logger.critical('Invalid upload folder.')
return INVALID_ARG_RETVAL
excl_re = regex_helper(args)
jobs = []
ret_val = 0
for path in args.path:
if not os.path.exists(path):
logger.error('Path "%s" does not exist.' % path)
ret_val |= INVALID_ARG_RETVAL
continue
ret_val |= create_upload_jobs([], path, args.parent, args.overwrite, args.force,
args.deduplicate, args.remove_source_files,
excl_re, args.exclude_path, jobs)
ql = QueuedLoader(args.max_connections, args.print_progress, max_retries=args.max_retries)
ql.add_jobs(jobs)
return ret_val | ql.start()
@no_autores_trash_action
def upload_stream_action(args: argparse.Namespace) -> int:
if not cache.get_node(args.parent):
logger.critical('Invalid upload folder')
return INVALID_ARG_RETVAL
prog = progress.FileProgress(0)
ql = QueuedLoader(print_progress=args.print_progress, max_retries=0)
job = partial(upload_stream,
sys.stdin.buffer, args.name, args.parent, args.overwrite, args.deduplicate,
pg_handler=prog)
ql.add_jobs([job])
return ql.start()
def overwrite_action(args: argparse.Namespace) -> int:
if not os.path.isfile(args.file):
logger.error('Invalid file.')
return INVALID_ARG_RETVAL
prog = progress.FileProgress(os.path.getsize(args.file))
ql = QueuedLoader(print_progress=args.print_progress, max_retries=args.max_retries)
job = partial(overwrite, args.node, args.file, pg_handler=prog)
ql.add_jobs([job])
return ql.start()
def download_action(args: argparse.Namespace) -> int:
excl_re = regex_helper(args)
jobs = []
ret_val = 0
ret_val |= create_dl_jobs(args.node, args.path, args.times, args.remove_source_files,
excl_re, jobs)
ql = QueuedLoader(args.max_connections, args.print_progress, args.max_retries)
ql.add_jobs(jobs)
return ret_val | ql.start()
def cat_action(args: argparse.Namespace) -> int:
n = cache.get_node(args.node)
if not n or not n.is_file:
return INVALID_ARG_RETVAL
try:
acd_client.chunked_download(args.node, sys.stdout.buffer)
except RequestError as e:
logger.error('Downloading failed. %s' % str(e))
return UL_DL_FAILED
return 0
def mkdir(parent, name: str) -> bool:
"""Creates a folder and inserts it into cache upon success."""
if parent.is_file:
logger.error('Cannot create directory "%s". Parent is not a folder.' % name)
return False
parent_id = parent.id
cn = cache.get_conflicting_node(name, parent_id)
if cn:
if cn.is_file:
logger.error('Cannot create directory "%s". A file of that name already exists.' % name)
return False
if cn.name != name:
logger.error('Folder name "%s" collides with remote folder "%s".' % (name, cn.name))
return False
logger.warning('Folder "%s" already exists.' % name)
return True
try:
r = acd_client.create_folder(name, parent_id)
except RequestError as e:
if e.status_code == 409:
logger.warning('Node "%s" already exists. %s' % (name, str(e)))
return False
else:
logger.error('Error creating folder "%s". %s' % (name, str(e)))
return False
else:
cache.insert_node(r)
return True
def create_action(args: argparse.Namespace) -> int:
segments = [seg for seg in args.new_folder.split('/') if seg] # non-empty path segments
if not segments:
return
cur_path = '/'
parent = cache.get_root_node()
for s in segments[:-1]:
cur_path += s + '/'
child = cache.get_child(parent.id, s)
if child:
parent = child
continue