forked from IsmaeelAkram/icloud-linux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.py
More file actions
2163 lines (1954 loc) · 82.3 KB
/
Copy pathdriver.py
File metadata and controls
2163 lines (1954 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import atexit
import datetime
import errno
import hashlib
import json
import logging
import os
import signal
import shutil
import sqlite3
import stat
import sys
import tempfile
import threading
import time
from contextlib import closing
from collections import deque
from concurrent.futures import ThreadPoolExecutor
import fuse
import yaml
from fuse import Fuse
from pyicloud import PyiCloudService
from pyicloud.exceptions import (
PyiCloud2FARequiredException,
PyiCloud2SARequiredException,
PyiCloudAPIResponseException,
PyiCloudAuthRequiredException,
PyiCloudFailedLoginException,
)
from pyicloud.services.drive import DriveNode
if not hasattr(fuse, "__version__"):
fuse.__version__ = "0.2"
fuse.fuse_python_api = (0, 2)
ROOT_DRIVEWSID = "FOLDER::com.apple.CloudDocs::root"
DIRECTORY_NODE_TYPES = {"folder", "app_library"}
IO_CHUNK_SIZE = 1024 * 1024
class Stat(fuse.Stat):
def __init__(self):
self.st_mode = 0
self.st_ino = 0
self.st_dev = 0
self.st_nlink = 0
self.st_uid = 0
self.st_gid = 0
self.st_size = 0
self.st_atime = 0
self.st_mtime = 0
self.st_ctime = 0
class IgnoreIcdrsWarning(logging.Filter):
def filter(self, record):
return "ICDRS is not disabled; requestWebAccessState=" not in record.getMessage()
def parse_remote_time(value):
if not value:
return int(time.time())
try:
parsed = datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
except ValueError:
return int(time.time())
return int(calendar_timegm(parsed.timetuple()))
def calendar_timegm(timetuple):
return int(datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc).timestamp())
def sha256_file(path):
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def row_to_dict(row):
return dict(row) if row is not None else None
class NamedFileStream:
def __init__(self, handle, name):
self._handle = handle
self.name = name
def __getattr__(self, attr):
return getattr(self._handle, attr)
class SyncState:
def __init__(self, db_path):
self.db_path = db_path
os.makedirs(os.path.dirname(db_path), exist_ok=True)
self.lock = threading.RLock()
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._init_db()
def _init_db(self):
with self.lock:
self.conn.executescript(
"""
CREATE TABLE IF NOT EXISTS entries (
path TEXT PRIMARY KEY,
type TEXT NOT NULL,
parent_path TEXT NOT NULL,
remote_drivewsid TEXT,
remote_docwsid TEXT,
remote_etag TEXT,
remote_zone TEXT,
remote_shareid TEXT,
size INTEGER NOT NULL DEFAULT 0,
mtime INTEGER NOT NULL DEFAULT 0,
hydrated INTEGER NOT NULL DEFAULT 0,
dirty INTEGER NOT NULL DEFAULT 0,
tombstone INTEGER NOT NULL DEFAULT 0,
local_sha256 TEXT,
last_synced_at INTEGER,
synced_path TEXT
);
CREATE INDEX IF NOT EXISTS idx_entries_remote_drivewsid
ON entries(remote_drivewsid);
CREATE INDEX IF NOT EXISTS idx_entries_dirty
ON entries(dirty, tombstone);
CREATE TABLE IF NOT EXISTS pending_ops (
id INTEGER PRIMARY KEY AUTOINCREMENT,
op TEXT NOT NULL,
path TEXT NOT NULL,
target_path TEXT,
queued_at INTEGER NOT NULL,
retry_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT
);
"""
)
columns = {
row["name"]
for row in self.conn.execute("PRAGMA table_info(entries)").fetchall()
}
if "remote_shareid" not in columns:
self.conn.execute("ALTER TABLE entries ADD COLUMN remote_shareid TEXT")
self.conn.commit()
def upsert_entry(self, entry):
payload = {
"path": entry["path"],
"type": entry["type"],
"parent_path": entry["parent_path"],
"remote_drivewsid": entry.get("remote_drivewsid"),
"remote_docwsid": entry.get("remote_docwsid"),
"remote_etag": entry.get("remote_etag"),
"remote_zone": entry.get("remote_zone"),
"remote_shareid": self._encode_shareid(entry.get("remote_shareid")),
"size": int(entry.get("size", 0) or 0),
"mtime": int(entry.get("mtime", 0) or 0),
"hydrated": int(bool(entry.get("hydrated", False))),
"dirty": int(bool(entry.get("dirty", False))),
"tombstone": int(bool(entry.get("tombstone", False))),
"local_sha256": entry.get("local_sha256"),
"last_synced_at": entry.get("last_synced_at"),
"synced_path": entry.get("synced_path", entry["path"]),
}
with self.lock:
self.conn.execute(
"""
INSERT INTO entries (
path, type, parent_path, remote_drivewsid, remote_docwsid, remote_etag,
remote_zone, remote_shareid, size, mtime, hydrated, dirty, tombstone, local_sha256,
last_synced_at, synced_path
) VALUES (
:path, :type, :parent_path, :remote_drivewsid, :remote_docwsid, :remote_etag,
:remote_zone, :remote_shareid, :size, :mtime, :hydrated, :dirty, :tombstone, :local_sha256,
:last_synced_at, :synced_path
)
ON CONFLICT(path) DO UPDATE SET
type = excluded.type,
parent_path = excluded.parent_path,
remote_drivewsid = excluded.remote_drivewsid,
remote_docwsid = excluded.remote_docwsid,
remote_etag = excluded.remote_etag,
remote_zone = excluded.remote_zone,
remote_shareid = excluded.remote_shareid,
size = excluded.size,
mtime = excluded.mtime,
hydrated = excluded.hydrated,
dirty = excluded.dirty,
tombstone = excluded.tombstone,
local_sha256 = excluded.local_sha256,
last_synced_at = excluded.last_synced_at,
synced_path = excluded.synced_path
""",
payload,
)
self.conn.commit()
def get_entry(self, path):
with self.lock:
row = self.conn.execute(
"SELECT * FROM entries WHERE path = ?",
(path,),
).fetchone()
return self._decode_entry(row_to_dict(row))
def get_entry_by_remote_id(self, remote_drivewsid):
with self.lock:
row = self.conn.execute(
"SELECT * FROM entries WHERE remote_drivewsid = ?",
(remote_drivewsid,),
).fetchone()
return self._decode_entry(row_to_dict(row))
def list_entries(self):
with self.lock:
rows = self.conn.execute("SELECT * FROM entries ORDER BY path").fetchall()
return [self._decode_entry(dict(row)) for row in rows]
def count_entries(self):
with self.lock:
row = self.conn.execute("SELECT COUNT(*) AS count FROM entries").fetchone()
return int(row["count"])
def list_unhydrated_paths(self):
with self.lock:
rows = self.conn.execute(
"""
SELECT path FROM entries
WHERE type = 'file' AND tombstone = 0 AND hydrated = 0
ORDER BY path
"""
).fetchall()
return [row["path"] for row in rows]
def list_dirty_entries(self):
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM entries
WHERE dirty = 1 OR tombstone = 1
ORDER BY path
"""
).fetchall()
return [self._decode_entry(dict(row)) for row in rows]
def mark_hydrated(self, path, local_sha256=None, size=None, mtime=None):
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET hydrated = 1,
local_sha256 = COALESCE(?, local_sha256),
size = COALESCE(?, size),
mtime = COALESCE(?, mtime)
WHERE path = ?
""",
(local_sha256, size, mtime, path),
)
self.conn.commit()
def mark_dirty(self, path, size=None, mtime=None, hydrated=None, local_sha256=None):
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET dirty = 1,
tombstone = 0,
size = COALESCE(?, size),
mtime = COALESCE(?, mtime),
hydrated = COALESCE(?, hydrated),
local_sha256 = COALESCE(?, local_sha256)
WHERE path = ?
""",
(size, mtime, hydrated, local_sha256, path),
)
self.conn.commit()
def mark_tombstone(self, path):
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET tombstone = 1,
dirty = 1
WHERE path = ?
""",
(path,),
)
self.conn.commit()
def mark_clean(self, path, remote_meta=None, local_sha256=None):
remote_meta = remote_meta or {}
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET dirty = 0,
tombstone = 0,
hydrated = CASE
WHEN type = 'file' THEN hydrated
ELSE 1
END,
remote_drivewsid = COALESCE(?, remote_drivewsid),
remote_docwsid = COALESCE(?, remote_docwsid),
remote_etag = COALESCE(?, remote_etag),
remote_zone = COALESCE(?, remote_zone),
size = COALESCE(?, size),
mtime = COALESCE(?, mtime),
local_sha256 = COALESCE(?, local_sha256),
last_synced_at = ?,
synced_path = path
WHERE path = ?
""",
(
remote_meta.get("remote_drivewsid"),
remote_meta.get("remote_docwsid"),
remote_meta.get("remote_etag"),
remote_meta.get("remote_zone"),
remote_meta.get("size"),
remote_meta.get("mtime"),
local_sha256,
int(time.time()),
path,
),
)
self.conn.execute(
"DELETE FROM pending_ops WHERE path = ? OR target_path = ?",
(path, path),
)
self.conn.commit()
def remove_entry(self, path):
with self.lock:
self.conn.execute("DELETE FROM entries WHERE path = ?", (path,))
self.conn.execute(
"DELETE FROM pending_ops WHERE path = ? OR target_path = ?",
(path, path),
)
self.conn.commit()
def remove_subtree(self, path):
prefix = path.rstrip("/") + "/"
with self.lock:
self.conn.execute(
"DELETE FROM entries WHERE path = ? OR path LIKE ?",
(path, prefix + "%"),
)
self.conn.execute(
"DELETE FROM pending_ops WHERE path = ? OR path LIKE ? OR target_path = ? OR target_path LIKE ?",
(path, prefix + "%", path, prefix + "%"),
)
self.conn.commit()
def rename_tree(self, oldpath, newpath, root_dirty=True, update_synced=False):
entries = self._fetch_subtree(oldpath)
if not entries:
return
prefix = oldpath.rstrip("/") + "/"
with self.lock:
for entry in entries:
current = entry["path"]
suffix = "" if current == oldpath else current[len(prefix) :]
updated = newpath if not suffix else newpath.rstrip("/") + "/" + suffix
updated_parent = os.path.dirname(updated) or "/"
dirty = 1 if (root_dirty and current == oldpath) else entry["dirty"]
self.conn.execute(
"""
UPDATE entries
SET path = ?,
parent_path = ?,
dirty = ?,
synced_path = CASE
WHEN ? = 1 AND synced_path = ? THEN ?
WHEN ? = 1 AND synced_path LIKE ? THEN ? || substr(synced_path, ?)
ELSE synced_path
END
WHERE path = ?
""",
(
updated,
updated_parent,
dirty,
int(update_synced),
oldpath,
newpath,
int(update_synced),
prefix + "%",
newpath.rstrip("/") + "/",
len(prefix) + 1,
current,
),
)
self.conn.execute(
"""
UPDATE pending_ops
SET path = CASE
WHEN path = ? THEN ?
WHEN path LIKE ? THEN ? || substr(path, ?)
ELSE path
END,
target_path = CASE
WHEN target_path = ? THEN ?
WHEN target_path LIKE ? THEN ? || substr(target_path, ?)
ELSE target_path
END
""",
(
oldpath,
newpath,
prefix + "%",
newpath.rstrip("/") + "/",
len(prefix) + 1,
oldpath,
newpath,
prefix + "%",
newpath.rstrip("/") + "/",
len(prefix) + 1,
),
)
self.conn.commit()
def mark_synced_subtree(self, path):
prefix = path.rstrip("/") + "/"
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET synced_path = path,
dirty = CASE
WHEN path = ? THEN 0
ELSE dirty
END,
tombstone = CASE
WHEN path = ? THEN 0
ELSE tombstone
END,
last_synced_at = ?
WHERE path = ? OR path LIKE ?
""",
(path, path, int(time.time()), path, prefix + "%"),
)
self.conn.commit()
def detach_subtree_as_conflict(self, oldpath, newpath):
entries = self._fetch_subtree(oldpath)
if not entries:
return
prefix = oldpath.rstrip("/") + "/"
with self.lock:
for entry in entries:
current = entry["path"]
suffix = "" if current == oldpath else current[len(prefix) :]
updated = newpath if not suffix else newpath.rstrip("/") + "/" + suffix
updated_parent = os.path.dirname(updated) or "/"
self.conn.execute(
"""
UPDATE entries
SET path = ?,
parent_path = ?,
remote_drivewsid = NULL,
remote_docwsid = NULL,
remote_etag = NULL,
remote_zone = NULL,
remote_shareid = NULL,
synced_path = NULL,
dirty = 1,
tombstone = 0
WHERE path = ?
""",
(updated, updated_parent, current),
)
self.conn.commit()
def clear_remote_identity(self, path):
with self.lock:
self.conn.execute(
"""
UPDATE entries
SET remote_drivewsid = NULL,
remote_docwsid = NULL,
remote_etag = NULL,
remote_zone = NULL,
remote_shareid = NULL,
synced_path = NULL,
dirty = 1,
tombstone = 0
WHERE path = ?
""",
(path,),
)
self.conn.commit()
def queue_op(self, op, path, target_path=None):
now = int(time.time())
with self.lock:
if op == "delete":
existing_create = self.conn.execute(
"SELECT id FROM pending_ops WHERE path = ? AND op IN ('create', 'mkdir')",
(path,),
).fetchone()
if existing_create:
self.conn.execute("DELETE FROM pending_ops WHERE path = ?", (path,))
self.conn.commit()
return
self.conn.execute(
"""
INSERT INTO pending_ops (op, path, target_path, queued_at)
VALUES (?, ?, ?, ?)
""",
(op, path, target_path, now),
)
self.conn.commit()
def _fetch_subtree(self, path):
prefix = path.rstrip("/") + "/"
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM entries
WHERE path = ? OR path LIKE ?
ORDER BY LENGTH(path) ASC, path ASC
""",
(path, prefix + "%"),
).fetchall()
return [self._decode_entry(dict(row)) for row in rows]
def _encode_shareid(self, shareid):
if not shareid:
return None
return json.dumps(shareid, sort_keys=True)
def _decode_entry(self, entry):
if entry is None:
return None
shareid = entry.get("remote_shareid")
if isinstance(shareid, str) and shareid:
try:
entry["remote_shareid"] = json.loads(shareid)
except json.JSONDecodeError:
entry["remote_shareid"] = None
return entry
class LocalMirror:
def __init__(self, cache_dir):
self.cache_dir = cache_dir
self.root = os.path.join(cache_dir, "mirror")
self.tmp_dir = os.path.join(cache_dir, "tmp")
os.makedirs(self.root, exist_ok=True)
os.makedirs(self.tmp_dir, exist_ok=True)
def local_path(self, path):
normalized = os.path.normpath(path)
if normalized == ".":
normalized = "/"
if not normalized.startswith("/"):
normalized = "/" + normalized
relative = normalized.lstrip("/")
local = os.path.abspath(os.path.join(self.root, relative))
if local != self.root and not local.startswith(self.root + os.sep):
raise ValueError(f"Path escapes mirror root: {path}")
return local
def ensure_dir(self, path):
local = self.local_path(path)
if os.path.exists(local) and not os.path.isdir(local):
os.unlink(local)
os.makedirs(local, exist_ok=True)
def ensure_parent(self, path):
parent = os.path.dirname(path) or "/"
os.makedirs(self.local_path(parent), exist_ok=True)
def materialize_placeholder(self, path, size, mtime):
local = self.local_path(path)
self.ensure_parent(path)
if os.path.isdir(local):
shutil.rmtree(local)
with open(local, "wb") as handle:
handle.truncate(int(size or 0))
os.utime(local, (mtime, mtime))
def write_atomic_bytes(self, path, content, mtime=None):
self.ensure_parent(path)
local = self.local_path(path)
fd, tmp_path = tempfile.mkstemp(dir=self.tmp_dir)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(content)
os.replace(tmp_path, local)
if mtime is not None:
os.utime(local, (mtime, mtime))
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def write_atomic_stream(self, path, source, mtime=None, chunk_size=IO_CHUNK_SIZE):
self.ensure_parent(path)
local = self.local_path(path)
fd, tmp_path = tempfile.mkstemp(dir=self.tmp_dir)
try:
with os.fdopen(fd, "wb") as handle:
shutil.copyfileobj(source, handle, length=chunk_size)
os.replace(tmp_path, local)
if mtime is not None:
os.utime(local, (mtime, mtime))
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def read(self, path, size, offset):
local = self.local_path(path)
with open(local, "rb") as handle:
handle.seek(offset)
return handle.read(size)
def write(self, path, buf, offset):
self.ensure_parent(path)
local = self.local_path(path)
mode = "r+b" if os.path.exists(local) else "w+b"
with open(local, mode) as handle:
handle.seek(offset)
handle.write(buf)
handle.flush()
return len(buf)
def truncate(self, path, length):
self.ensure_parent(path)
local = self.local_path(path)
mode = "r+b" if os.path.exists(local) else "w+b"
with open(local, mode) as handle:
handle.truncate(length)
def create_file(self, path):
self.ensure_parent(path)
local = self.local_path(path)
with open(local, "ab"):
pass
def listdir(self, path):
return os.listdir(self.local_path(path))
def exists(self, path):
return os.path.exists(self.local_path(path))
def is_dir(self, path):
return os.path.isdir(self.local_path(path))
def remove_file(self, path):
os.unlink(self.local_path(path))
def remove_dir(self, path):
os.rmdir(self.local_path(path))
def remove_tree(self, path):
local = self.local_path(path)
if os.path.isdir(local):
shutil.rmtree(local)
elif os.path.exists(local):
os.unlink(local)
def rename_path(self, oldpath, newpath):
self.ensure_parent(newpath)
os.replace(self.local_path(oldpath), self.local_path(newpath))
def stat_local(self, path):
return os.lstat(self.local_path(path))
def statvfs(self):
return os.statvfs(self.root)
def set_mtime(self, path, mtime):
local = self.local_path(path)
os.utime(local, (mtime, mtime))
def file_sha256(self, path):
return sha256_file(self.local_path(path))
class ICloudSyncEngine:
def __init__(
self,
api,
mirror,
state,
logger,
warmup_mode="background",
conflict_mode="copy",
upload_interval_seconds=30,
remote_refresh_interval_seconds=300,
warmup_workers=1,
sync_paths=None,
exclude_paths=None,
auto_sync=True,
):
self.api = api
self.mirror = mirror
self.state = state
self.logger = logger
self.warmup_mode = warmup_mode if warmup_mode in {"background", "lazy"} else "background"
self.conflict_mode = conflict_mode if conflict_mode in {"copy"} else "copy"
self.upload_interval_seconds = upload_interval_seconds
self.remote_refresh_interval_seconds = remote_refresh_interval_seconds
self.warmup_workers = max(1, int(warmup_workers))
self.auto_sync = bool(auto_sync)
# Normalise sync_paths: list of /-prefixed strings, or None = allow all
if sync_paths:
self.sync_paths = [p if p.startswith('/') else '/' + p for p in sync_paths]
else:
self.sync_paths = None
# Normalise exclude_paths: deny-list applied before sync_paths
if exclude_paths:
self.exclude_paths = [p if p.startswith('/') else '/' + p for p in exclude_paths]
else:
self.exclude_paths = []
self.executor = ThreadPoolExecutor(max_workers=self.warmup_workers, thread_name_prefix="warmup")
self.stop_event = threading.Event()
self.refresh_now_event = threading.Event()
self.path_locks = {}
self.path_locks_lock = threading.Lock()
self.scheduled_downloads = set()
self.downloads_lock = threading.Lock()
self.download_retry_attempts = {}
self.download_retry_timers = {}
self.threads = []
self.hydration_total = 0
self.hydration_completed = 0
self.hydration_progress_lock = threading.Lock()
self.shutdown_lock = threading.Lock()
self.is_shutdown = False
# PyiCloud downloads appear sensitive to concurrent use of one session.
self.download_semaphore = threading.Semaphore(1)
def _log_sync(self, event, level=logging.INFO, **fields):
details = " ".join(f"{key}={value!r}" for key, value in fields.items() if value is not None)
if details:
self.logger.log(level, "sync %s %s", event, details)
return
self.logger.log(level, "sync %s", event)
def start(self):
if self.has_persistent_cache():
self.logger.info("Using persistent local cache from %s", self.mirror.root)
self._reconcile_persistent_cache()
if self.warmup_mode == "background":
self._schedule_all_unhydrated()
else:
self.logger.info("Persistent cache not initialized yet; performing first remote crawl")
self.initial_scan()
if self.warmup_mode == "background":
self._schedule_all_unhydrated()
if self.auto_sync:
self._start_background_threads()
else:
self.logger.info(
"auto_sync disabled — background upload/refresh threads not started. "
"Use 'icloudctl sync' to trigger a one-shot refresh on demand."
)
def _start_background_threads(self):
upload_thread = threading.Thread(target=self._upload_loop, name="icloud-upload", daemon=True)
refresh_thread = threading.Thread(target=self._refresh_loop, name="icloud-refresh", daemon=True)
upload_thread.start()
refresh_thread.start()
self.threads.extend([upload_thread, refresh_thread])
def shutdown(self):
with self.shutdown_lock:
if self.is_shutdown:
return
self.is_shutdown = True
self.stop_event.set()
self.refresh_now_event.set()
with self.downloads_lock:
timers = list(self.download_retry_timers.values())
self.download_retry_timers.clear()
self.scheduled_downloads.clear()
for timer in timers:
timer.cancel()
try:
self.executor.shutdown(wait=False, cancel_futures=True)
except TypeError:
self.executor.shutdown(wait=False)
for thread in list(self.threads):
thread.join(timeout=1)
def has_persistent_cache(self):
return self.state.count_entries() > 0 and os.path.isdir(self.mirror.root)
def initial_scan(self):
snapshot = self._crawl_remote_snapshot()
self._apply_remote_snapshot(snapshot)
def _reconcile_persistent_cache(self):
entries = self.state.list_entries()
missing_files = 0
recreated_dirs = 0
for entry in entries:
path = entry["path"]
if entry["tombstone"]:
continue
if self._is_directory_type(entry["type"]):
if not self.mirror.is_dir(path):
self.mirror.ensure_dir(path)
recreated_dirs += 1
continue
if self.mirror.exists(path):
stats = self.mirror.stat_local(path)
checksum = entry.get("local_sha256")
hydrated = bool(entry["hydrated"])
if entry["type"] == "file" and (hydrated or not entry["remote_drivewsid"]):
hydrated = True
# Only recompute the SHA256 if size or mtime changed since
# the last recorded sync — reading every file on startup is
# the cause of the 4-minute / 11 GB memory blowup at boot.
size_changed = stats.st_size != int(entry.get("size") or 0)
mtime_changed = int(stats.st_mtime) != int(entry.get("mtime") or 0)
if size_changed or mtime_changed or not checksum:
checksum = self.mirror.file_sha256(path)
self.state.upsert_entry(
{
**entry,
"size": stats.st_size,
"mtime": int(stats.st_mtime),
"hydrated": hydrated,
"local_sha256": checksum,
}
)
continue
missing_files += 1
if entry["remote_drivewsid"]:
self.mirror.materialize_placeholder(path, entry["size"], entry["mtime"])
self.state.upsert_entry({**entry, "hydrated": entry["size"] == 0})
else:
self.mirror.create_file(path)
stats = self.mirror.stat_local(path)
checksum = self.mirror.file_sha256(path)
self.state.upsert_entry(
{
**entry,
"size": stats.st_size,
"mtime": int(stats.st_mtime),
"hydrated": True,
"local_sha256": checksum,
}
)
self.logger.info(
"Persistent cache ready: %s entries, %s directories recreated, %s files queued for hydration",
len(entries),
recreated_dirs,
missing_files,
)
def _is_directory_type(self, node_type):
return (node_type or "").lower() in DIRECTORY_NODE_TYPES
def ensure_local_file(self, path):
if not self._path_allowed(path):
return
entry = self.state.get_entry(path)
if not entry or entry["type"] != "file" or entry["tombstone"]:
return
if entry["hydrated"] and self.mirror.exists(path):
return
lock = self._path_lock(path)
with lock:
entry = self.state.get_entry(path)
if not entry or entry["type"] != "file" or entry["tombstone"]:
return
if entry["hydrated"] and self.mirror.exists(path):
return
if not entry["remote_drivewsid"]:
self._log_sync("hydrate-local", level=logging.DEBUG, path=path)
if not self.mirror.exists(path):
self.mirror.create_file(path)
checksum = self.mirror.file_sha256(path)
stats = self.mirror.stat_local(path)
self.state.mark_hydrated(path, checksum, stats.st_size, int(stats.st_mtime))
self._log_sync(
"hydrate-complete",
level=logging.INFO,
path=path,
source="local",
size=stats.st_size,
)
return
self._log_sync(
"hydrate-start",
level=logging.INFO,
path=path,
drivewsid=entry.get("remote_drivewsid"),
size=entry.get("size"),
)
self.logger.debug("Hydrating %s", path)
with self.download_semaphore:
self.logger.debug(
"Hydrating file path=%s drivewsid=%s docwsid=%s zone=%s size=%s",
path,
entry.get("remote_drivewsid"),
entry.get("remote_docwsid"),
entry.get("remote_zone"),
entry.get("size"),
)
node = self._node_from_entry(entry)
with closing(node.open(stream=True)) as response:
self.mirror.write_atomic_stream(path, response.raw, entry["mtime"])
stats = self.mirror.stat_local(path)
checksum = self.mirror.file_sha256(path)
self.state.mark_hydrated(path, checksum, stats.st_size, int(stats.st_mtime))
self._log_sync("hydrate-complete", level=logging.INFO, path=path, source="remote", size=stats.st_size)
def _crawl_remote_snapshot(self):
self.logger.info("Starting remote metadata crawl")
snapshot = {}
queue = deque()
root = self.api.drive.root
queue.append((root, "/"))
started_at = time.time()
last_progress_log = started_at
scanned_folders = 0
_crawl_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="icloud-crawl")
FOLDER_TIMEOUT = 60 # seconds per folder before giving up
while queue:
node, path = queue.popleft()
scanned_folders += 1
try:
future = _crawl_executor.submit(node.get_children, True)
children = future.result(timeout=FOLDER_TIMEOUT)
except TimeoutError:
self.logger.warning(
"Timed out enumerating %s after %ss — skipping folder", path, FOLDER_TIMEOUT
)
continue
except Exception as exc:
self.logger.error("Failed to enumerate %s: %s", path, exc)
continue
for child in children:
child_path = "/" + child.name if path == "/" else path.rstrip("/") + "/" + child.name
meta = self._node_to_meta(child, child_path)
snapshot[meta["remote_drivewsid"]] = meta
if self._is_directory_type(meta["type"]):
# If sync_paths is set, only recurse into directories that are
# on the path to or inside a sync_path. This avoids crawling
# the entire iCloud Drive when only /Downloads is needed.
if self.sync_paths is not None:
should_recurse = False
for sp in self.sync_paths:
sp = sp.rstrip("/")
cp = child_path.rstrip("/")
# Recurse if child is a prefix of sync_path (ancestor)
# or if child is inside sync_path (descendant)
if sp.startswith(cp + "/") or sp == cp or cp.startswith(sp + "/"):
should_recurse = True
break
if not should_recurse:
continue
queue.append((child, child_path))
now = time.time()
if scanned_folders == 1 or scanned_folders % 25 == 0 or now - last_progress_log >= 5:
self.logger.info(
"Remote metadata crawl progress: %s folders scanned, %s entries discovered, %s folders queued",
scanned_folders,
len(snapshot),
len(queue),
)
last_progress_log = now
self.logger.info(
"Remote metadata crawl complete: %s entries across %s folders in %.1fs",
len(snapshot),
scanned_folders,
time.time() - started_at,
)
return snapshot
def _apply_remote_snapshot(self, snapshot):
remote_ids = set(snapshot.keys())
for meta in snapshot.values():
existing = self.state.get_entry_by_remote_id(meta["remote_drivewsid"])
if existing and existing["dirty"] and self._entry_conflicts(existing, meta):
self._resolve_conflict(existing)