-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdb.py
More file actions
executable file
·1739 lines (1441 loc) · 68.4 KB
/
Copy pathdb.py
File metadata and controls
executable file
·1739 lines (1441 loc) · 68.4 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
import logging
import sqlite3
import threading
from contextlib import contextmanager
from config import DB_PATH
log = logging.getLogger(__name__)
# Thread-local connection cache: one open SQLite handle per thread, reused for
# the lifetime of the thread. Eliminates the open/close churn on every query
# under heavy load (dashboard polling + scheduler + webhooks running together).
_tls = threading.local()
def _raw_connect() -> sqlite3.Connection:
conn = sqlite3.connect(DB_PATH, isolation_level=None, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=5000")
return conn
def _thread_conn() -> sqlite3.Connection:
conn = getattr(_tls, "conn", None)
if conn is None:
conn = _raw_connect()
_tls.conn = conn
return conn
@contextmanager
def _connect():
"""Yield a per-thread sqlite3 connection. We deliberately do NOT close it
on exit; the connection lives for the thread's lifetime."""
conn = _thread_conn()
try:
yield conn
except Exception:
try:
conn.execute("ROLLBACK")
except Exception:
pass
raise
_DDL = """
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
imdb_id TEXT NOT NULL UNIQUE,
media_type TEXT NOT NULL,
seasons TEXT,
status TEXT NOT NULL DEFAULT 'pending',
quality TEXT,
source TEXT,
info_hash TEXT,
error TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS monitored_series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imdb_id TEXT NOT NULL UNIQUE,
tmdb_id INTEGER,
title TEXT NOT NULL,
seasons TEXT,
status TEXT NOT NULL DEFAULT 'active',
last_checked TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS wanted_episodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imdb_id TEXT NOT NULL,
tmdb_id INTEGER,
title TEXT NOT NULL,
season INTEGER NOT NULL,
episode INTEGER NOT NULL,
air_date TEXT,
status TEXT NOT NULL DEFAULT 'wanted',
attempt_count INTEGER NOT NULL DEFAULT 0,
first_attempted TEXT,
last_attempted TEXT,
UNIQUE(imdb_id, season, episode)
);
CREATE TABLE IF NOT EXISTS media_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imdb_id TEXT NOT NULL,
title TEXT NOT NULL,
media_type TEXT NOT NULL DEFAULT 'movie',
seerr_request_id INTEGER,
requested_by TEXT,
requested_at TEXT,
status TEXT NOT NULL DEFAULT 'pending',
strm_found INTEGER NOT NULL DEFAULT 0,
last_checked TEXT,
UNIQUE(imdb_id, media_type)
);
CREATE TABLE IF NOT EXISTS cleanup_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ran_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
scanned INTEGER NOT NULL DEFAULT 0,
repaired INTEGER NOT NULL DEFAULT 0,
deleted INTEGER NOT NULL DEFAULT 0,
unfixable INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS activity_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event TEXT NOT NULL,
title TEXT,
message TEXT,
success INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS poster_cache (
imdb_id TEXT PRIMARY KEY,
poster_path TEXT,
cached_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS virtual_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT NOT NULL UNIQUE,
info_hash TEXT NOT NULL,
magnet TEXT NOT NULL,
title TEXT NOT NULL,
media_type TEXT NOT NULL,
strm_path TEXT,
torbox_id INTEGER,
file_id INTEGER,
last_played TEXT,
play_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS failed_hashes (
info_hash TEXT PRIMARY KEY,
fail_count INTEGER NOT NULL DEFAULT 1,
last_error TEXT,
last_attempt TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS webhook_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dedup_key TEXT NOT NULL UNIQUE,
received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS retry_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imdb_id TEXT NOT NULL,
title TEXT NOT NULL,
media_type TEXT NOT NULL,
seasons TEXT,
attempt INTEGER NOT NULL DEFAULT 0,
next_retry_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS show_quality_override (
imdb_id TEXT PRIMARY KEY,
quality_preference TEXT,
allow_4k INTEGER,
prefer_hevc INTEGER,
notes TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS metric_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
metric TEXT NOT NULL,
label TEXT,
value_int INTEGER,
value_real REAL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE TABLE IF NOT EXISTS repair_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cleanup_run_id INTEGER NOT NULL REFERENCES cleanup_runs(id),
path TEXT NOT NULL,
title TEXT,
media_type TEXT,
old_torrent_id TEXT,
new_info_hash TEXT,
status TEXT NOT NULL DEFAULT 'unknown',
reason TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_requests_imdb_unique ON requests(imdb_id);
CREATE INDEX IF NOT EXISTS idx_requests_status_created ON requests(status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_monitored_series_status ON monitored_series(status);
CREATE INDEX IF NOT EXISTS idx_wanted_status_attempts ON wanted_episodes(status, attempt_count);
CREATE INDEX IF NOT EXISTS idx_wanted_imdb ON wanted_episodes(imdb_id);
CREATE INDEX IF NOT EXISTS idx_media_items_status ON media_items(status);
CREATE INDEX IF NOT EXISTS idx_failed_hashes_failcount ON failed_hashes(fail_count);
CREATE INDEX IF NOT EXISTS idx_virtual_items_torbox ON virtual_items(torbox_id);
CREATE INDEX IF NOT EXISTS idx_virtual_items_lastplayed ON virtual_items(last_played);
CREATE INDEX IF NOT EXISTS idx_metric_events_metric_time ON metric_events(metric, created_at);
CREATE INDEX IF NOT EXISTS idx_metric_events_created ON metric_events(created_at);
CREATE INDEX IF NOT EXISTS idx_activity_log_created ON activity_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_webhook_events_received ON webhook_events(received_at);
CREATE INDEX IF NOT EXISTS idx_retry_queue_next ON retry_queue(next_retry_at);
CREATE INDEX IF NOT EXISTS idx_repair_items_run ON repair_items(cleanup_run_id, created_at DESC);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
quota_monthly INTEGER NOT NULL DEFAULT 0,
auto_approve INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
last_login TEXT
);
CREATE TABLE IF NOT EXISTS watchlist (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
imdb_id TEXT NOT NULL,
tmdb_id INTEGER,
media_type TEXT NOT NULL,
title TEXT NOT NULL,
poster_path TEXT,
added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
UNIQUE(user_id, imdb_id, media_type)
);
CREATE TABLE IF NOT EXISTS user_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
imdb_id TEXT NOT NULL,
tmdb_id INTEGER,
media_type TEXT NOT NULL,
title TEXT NOT NULL,
seasons TEXT,
status TEXT NOT NULL DEFAULT 'pending',
reviewed_by INTEGER,
reviewed_at TEXT,
note TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_watchlist_user ON watchlist(user_id);
CREATE INDEX IF NOT EXISTS idx_user_requests_user_status ON user_requests(user_id, status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_user_requests_status ON user_requests(status, created_at DESC);
CREATE TABLE IF NOT EXISTS wanted_movies (
imdb_id TEXT PRIMARY KEY,
tmdb_id INTEGER,
title TEXT NOT NULL,
reason TEXT,
attempts INTEGER NOT NULL DEFAULT 0,
added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
last_checked TEXT
);
CREATE TABLE IF NOT EXISTS playability_state (
content_key TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'unknown',
last_ok_provider TEXT,
last_ok_at TEXT,
last_fail_reason TEXT,
consecutive_failures INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_playability_status ON playability_state(status, updated_at);
CREATE TABLE IF NOT EXISTS createtorrent_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts REAL NOT NULL,
reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_createtorrent_ts ON createtorrent_log(ts);
"""
def init() -> None:
# PRAGMAs are applied in _raw_connect() on every new thread-local connection.
with _connect() as conn:
for stmt in _DDL.split(";"):
stmt = stmt.strip()
if stmt:
conn.execute(stmt)
_dedup_requests(conn)
conn.commit()
_migrate()
integrity_check()
def _dedup_requests(conn) -> None:
"""Remove duplicate imdb_id rows before the UNIQUE index is created."""
dupes = conn.execute(
"SELECT imdb_id, COUNT(*) AS cnt FROM requests "
"GROUP BY imdb_id HAVING cnt > 1"
).fetchall()
if not dupes:
return
for row in dupes:
ids = conn.execute(
"SELECT id FROM requests WHERE imdb_id=? ORDER BY created_at DESC",
(row["imdb_id"],),
).fetchall()
keep = ids[0]["id"]
conn.execute(
"DELETE FROM requests WHERE imdb_id=? AND id!=?",
(row["imdb_id"], keep),
)
conn.commit()
log.info("Dedup: removed duplicates for %d imdb_id(s) in requests", len(dupes))
def _migrate() -> None:
"""Lightweight additive migrations for columns added after first release."""
with _connect() as conn:
cols = {r["name"] for r in conn.execute("PRAGMA table_info(monitored_series)")}
if "monitor_mode" not in cols:
conn.execute("ALTER TABLE monitored_series ADD COLUMN monitor_mode TEXT NOT NULL DEFAULT 'all'")
log.info("Migration: added monitored_series.monitor_mode")
if "added_at_date" not in cols:
conn.execute("ALTER TABLE monitored_series ADD COLUMN added_at_date TEXT")
log.info("Migration: added monitored_series.added_at_date")
vi_cols = {r["name"] for r in conn.execute("PRAGMA table_info(virtual_items)")}
for col, typedef in [
("imdb_id", "TEXT"),
("quality", "TEXT"),
("source", "TEXT"),
("size_gb", "REAL"),
("season", "INTEGER"),
("episode", "INTEGER"),
("year", "INTEGER"),
("debrid_provider", "TEXT DEFAULT 'torbox'"),
("rd_id", "TEXT"),
("spore_tracks", "TEXT"),
]:
if col not in vi_cols:
try:
conn.execute(f"ALTER TABLE virtual_items ADD COLUMN {col} {typedef}")
log.info("Migration: added virtual_items.%s", col)
except Exception as _e:
log.warning("Migration: could not add virtual_items.%s: %s", col, _e)
req_cols = {r["name"] for r in conn.execute("PRAGMA table_info(requests)")}
if "tmdb_id" not in req_cols:
conn.execute("ALTER TABLE requests ADD COLUMN tmdb_id INTEGER")
log.info("Migration: added requests.tmdb_id")
conn.execute("""
UPDATE requests SET tmdb_id = (
SELECT COALESCE(w.tmdb_id, ms.tmdb_id, ur.tmdb_id)
FROM requests r2
LEFT JOIN watchlist w ON w.imdb_id = r2.imdb_id AND w.tmdb_id IS NOT NULL
LEFT JOIN monitored_series ms ON ms.imdb_id = r2.imdb_id AND ms.tmdb_id IS NOT NULL
LEFT JOIN user_requests ur ON ur.imdb_id = r2.imdb_id AND ur.tmdb_id IS NOT NULL
WHERE r2.id = requests.id
LIMIT 1
) WHERE tmdb_id IS NULL
""")
log.info("Migration: backfilled requests.tmdb_id from related tables")
user_cols = {r["name"] for r in conn.execute("PRAGMA table_info(users)")}
if "region" not in user_cols:
conn.execute("ALTER TABLE users ADD COLUMN region TEXT NOT NULL DEFAULT 'NL'")
log.info("Migration: added users.region")
if "library_click_jellyfin" not in user_cols:
conn.execute("ALTER TABLE users ADD COLUMN library_click_jellyfin INTEGER NOT NULL DEFAULT 0")
log.info("Migration: added users.library_click_jellyfin")
for col in ("discover_language_include", "discover_language_exclude"):
if col not in user_cols:
conn.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT NOT NULL DEFAULT ''")
log.info("Migration: added users.%s", col)
for col in ("mdblist_api_key", "mdblist_list_ids"):
if col not in user_cols:
conn.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT NOT NULL DEFAULT ''")
log.info("Migration: added users.%s", col)
# plugins/trakt owns trakt_watched (created by its own run_migrations(),
# which runs after this function via plugin_loader.load_all()). An earlier
# version of this migration also created a trakt_watched table with an
# incompatible schema (extra tmdb_id NOT NULL/season/episode columns, no
# UNIQUE(user_id, imdb_id)); since db.init() runs before plugin loading,
# that wrong-shaped table would win the CREATE TABLE IF NOT EXISTS race and
# the plugin's own inserts (ON CONFLICT(user_id, imdb_id)) would then fail.
# Drop it here if it's still in that shape so the plugin can recreate it
# correctly on next startup.
_cols = {r["name"] for r in conn.execute("PRAGMA table_info(trakt_watched)")}
if _cols and "season" in _cols:
conn.execute("DROP TABLE trakt_watched")
log.info("Migration: dropped trakt_watched (wrong schema from a removed "
"duplicate integration); plugins/trakt will recreate it correctly")
conn.execute("""
CREATE TABLE IF NOT EXISTS favorite_actors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
person_id INTEGER NOT NULL,
name TEXT NOT NULL,
profile_path TEXT,
added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now')),
UNIQUE(user_id, person_id)
)
""")
conn.commit()
def integrity_check() -> bool:
"""Run SQLite integrity_check. Logs warnings on failure, returns True if OK."""
try:
with _connect() as conn:
row = conn.execute("PRAGMA integrity_check").fetchone()
ok = bool(row) and (row[0] == "ok" or row["integrity_check"] == "ok")
if ok:
log.info("DB integrity: ok")
else:
log.error("DB integrity: %s", row)
return ok
except Exception as exc:
log.error("DB integrity check failed: %s", exc)
return False
def vacuum() -> None:
try:
with _connect() as conn:
conn.execute("VACUUM")
log.info("DB vacuum: done")
except Exception as exc:
log.warning("DB vacuum failed: %s", exc)
_PRUNE_TARGETS: dict[str, str] = {
# table_name : timestamp_column. Whitelist so the table name never comes from input.
"activity_log": "created_at",
"webhook_events": "received_at",
"metric_events": "created_at",
"playability_state": "updated_at",
}
def prune_old(days: int = 90) -> dict[str, int]:
"""Delete rows in volatile tables older than N days. Returns count per table.
Table names come from a hardcoded whitelist; only the day count is parameterized."""
if not isinstance(days, int) or days < 0:
raise ValueError("days must be a non-negative int")
out: dict[str, int] = {}
cutoff_modifier = f"-{days} days"
with _connect() as conn:
for tbl, ts_col in _PRUNE_TARGETS.items():
try:
cur = conn.execute(
f"DELETE FROM {tbl} WHERE {ts_col} < datetime('now', ?)",
(cutoff_modifier,),
)
out[tbl] = cur.rowcount or 0
except Exception as exc:
log.debug("prune %s failed: %s", tbl, exc)
out[tbl] = 0
conn.commit()
total = sum(out.values())
if total:
log.info("Pruned %d old row(s): %s", total, out)
return out
# ── requests ──────────────────────────────────────────────────────────────────
def insert_request(title: str, imdb_id: str, media_type: str, seasons: list[int] | None = None,
tmdb_id: int | None = None) -> int:
seasons_str = ",".join(str(s) for s in (seasons or []))
with _connect() as conn:
# cursor.lastrowid is unreliable here: on the ON CONFLICT/UPDATE path
# (i.e. every retry of an existing imdb_id) SQLite does NOT update
# last_insert_rowid(), so it can return a stale id left over from some
# unrelated row's last real INSERT on this connection. Look the row up
# explicitly instead of trusting lastrowid.
conn.execute(
"INSERT INTO requests (title, imdb_id, media_type, seasons, tmdb_id) VALUES (?, ?, ?, ?, ?) "
"ON CONFLICT(imdb_id) DO UPDATE SET "
"title=excluded.title, seasons=COALESCE(excluded.seasons, seasons), "
"tmdb_id=COALESCE(excluded.tmdb_id, tmdb_id), "
"updated_at=strftime('%Y-%m-%d %H:%M:%S', 'now')",
(title, imdb_id, media_type, seasons_str or None, tmdb_id),
)
row = conn.execute("SELECT id FROM requests WHERE imdb_id=?", (imdb_id,)).fetchone()
conn.commit()
return row["id"]
def update_request(row_id: int, status: str, quality: str | None = None,
source: str | None = None, info_hash: str | None = None,
error: str | None = None) -> None:
with _connect() as conn:
conn.execute(
"""UPDATE requests SET status=?, quality=?, source=?, info_hash=?, error=?,
updated_at=strftime('%Y-%m-%d %H:%M:%S','now') WHERE id=?""",
(status, quality, source, info_hash, error, row_id),
)
conn.commit()
def get_request_by_imdb(imdb_id: str) -> dict | None:
with _connect() as conn:
row = conn.execute(
"SELECT * FROM requests WHERE imdb_id=? ORDER BY created_at DESC LIMIT 1",
(imdb_id,)
).fetchone()
return dict(row) if row else None
def get_recent(limit: int = 100) -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM requests ORDER BY created_at DESC LIMIT ?", (limit,)
).fetchall()
return [dict(r) for r in rows]
def reconcile_wanted_movies() -> int:
"""Mark wanted movies as success if they already have a virtual_item (strm)."""
with _connect() as conn:
cur = conn.execute(
"UPDATE requests SET status='success' "
"WHERE status='wanted' AND media_type='movie' "
"AND EXISTS (SELECT 1 FROM virtual_items v "
"WHERE v.imdb_id=requests.imdb_id AND v.media_type='movie')"
)
conn.commit()
return cur.rowcount
def reconcile_wanted_episodes() -> int:
"""Mark wanted episodes as found if a matching strm file exists in virtual_items."""
import re as _re
_EP_RE = _re.compile(r'[Ss](\d{1,2})[Ee](\d{1,3})')
with _connect() as conn:
vis = conn.execute(
"SELECT imdb_id, strm_path FROM virtual_items "
"WHERE media_type='series' AND strm_path IS NOT NULL AND imdb_id IS NOT NULL"
).fetchall()
have: set[tuple[str, int, int]] = set()
for v in vis:
m = _EP_RE.search(v["strm_path"] or "")
if m:
have.add((v["imdb_id"], int(m.group(1)), int(m.group(2))))
if not have:
return 0
updated = 0
for imdb_id, season, episode in have:
cur = conn.execute(
"UPDATE wanted_episodes SET status='found' "
"WHERE imdb_id=? AND season=? AND episode=? AND status='wanted'",
(imdb_id, season, episode),
)
updated += cur.rowcount
conn.commit()
return updated
# ── monitored_series ──────────────────────────────────────────────────────────
def upsert_monitored_series(imdb_id: str, tmdb_id: int | None, title: str,
seasons: list[int], monitor_mode: str = "all") -> None:
seasons_str = ",".join(str(s) for s in seasons)
with _connect() as conn:
conn.execute(
"""INSERT INTO monitored_series (imdb_id, tmdb_id, title, seasons, monitor_mode, added_at_date)
VALUES (?, ?, ?, ?, ?, strftime('%Y-%m-%d','now'))
ON CONFLICT(imdb_id) DO UPDATE SET
tmdb_id=COALESCE(excluded.tmdb_id, tmdb_id),
title=excluded.title,
seasons=excluded.seasons,
monitor_mode=excluded.monitor_mode,
status='active'""",
(imdb_id, tmdb_id, title, seasons_str, monitor_mode),
)
conn.commit()
def get_monitored_series(status: str = "active") -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM monitored_series WHERE status=? ORDER BY title", (status,)
).fetchall()
return [dict(r) for r in rows]
def get_all_monitored_series() -> list[dict]:
with _connect() as conn:
rows = conn.execute("SELECT * FROM monitored_series ORDER BY title").fetchall()
return [dict(r) for r in rows]
def update_monitored_series(series_id: int, tmdb_id: int | None = None,
seasons: list[int] | None = None) -> None:
with _connect() as conn:
if tmdb_id is not None:
conn.execute("UPDATE monitored_series SET tmdb_id=? WHERE id=?", (tmdb_id, series_id))
if seasons is not None:
conn.execute("UPDATE monitored_series SET seasons=? WHERE id=?",
(",".join(str(s) for s in seasons), series_id))
conn.execute("UPDATE monitored_series SET last_checked=strftime('%Y-%m-%d %H:%M:%S','now') WHERE id=?",
(series_id,))
conn.commit()
# ── wanted_episodes ───────────────────────────────────────────────────────────
def upsert_wanted_episode(imdb_id: str, tmdb_id: int | None, title: str,
season: int, episode: int, air_date: str | None) -> None:
with _connect() as conn:
conn.execute(
"""INSERT INTO wanted_episodes (imdb_id, tmdb_id, title, season, episode, air_date)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(imdb_id, season, episode) DO UPDATE SET
air_date=COALESCE(excluded.air_date, air_date),
status=CASE WHEN status='found' THEN 'found' ELSE status END""",
(imdb_id, tmdb_id, title, season, episode, air_date),
)
conn.commit()
def get_wanted_episodes(max_attempts: int = 10) -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"""SELECT * FROM wanted_episodes
WHERE status='wanted' AND attempt_count < ?
ORDER BY title, season, episode""",
(max_attempts,),
).fetchall()
return [dict(r) for r in rows]
def get_series_folder_imdb_map() -> dict[str, str]:
"""Map series folder names to imdb_id via virtual_items strm_path."""
with _connect() as conn:
rows = conn.execute(
"SELECT DISTINCT imdb_id, strm_path FROM virtual_items "
"WHERE media_type='series' AND imdb_id IS NOT NULL AND strm_path IS NOT NULL"
).fetchall()
folder_map: dict[str, str] = {}
for r in rows:
parts = r["strm_path"].replace("\\", "/").split("/")
for i, p in enumerate(parts):
if p == "series" and i + 1 < len(parts):
folder_map[parts[i + 1].lower()] = r["imdb_id"]
break
return folder_map
def get_all_wanted_episodes() -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM wanted_episodes ORDER BY title, season, episode"
).fetchall()
return [dict(r) for r in rows]
def mark_episode_status(imdb_id: str, season: int, episode: int, status: str) -> None:
with _connect() as conn:
conn.execute(
"UPDATE wanted_episodes SET status=? WHERE imdb_id=? AND season=? AND episode=?",
(status, imdb_id, season, episode),
)
conn.commit()
def increment_episode_attempt(episode_id: int) -> None:
with _connect() as conn:
conn.execute(
"""UPDATE wanted_episodes SET
attempt_count = attempt_count + 1,
last_attempted = strftime('%Y-%m-%d %H:%M:%S','now'),
first_attempted = COALESCE(first_attempted, strftime('%Y-%m-%d %H:%M:%S','now'))
WHERE id=?""",
(episode_id,),
)
conn.commit()
# ── media_items ───────────────────────────────────────────────────────────────
def upsert_media_item(imdb_id: str, title: str, media_type: str,
seerr_request_id: int | None = None,
requested_by: str | None = None,
requested_at: str | None = None) -> None:
with _connect() as conn:
conn.execute(
"""INSERT INTO media_items (imdb_id, title, media_type, seerr_request_id,
requested_by, requested_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(imdb_id, media_type) DO UPDATE SET
title=excluded.title,
seerr_request_id=COALESCE(excluded.seerr_request_id, seerr_request_id),
requested_by=COALESCE(excluded.requested_by, requested_by),
requested_at=COALESCE(excluded.requested_at, requested_at)""",
(imdb_id, title, media_type, seerr_request_id, requested_by, requested_at),
)
conn.commit()
def update_media_item_status(imdb_id: str, media_type: str,
status: str, strm_found: bool = False) -> None:
with _connect() as conn:
conn.execute(
"""UPDATE media_items SET status=?, strm_found=?,
last_checked=strftime('%Y-%m-%d %H:%M:%S','now')
WHERE imdb_id=? AND media_type=?""",
(status, int(strm_found), imdb_id, media_type),
)
conn.commit()
def get_media_items(media_type: str | None = None) -> list[dict]:
with _connect() as conn:
if media_type:
rows = conn.execute(
"SELECT * FROM media_items WHERE media_type=? ORDER BY requested_at DESC",
(media_type,),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM media_items ORDER BY requested_at DESC"
).fetchall()
return [dict(r) for r in rows]
def get_unknown_media_items() -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM media_items WHERE imdb_id LIKE 'unknown_%'"
).fetchall()
return [dict(r) for r in rows]
def rekey_media_item(old_id: str, new_id: str, media_type: str) -> bool:
with _connect() as conn:
try:
cur = conn.execute(
"UPDATE media_items SET imdb_id=? WHERE imdb_id=? AND media_type=?",
(new_id, old_id, media_type),
)
conn.commit()
return cur.rowcount > 0
except sqlite3.IntegrityError:
conn.rollback()
# new_id already exists (UNIQUE conflict) - the unknown_ row is a duplicate;
# just delete it so the canonical entry remains. Only a real
# UNIQUE-constraint violation means this - any other exception
# (disk I/O, lock timeout) must not be treated the same way, or
# a transient error would silently delete data instead of
# surfacing the real problem.
try:
conn.execute(
"DELETE FROM media_items WHERE imdb_id=? AND media_type=?",
(old_id, media_type),
)
conn.commit()
return True
except Exception:
conn.rollback()
return False
# ── cleanup_runs ──────────────────────────────────────────────────────────────
def insert_cleanup_run() -> int:
with _connect() as conn:
cur = conn.execute("INSERT INTO cleanup_runs DEFAULT VALUES")
conn.commit()
return cur.lastrowid # type: ignore[return-value]
def update_cleanup_run(run_id: int, scanned: int, repaired: int,
deleted: int, unfixable: int) -> None:
with _connect() as conn:
conn.execute(
"UPDATE cleanup_runs SET scanned=?, repaired=?, deleted=?, unfixable=? WHERE id=?",
(scanned, repaired, deleted, unfixable, run_id),
)
conn.commit()
def get_last_cleanup_run() -> dict | None:
with _connect() as conn:
row = conn.execute(
"SELECT * FROM cleanup_runs ORDER BY id DESC LIMIT 1"
).fetchone()
return dict(row) if row else None
# ── repair_items ──────────────────────────────────────────────────────────────
def insert_repair_item(run_id: int, path: str, title: str | None, media_type: str | None,
old_torrent_id: str | None, new_info_hash: str | None,
status: str, reason: str | None) -> None:
with _connect() as conn:
conn.execute(
"""INSERT INTO repair_items
(cleanup_run_id, path, title, media_type, old_torrent_id, new_info_hash, status, reason)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(run_id, path, title, media_type, old_torrent_id, new_info_hash, status, reason),
)
conn.commit()
# ── activity_log ──────────────────────────────────────────────────────────────
def log_activity(event: str, title: str | None = None, message: str | None = None,
success: bool = True) -> None:
with _connect() as conn:
conn.execute(
"INSERT INTO activity_log (event, title, message, success) VALUES (?, ?, ?, ?)",
(event, title, message, int(success)),
)
conn.commit()
def get_activity(limit: int = 100) -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM activity_log ORDER BY id DESC LIMIT ?", (limit,)
).fetchall()
return [dict(r) for r in rows]
# ── poster_cache ──────────────────────────────────────────────────────────────
def get_poster(imdb_id: str) -> str | None:
with _connect() as conn:
row = conn.execute(
"SELECT poster_path FROM poster_cache WHERE imdb_id=?", (imdb_id,)
).fetchone()
return row["poster_path"] if row else None
def set_poster(imdb_id: str, poster_path: str | None) -> None:
with _connect() as conn:
conn.execute(
"""INSERT INTO poster_cache (imdb_id, poster_path) VALUES (?, ?)
ON CONFLICT(imdb_id) DO UPDATE SET poster_path=excluded.poster_path,
cached_at=strftime('%Y-%m-%d %H:%M:%S','now')""",
(imdb_id, poster_path),
)
conn.commit()
def get_posters_batch(imdb_ids: list[str]) -> dict[str, str | None]:
"""Return poster_path for each imdb_id from the poster_cache, as a dict."""
if not imdb_ids:
return {}
ph = ",".join("?" * len(imdb_ids))
with _connect() as conn:
rows = conn.execute(
f"SELECT imdb_id, poster_path FROM poster_cache WHERE imdb_id IN ({ph})",
imdb_ids,
).fetchall()
return {r["imdb_id"]: r["poster_path"] for r in rows}
# ── virtual_items (Catbox mode) ───────────────────────────────────────────────
def insert_virtual_item(token: str, info_hash: str, magnet: str, title: str,
media_type: str, strm_path: str | None = None,
torbox_id: int | None = None, file_id: int | None = None,
imdb_id: str | None = None, quality: str | None = None,
source: str | None = None, size_gb: float | None = None,
season: int | None = None, episode: int | None = None,
year: int | None = None) -> int:
with _connect() as conn:
cur = conn.execute(
"""INSERT INTO virtual_items
(token, info_hash, magnet, title, media_type, strm_path, torbox_id, file_id,
imdb_id, quality, source, size_gb, season, episode, year)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(token, info_hash, magnet, title, media_type, strm_path, torbox_id, file_id,
imdb_id, quality, source, size_gb, season, episode, year),
)
conn.commit()
return cur.lastrowid # type: ignore[return-value]
def update_virtual_item_upgrade(token: str, info_hash: str, magnet: str,
quality: str | None, source: str | None) -> None:
"""Swap in a better torrent for an existing virtual item (upgrade). Clears the
cached torbox_id and file_id so next playback re-materializes with new hash."""
with _connect() as conn:
conn.execute(
"""UPDATE virtual_items
SET info_hash=?, magnet=?, quality=?, source=?,
torbox_id=NULL, file_id=NULL
WHERE token=?""",
(info_hash, magnet, quality, source, token),
)
conn.commit()
def get_upgradeable_virtual_items() -> list[dict]:
"""Return movie virtual items that have a stored quality below 2160p."""
with _connect() as conn:
rows = conn.execute(
"""SELECT * FROM virtual_items
WHERE imdb_id IS NOT NULL AND media_type='movie'
ORDER BY created_at DESC"""
).fetchall()
ranks = {"2160p": 4, "1080p": 3, "720p": 2, "480p": 1}
return [dict(r) for r in rows if ranks.get((r["quality"] or "?"), 0) < 4]
def get_virtual_item(token: str) -> dict | None:
with _connect() as conn:
row = conn.execute("SELECT * FROM virtual_items WHERE token=?", (token,)).fetchone()
return dict(row) if row else None
def get_virtual_item_by_hash(info_hash: str) -> dict | None:
with _connect() as conn:
row = conn.execute(
"SELECT * FROM virtual_items WHERE info_hash=?", (info_hash.lower(),)
).fetchone()
return dict(row) if row else None
def get_virtual_items_by_hash(info_hash: str) -> list[dict]:
"""Return ALL virtual_items with this info_hash (movies: 1, season packs: N episodes)."""
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM virtual_items WHERE info_hash=?", (info_hash.lower(),)
).fetchall()
return [dict(r) for r in rows]
def get_unprobed_spore_items() -> list[dict]:
"""Return virtual_items that have a strm_path but no spore_tracks yet."""
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM virtual_items WHERE strm_path IS NOT NULL AND spore_tracks IS NULL"
).fetchall()
return [dict(r) for r in rows]
def get_all_virtual_items() -> list[dict]:
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM virtual_items ORDER BY last_played DESC, created_at DESC"
).fetchall()
return [dict(r) for r in rows]
def get_virtual_items_by_imdb(imdb_id: str, media_type: str | None = None) -> list[dict]:
with _connect() as conn:
if media_type:
rows = conn.execute(
"SELECT * FROM virtual_items WHERE imdb_id=? AND media_type=? ORDER BY created_at DESC",
(imdb_id, media_type),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM virtual_items WHERE imdb_id=? ORDER BY created_at DESC",
(imdb_id,),
).fetchall()
return [dict(r) for r in rows]
def get_virtual_item_by_episode(imdb_id: str, season: int, episode: int) -> dict | None:
"""Return the virtual_item for a specific series episode, or None if not registered."""
with _connect() as conn:
row = conn.execute(
"SELECT * FROM virtual_items WHERE imdb_id=? AND season=? AND episode=? LIMIT 1",
(imdb_id, season, episode),
).fetchone()
return dict(row) if row else None
def update_virtual_torbox_id(token: str, torbox_id: int | None) -> None:
with _connect() as conn:
conn.execute("UPDATE virtual_items SET torbox_id=? WHERE token=?", (torbox_id, token))
conn.commit()
def update_virtual_file_id(token: str, file_id: int) -> None: