forked from cmc0619/vod2strm
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.py
More file actions
2329 lines (1979 loc) · 97.7 KB
/
Copy pathplugin.py
File metadata and controls
2329 lines (1979 loc) · 97.7 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
"""
vod2strm – Dispatcharr Plugin
Version: 0.0.14.ds
Spec:
- ORM (in-process) with Celery background tasks (non-blocking UI).
- Buttons: Stats, Generate Movies, Generate Series, Generate All.
- STRM generation:
* Movies -> <root>/Movies/{Name} ({Year})/{Name} ({Year}).strm
* Series -> <root>/TV/{SeriesName (Year) or SeriesName + (year)}/Season {SS or 00}/S{SS}E{EE} - {Title}.strm
* Season 00 labeled "Season 00 (Specials)".
* .strm contents use {base_url}/proxy/vod/(movie|episode)/{uuid}?stream_id={stream_id}
- NFO generation (compare-before-write):
* Movies: movie.nfo in movie folder
* Seasons: season.nfo per season folder
* Episodes: SxxExx.nfo next to episode file
- Cleanup (preview/apply) of stale files/folders.
- CSV reports -> /data/plugins/vod2strm/reports/
- Robust debug logging -> /data/plugins/vod2strm/logs/
"""
from __future__ import annotations
# Ensure plugin directory is in sys.path so Celery workers can import this module
import sys
from pathlib import Path
_plugin_parent = Path(__file__).parent.parent
if str(_plugin_parent) not in sys.path:
sys.path.insert(0, str(_plugin_parent))
import csv
import fcntl
import hashlib
import io
import json
import logging
import logging.handlers
import math
import os
try:
import regex as re # Use regex library for better Unicode support (aligns with Dispatcharr)
except ImportError:
import re # Fallback to standard library if regex not available
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from typing import Iterable, List, Tuple, Dict, Any, Optional
from xml.sax.saxutils import escape as xml_escape
from django.db import connection, transaction
from django.db.models import Count, Exists, OuterRef, Prefetch, Q
from django.utils.timezone import now # noqa:F401
# ORM models (plugin runs in-process with the app)
try:
from apps.vod.models import (
Movie,
Series,
Episode,
M3UMovieRelation,
M3UEpisodeRelation,
M3USeriesRelation,
M3UVODCategoryRelation,
)
from apps.m3u.models import M3UAccount
except Exception: # pragma: no cover
from vod.models import ( # type: ignore
Movie,
Series,
Episode,
M3UMovieRelation,
M3UEpisodeRelation,
M3USeriesRelation,
M3UVODCategoryRelation,
)
from m3u.models import M3UAccount # type: ignore
# Celery (required - Dispatcharr depends on Celery to function)
# Import is in try/except for testing purposes only
try:
from celery import current_app as celery_app
from celery import shared_task
except Exception: # pragma: no cover
celery_app = None # type: ignore
shared_task = None # type: ignore
# -------------------- Constants / Defaults --------------------
DEFAULT_BASE_URL = "http://localhost:9191"
DEFAULT_ROOT = "/data/STRM"
REPORT_ROOT = "/data/plugins/vod2strm/reports"
LOG_ROOT = "/data/plugins/vod2strm/logs"
CLEANUP_OFF = "off"
CLEANUP_PREVIEW = "preview"
CLEANUP_APPLY = "apply"
# -------------------- Logging --------------------
LOGGER = logging.getLogger("plugins.vod2strm")
if not LOGGER.handlers:
LOGGER.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
LOGGER.addHandler(sh)
_FILE_LOGGER_CONFIGURED = False
_LOG_LOCK = threading.Lock()
_MANIFEST_LOCK = threading.Lock() # Protects manifest dict from concurrent modification
# -------------------- Auto-Monitor State --------------------
_monitor_thread = None # Reference to daemon polling thread
_monitor_stop_event = threading.Event() # Signal to stop the monitor loop
_monitor_lock = threading.Lock() # Protects monitor start/stop operations
# -------------------- Query Helpers --------------------
def _enabled_category_subquery(account_field: str, category_field: str) -> Exists:
"""
Build an Exists() subquery that ensures a given account/category pair is enabled.
account_field/category_field refer to columns available on the outer queryset.
"""
return Exists(
M3UVODCategoryRelation.objects.filter(
m3u_account_id=OuterRef(account_field),
category_id=OuterRef(category_field),
enabled=True,
)
)
def _eligible_movie_queryset():
"""
Movies with active account relations AND optional content filter.
Content filter: Comma-separated database IDs from plugin settings.
When filter is empty, all eligible movies are included.
"""
allowed_relations = M3UMovieRelation.objects.filter(
movie_id=OuterRef("pk"),
m3u_account__is_active=True,
).filter(
Q(category__isnull=True) | _enabled_category_subquery("m3u_account_id", "category_id")
)
base_qs = Movie.objects.annotate(_vod2_allowed_movie=Exists(allowed_relations)).filter(_vod2_allowed_movie=True)
# Load content filter settings from plugin config
try:
from apps.plugins.models import PluginConfig
config = PluginConfig.objects.filter(key="vod2strm").first()
settings = config.settings if config else {}
filter_movie_ids_str = settings.get("filter_movie_ids", "").strip()
filter_movie_category_ids_str = settings.get("filter_movie_category_ids", "").strip()
except Exception:
filter_movie_ids_str = ""
filter_movie_category_ids_str = ""
movie_ids = []
category_ids = []
# Parse UI IDs
if filter_movie_ids_str:
movie_ids = [
int(x.strip())
for x in filter_movie_ids_str.split(',')
if x.strip().isdigit()
]
if filter_movie_category_ids_str:
category_ids = [
int(x.strip())
for x in filter_movie_category_ids_str.split(',')
if x.strip().isdigit()
]
if movie_ids or category_ids:
filters = Q()
if movie_ids:
filters |= Q(id__in=movie_ids)
if category_ids:
category_match = allowed_relations.filter(category_id__in=category_ids)
filters |= Exists(category_match)
base_qs = base_qs.filter(filters)
return base_qs
def _eligible_series_queryset():
"""
Series with active account relations AND optional content filter.
Content filter: Comma-separated database IDs from plugin settings.
When filter is empty, all eligible series are included.
"""
allowed_relations = M3USeriesRelation.objects.filter(
series_id=OuterRef("pk"),
m3u_account__is_active=True,
).filter(
Q(category__isnull=True) | _enabled_category_subquery("m3u_account_id", "category_id")
)
base_qs = Series.objects.annotate(_vod2_allowed_series=Exists(allowed_relations)).filter(_vod2_allowed_series=True)
# Load content filter settings from plugin config
try:
from apps.plugins.models import PluginConfig
config = PluginConfig.objects.filter(key="vod2strm").first()
settings = config.settings if config else {}
filter_series_ids_str = settings.get("filter_series_ids", "").strip()
filter_series_category_ids_str = settings.get("filter_series_category_ids", "").strip()
except Exception:
filter_series_ids_str = ""
filter_series_category_ids_str = ""
series_ids = []
category_ids = []
if filter_series_ids_str:
series_ids = [
int(x.strip())
for x in filter_series_ids_str.split(',')
if x.strip().isdigit()
]
if filter_series_category_ids_str:
category_ids = [
int(x.strip())
for x in filter_series_category_ids_str.split(',')
if x.strip().isdigit()
]
if series_ids or category_ids:
filters = Q()
if series_ids:
filters |= Q(id__in=series_ids)
if category_ids:
category_match = allowed_relations.filter(category_id__in=category_ids)
filters |= Exists(category_match)
base_qs = base_qs.filter(filters)
return base_qs
def _get_movie_stream_id(movie: Movie) -> str | None:
"""
Get stream_id from the highest priority active M3U provider for a movie.
Returns stream_id or None if no active provider found.
"""
try:
# Get highest priority active relation
relation = M3UMovieRelation.objects.filter(
movie_id=movie.id,
m3u_account__is_active=True,
).filter(
Q(category__isnull=True) | _enabled_category_subquery("m3u_account_id", "category_id")
).select_related('m3u_account').order_by(
'-m3u_account__priority', 'id'
).first()
if relation:
return getattr(relation, 'stream_id', None)
return None
except Exception as e:
LOGGER.debug("Failed to get stream_id for movie id=%s: %s", movie.id, e)
return None
def _get_episode_stream_id(episode: Episode) -> str | None:
"""
Get stream_id from the highest priority active M3U provider for an episode.
Returns stream_id or None if no active provider found.
"""
try:
# Get highest priority active relation
# NOTE: M3UEpisodeRelation has no category_id field (unlike M3UMovieRelation/M3USeriesRelation)
# Episodes inherit category from parent series, so we don't filter by category here
relation = M3UEpisodeRelation.objects.filter(
episode_id=episode.id,
m3u_account__is_active=True,
).select_related('m3u_account').order_by(
'-m3u_account__priority', 'id'
).first()
if relation:
return getattr(relation, 'stream_id', None)
return None
except Exception as e:
LOGGER.debug("Failed to get stream_id for episode id=%s: %s", episode.id, e)
return None
def _get_relation_from_prefetch(instance, relation_attr: str = 'active_relation'):
"""
Get the prefetched relation object from a Movie or Episode instance.
Expects the instance to have a prefetched attribute containing the highest
priority active M3U relation. This avoids N+1 queries.
Args:
instance: Movie or Episode instance with prefetched relation
relation_attr: Name of the prefetched attribute (default: 'active_relation')
Returns:
M3UMovieRelation or M3UEpisodeRelation object, or None if not found
"""
try:
relations = getattr(instance, relation_attr, [])
if relations:
return relations[0]
except (AttributeError, IndexError, TypeError) as e:
LOGGER.debug("Failed to get relation from prefetch: %s", e)
return None
return None
def _ensure_dirs() -> None:
Path(REPORT_ROOT).mkdir(parents=True, exist_ok=True)
Path(LOG_ROOT).mkdir(parents=True, exist_ok=True)
def _configure_file_logger(debug_enabled: bool) -> None:
global _FILE_LOGGER_CONFIGURED
with _LOG_LOCK:
if _FILE_LOGGER_CONFIGURED:
return
_ensure_dirs()
level = logging.DEBUG if debug_enabled else logging.INFO
LOGGER.setLevel(level)
try:
fh = logging.handlers.RotatingFileHandler(
filename=str(Path(LOG_ROOT) / "vod2strm.log"),
maxBytes=10 * 1024 * 1024,
backupCount=5,
encoding="utf-8",
)
fmt = logging.Formatter(
"%(asctime)s %(levelname)s %(name)s %(threadName)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
fh.setFormatter(fmt)
fh.setLevel(level)
LOGGER.addHandler(fh)
except Exception as e: # pragma: no cover
LOGGER.warning("Failed to attach file logger: %s", e)
_FILE_LOGGER_CONFIGURED = True
# -------------------- Manifest (Metadata Cache) --------------------
def _load_manifest(root: Path) -> Dict[str, Any]:
"""
Load manifest file or return default.
Manifest tracks written files to avoid unnecessary disk writes.
Structure: {"files": {"/path/to/file.strm": {"uuid": "...", "type": "movie|episode", "url": "..."}}, "version": 1}
Note: Including "url" field allows detection of URL changes (e.g., when stream_id parameter is added).
Uses file-level locking (flock) to prevent concurrent jobs from corrupting manifest.
"""
manifest_path = root / ".vod2strm_manifest.json"
try:
if manifest_path.exists():
with manifest_path.open("r", encoding="utf-8") as f:
# Acquire shared lock for reading (multiple readers allowed)
fcntl.flock(f.fileno(), fcntl.LOCK_SH)
try:
data = json.load(f)
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
return data
except Exception as e:
LOGGER.warning("Failed to load manifest from %s: %s", manifest_path, e)
return {"files": {}, "version": 1}
def _save_manifest(root: Path, manifest: Dict[str, Any]) -> None:
"""
Save manifest file atomically using temp file + rename.
Minimizes risk of corruption if interrupted.
Uses file-level locking (flock) to prevent concurrent jobs from corrupting manifest.
Exclusive lock prevents other processes from reading/writing during save.
"""
manifest_path = root / ".vod2strm_manifest.json"
try:
manifest_path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = manifest_path.with_suffix(f".tmp.{int(time.time() * 1000)}")
# Write to temp file first (atomic write pattern)
with tmp_path.open("w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, sort_keys=True)
# Acquire exclusive lock before replacing manifest file
# Create lock file to coordinate with other processes
lock_path = manifest_path.with_suffix(".lock")
with lock_path.open("a", encoding="utf-8") as lock_file:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
try:
tmp_path.replace(manifest_path)
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
except Exception as e:
LOGGER.warning("Failed to save manifest to %s: %s", manifest_path, e)
# -------------------- Adaptive Throttle --------------------
class AdaptiveThrottle:
"""
Monitors write performance and adjusts concurrency dynamically.
Strategy:
- Start conservative with 1 worker, scale up based on performance
- Track average write latency over rolling window (20 writes)
- If writes are slow (>100ms), cut workers in half
- If writes are fast (<30ms), increase workers by 50%
- Check every 10 writes for faster response
- Bounds: min=1, max=user_setting (capped at 4)
"""
def __init__(self, max_workers: int, enabled: bool = True):
# Hard cap at 4 to prevent DB connection exhaustion (Django creates 1 conn per thread)
# Even though workers do file I/O, accessing model attributes triggers DB connections
self.max_workers = min(max_workers, 4)
self.enabled = enabled
# Start conservative - begin with 1 worker and scale up based on performance
self.current_workers = 1 if enabled else self.max_workers
self.write_times = [] # Rolling window of last N write times
self.window_size = 20 # Track last 20 writes (smaller window for faster response)
self.lock = threading.Lock()
# Thresholds (in seconds) - more aggressive to protect NAS
self.slow_threshold = 0.100 # 100ms (down from 200ms)
self.fast_threshold = 0.030 # 30ms (down from 50ms)
# Adjustment rates
self.scale_down_factor = 0.5 # Cut in half when slow (more aggressive)
self.scale_up_factor = 1.5 # Increase by 50% when fast (scale up faster)
# Check interval - adjust every N writes (smaller for faster response)
self.check_interval = 10
self.writes_since_check = 0
def record_write(self, write_time: float) -> None:
"""Record a write operation's duration."""
if not self.enabled:
return
with self.lock:
self.write_times.append(write_time)
if len(self.write_times) > self.window_size:
self.write_times.pop(0)
self.writes_since_check += 1
if self.writes_since_check >= self.check_interval:
self._adjust_concurrency()
self.writes_since_check = 0
def _adjust_concurrency(self) -> None:
"""Adjust concurrency based on average write time."""
if not self.write_times:
return
avg_write_time = sum(self.write_times) / len(self.write_times)
old_workers = self.current_workers
if avg_write_time > self.slow_threshold:
# NAS is slow, reduce workers
self.current_workers = max(1, int(self.current_workers * self.scale_down_factor))
LOGGER.info(
"Adaptive throttle: NAS slow (avg %.3fs), reducing workers %d → %d",
avg_write_time, old_workers, self.current_workers
)
elif avg_write_time < self.fast_threshold and self.current_workers < self.max_workers:
# NAS is fast, increase workers
self.current_workers = min(self.max_workers, math.ceil(self.current_workers * self.scale_up_factor))
if self.current_workers != old_workers:
LOGGER.info(
"Adaptive throttle: NAS fast (avg %.3fs), increasing workers %d → %d",
avg_write_time, old_workers, self.current_workers
)
def get_workers(self) -> int:
"""Get current worker count."""
with self.lock:
return self.current_workers if self.enabled else self.max_workers
# -------------------- Small helpers --------------------
def _ts() -> str:
return datetime.now().strftime("%Y%m%d_%H%M%S")
def _norm_fs_name(s: str) -> str:
s = (s or "").strip()
s = s.replace("/", "-").replace("\\", "-").replace(":", " -")
s = s.replace("?", "").replace("*", "").replace('"', "'")
s = s.replace("<", "(").replace(">", ")").replace("|", "-")
s = re.sub(r"\s+", " ", s).strip()
return s or "Unknown"
def _clean_name(name: str, pattern: str | None) -> str:
"""
Clean a name using the provided regex pattern.
Used to strip prefixes like "EN - " or "TOP - " from names.
"""
if not name or not pattern:
return name
try:
# Strip the pattern from the name
# We use sub() to replace matches with empty string
return re.sub(pattern, "", name).strip()
except re.error as e:
LOGGER.warning("Invalid name cleaning regex '%s': %s", pattern, e)
return name
def _season_folder_name(season_number: int) -> str:
if season_number == 0:
return "Season 00 (Specials)"
return f"Season {season_number:02d}"
def _series_folder_name(name: str, year: int | None) -> str:
# Avoid double "(YYYY)" if already present and matches DB year
year_suffix = re.search(r"\((\d{4})\)\s*$", name or "")
if year and year_suffix and int(year_suffix.group(1)) == int(year):
return _norm_fs_name(name)
if year:
return _norm_fs_name(f"{name} ({year})")
return _norm_fs_name(name or "Unknown Series")
def _movie_folder_name(name: str, year: int | None) -> str:
"""
Generate folder name for movie.
Strips any existing (YYYY) pattern from name to avoid duplication when adding year.
"""
if not name:
name = "Unknown Movie"
# Strip trailing (YYYY) pattern if present to avoid duplication
# Example: "The Matrix (1999)" -> "The Matrix"
name = re.sub(r'\s*\(\d{4}\)\s*$', '', name).strip()
if year:
return _norm_fs_name(f"{name} ({year})")
return _norm_fs_name(name)
def _hash_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def _read_file_bytes(p: Path) -> bytes | None:
try:
return p.read_bytes()
except FileNotFoundError:
return None
def _write_if_changed(path: Path, content: bytes) -> Tuple[bool, str]:
"""
Compare-before-write. Returns (written, reason)
reason ∈ {"created","updated","same_contents"}
"""
existing = _read_file_bytes(path)
new_hash = _hash_bytes(content)
if existing is not None and _hash_bytes(existing) == new_hash:
return (False, "same_contents")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
return (True, "created" if existing is None else "updated")
def _write_strm_if_changed(path: Path, uuid: str, url: str, manifest: Dict[str, Any], file_type: str, dry_run: bool = False) -> Tuple[bool, str]:
"""
Write .strm file only if UUID, URL, or type changed, or file doesn't exist in manifest.
Checks manifest first to avoid disk reads when possible.
Returns (written, reason)
reason ∈ {"created", "updated", "cached_skip", "dry_run"}
"""
path_str = str(path)
manifest_files = manifest.get("files", {})
# Check manifest cache first - avoid disk I/O entirely
# Include URL in cache check to detect when stream_id or other URL params change
cache_matches = False
with _MANIFEST_LOCK:
if path_str in manifest_files:
cached_entry = manifest_files[path_str]
cache_matches = (
cached_entry.get("uuid") == uuid and
cached_entry.get("type") == file_type and
cached_entry.get("url") == url
)
# If cache matches, verify file exists (outside lock to minimize lock time)
if cache_matches:
if path.exists():
return (False, "cached_skip")
# Manifest is stale - file was deleted/corrupted
LOGGER.warning("Manifest entry for %s is stale (file missing); regenerating.", path_str)
# UUID, URL, or type changed, or not in manifest
if dry_run:
# Don't write, but report what would happen
with _MANIFEST_LOCK:
is_new = path_str not in manifest_files
return (False, f"dry_run_{'create' if is_new else 'update'}")
# Write for real
content = (url + "\n").encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
# Update manifest - include URL so we can detect URL changes on next run
with _MANIFEST_LOCK:
is_new = path_str not in manifest_files
manifest_files[path_str] = {"uuid": uuid, "type": file_type, "url": url}
return (True, "created" if is_new else "updated")
def _xml_escape(text: str | None) -> str:
"""
Escape text for XML using standard library function.
Uses xml.sax.saxutils.escape for robustness against edge cases.
"""
if not text:
return ""
# xml_escape handles &, <, > by default
# Add quotes for attribute safety
return xml_escape(text).replace('"', """).replace("'", "'")
# -------------------- NFO Builders --------------------
def _nfo_movie(m: Movie, clean_name: str | None = None) -> bytes:
# Use name field - title field doesn't exist in Movie model
# Use clean_name if provided (for title tag), otherwise fall back to DB name
title = clean_name if clean_name else (m.name or "")
fields = {
"title": title,
"plot": getattr(m, "description", "") or "",
"year": str(getattr(m, "year", "") or ""),
"rating": str(getattr(m, "rating", "") or ""),
"genre": getattr(m, "genre", "") or "",
"uniqueid_tmdb": str(getattr(m, "tmdb_id", "") or ""),
"uniqueid_imdb": str(getattr(m, "imdb_id", "") or ""),
}
xml = io.StringIO()
xml.write("<movie>\n")
for tag, val in fields.items():
if val:
if tag.startswith("uniqueid_"):
typ = tag.split("_", 1)[1]
xml.write(f' <uniqueid type="{typ}">{_xml_escape(val)}</uniqueid>\n')
else:
xml.write(f" <{tag}>{_xml_escape(val)}</{tag}>\n")
logo = getattr(m, "logo", None)
if logo:
xml.write(f" <thumb>{_xml_escape(str(logo))}</thumb>\n")
xml.write("</movie>\n")
return xml.getvalue().encode("utf-8")
def _nfo_season(s: Series, season_number: int, clean_series_name: str | None = None) -> bytes:
xml = io.StringIO()
xml.write("<season>\n")
xml.write(f" <seasonnumber>{season_number}</seasonnumber>\n")
name = clean_series_name if clean_series_name else (s.name or "")
year = getattr(s, "year", None)
xml.write(f" <tvshowtitle>{_xml_escape(_series_folder_name(name, year))}</tvshowtitle>\n")
xml.write("</season>\n")
return xml.getvalue().encode("utf-8")
def _nfo_episode(e: Episode, clean_name: str | None = None) -> bytes:
# Use clean_name if provided (for title tag), otherwise fall back to DB name
title = clean_name if clean_name else (e.name or "")
fields = {
"title": title,
"season": str(getattr(e, "season_number", "") or ""),
"episode": str(getattr(e, "episode_number", "") or ""),
"aired": str(getattr(e, "air_date", "") or ""),
"plot": getattr(e, "description", "") or "",
"rating": str(getattr(e, "rating", "") or ""),
"uniqueid_tmdb": str(getattr(e, "tmdb_id", "") or ""),
"uniqueid_imdb": str(getattr(e, "imdb_id", "") or ""),
}
xml = io.StringIO()
xml.write("<episodedetails>\n")
for tag, val in fields.items():
if val:
if tag.startswith("uniqueid_"):
typ = tag.split("_", 1)[1]
xml.write(f' <uniqueid type="{typ}">{_xml_escape(val)}</uniqueid>\n')
else:
xml.write(f" <{tag}>{_xml_escape(val)}</{tag}>\n")
xml.write("</episodedetails>\n")
return xml.getvalue().encode("utf-8")
def _nfo_tvshow(s: Series, clean_name: str | None = None) -> bytes:
"""
Generate tvshow.nfo for series root directory.
Contains series-level metadata for Kodi/Plex/Jellyfin.
"""
# Use clean_name if provided, otherwise fall back to DB name
title = clean_name if clean_name else (s.name or "")
fields = {
"title": title,
"plot": getattr(s, "description", "") or "",
"year": str(getattr(s, "year", "") or ""),
"rating": str(getattr(s, "rating", "") or ""),
"genre": getattr(s, "genre", "") or "",
"uniqueid_tmdb": str(getattr(s, "tmdb_id", "") or ""),
"uniqueid_imdb": str(getattr(s, "imdb_id", "") or ""),
}
xml = io.StringIO()
xml.write("<tvshow>\n")
for tag, val in fields.items():
if val:
if tag.startswith("uniqueid_"):
typ = tag.split("_", 1)[1]
xml.write(f' <uniqueid type="{typ}">{_xml_escape(val)}</uniqueid>\n')
else:
xml.write(f" <{tag}>{_xml_escape(val)}</{tag}>\n")
logo = getattr(s, "logo", None)
if logo:
xml.write(f" <thumb>{_xml_escape(str(logo))}</thumb>\n")
xml.write("</tvshow>\n")
return xml.getvalue().encode("utf-8")
# -------------------- Filename helpers --------------------
def _episode_filename(e: Episode) -> str:
ss = getattr(e, "season_number", 0) or 0
ee = getattr(e, "episode_number", 0) or 0
title = _norm_fs_name(getattr(e, "name", "") or "Episode")
return f"S{ss:02d}E{ee:02d} - {title}.strm"
def _episode_nfo_filename(e: Episode) -> str:
ss = getattr(e, "season_number", 0) or 0
ee = getattr(e, "episode_number", 0) or 0
return f"S{ss:02d}E{ee:02d}.nfo"
def _series_expected_count(series_id: int) -> int:
return Episode.objects.filter(series_id=series_id).count()
def _compare_tree_quick(series_root: Path, expected_count: int, want_nfos: bool) -> bool:
"""
Quick short-circuit: if .strm count matches expected (and NFOs if enabled),
assume series is complete (skip expensive per-file checks).
"""
if not series_root.exists():
return False
strm_count = len(list(series_root.rglob("*.strm")))
if strm_count != expected_count:
return False
if want_nfos:
# Check for tvshow.nfo in series root
tvshow_nfo = series_root / "tvshow.nfo"
if not tvshow_nfo.exists():
return False
# Check episode NFO count
nfo_eps = len(list(series_root.rglob("S??E??.nfo")))
if nfo_eps != expected_count:
return False
return True
# -------------------- Generators --------------------
def _make_movie_strm_and_nfo(movie: Movie, base_url: str, root: Path, write_nfos: bool, report_rows: List[List[str]], lock: threading.Lock, manifest: Dict[str, Any], relation: M3UMovieRelation, dry_run: bool = False, throttle: AdaptiveThrottle | None = None, clean_regex: str | None = None, use_direct_urls: bool = False, provider_suffix: Optional[str] = None) -> None:
# Use name field - title field doesn't exist in Movie model
raw_name = movie.name or ""
movie_name = _clean_name(raw_name, clean_regex)
movie_year = getattr(movie, "year", None)
m_folder = root / "Movies" / _movie_folder_name(movie_name, movie_year)
# Build .strm filename - add provider suffix for multi-provider mode
base_filename = _movie_folder_name(movie_name, movie_year)
if provider_suffix:
# Add provider suffix: "Movie (2023) - ProviderName.strm"
strm_filename = f"{base_filename} - {_norm_fs_name(provider_suffix)}.strm"
else:
strm_filename = f"{base_filename}.strm"
strm_path = m_folder / strm_filename
# Get stream_id from relation
stream_id = getattr(relation, 'stream_id', None) if relation else None
# Build URL - either direct provider URL or proxy URL
if use_direct_urls and relation:
url = relation.get_stream_url()
if not url:
# Fallback to proxy if direct URL not available (non-XC account)
url = f"{base_url.rstrip('/')}/proxy/vod/movie/{movie.uuid}"
if stream_id:
url = f"{url}?stream_id={stream_id}"
else:
url = f"{base_url.rstrip('/')}/proxy/vod/movie/{movie.uuid}"
if stream_id:
url = f"{url}?stream_id={stream_id}"
# Time the write operation for adaptive throttling
start_time = time.time()
wrote, reason = _write_strm_if_changed(strm_path, str(movie.uuid), url, manifest, "movie", dry_run)
if wrote and throttle:
throttle.record_write(time.time() - start_time)
with lock:
report_rows.append(["movie", "", "", raw_name, getattr(movie, "year", ""), str(movie.uuid), str(strm_path), "", "written" if wrote else "skipped", reason])
if write_nfos and not dry_run:
nfo_start = time.time()
nfo_path = m_folder / "movie.nfo"
nfo_bytes = _nfo_movie(movie, clean_name=movie_name)
wrote_nfo, nfo_reason = _write_if_changed(nfo_path, nfo_bytes)
if wrote_nfo and throttle:
throttle.record_write(time.time() - nfo_start)
with lock:
report_rows.append(["movie_nfo", "", "", raw_name, movie_year or "", str(movie.uuid), "", str(nfo_path), "written" if wrote_nfo else "skipped", nfo_reason])
def _make_episode_strm_and_nfo(series: Series, episode: Episode, base_url: str, root: Path, write_nfos: bool, report_rows: List[List[str]], lock: threading.Lock, manifest: Dict[str, Any], relation: M3UEpisodeRelation, dry_run: bool = False, throttle: AdaptiveThrottle | None = None, written_seasons: set | None = None, written_tvshows: set | None = None, clean_regex: str | None = None, use_direct_urls: bool = False, provider_suffix: Optional[str] = None) -> None:
# Workaround for Dispatcharr issue #556: Validate episode still exists before writing
# Episodes can disappear mid-generation due to sync conflicts
try:
episode_exists = Episode.objects.filter(id=episode.id).exists()
if not episode_exists:
title = getattr(episode, "name", "") or ""
season_number = getattr(episode, "season_number", 0) or 0
LOGGER.warning(
"Dispatcharr issue #556: Episode id=%s (S%02dE%02d - %s) vanished from database during generation. Skipping.",
episode.id,
season_number,
getattr(episode, "episode_number", 0) or 0,
title
)
with lock:
report_rows.append(["episode", series.name or "", season_number, title, getattr(series, "year", ""), str(episode.uuid), "", "", "skipped", "episode_vanished"])
return
except Exception as validation_error:
LOGGER.debug("Episode validation check failed: %s. Continuing anyway.", validation_error)
s_folder = root / "TV" / _series_folder_name(_clean_name(series.name or "", clean_regex), getattr(series, "year", None))
season_number = getattr(episode, "season_number", 0) or 0
e_folder = s_folder / _season_folder_name(season_number)
# Build .strm filename - add provider suffix for multi-provider mode
base_strm_name = _episode_filename(episode)
if provider_suffix:
# Add provider suffix: "S01E01 - Episode Title - ProviderName.strm"
# Extract extension from base filename
base_name_without_ext = base_strm_name.rsplit('.', 1)[0] if '.' in base_strm_name else base_strm_name
ext = base_strm_name.rsplit('.', 1)[1] if '.' in base_strm_name else 'strm'
strm_name = f"{base_name_without_ext} - {_norm_fs_name(provider_suffix)}.{ext}"
else:
strm_name = base_strm_name
strm_path = e_folder / strm_name
# Get stream_id from relation
stream_id = getattr(relation, 'stream_id', None) if relation else None
# Build URL - either direct provider URL or proxy URL
if use_direct_urls and relation:
url = relation.get_stream_url()
if not url:
# Fallback to proxy if direct URL not available (non-XC account)
url = f"{base_url.rstrip('/')}/proxy/vod/episode/{episode.uuid}"
if stream_id:
url = f"{url}?stream_id={stream_id}"
else:
url = f"{base_url.rstrip('/')}/proxy/vod/episode/{episode.uuid}"
if stream_id:
url = f"{url}?stream_id={stream_id}"
# Time the write operation for adaptive throttling
start_time = time.time()
wrote, reason = _write_strm_if_changed(strm_path, str(episode.uuid), url, manifest, "episode", dry_run)
if wrote and throttle:
throttle.record_write(time.time() - start_time)
title = getattr(episode, "name", "") or ""
with lock:
report_rows.append(["episode", series.name or "", season_number, title, getattr(series, "year", ""), str(episode.uuid), str(strm_path), "", "written" if wrote else "skipped", reason])
if write_nfos and not dry_run:
# tvshow.nfo (only write once per series - in series root directory)
should_write_tvshow = False
if written_tvshows is not None:
with lock:
if series.id not in written_tvshows:
written_tvshows.add(series.id)
should_write_tvshow = True
else:
# Fallback if no set provided (shouldn't happen)
should_write_tvshow = True
if should_write_tvshow:
tvshow_start = time.time()
tvshow_nfo_path = s_folder / "tvshow.nfo"
clean_series_name = _clean_name(series.name or "", clean_regex)
tvshow_nfo_bytes = _nfo_tvshow(series, clean_name=clean_series_name)
wrote_tv, reason_tv = _write_if_changed(tvshow_nfo_path, tvshow_nfo_bytes)
if wrote_tv and throttle:
throttle.record_write(time.time() - tvshow_start)
with lock:
report_rows.append(["tvshow_nfo", series.name or "", "", "", getattr(series, "year", ""), str(series.uuid), "", str(tvshow_nfo_path), "written" if wrote_tv else "skipped", reason_tv])
# season.nfo (only write once per season)
season_key = (series.id, season_number)
should_write_season = False
if written_seasons is not None:
with lock:
if season_key not in written_seasons:
written_seasons.add(season_key)
should_write_season = True
else:
# Fallback if no set provided (shouldn't happen)
should_write_season = True
if should_write_season:
season_start = time.time()
season_nfo_path = e_folder / "season.nfo"
season_nfo_bytes = _nfo_season(series, season_number, clean_series_name=_clean_name(series.name or "", clean_regex))
wrote_s, reason_s = _write_if_changed(season_nfo_path, season_nfo_bytes)
if wrote_s and throttle:
throttle.record_write(time.time() - season_start)
with lock:
report_rows.append(["season_nfo", series.name or "", season_number, "", getattr(series, "year", ""), "", "", str(season_nfo_path), "written" if wrote_s else "skipped", reason_s])
# episode nfo
ep_start = time.time()
ep_nfo_path = e_folder / _episode_nfo_filename(episode)
# Pass cleaned episode name for consistency with movie/season NFO generation
episode_name = _clean_name(getattr(episode, "name", "") or "", clean_regex)
ep_nfo_bytes = _nfo_episode(episode, clean_name=episode_name)
wrote_e, reason_e = _write_if_changed(ep_nfo_path, ep_nfo_bytes)
if wrote_e and throttle:
throttle.record_write(time.time() - ep_start)
with lock:
report_rows.append(["episode_nfo", series.name or "", season_number, title, getattr(series, "year", ""), str(episode.uuid), "", str(ep_nfo_path), "written" if wrote_e else "skipped", reason_e])
# -------------------- Cleanup --------------------
def _cleanup(rows: List[List[str]], root: Path, manifest: Dict[str, Any], apply: bool) -> None:
"""
Identify and optionally remove stale *.strm files that reference UUIDs not present in DB.
Also deletes associated NFO files and prunes empty directories.
"""
LOGGER.info("Cleanup started (apply=%s)", apply)
manifest_files = manifest.get("files", {})
# Convert UUIDs to strings for comparison with regex-extracted UUID strings
movie_uuids = set(str(u) for u in _eligible_movie_queryset().values_list("uuid", flat=True))
allowed_series_ids = _eligible_series_queryset().values_list("id", flat=True)
episode_uuids = set(
str(u) for u in Episode.objects.filter(series_id__in=allowed_series_ids).values_list("uuid", flat=True)
)
def check_one(p: Path):
try:
# Prefer manifest as source of truth (works for both proxy and direct URLs)
path_str = str(p)
cached = manifest_files.get(path_str)
if cached:
typ = cached.get("type")
uid = cached.get("uuid")
if typ in ("movie", "episode") and uid:
present = (uid in movie_uuids) if typ == "movie" else (uid in episode_uuids)
return ("ok", (typ, uid, present))
# Fallback for legacy files or ones not tracked in manifest
data = p.read_text(encoding="utf-8", errors="ignore").strip()