-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2341 lines (2062 loc) · 92.8 KB
/
Copy pathapp.py
File metadata and controls
2341 lines (2062 loc) · 92.8 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 concurrent.futures
import json
import os
import re
import shutil
import subprocess
import threading
import time
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from http.server import ThreadingHTTPServer
from pathlib import Path
from data_manager_config import *
from data_manager_inventory import empty_inventory, scan_media_files
from data_manager_jobs import get_job, start_background_job, update_job
from data_manager_media import *
from data_manager_store import *
from data_manager_utils import *
from data_manager_server import Handler, configure_server, sso_health_check
from data_manager_views import configure_views
scan_event = threading.Event()
inventory_lock = threading.Lock()
pushover_lock = threading.Lock()
pushover_validation_cache = {"checked_at": 0, "settings_key": "", "result": None}
malware_lock = threading.Lock()
malware_definition_cache = {"checked_at": 0, "ok": False, "detail": "Not checked yet"}
clamav_slot_condition = threading.Condition()
clamav_active_scans = 0
tmdb_lock = threading.Lock()
tmdb_validation_cache = {"checked_at": 0, "settings_key": "", "movie": None, "tv": None}
tvmaze_lock = threading.Lock()
tvmaze_cache = {}
tvmaze_backoff_until = 0
preflight_lock = threading.Lock()
preflight_state = {"logged_at": 0, "message": ""}
watch_inventory_cache = {
"total": 0,
"supported": 0,
"ignored_exts": {},
"samples": [],
"updated_at": "Never",
}
library_visibility_lock = threading.Lock()
library_visibility_cache = {}
def get_queue():
settings = get_settings()
stable_seconds = max(0, int(settings.get("stable_seconds", "30") or "30"))
display_limit = int_setting(settings, "max_queue_display", MAX_QUEUE_DISPLAY, minimum=1, maximum=500)
now = time.time()
with db_lock, db() as conn:
rows = conn.execute(
"select * from seen_files where processed = 0 order by first_seen limit ?",
(display_limit,),
).fetchall()
queue = []
for row in rows:
remaining = max(0, int(stable_seconds - (now - row["first_seen"])))
reason = row["reason"] or "Waiting to be scanned"
if row["stage"] == "queued" and remaining:
reason = f"Waiting {remaining}s for file to stay stable before processing"
item = {**dict(row), "remaining_seconds": remaining, "reason": reason}
item["display_file"] = Path(row["path"]).name
queue.append(item)
return queue
def stats():
settings = get_settings()
display_limit = int_setting(settings, "max_queue_display", MAX_QUEUE_DISPLAY, minimum=1, maximum=500)
with db_lock, db() as conn:
totals = conn.execute(
"select media_type, status, count(*) as total from events group by media_type, status"
).fetchall()
queued = conn.execute("select count(*) as total from seen_files where processed = 0").fetchone()
active = conn.execute("select count(*) as total from seen_files where processed = 0 and stage != 'queued'").fetchone()
watch_inventory = get_watch_inventory_cache()
result = {
"movie": {"done": 0, "error": 0},
"tv": {"done": 0, "error": 0},
"queued": queued["total"],
"active": active["total"],
"display_limit": display_limit,
"hidden_queue": max(0, queued["total"] - display_limit),
"watch_visible": watch_inventory["supported"],
"watch_total": watch_inventory["total"],
"watch_inventory_updated_at": watch_inventory["updated_at"],
}
for row in totals:
result.setdefault(row["media_type"], {})
result[row["media_type"]][row["status"]] = row["total"]
return result
def get_watch_inventory_cache():
with inventory_lock:
return {
"total": watch_inventory_cache["total"],
"supported": watch_inventory_cache["supported"],
"ignored_exts": dict(watch_inventory_cache["ignored_exts"]),
"samples": list(watch_inventory_cache["samples"]),
"updated_at": watch_inventory_cache["updated_at"],
}
def update_watch_inventory_cache(inventory):
with inventory_lock:
watch_inventory_cache.update({
"total": inventory["total"],
"supported": inventory["supported"],
"ignored_exts": dict(inventory["ignored_exts"]),
"samples": list(inventory["samples"]),
"updated_at": now_iso(),
})
def count_watch_files(settings):
return watch_file_inventory(settings)["supported"]
def watch_file_inventory(settings):
watch_folder = Path(settings["watch_folder"])
inventory = {"total": 0, "supported": 0, "ignored_exts": {}, "samples": []}
if not watch_folder.exists():
return inventory
exts = extension_set(settings)
for path in watch_folder.rglob("*"):
if not path.is_file():
continue
inventory["total"] += 1
suffix = path.suffix.lower() or "(none)"
if suffix in exts:
inventory["supported"] += 1
else:
inventory["ignored_exts"][suffix] = inventory["ignored_exts"].get(suffix, 0) + 1
if len(inventory["samples"]) < 5:
inventory["samples"].append(str(path))
return inventory
def inventory_message(inventory, settings):
ignored = ", ".join(
f"{ext}: {count}" for ext, count in sorted(inventory["ignored_exts"].items())
) or "none"
samples = "; ".join(inventory["samples"]) or "none"
return (
f"Watch scan at {settings['watch_folder']}: "
f"{inventory['total']} total files, {inventory['supported']} supported media files. "
f"Ignored extensions: {ignored}. Samples: {samples}"
)
def int_setting(settings, key, default, minimum=1, maximum=None):
try:
value = int(settings.get(key, str(default)) or default)
except (TypeError, ValueError):
value = default
value = max(minimum, value)
if maximum is not None:
value = min(maximum, value)
return value
def requeue_watch_files():
settings = get_settings()
watch_folder = Path(settings["watch_folder"])
if not watch_folder.exists():
add_event("system", "error", watch_folder, message="Cannot requeue: watch folder does not exist")
return 0
inventory = watch_file_inventory(settings)
update_watch_inventory_cache(inventory)
exts = extension_set(settings)
now = time.time()
stable_seconds = max(0, int(settings.get("stable_seconds", "30") or "30"))
ready_time = now - stable_seconds - 1
max_requeue = int_setting(settings, "max_requeue_per_click", MAX_REQUEUE_PER_CLICK, minimum=1, maximum=5000)
count = 0
with db_lock, db() as conn:
for path in watch_folder.rglob("*"):
if not path.is_file() or path.suffix.lower() not in exts:
continue
if count >= max_requeue:
break
stat = path.stat()
conn.execute(
"""
insert into seen_files
(path, size, mtime, first_seen, processed, stage, reason, transfer_progress, transferred_bytes, total_bytes)
values (?, ?, ?, ?, 0, 'queued', ?, 0, 0, 0)
on conflict(path) do update set
size = excluded.size,
mtime = excluded.mtime,
first_seen = excluded.first_seen,
processed = 0,
stage = 'queued',
reason = excluded.reason,
media_type = null,
planned_name = null,
target_path = null,
last_error = null,
transfer_progress = 0,
transferred_bytes = 0,
total_bytes = 0
""",
(str(path), stat.st_size, stat.st_mtime, ready_time, "Manually requeued and ready for processing"),
)
count += 1
conn.commit()
add_event(
"system",
"stage_queued",
watch_folder,
message=(
f"Manually requeued {count} watch files for immediate processing "
f"(limit {max_requeue} per click). {inventory_message(inventory, settings)}"
),
)
scan_event.set()
return count
def dashboard_health():
settings = get_settings()
checks = [
access_control_health_check(settings),
sso_health_check(settings),
tmdb_health_check(settings),
tmdb_tv_health_check(settings),
ffprobe_health_check(),
clamav_health_check(settings),
pushover_health_check(settings),
path_health_check("Watch mount", settings["watch_folder"], needs_write=True),
path_health_check("Movie mount", settings["movie_folder"], needs_write=True),
path_health_check("TV mount", settings["tv_folder"], needs_write=True),
path_health_check("Review mount", settings["review_folder"], needs_write=True),
path_health_check("Quarantine mount", settings["quarantine_folder"], needs_write=True),
path_health_check("Database", DB_PATH.parent, needs_write=True),
]
return checks
def access_control_health_check(settings):
issues = []
if SESSION_SECRET == "change-me-in-production" or len(str(SESSION_SECRET)) < 32:
issues.append("set a long DATA_MANAGER_SESSION_SECRET")
local_users = get_local_users()
active_admins = [user for user in local_users if user["role"] == "admin" and int(user["enabled"])]
if not active_admins:
issues.append("create at least one enabled admin account")
active_admin_details = [get_local_user(user["username"]) for user in active_admins]
if any((user or {}).get("password_hash") in {"", "changeme"} for user in active_admin_details):
issues.append("change the default admin password")
if setting_enabled(settings, "viewer_enabled") and not settings.get("viewer_password", "").strip():
issues.append("set a view-only password or disable the viewer user")
if issues:
return {"name": "Access Control", "status": "fail", "detail": "; ".join(issues)}
return {"name": "Access Control", "status": "ok", "detail": "Role checks and CSRF protection are active"}
def tmdb_api_key(settings=None):
settings = settings or get_settings()
return settings.get("tmdb_api_key", "").strip() or TMDB_API_KEY
def cached_tmdb_checks(settings, force=False):
settings_key = tmdb_api_key(settings)
now = time.time()
with tmdb_lock:
fresh = now - tmdb_validation_cache["checked_at"] < 300
if (
not force
and fresh
and tmdb_validation_cache["settings_key"] == settings_key
and tmdb_validation_cache["movie"]
and tmdb_validation_cache["tv"]
):
return tmdb_validation_cache["movie"], tmdb_validation_cache["tv"]
movie = uncached_tmdb_movie_health_check(settings)
tv = uncached_tmdb_tv_health_check(settings)
with tmdb_lock:
tmdb_validation_cache.update({
"checked_at": now,
"settings_key": settings_key,
"movie": movie,
"tv": tv,
})
return movie, tv
def tmdb_health_check(settings=None):
return cached_tmdb_checks(settings or get_settings())[0]
def tmdb_tv_health_check(settings=None):
return cached_tmdb_checks(settings or get_settings())[1]
def uncached_tmdb_movie_health_check(settings):
if not tmdb_api_key(settings):
return {
"name": "TMDB API",
"status": "fail",
"detail": "TMDB API key is missing in Settings",
}
try:
data = tmdb_get("/search/movie", {"query": "Fight Club", "year": "1999", "include_adult": "false", "page": "1"})
if data and isinstance(data.get("results"), list):
return {
"name": "TMDB API",
"status": "ok",
"detail": "API key accepted and search is responding",
}
return {
"name": "TMDB API",
"status": "warn",
"detail": "API responded, but the response did not include results",
}
except urllib.error.HTTPError as exc:
if exc.code in {401, 403}:
detail = "API key rejected by TMDB"
else:
detail = f"HTTP {exc.code} from TMDB"
return {"name": "TMDB API", "status": "fail", "detail": detail}
except Exception as exc:
return {"name": "TMDB API", "status": "fail", "detail": f"Connection failed: {exc}"}
def ffprobe_health_check():
if not shutil.which("ffprobe"):
return {"name": "ffprobe", "status": "fail", "detail": "ffprobe is not installed in the container"}
try:
result = subprocess.run(["ffprobe", "-version"], capture_output=True, text=True, timeout=5, check=False)
if result.returncode == 0:
first_line = (result.stdout or "ffprobe available").splitlines()[0]
return {"name": "ffprobe", "status": "ok", "detail": first_line[:120]}
return {"name": "ffprobe", "status": "fail", "detail": "ffprobe command failed"}
except Exception as exc:
return {"name": "ffprobe", "status": "fail", "detail": str(exc)}
def clamav_health_check(settings):
if not setting_enabled(settings, "malware_enabled"):
return {"name": "ClamAV Malware Scan", "status": "warn", "detail": "Malware scanning is disabled"}
if not shutil.which("clamscan"):
return {"name": "ClamAV Malware Scan", "status": "fail", "detail": "clamscan is not installed in the container"}
try:
result = subprocess.run(["clamscan", "--version"], capture_output=True, text=True, timeout=10, check=False)
except Exception as exc:
return {"name": "ClamAV Malware Scan", "status": "fail", "detail": str(exc)}
version = (result.stdout or result.stderr or "ClamAV available").strip().splitlines()[0]
with malware_lock:
cached = dict(malware_definition_cache)
if cached["ok"]:
return {"name": "ClamAV Malware Scan", "status": "ok", "detail": f"{version}; definitions ready"}
if time.time() - cached["checked_at"] < 3600:
return {"name": "ClamAV Malware Scan", "status": "warn", "detail": f"{version}; {cached['detail']}"}
if clamav_database_available():
return {"name": "ClamAV Malware Scan", "status": "ok", "detail": f"{version}; local definitions present"}
return {"name": "ClamAV Malware Scan", "status": "warn", "detail": f"{version}; definitions not verified yet"}
def uncached_tmdb_tv_health_check(settings):
if not tmdb_api_key(settings):
return {
"name": "TMDB TV API",
"status": "fail",
"detail": "TMDB API key is missing in Settings",
}
try:
data = tmdb_get("/search/tv", {"query": "Breaking Bad", "first_air_date_year": "2008", "include_adult": "false", "page": "1"})
if data and isinstance(data.get("results"), list):
return {
"name": "TMDB TV API",
"status": "ok",
"detail": "TV database search is responding",
}
return {
"name": "TMDB TV API",
"status": "warn",
"detail": "TV API responded, but the response did not include results",
}
except urllib.error.HTTPError as exc:
detail = "API key rejected by TMDB" if exc.code in {401, 403} else f"HTTP {exc.code} from TMDB"
return {"name": "TMDB TV API", "status": "fail", "detail": detail}
except Exception as exc:
return {"name": "TMDB TV API", "status": "fail", "detail": f"Connection failed: {exc}"}
def pushover_health_check(settings):
if not setting_enabled(settings, "pushover_enabled"):
return {"name": "Pushover", "status": "warn", "detail": "Notifications are disabled"}
if not settings.get("pushover_app_token", "").strip() or not settings.get("pushover_user_key", "").strip():
return {"name": "Pushover", "status": "fail", "detail": "Token or user key is missing"}
return validate_pushover_cached(settings)
def validate_pushover_cached(settings, force=False):
settings_key = "|".join([
settings.get("pushover_app_token", "").strip(),
settings.get("pushover_user_key", "").strip(),
settings.get("pushover_device", "").strip(),
])
now = time.time()
with pushover_lock:
cached = pushover_validation_cache["result"]
fresh = now - pushover_validation_cache["checked_at"] < 300
if cached and fresh and pushover_validation_cache["settings_key"] == settings_key and not force:
return cached
result = validate_pushover(settings)
with pushover_lock:
pushover_validation_cache.update({
"checked_at": now,
"settings_key": settings_key,
"result": result,
})
return result
def validate_pushover(settings):
payload = {
"token": settings.get("pushover_app_token", "").strip(),
"user": settings.get("pushover_user_key", "").strip(),
}
device = settings.get("pushover_device", "").strip()
if device:
payload["device"] = device
try:
data = post_form("https://api.pushover.net/1/users/validate.json", payload, timeout=8)
if data.get("status") == 1:
devices = data.get("devices") or []
device_detail = f"; devices: {', '.join(devices[:5])}" if devices else ""
return {"name": "Pushover", "status": "ok", "detail": f"Connection valid{device_detail}"}
return {"name": "Pushover", "status": "fail", "detail": pushover_error_detail(data)}
except urllib.error.HTTPError as exc:
return {"name": "Pushover", "status": "fail", "detail": f"Validation failed: HTTP {exc.code}"}
except Exception as exc:
return {"name": "Pushover", "status": "fail", "detail": f"Validation failed: {exc}"}
def path_health_check(name, path_value, needs_write=False):
path = Path(path_value)
if not path.exists():
return {"name": name, "status": "fail", "detail": f"{path} does not exist"}
if not path.is_dir():
return {"name": name, "status": "fail", "detail": f"{path} is not a directory"}
if not os.access(path, os.R_OK | os.X_OK):
return {"name": name, "status": "fail", "detail": f"{path} is not readable"}
if needs_write:
probe = path / ".data-manager-healthcheck"
try:
with open(probe, "w", encoding="utf-8") as handle:
handle.write(now_iso())
except Exception as exc:
return {"name": name, "status": "fail", "detail": f"{path} is not writable: {exc}"}
return {"name": name, "status": "ok", "detail": f"{path} is available"}
def processing_preflight(settings):
checks = [
path_health_check("Watch mount", settings["watch_folder"], needs_write=True),
path_health_check("Movie mount", settings["movie_folder"], needs_write=True),
path_health_check("TV mount", settings["tv_folder"], needs_write=True),
path_health_check("Review mount", settings["review_folder"], needs_write=True),
path_health_check("Quarantine mount", settings["quarantine_folder"], needs_write=True),
path_health_check("Database", DB_PATH.parent, needs_write=True),
]
if metadata_enabled(settings) and metadata_required(settings) and settings.get("metadata_provider") == "tmdb":
movie_check, tv_check = cached_tmdb_checks(settings)
checks.extend([movie_check, tv_check])
failures = [check for check in checks if check["status"] == "fail"]
if failures:
message = "; ".join(f"{check['name']}: {check['detail']}" for check in failures)
throttled_preflight_event(message)
return False
return True
def throttled_preflight_event(message):
now = time.time()
with preflight_lock:
if preflight_state["message"] == message and now - preflight_state["logged_at"] < 300:
return
preflight_state.update({"message": message, "logged_at": now})
add_event("system", "error", "preflight", message=f"Auto scan paused: {message}")
def tmdb_get(endpoint, params):
api_key = tmdb_api_key()
if not api_key:
return None
params = dict(params)
params["api_key"] = api_key
params.setdefault("language", "en-US")
url = f"{TMDB_BASE_URL}{endpoint}?{urllib.parse.urlencode(params)}"
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def tvmaze_get(endpoint, params, settings=None):
global tvmaze_backoff_until
settings = settings or get_settings()
now = time.time()
with tvmaze_lock:
if now < tvmaze_backoff_until:
remaining = int(tvmaze_backoff_until - now)
raise RuntimeError(f"TVmaze is rate limited; backing off for {remaining}s")
cache_key = (endpoint, tuple(sorted((params or {}).items())))
cached = tvmaze_cache.get(cache_key)
if cached and now - cached["time"] < 24 * 3600:
return cached["data"]
url = f"{TVMAZE_BASE_URL}{endpoint}?{urllib.parse.urlencode(params)}"
req = urllib.request.Request(url, headers={"Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=5) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
if exc.code == 429:
retry_after = exc.headers.get("Retry-After")
backoff = int_setting(settings, "tvmaze_backoff_seconds", 900, minimum=60, maximum=86400)
if retry_after and retry_after.isdigit():
backoff = max(backoff, int(retry_after))
with tvmaze_lock:
tvmaze_backoff_until = time.time() + backoff
raise RuntimeError(f"TVmaze rate limit reached; backing off for {backoff}s") from exc
raise
with tvmaze_lock:
tvmaze_cache[cache_key] = {"time": time.time(), "data": data}
if len(tvmaze_cache) > 1000:
oldest = sorted(tvmaze_cache, key=lambda key: tvmaze_cache[key]["time"])[:200]
for key in oldest:
tvmaze_cache.pop(key, None)
return data
def send_pushover(settings, title, message, priority=0):
if not setting_enabled(settings, "pushover_enabled"):
return False
token = settings.get("pushover_app_token", "").strip()
user = settings.get("pushover_user_key", "").strip()
if not token or not user:
add_event("system", "error", "pushover", message="Pushover is enabled but token or user key is missing")
return False
payload = {
"token": token,
"user": user,
"title": title,
"message": message,
"priority": str(priority),
}
device = settings.get("pushover_device", "").strip()
if device:
payload["device"] = device
try:
data = post_form("https://api.pushover.net/1/messages.json", payload, timeout=8)
if data.get("status") != 1:
raise ValueError(pushover_error_detail(data))
return True
except Exception as exc:
add_event("system", "error", "pushover", message=f"Pushover notification failed: {exc}")
return False
def post_form(url, payload, timeout=8):
data = urllib.parse.urlencode(payload).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
)
with urllib.request.urlopen(req, timeout=timeout) as response:
raw = response.read().decode("utf-8")
return json.loads(raw) if raw else {}
def pushover_error_detail(data):
errors = data.get("errors") if isinstance(data, dict) else None
if errors:
return "; ".join(str(error) for error in errors)
if isinstance(data, dict):
for key, value in data.items():
if key not in {"status", "request"}:
return f"{key}: {value}"
return "Pushover rejected the request"
def test_pushover():
settings = get_settings()
validation = validate_pushover_cached(settings, force=True)
if validation["status"] != "ok":
add_event("system", "error", "pushover", message=f"Pushover test failed validation: {validation['detail']}")
return False
message = "\n".join([
"Test notification from Data Manager",
f"Server time: {now_iso()}",
"If you received this, Pushover alerts are working.",
])
if send_pushover(settings, "Data Manager: Test Alert", message, priority=0):
add_event("system", "done", "pushover", message="Pushover test notification sent successfully")
validate_pushover_cached(settings, force=True)
return True
return False
def notify_success(settings, media_type, original_path, renamed_to, moved_to, source):
if not setting_enabled(settings, "notify_success"):
return
message = "\n".join([
"Completed successfully",
f"Type: {media_type}",
f"Original: {Path(original_path).name}",
f"Renamed: {renamed_to}",
f"Moved to: {moved_to}",
f"Metadata: {source}",
])
send_pushover(settings, "Data Manager: Completed", message, priority=0)
def notify_failure(settings, original_path, error):
if not setting_enabled(settings, "notify_failure"):
return
message = "\n".join([
"Processing failed",
f"Original: {Path(original_path).name}",
f"Path: {original_path}",
f"Error: {error}",
])
send_pushover(settings, "Data Manager: Failed", message, priority=1)
def notify_duplicate(settings, detail, existing_path=None, review_path=None):
if not setting_enabled(settings, "notify_duplicate"):
return
message = "\n".join([
"Duplicate/conflict detected",
f"Detail: {detail}",
f"Existing: {existing_path or 'n/a'}",
f"Review: {review_path or 'n/a'}",
])
send_pushover(settings, "Data Manager: Duplicate", message, priority=0)
def notify_scan_complete(settings, scan_name, message):
if not setting_enabled(settings, "notify_scan_complete"):
return
send_pushover(settings, f"Data Manager: {scan_name} Complete", message, priority=0)
def notify_mount_unavailable(settings, mount_name, path_value):
if not setting_enabled(settings, "notify_mount_unavailable"):
return
send_pushover(settings, "Data Manager: Mount Unavailable", f"{mount_name}: {path_value}", priority=1)
def notify_metadata_down(settings, provider, error):
if not setting_enabled(settings, "notify_metadata_down"):
return
send_pushover(settings, "Data Manager: Metadata Provider Down", f"{provider}: {error}", priority=1)
def notify_malware(settings, original_path, quarantine_path, detail):
if not setting_enabled(settings, "notify_malware"):
return
message = "\n".join([
"Malware or virus detection",
f"Original: {original_path}",
f"Quarantine: {quarantine_path}",
f"Detail: {detail}",
])
send_pushover(settings, "Data Manager: Malware Quarantined", message, priority=1)
def first_year(value):
if value and re.match(r"\d{4}-\d{2}-\d{2}", value):
return value[:4]
return "Unknown Year"
def metadata_enabled(settings):
return settings.get("metadata_enabled", "yes").lower() in {"yes", "true", "1", "on"}
def metadata_required(settings):
return settings.get("metadata_required", "yes").lower() in {"yes", "true", "1", "on"}
def metadata_source_ok(media_type, source):
if media_type == "tv":
return source != "filename"
return source == "tmdb"
def enrich_movie(movie, settings):
if not metadata_enabled(settings) or settings.get("metadata_provider") != "tmdb":
return movie, "filename"
try:
params = {"query": movie["title"], "include_adult": "false", "page": "1"}
if movie["year"] != "Unknown Year":
params["year"] = movie["year"]
data = tmdb_get("/search/movie", params)
results = data.get("results", []) if data else []
if not results and movie["year"] != "Unknown Year":
data = tmdb_get("/search/movie", {"query": movie["title"], "include_adult": "false", "page": "1"})
results = data.get("results", []) if data else []
if results:
best = results[0]
title = best.get("title") or best.get("original_title") or movie["title"]
year = first_year(best.get("release_date")) or movie["year"]
return {"title": title, "year": year}, "tmdb"
except Exception as exc:
add_event("system", "error", movie["title"], message=f"TMDB movie lookup failed: {exc}")
notify_metadata_down(settings, "TMDB movie", exc)
return movie, "filename"
def enrich_tv(tv, settings):
if not metadata_enabled(settings) or settings.get("metadata_provider") != "tmdb":
return tv, "filename"
enriched = None
source = "filename"
try:
results = search_tmdb_tv(tv)
if results:
best = choose_tmdb_tv_show(results, tv)
title = best.get("name") or best.get("original_name") or tv["title"]
year = first_year(best.get("first_air_date")) or tv["year"]
enriched = dict(tv)
enriched["title"] = title
enriched["year"] = year
source = "tmdb"
try:
episode = tmdb_get(
f"/tv/{best['id']}/season/{tv['season']}/episode/{tv['episode']}",
{},
)
if episode and episode.get("name"):
enriched["episode_name"] = episode["name"]
except Exception as exc:
add_event("system", "error", tv["title"], message=f"TMDB TV episode lookup failed: {exc}; trying TVmaze")
except Exception as exc:
add_event("system", "error", tv["title"], message=f"TMDB TV lookup failed: {exc}")
notify_metadata_down(settings, "TMDB TV", exc)
needs_episode_name = not (enriched or tv).get("episode_name")
if setting_enabled(settings, "tvmaze_fallback_enabled") and (source == "filename" or needs_episode_name):
tvmaze_enriched, tvmaze_source = enrich_tv_with_tvmaze(enriched or tv, settings)
if tvmaze_source == "tvmaze":
return tvmaze_enriched, "tvmaze" if source == "filename" else f"{source}+tvmaze"
if enriched:
return enriched, source
return tv, "filename"
def search_tmdb_tv(tv):
combined = []
seen_ids = set()
for title in tv_title_variants(tv["title"]):
params = {"query": title, "include_adult": "false", "page": "1"}
if tv["year"] != "Unknown Year":
params["first_air_date_year"] = tv["year"]
data = tmdb_get("/search/tv", params)
results = data.get("results", []) if data else []
if not results and tv["year"] != "Unknown Year":
data = tmdb_get("/search/tv", {"query": title, "include_adult": "false", "page": "1"})
results = data.get("results", []) if data else []
for item in results:
item_id = item.get("id")
if item_id in seen_ids:
continue
seen_ids.add(item_id)
combined.append(item)
return combined
def choose_tmdb_tv_show(results, tv):
desired_country = desired_tv_country(tv["title"])
title_keys = {normalize_lookup_title(title) for title in tv_title_variants(tv["title"])}
exact = [
item for item in results
if normalize_lookup_title(item.get("name") or item.get("original_name") or "") in title_keys
]
if desired_country:
country_match = [
item for item in exact or results
if desired_country in (item.get("origin_country") or [])
]
if country_match:
return country_match[0]
if exact:
return exact[0]
if not desired_country and normalize_lookup_title(tv["title"]) == "love island":
gb = [item for item in results if "GB" in (item.get("origin_country") or [])]
if gb:
return gb[0]
return results[0]
def enrich_tv_with_tvmaze(tv, settings):
try:
data = []
for title in tv_title_variants(tv["title"]):
data = tvmaze_get("/search/shows", {"q": title}, settings=settings)
if data:
break
if not data:
return tv, "filename"
best = choose_tvmaze_show(data, tv["title"])
show = best.get("show", best)
enriched = dict(tv)
enriched["title"] = show.get("name") or tv["title"]
enriched["year"] = first_year(show.get("premiered")) or tv["year"]
episode = tvmaze_get(
f"/shows/{show['id']}/episodebynumber",
{"season": tv["season"], "number": tv["episode"]},
settings=settings,
)
if episode and episode.get("name"):
enriched["episode_name"] = episode["name"]
return enriched, "tvmaze"
except Exception as exc:
add_event("system", "error", tv["title"], message=f"TVmaze lookup failed: {exc}")
return tv, "filename"
def choose_tvmaze_show(results, title):
desired_country = desired_tv_country(title)
title_keys = {normalize_lookup_title(item) for item in tv_title_variants(title)}
exact = [
item for item in results
if normalize_lookup_title(item.get("show", {}).get("name", "")) in title_keys
]
if desired_country:
country_match = [
item for item in exact or results
if tvmaze_show_country(item.get("show", {})) == desired_country
]
if country_match:
return country_match[0]
gb = [
item for item in exact
if tvmaze_show_country(item.get("show", {})) == "GB"
]
if gb:
return gb[0]
if exact:
return exact[0]
return results[0]
def tv_title_variants(title):
variants = []
def add(value):
value = re.sub(r"\s+", " ", value).strip()
if value and value.lower() not in {item.lower() for item in variants}:
variants.append(value)
add(title)
usa_title = re.sub(r"\bU[ ._-]?S[ ._-]?A?\b$", "USA", title, flags=re.I)
add(usa_title)
add(re.sub(r"\bUSA\b$", "(US)", usa_title, flags=re.I))
add(re.sub(r"\bUSA\b$", "United States", usa_title, flags=re.I))
add(re.sub(r"\bUK\b$", "United Kingdom", title, flags=re.I))
return variants
def normalize_lookup_title(title):
title = re.sub(r"\(\s*U[ ._-]?S[ ._-]?A?\s*\)", " USA ", title, flags=re.I)
title = re.sub(r"\(\s*United States\s*\)", " USA ", title, flags=re.I)
title = re.sub(r"\(\s*UK\s*\)", " UK ", title, flags=re.I)
title = re.sub(r"\(\s*United Kingdom\s*\)", " UK ", title, flags=re.I)
title = re.sub(r"\([^)]*\)", " ", title)
title = re.sub(r"\bUnited States\b", "USA", title, flags=re.I)
title = re.sub(r"\bU[ ._-]?S[ ._-]?A?\b", "USA", title, flags=re.I)
title = re.sub(r"\bUnited Kingdom\b", "UK", title, flags=re.I)
title = re.sub(r"[^a-z0-9]+", " ", title.lower())
return re.sub(r"\s+", " ", title).strip()
def desired_tv_country(title):
normalized = normalize_lookup_title(title)
if re.search(r"\busa\b$", normalized):
return "US"
if re.search(r"\buk\b$", normalized):
return "GB"
return None
def tvmaze_show_country(show):
network = show.get("network") or {}
web_channel = show.get("webChannel") or {}
country = (network.get("country") or web_channel.get("country") or {})
return country.get("code")
def library_folder_name(title, year):
return movie_folder_name(title, year)
def resolve_library_folder(root, desired_name):
root = Path(root)
desired = root / desired_name
if desired.exists() and desired.is_dir():
return desired, True, f"Existing folder found: {desired.name}"
if root.exists():
wanted = normalize_folder_name(desired_name)
for child in root.iterdir():
if child.is_dir() and normalize_folder_name(child.name) == wanted:
return child, True, f"Existing folder found with matching name: {child.name}"
return desired, False, f"Folder does not exist yet and will be created: {desired.name}"
def normalize_folder_name(name):
name = re.sub(r"[^a-z0-9]+", " ", str(name).lower())
return re.sub(r"\s+", " ", name).strip()
def duplicate_movie_file(target_dir):
if not target_dir.exists():
return None
for path in target_dir.iterdir():
if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
return path
return None
def duplicate_tv_episode_file(target_dir, season, episode):
if not target_dir.exists():
return None
pattern = re.compile(rf"\bS{season:02d}E{episode:02d}\b", re.I)
for path in target_dir.iterdir():
if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS and pattern.search(path.stem):
return path
return None
def review_target(settings, media_type, folder_name, subfolder_name, base_name, suffix):
root = Path(settings["review_folder"])
if media_type == "tv":
target_dir = root / "TV Shows" / folder_name / subfolder_name
else:
target_dir = root / "Movies" / folder_name
return target_dir, unique_path(target_dir / f"{base_name}{suffix.lower()}")
def conflict_decision(incoming, existing, settings, media_type, folder_name, subfolder_name, base_name):
existing_review_dir, existing_review_file = review_target(settings, media_type, folder_name, subfolder_name, existing.stem, existing.suffix)
incoming_review_dir, incoming_review_file = review_target(settings, media_type, folder_name, subfolder_name, base_name, incoming.suffix)
incoming_score = quality_score(incoming)
existing_score = quality_score(existing)
if incoming_score > existing_score:
return {
"duplicate": True,
"conflict_action": "replace_with_incoming",
"existing_duplicate": existing,
"existing_review_target": existing_review_file,
"review_dir": existing_review_dir,
"duplicate_status": (
f"Incoming file appears higher quality than {existing.name}; "
f"deleting lower-quality existing video after upgrade verifies"
),
}
return {
"duplicate": True,
"conflict_action": "incoming_to_review",
"existing_duplicate": existing,
"existing_review_target": None,
"review_dir": incoming_review_dir,
"duplicate_status": (
f"Existing file appears same or better quality: {existing.name}; "
f"moving incoming file to review"
),
}
def set_file_stage(path, stage, reason=None, media_type=None, planned_name=None, target_path=None, last_error=None):
with db_lock, db() as conn:
conn.execute(
"""
update seen_files
set stage = ?,
reason = coalesce(?, reason),
media_type = coalesce(?, media_type),
planned_name = coalesce(?, planned_name),
target_path = coalesce(?, target_path),
last_error = coalesce(?, last_error)
where path = ?
""",
(stage, reason, media_type, planned_name, str(target_path) if target_path else None, last_error, str(path)),
)
conn.commit()
def set_transfer_progress(path, transferred_bytes, total_bytes, force=False):