Repository navigation
Expand file tree
/
Copy pathfilepodsync.py
More file actions
1909 lines (1636 loc) · 87 KB
/
Copy pathfilepodsync.py
File metadata and controls
1909 lines (1636 loc) · 87 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
"""
filepodsync.py — FilePodSync Client Library v1.3
=================================================
Provider-agnostic, file-based podcast synchronization.
Zero-API · LWW-EL merge · atomic writes · op-based queue · conflict-resistant.
Spec: agent.md v1.3 / README.md v1.3
Author: FilePodSync contributors
License: MIT
Changes from v1.2
-----------------
- Device ID persisted as plain UTF-8; json.dumps quoting bug eliminated.
- Queue ops carry device_id; sort key is (ts, device_id) for determinism.
- Queue reconstruction skips ops with ts <= consolidated_through_ts.
- Consolidation resets ONLY the local device's op file (sovereignty rule).
- consolidated_through_ts written to queue.json snapshot after consolidation.
- Log rotation driven by filename date, not filesystem mtime.
- _flush_queue_ops drains pending list atomically (swap before I/O).
- Snapshot restore preserves original per-record updated_at values.
- Bootstrap guards against resurrecting remotely-deleted feeds.
- _is_conflict_file covers Syncthing, Dropbox, Google Drive, iCloud.
- Device records carry status/updated_at/updated_by; retirement policy added.
- Schema version validated by integer major comparison, not string prefix.
- Unknown queue op types silently skipped (forward-compat).
- Unknown JSON fields preserved on read/write (forward-compat).
- sync() throttled by MIN_SYNC_INTERVAL_S; force=True bypasses.
- device_name, platform, client exposed as constructor params.
- redirect_feed_http_to_https() helper for 301-redirect handling.
- retire_stale_devices() and prune_retired_device_ops() added.
- Context manager support (__enter__/__exit__).
- Comprehensive smoke test expanded to cover all new behaviour.
"""
from __future__ import annotations
import gzip
import hashlib
import json
import logging
import os
import re
import threading
import time as _time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import unquote, urlparse, urlunparse
# ─────────────────────────────────────────────────────────────────────────────
# CONSTANTS
# ─────────────────────────────────────────────────────────────────────────────
SCHEMA_VERSION = "1.3.0"
SCHEMA_COMPATIBLE_MAJOR = 1 # int; reject files whose major differs
LOG_MAX_MB = 10
LOG_MAX_DAYS = 30
SNAPSHOT_RETENTION = 5
QUEUE_DEBOUNCE_S = 2.0
QUEUE_OPS_CONSOLIDATE_AT = 50
SKEW_WARNING_MS = 300_000 # 5 minutes
DEVICE_RETIREMENT_DAYS = 90
MIN_SYNC_INTERVAL_S = 5.0
_VALID_EPISODE_STATES = frozenset({"unplayed", "in_progress", "completed", "skipped"})
_VALID_FEED_STATUSES = frozenset({"active", "archived", "deleted"})
_VALID_HEALTH_STATUSES = frozenset({"healthy", "stale", "error"})
_VALID_DEVICE_STATUSES = frozenset({"active", "retired"})
# ─────────────────────────────────────────────────────────────────────────────
# LOGGING
# ─────────────────────────────────────────────────────────────────────────────
logger = logging.getLogger("filepodsync")
logger.setLevel(logging.INFO)
if not logger.handlers:
_h = logging.StreamHandler()
_h.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
logger.addHandler(_h)
# ─────────────────────────────────────────────────────────────────────────────
# PURE UTILITY FUNCTIONS
# ─────────────────────────────────────────────────────────────────────────────
def get_utc_ms() -> int:
"""Return the current UTC time in milliseconds since the Unix epoch."""
return int(datetime.now(timezone.utc).timestamp() * 1000)
def _atomic_write(path: Path, data: Any) -> None:
"""
Write *data* as JSON to *path* atomically.
Writes to ``<path>.tmp`` first, then renames. The .tmp file must live on
the same filesystem as the target so the rename is atomic (POSIX) or
best-effort (Windows).
**Do not use this for the device-ID file.** The device ID is a plain
string; calling json.dumps on it would wrap it in JSON quotes, producing
``"uuid-here"`` instead of ``uuid-here``. Use ``Path.write_text()``
directly for that file.
"""
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(
json.dumps(data, indent=2, ensure_ascii=False, default=str),
encoding="utf-8",
)
os.replace(str(tmp), str(path))
def _load_json_safe(path: Path, fallback: Any = None) -> Any:
"""Load a JSON file; return *fallback* on missing, corrupt, or I/O error."""
if not path.exists():
return fallback
try:
return json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, ValueError, OSError) as exc:
logger.warning("Failed to load %s: %s", path, exc)
return fallback
def _is_conflict_file(name: str) -> bool:
"""
Return True if *name* identifies a provider-generated conflict or temp file.
Patterns covered:
============ =============================================
Provider Pattern
============ =============================================
Syncthing ``.sync-conflict`` anywhere in name
Dropbox ``(conflicted copy)`` anywhere in name
Google Drive trailing `` (N).json`` / `` (N).jsonl``
iCloud ``(conflicted copy DATE)`` (same as Dropbox)
Any ends with ``.tmp`` or ``.partial``
Any starts with ``.`` (hidden / system)
============ =============================================
"""
low = name.lower()
return (
".sync-conflict" in low
or " (conflicted copy)" in low
or bool(re.search(r" \(\d+\)\.(json|jsonl)$", low))
or low.endswith(".tmp")
or low.endswith(".partial")
or name.startswith(".")
)
def _normalize_url(url: str) -> str:
"""
Normalize a feed URL for use as a stable dictionary key.
Rules (spec §feeds.json URL Normalization):
1. Lowercase scheme and host.
2. Remove default ports (``:80`` for http, ``:443`` for https).
3. Decode percent-encoding in the path.
4. Remove a trailing ``/`` from the path (unless path is just ``/``).
5. Preserve query string and fragment.
``http://`` and ``https://`` variants are distinct keys.
Returns ``""`` for an empty or un-parseable input.
"""
if not url:
return ""
p = urlparse(url.strip())
scheme = p.scheme.lower()
netloc = p.netloc.lower()
if ":" in netloc:
host, port = netloc.rsplit(":", 1)
if (scheme == "http" and port == "80") or (scheme == "https" and port == "443"):
netloc = host
path = unquote(p.path)
if path.endswith("/") and len(path) > 1:
path = path[:-1]
return urlunparse((scheme, netloc, path, "", p.query, p.fragment))
def _generate_episode_id(guid: Optional[str], url: str) -> str:
"""
Generate a stable, cross-client episode identifier.
Priority:
1. RSS ``<guid>`` — ``"guid:<stripped_guid>"``
2. URL hash — ``"url:<sha256(normalized_url)[:16]>"``
"""
if guid and guid.strip().lower() not in ("", "none"):
return f"guid:{guid.strip()}"
return f"url:{hashlib.sha256(_normalize_url(url).encode()).hexdigest()[:16]}"
def _validate_schema_version(data: Dict, label: Any) -> bool:
"""
Validate *data*'s ``schema_version`` field against SCHEMA_COMPATIBLE_MAJOR.
Uses integer comparison on the major component — never a string-prefix
check — so ``"1.99.0"`` is accepted and ``"2.0.0"`` is rejected cleanly.
"""
raw = data.get("schema_version", "")
if not raw:
logger.warning("Missing schema_version in %s", label)
return False
try:
major = int(str(raw).split(".")[0])
except (ValueError, IndexError):
logger.warning("Un-parseable schema_version %r in %s", raw, label)
return False
if major != SCHEMA_COMPATIBLE_MAJOR:
logger.error(
"Schema major-version mismatch in %s: found %s, "
"compatible major is %d — file rejected",
label, raw, SCHEMA_COMPATIBLE_MAJOR,
)
return False
return True
# ─────────────────────────────────────────────────────────────────────────────
# LWW-EL MERGE
# ─────────────────────────────────────────────────────────────────────────────
def _merge_records(local: Dict[str, Dict], remote: Dict[str, Dict]) -> Dict[str, Dict]:
"""
Last-Write-Wins at Element Level merge for feeds / episodes / devices maps.
Winner per key:
1. Higher ``updated_at`` wins.
2. Tie: lexicographically larger ``updated_by`` UUID wins (deterministic).
The file-level wrapper ``updated_at`` is **never** consulted here.
Unknown fields inside records are preserved verbatim (forward-compat).
"""
merged: Dict[str, Dict] = dict(local)
for key, rrec in remote.items():
lrec = local.get(key)
if lrec is None:
merged[key] = rrec
continue
r_ts = rrec.get("updated_at", 0)
l_ts = lrec.get("updated_at", 0)
if r_ts > l_ts:
merged[key] = rrec
elif r_ts == l_ts and rrec.get("updated_by", "") > lrec.get("updated_by", ""):
merged[key] = rrec
return merged
# ─────────────────────────────────────────────────────────────────────────────
# QUEUE OPERATION HELPERS
# ─────────────────────────────────────────────────────────────────────────────
def _apply_queue_op(items: List[Dict], op: Dict) -> List[Dict]:
"""
Apply one queue operation to *items* and return the updated list.
Unknown ``op`` values are silently skipped for forward-compatibility
with future op types.
"""
op_type = op.get("op")
if op_type == "add":
new_items = list(op.get("items", []))
after_id = op.get("after_id")
if after_id is None:
return items + new_items
try:
idx = next(i for i, it in enumerate(items) if it.get("ep_id") == after_id)
return items[: idx + 1] + new_items + items[idx + 1 :]
except StopIteration:
return items + new_items # after_id not found → append
elif op_type == "remove":
rm = set(op.get("ids", []))
return [it for it in items if it.get("ep_id") not in rm]
elif op_type == "reorder":
order_map = {eid: i for i, eid in enumerate(op.get("ids", []))}
mentioned = sorted(
[it for it in items if it.get("ep_id") in order_map],
key=lambda it: order_map[it["ep_id"]],
)
rest = [it for it in items if it.get("ep_id") not in order_map]
return mentioned + rest
elif op_type == "clear":
return []
else:
logger.warning("Unknown queue op type %r — skipping (forward-compat)", op_type)
return items
def _rebuild_queue(
snapshot: Optional[Dict],
ops_dir: Path,
) -> Tuple[List[Dict], int]:
"""
Reconstruct the canonical queue from a snapshot and per-device op logs.
Algorithm
---------
1. Start with ``snapshot["items"]`` (or ``[]`` if absent).
2. Read ``consolidated_through_ts`` from the snapshot (default ``0``).
3. Collect all ops from every non-conflict ``.jsonl`` file in *ops_dir*
whose ``ts`` is **strictly greater** than ``consolidated_through_ts``.
4. Sort collected ops by ``(ts, device_id)`` — deterministic on ties.
5. Apply ops in order.
Returns
-------
``(items, max_applied_ts)`` where *max_applied_ts* is the highest ``ts``
among ops that were actually applied. The caller uses this to set
``consolidated_through_ts`` when writing a new snapshot.
"""
snap = snapshot or {}
items: List[Dict] = list(snap.get("items", []))
cutoff_ts: int = snap.get("consolidated_through_ts", 0)
ops: List[Dict] = []
if ops_dir.exists():
for f in ops_dir.iterdir():
if not f.is_file() or f.suffix != ".jsonl":
continue
if _is_conflict_file(f.name):
continue
try:
for raw_line in f.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line:
continue
op = json.loads(line)
if op.get("ts", 0) > cutoff_ts:
ops.append(op)
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Failed to parse queue ops in %s: %s", f, exc)
# Deterministic sort: primary key ts, secondary key device_id
ops.sort(key=lambda o: (o.get("ts", 0), o.get("device_id", "")))
max_ts = cutoff_ts
for op in ops:
items = _apply_queue_op(items, op)
max_ts = max(max_ts, op.get("ts", 0))
return items, max_ts
# ─────────────────────────────────────────────────────────────────────────────
# MAIN CLIENT CLASS
# ─────────────────────────────────────────────────────────────────────────────
class FilePodSync:
"""
FilePodSync client v1.3.
Manages local podcast state, syncs it with a shared folder, and exposes a
clean API for subscribing, tracking playback, and managing the play queue.
Thread-safety
-------------
All public methods that touch state acquire ``self._lock`` (RLock).
The queue-debounce timer runs on a daemon thread; it uses an atomic
list-swap to avoid double-write races when shutdown() is called
concurrently.
Usage
-----
::
fps = FilePodSync("/path/to/sync-folder", device_name="My Laptop")
fps.add_feed("https://feeds.example.com/podcast", "Example Pod")
ep = fps.update_episode("https://…/ep1.mp3", "https://feeds.example.com/podcast",
guid="ep-001", state="in_progress", position=600)
fps.queue_add(ep)
fps.sync()
fps.shutdown()
Or as a context manager::
with FilePodSync("/path/to/sync-folder") as fps:
fps.sync()
"""
def __init__(
self,
sync_dir: str,
device_name: str = "FilePodSync Client",
platform: str = "python",
client: str = "filepodsync",
) -> None:
self.sync_dir = Path(sync_dir)
self.device_name = device_name
self.platform = platform
self.client = client
self.sync_dir.mkdir(parents=True, exist_ok=True)
# Load (or generate) the persistent device UUID *before* init_structure
# so the device record is stamped correctly on first run.
self.device_id: str = self._load_device_id()
self._lock = threading.RLock()
# Debounce state for queue writes
self._queue_debounce_timer: Optional[threading.Timer] = None
self._pending_queue_ops: List[Dict] = []
# Three-state sync architecture
# _synced_state = last successfully written full state
# _pending_local_ops = feed/episode mutations not yet in a sync cycle
self._synced_state: Dict[str, Any] = {}
self._pending_local_ops: List[Dict] = []
# Throttle: monotonic clock of the last completed sync()
self._last_sync_at: float = 0.0
self._init_structure()
self._synced_state = self._load_state()
logger.info(
"FilePodSync v%s initialized | device=%s | dir=%s",
SCHEMA_VERSION, self.device_id, self.sync_dir,
)
# ─────────────────────────────────────────────────────────────────────────
# DEVICE ID
# ─────────────────────────────────────────────────────────────────────────
def _load_device_id(self) -> str:
"""
Load or generate the persistent device UUID.
Stored as a **plain UTF-8 text file** — never via ``json.dumps``.
``json.dumps`` on a bare string adds surrounding double-quotes, which
would make the stored value ``"uuid-here"`` and cause every downstream
comparison to include the literal quote characters.
Migration guard: if the file was written by a v1.2 client with the
quoting bug, the surrounding quotes are stripped and a warning is
logged so the operator knows to verify ``devices.json``.
"""
id_file = self.sync_dir / ".fps_device_id"
if id_file.exists():
raw = id_file.read_text(encoding="utf-8").strip()
if raw.startswith('"') and raw.endswith('"'):
raw = raw[1:-1]
logger.warning(
"Device ID was JSON-quoted (v1.2 bug); stripped quotes. "
"Value: %s. If devices.json contains quoted UUIDs, "
"delete .fps_device_id and re-initialize to get a clean ID.",
raw,
)
return raw
new_id = str(uuid.uuid4())
id_file.write_text(new_id, encoding="utf-8") # plain text — no json.dumps
logger.info("Generated new device ID: %s", new_id)
return new_id
# ─────────────────────────────────────────────────────────────────────────
# INITIALIZATION
# ─────────────────────────────────────────────────────────────────────────
def _init_structure(self) -> None:
"""
Create the folder skeleton and write missing state files with defaults.
Existing files are never overwritten; only absent ones are created.
"""
for sub in ("logs", "snapshots", "queue_ops"):
(self.sync_dir / sub).mkdir(exist_ok=True)
defaults: Dict[str, Dict] = {
"config": {
"schema_version": SCHEMA_VERSION,
"sync_interval_ms": 1_800_000,
"capabilities": {
"queue_sync": True,
"tag_sync": False,
"snapshot_sync": True,
"dead_feed_tracking": True,
},
"rotation": {
"log_max_days": LOG_MAX_DAYS,
"log_max_mb": LOG_MAX_MB,
"snapshot_retention": SNAPSHOT_RETENTION,
"queue_ops_consolidate_at": QUEUE_OPS_CONSOLIDATE_AT,
},
},
"devices": {
"schema_version": SCHEMA_VERSION,
"updated_at": 0,
"updated_by": "",
"devices": {},
},
"feeds": {
"schema_version": SCHEMA_VERSION,
"updated_at": 0,
"updated_by": "",
"feeds": {},
},
"episodes": {
"schema_version": SCHEMA_VERSION,
"updated_at": 0,
"updated_by": "",
"episodes": {},
},
"queue": {
"schema_version": SCHEMA_VERSION,
"updated_at": 0,
"updated_by": "",
"consolidated_through_ts": 0,
"items": [],
},
}
for fname, default in defaults.items():
path = self.sync_dir / f"{fname}.json"
if not path.exists():
_atomic_write(path, default)
def _load_state(self) -> Dict[str, Any]:
"""Load all five state files from disk into memory."""
state: Dict[str, Any] = {}
for fname in ("config", "devices", "feeds", "episodes", "queue"):
state[fname] = _load_json_safe(self.sync_dir / f"{fname}.json", {})
return state
# ─────────────────────────────────────────────────────────────────────────
# INTERNAL HELPERS
# ─────────────────────────────────────────────────────────────────────────
def _validate_schema(self, data: Dict, path: Path) -> bool:
return _validate_schema_version(data, path)
def _wrap_meta(self, payload: Any, key: str, extra: Optional[Dict] = None) -> Dict:
"""Wrap a data payload with standard file-level metadata."""
wrapper: Dict[str, Any] = {
"schema_version": SCHEMA_VERSION,
"updated_at": get_utc_ms(),
"updated_by": self.device_id,
key: payload,
}
if extra:
wrapper.update(extra)
return wrapper
def _save_state_file(
self,
fname: str,
data: Any,
extra: Optional[Dict] = None,
) -> None:
"""
Atomically write one state file and update the in-memory synced state.
*extra* allows injecting additional top-level fields (e.g.
``consolidated_through_ts`` for queue.json).
"""
key = "items" if fname == "queue" else fname
wrapped = self._wrap_meta(data, key, extra)
_atomic_write(self.sync_dir / f"{fname}.json", wrapped)
self._synced_state[fname] = wrapped
def _detect_clock_skew(self, remote_state: Dict) -> None:
"""Warn if local and remote active timestamps differ significantly."""
local_max = max(
(self._synced_state.get(f, {}).get("updated_at", 0)
for f in ("feeds", "episodes", "devices", "queue")),
default=0,
)
remote_max = max(
(remote_state.get(f, {}).get("updated_at", 0)
for f in ("feeds", "episodes", "devices", "queue")),
default=0,
)
# Solo advertir si ambos lados tienen actividad reciente (últimas 24h)
# y sus timestamps máximos difieren significativamente.
now = get_utc_ms()
day_ms = 86_400_000
if (local_max > now - day_ms and remote_max > now - day_ms and
local_max and remote_max and
abs(local_max - remote_max) > SKEW_WARNING_MS):
logger.warning(
"Clock skew detected: local_max=%d remote_max=%d diff=%dms — "
"LWW results may be incorrect during skew window",
local_max, remote_max, abs(local_max - remote_max),
)
# ─────────────────────────────────────────────────────────────────────────
# SNAPSHOT RECOVERY
# ─────────────────────────────────────────────────────────────────────────
def _restore_from_snapshot(self, fname: str) -> Dict:
"""
Restore a corrupted state file from the most recent snapshot.
**Critical:** per-record ``updated_at`` values are preserved verbatim.
Do *not* re-stamp records with the current time; that would cause
restored stale data to win LWW conflicts against other devices' more
recent writes on the next sync cycle.
"""
snap_dir = self.sync_dir / "snapshots"
if not snap_dir.exists():
return {}
snaps = sorted(
snap_dir.glob("snapshot-*.json.gz"),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
for snap in snaps:
try:
with gzip.open(snap, "rt", encoding="utf-8") as fh:
data = json.load(fh)
recovered = data.get(fname, {})
if recovered:
logger.info("Restored %s from snapshot %s", fname, snap.name)
return recovered # original timestamps preserved
except (gzip.BadGzipFile, json.JSONDecodeError, OSError):
continue
logger.warning("Could not restore %s from any snapshot; using empty state", fname)
return {}
# ─────────────────────────────────────────────────────────────────────────
# DEVICE REGISTRY
# ─────────────────────────────────────────────────────────────────────────
def _stamp_own_device(self, devices: Dict[str, Dict]) -> Dict[str, Dict]:
"""
Upsert this device's record with current ``last_seen`` and ``status``.
Preserves ``first_seen`` from any existing record.
"""
now = get_utc_ms()
existing = devices.get(self.device_id, {})
devices[self.device_id] = {
"name": self.device_name,
"platform": self.platform,
"client": self.client,
"status": "active",
"first_seen": existing.get("first_seen", now),
"last_seen": now,
"updated_by": self.device_id,
"updated_at": now,
}
return devices
def retire_stale_devices(self) -> List[str]:
"""
Mark devices not seen in ``DEVICE_RETIREMENT_DAYS`` days as ``"retired"``.
The change is written to ``devices.json`` immediately.
Returns the list of retired device UUIDs.
"""
with self._lock:
devices = self._synced_state.get("devices", {}).get("devices", {})
now = get_utc_ms()
cutoff = now - DEVICE_RETIREMENT_DAYS * 86_400_000
retired = []
for dev_id, rec in devices.items():
if dev_id == self.device_id:
continue
if rec.get("status") == "retired":
continue
if rec.get("last_seen", now) < cutoff:
rec["status"] = "retired"
rec["updated_by"] = self.device_id
rec["updated_at"] = now
retired.append(dev_id)
if retired:
self._save_state_file("devices", devices)
logger.info("Retired %d stale device(s): %s", len(retired), retired)
return retired
def prune_retired_device_ops(self) -> List[str]:
"""
Delete op files for ``"retired"`` devices whose every op has already
been folded into the queue snapshot (i.e. ``max_ts_in_file <=
consolidated_through_ts``).
Returns the list of pruned filenames.
"""
with self._lock:
devices = self._synced_state.get("devices", {}).get("devices", {})
ctt = self._synced_state.get("queue", {}).get("consolidated_through_ts", 0)
ops_dir = self.sync_dir / "queue_ops"
pruned: List[str] = []
for dev_id, rec in devices.items():
if rec.get("status") != "retired":
continue
ops_file = ops_dir / f"{dev_id}.jsonl"
if not ops_file.exists():
continue
try:
raw_lines = [
l for l in ops_file.read_text(encoding="utf-8").splitlines()
if l.strip()
]
if not raw_lines:
ops_file.unlink(missing_ok=True)
pruned.append(ops_file.name)
continue
max_in_file = max(
json.loads(l).get("ts", 0) for l in raw_lines
)
if max_in_file <= ctt:
ops_file.unlink(missing_ok=True)
pruned.append(ops_file.name)
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Could not inspect %s for pruning: %s", ops_file, exc)
if pruned:
logger.info("Pruned retired-device op files: %s", pruned)
return pruned
# ─────────────────────────────────────────────────────────────────────────
# PUBLIC API — FEEDS
# ─────────────────────────────────────────────────────────────────────────
def add_feed(self, url: str, title: str = "", custom: Optional[Dict] = None) -> bool:
"""
Subscribe to a feed.
The URL is normalized before storage. If the same normalized URL
already exists, the record is updated (title, status reset to
``"active"``) while preserving ``added_by`` and ``added_at``.
Returns ``False`` if the URL normalizes to an empty string.
"""
with self._lock:
norm = _normalize_url(url)
if not norm:
logger.warning("add_feed: empty or invalid URL %r — ignored", url)
return False
feeds = self._synced_state.get("feeds", {}).get("feeds", {})
now = get_utc_ms()
existing = feeds.get(norm, {})
feeds[norm] = {
"url": norm,
"title": title or existing.get("title", ""),
"status": "active",
"health_status": existing.get("health_status", "healthy"),
"last_check": existing.get("last_check", 0),
"error_count": 0,
"added_by": existing.get("added_by", self.device_id),
"added_at": existing.get("added_at", now),
"updated_by": self.device_id,
"updated_at": now,
"custom": {**existing.get("custom", {}), **(custom or {})},
}
self._save_state_file("feeds", feeds)
self._log_event("feed_add", {"url": norm, "title": title})
return True
def remove_feed(self, url: str, archive: bool = False) -> bool:
"""
Soft-delete (``status="deleted"``) or archive (``status="archived"``) a feed.
Returns ``False`` if the normalized URL is not found.
Note: deleted feeds are **retained** in ``feeds.json`` so the deletion
propagates to every other device on the next sync.
"""
with self._lock:
norm = _normalize_url(url)
feeds = self._synced_state.get("feeds", {}).get("feeds", {})
if norm not in feeds:
logger.warning("remove_feed: URL not found: %s", norm)
return False
feeds[norm]["status"] = "archived" if archive else "deleted"
feeds[norm]["updated_by"] = self.device_id
feeds[norm]["updated_at"] = get_utc_ms()
self._save_state_file("feeds", feeds)
self._log_event("feed_remove", {"url": norm, "archived": archive})
return True
def update_feed_health(
self,
url: str,
health_status: str,
error_count: int = 0,
) -> bool:
"""
Record a dead-feed-tracking update for *url*.
``health_status`` must be one of ``"healthy"``, ``"stale"``, ``"error"``.
Returns ``False`` if the feed is not found or the status value is invalid.
"""
with self._lock:
if health_status not in _VALID_HEALTH_STATUSES:
logger.warning("update_feed_health: invalid status %r", health_status)
return False
norm = _normalize_url(url)
feeds = self._synced_state.get("feeds", {}).get("feeds", {})
if norm not in feeds:
return False
now = get_utc_ms()
feeds[norm].update({
"health_status": health_status,
"error_count": error_count,
"last_check": now,
"updated_by": self.device_id,
"updated_at": now,
})
self._save_state_file("feeds", feeds)
return True
def redirect_feed_http_to_https(self, http_url: str) -> bool:
"""
Handle a permanent HTTP→HTTPS redirect (HTTP 301) for a feed.
Marks the ``http://`` entry as ``"deleted"`` and ensures the
``https://`` variant exists as ``"active"``, copying metadata
from the old record. Both keys are written atomically.
Returns ``False`` if *http_url* does not normalize to an ``http://``
URL.
"""
with self._lock:
http_norm = _normalize_url(http_url)
if not http_norm.startswith("http://"):
logger.warning(
"redirect_feed_http_to_https: URL does not use http: %s", http_norm
)
return False
https_norm = "https://" + http_norm[len("http://"):]
feeds = self._synced_state.get("feeds", {}).get("feeds", {})
now = get_utc_ms()
source = feeds.get(http_norm, {})
# Retire the http:// entry
if http_norm in feeds:
feeds[http_norm]["status"] = "deleted"
feeds[http_norm]["updated_by"] = self.device_id
feeds[http_norm]["updated_at"] = now
# Ensure the https:// entry exists (promote from old record)
if https_norm not in feeds:
feeds[https_norm] = {
"url": https_norm,
"title": source.get("title", ""),
"status": "active",
"health_status": "healthy",
"last_check": 0,
"error_count": 0,
"added_by": source.get("added_by", self.device_id),
"added_at": source.get("added_at", now),
"updated_by": self.device_id,
"updated_at": now,
"custom": source.get("custom", {}),
}
self._save_state_file("feeds", feeds)
self._log_event("feed_redirect", {"from": http_norm, "to": https_norm})
return True
# ─────────────────────────────────────────────────────────────────────────
# PUBLIC API — EPISODES
# ─────────────────────────────────────────────────────────────────────────
def update_episode(
self,
episode_url: str,
feed_url: str,
guid: Optional[str] = None,
title: str = "",
position: int = 0,
total: int = 0,
state: str = "unplayed",
custom: Optional[Dict] = None,
) -> str:
"""
Create or update an episode record.
``position`` is stored **exactly** — no ``max()`` clamping. Rewinding
to an earlier position is a valid operation (spec §Rewinding progress).
``feed_url`` is informative, not normative: when the same GUID appears
in multiple feeds (cross-posted content), LWW-EL determines which
``feed_url`` survives.
Returns the stable episode ID (e.g. ``"guid:episode-001"``).
"""
with self._lock:
ep_id = _generate_episode_id(guid, episode_url)
eps = self._synced_state.get("episodes", {}).get("episodes", {})
now = get_utc_ms()
if ep_id not in eps:
eps[ep_id] = {
"feed_url": _normalize_url(feed_url),
"guid": guid.strip() if guid else None,
"url": episode_url,
"title": title,
"state": state if state in _VALID_EPISODE_STATES else "unplayed",
"progress_seconds": position,
"duration_seconds": total,
"updated_by": self.device_id,
"updated_at": now,
"custom": custom or {},
}
else:
rec = eps[ep_id]
rec["progress_seconds"] = position # exact — no clamping
if total > 0:
rec["duration_seconds"] = total
if state in _VALID_EPISODE_STATES:
rec["state"] = state
if title:
rec["title"] = title
if custom:
rec["custom"] = {**rec.get("custom", {}), **custom}
rec["updated_by"] = self.device_id
rec["updated_at"] = now
self._save_state_file("episodes", eps)
self._log_event("ep_update", {
"ep_id": ep_id, "state": state, "position": position,
})
return ep_id
# ─────────────────────────────────────────────────────────────────────────
# PUBLIC API — QUEUE (Op-Based)
# ─────────────────────────────────────────────────────────────────────────
def queue_add(self, ep_id: str, after_id: Optional[str] = None) -> None:
"""
Enqueue *ep_id*, optionally after *after_id*.
If *after_id* is ``None``, the episode is appended to the end.
The write is debounced by ``QUEUE_DEBOUNCE_S`` seconds.
"""
now = get_utc_ms()
self._pending_queue_ops.append({
"ts": now,
"device_id": self.device_id,
"op": "add",
"items": [{"ep_id": ep_id, "added_at": now}],
"after_id": after_id,
})
self._debounce_queue_flush()
def queue_remove(self, ep_ids: List[str]) -> None:
"""Remove all *ep_ids* from the queue (debounced)."""
self._pending_queue_ops.append({
"ts": get_utc_ms(),
"device_id": self.device_id,
"op": "remove",
"ids": ep_ids,
})
self._debounce_queue_flush()
def queue_reorder(self, ep_ids: List[str]) -> None:
"""
Reorder the queue so that items appear in *ep_ids* order.
Items not listed in *ep_ids* retain their relative order and move
to the end. Concurrent reorders from different devices are resolved
by ``(ts, device_id)`` — the later one wins.
"""
self._pending_queue_ops.append({
"ts": get_utc_ms(),
"device_id": self.device_id,
"op": "reorder",
"ids": ep_ids,
})
self._debounce_queue_flush()
def queue_clear(self) -> None:
"""Remove all items from the queue (debounced)."""
self._pending_queue_ops.append({
"ts": get_utc_ms(),
"device_id": self.device_id,
"op": "clear",
})
self._debounce_queue_flush()
def _debounce_queue_flush(self) -> None:
"""Reset (or start) the debounce timer for queue writes."""
if self._queue_debounce_timer:
self._queue_debounce_timer.cancel()
t = threading.Timer(QUEUE_DEBOUNCE_S, self._flush_queue_ops)
t.daemon = True
t.start()