-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
2328 lines (2056 loc) · 104 KB
/
Copy pathplugin.py
File metadata and controls
2328 lines (2056 loc) · 104 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
"""
EPGeditARR — Dispatcharr Plugin
Maintains transformed virtual copies of EPG sources using per-source, per-field
regex and find/replace rules. Fields are generated dynamically from the DB so
any user's EPG sources appear as toggles without hardcoded names.
Also generates fill EPG schedules for channels with no EPG data.
"""
import logging
import re
from django.db import transaction
LOGGER = logging.getLogger("plugins.epgeditarr")
VIRTUAL_PREFIX = "EPGeditARR: "
PLUGIN_KEY = "epgeditarr"
FILL_SOURCE_NAME = "EPGeditARR: Fill"
SXM_SOURCE_NAME = "EPGeditARR: SiriusXM"
SXM_EPG_URL = "https://jstevenscl.github.io/epgeditarr/siriusxm_epg.xml"
FILL_CACHE_KEY = "fill_channel_cache"
FILL_CACHE_UPDATED_KEY = "fill_channel_cache_updated"
FILL_CACHE_TTL_DAYS = 7
UNMATCHED_LOG_KEY = "sxm_unmatched_log"
# Bytes that are invalid in XML 1.0 (excludes tab \x09, newline \x0a, CR \x0d).
_INVALID_XML_BYTES = re.compile(rb'[\x00-\x08\x0b\x0c\x0e-\x1f]')
SPORTS_SCHEDULE_URL = "https://jstevenscl.github.io/epgeditarr/sports_schedule.json"
# Prevent running the heavy SXM fill (200MB download + 248k inserts) more than once per
# refresh cycle — multiple sources refreshing in quick succession each fire the signal.
SXM_FILL_COOLDOWN_SECS = 4 * 3600
# Sport team → sort key matching SiriusXM app-stream channel numbers.
# Values only affect sort ORDER within the lineup — not the actual assigned channel numbers.
_SPORT_TEAM_SORT = {
# NFL app streams (800-831) — official SiriusXM channel numbers from API
"arizona cardinals": 800, "atlanta falcons": 801, "baltimore ravens": 802,
"buffalo bills": 803, "carolina panthers": 804, "chicago bears": 805,
"cincinnati bengals": 806, "cleveland browns": 807, "dallas cowboys": 808,
"denver broncos": 809, "detroit lions": 810, "green bay packers": 811,
"houston texans": 812, "indianapolis colts": 813, "jacksonville jaguars": 814,
"kansas city chiefs": 815, "las vegas raiders": 816, "los angeles chargers": 817,
"los angeles rams": 818, "miami dolphins": 819, "minnesota vikings": 820,
"new england patriots": 821, "new orleans saints": 822, "new york giants": 823,
"new york jets": 824, "philadelphia eagles": 825, "pittsburgh steelers": 826,
"san francisco 49ers": 827, "seattle seahawks": 828, "tampa bay buccaneers": 829,
"tennessee titans": 830, "washington commanders": 831,
# MLB app streams (840-869)
"arizona diamondbacks": 840, "athletics": 841, "atlanta braves": 842,
"baltimore orioles": 843, "boston red sox": 844, "chicago cubs": 845,
"chicago white sox": 846, "cincinnati reds": 847, "cleveland guardians": 848,
"colorado rockies": 849, "detroit tigers": 850, "houston astros": 851,
"kansas city royals": 852, "los angeles angels": 853, "los angeles dodgers": 854,
"miami marlins": 855, "milwaukee brewers": 856, "minnesota twins": 857,
"new york mets": 858, "new york yankees": 859, "philadelphia phillies": 860,
"pittsburgh pirates": 861, "san diego padres": 862, "san francisco giants": 863,
"seattle mariners": 864, "st. louis cardinals": 865, "tampa bay rays": 866,
"texas rangers": 867, "toronto blue jays": 868, "washington nationals": 869,
# NBA app streams (880-909)
"atlanta hawks": 880, "boston celtics": 881, "brooklyn nets": 882,
"charlotte hornets": 883, "chicago bulls": 884, "cleveland cavaliers": 885,
"dallas mavericks": 886, "denver nuggets": 887, "detroit pistons": 888,
"golden state warriors": 889, "houston rockets": 890, "indiana pacers": 891,
"los angeles clippers": 892, "los angeles lakers": 893, "memphis grizzlies": 894,
"miami heat": 895, "milwaukee bucks": 896, "minnesota timberwolves": 897,
"new orleans pelicans": 898, "new york knicks": 899, "oklahoma city thunder": 900,
"orlando magic": 901, "philadelphia 76ers": 902, "phoenix suns": 903,
"portland trail blazers": 904, "sacramento kings": 905, "san antonio spurs": 906,
"toronto raptors": 907, "utah jazz": 908, "washington wizards": 909,
# NHL app streams (920-951)
"anaheim ducks": 920, "boston bruins": 921, "buffalo sabres": 922,
"calgary flames": 923, "carolina hurricanes": 924, "chicago blackhawks": 925,
"colorado avalanche": 926, "columbus blue jackets": 927, "dallas stars": 928,
"detroit red wings": 929, "edmonton oilers": 930, "florida panthers": 931,
"los angeles kings": 932, "minnesota wild": 933, "montreal canadiens": 934,
"nashville predators": 935, "new jersey devils": 936, "new york islanders": 937,
"new york rangers": 938, "ottawa senators": 939, "philadelphia flyers": 940,
"pittsburgh penguins": 941, "san jose sharks": 942, "seattle kraken": 943,
"st. louis blues": 944, "tampa bay lightning": 945, "toronto maple leafs": 946,
"utah hockey club": 947, "vancouver canucks": 948, "vegas golden knights": 949,
"washington capitals": 950, "winnipeg jets": 951,
}
# Hard override for user channel names that fuzzy matching can't resolve.
# Key: _normalize_channel_name(user_channel_name)
# Value: exact lowercase key in channels.json
# Only add entries when fuzzy matching genuinely fails (check unmatched log).
_CHANNEL_ALIASES = {
"pro wrestling nation24/7": "pro wrestling nation 24/7", # space before 24/7 varies
"smokey's holidaysoultown": "smokey's soul town", # channel was renamed
}
_RULE_FORMAT_HELP = (
"One rule per line. Lines starting with # are comments.\n"
"Formats:\n"
" regex::PATTERN::REPLACEMENT\n"
" replace::FIND::REPLACEMENT\n"
"Leave REPLACEMENT empty to strip the match.\n"
"Use $1 $2 in REPLACEMENT to insert capture groups.\n"
"To add text: regex::$:: (New) or regex::^::PREFIX: \n"
"Examples:\n"
" regex::S\\d+E\\d+\\s*::\n"
" replace::[HD]::\n"
" regex::^(.+)$::$1 [HD]\n"
" regex::$:: (New)"
)
class Plugin:
name = "EPGeditARR"
version = "0.2.07"
description = (
"Transform EPG program data into virtual EPG sources using "
"per-source, per-field regex and find/replace rules. "
"Also generates fill EPG schedules for channels with no EPG data."
)
def __init__(self):
self._signal_uid = "epgeditarr_transform"
self._sxm_fill_last_run = 0.0
self.fields = self._build_fields()
LOGGER.info("EPGeditARR: initialized")
self._connect_signal()
# ── Dynamic field generation ──────────────────────────────────────────
# Fields are built from the live DB so every user sees their own EPG
# sources as toggles — no hardcoded names required.
_channel_scope_fields = [
{
"id": "_section_channels",
"label": "Channel Scope",
"type": "info",
"description": (
"Controls which channels get reassigned to each virtual EPG "
"during Setup. Leave both group fields empty to reassign all "
"channels currently mapped to that source."
),
},
{
"id": "auto_reassign",
"label": "Auto-Reassign Channels on Setup",
"type": "boolean",
"default": True,
"help_text": (
"When ON, channels mapped to each enabled source are "
"automatically moved to its virtual EPG when Setup runs."
),
},
{
"id": "include_groups",
"label": "Include Channel Groups",
"type": "text",
"default": "",
"placeholder": "e.g. Sports, News, Movies",
"help_text": (
"Comma-separated group names. Only channels in these groups "
"will be reassigned. Leave empty to include all groups."
),
},
{
"id": "exclude_groups",
"label": "Exclude Channel Groups",
"type": "text",
"default": "",
"placeholder": "e.g. PPV, Adult",
"help_text": "Comma-separated group names to skip. Applied after Include Groups.",
},
]
_fill_fields = [
{
"id": "_section_fill",
"label": "EPG Fill",
"type": "info",
"description": (
"Generate a repeating placeholder EPG schedule for channels that have no EPG data. "
"Use 'Scan' to discover which channels need filling, then set Fill Groups "
"and optionally add channel names to Skip Channels."
),
},
{
"id": "fill_groups",
"label": "Fill Groups",
"type": "text",
"default": "",
"placeholder": "e.g. Radio, Local",
"help_text": (
"Comma-separated channel group names. Channels in these groups "
"with no EPG will get a generated schedule. Leave empty to disable."
),
},
{
"id": "fill_skip_channels",
"label": "Skip Channels",
"type": "text",
"default": "",
"placeholder": "Sports 969\nSports 970\nSports 971",
"help_text": (
"One channel name per line. These channels are excluded from Fill EPG "
"even if they are in a Fill Group. Copy names from Scan output."
),
},
{
"id": "_section_schedule",
"label": "── Schedule Settings ───────────────────────────",
"type": "info",
"description": (
"Block Duration and Days Ahead apply to both Fill EPG and SiriusXM Fill. "
"Both features use these same schedule generation settings."
),
},
{
"id": "fill_block_hours",
"label": "Block Duration",
"type": "select",
"options": [
{"value": "1", "label": "1 hour"},
{"value": "2", "label": "2 hours"},
{"value": "4", "label": "4 hours"},
{"value": "6", "label": "6 hours"},
{"value": "12", "label": "12 hours"},
{"value": "24", "label": "24 hours"},
],
"default": "1",
"help_text": "Duration of each generated program block. Used by both Fill EPG and SiriusXM Fill.",
},
{
"id": "fill_days_ahead",
"label": "Days Ahead",
"type": "select",
"options": [
{"value": "7", "label": "7 days"},
{"value": "14", "label": "14 days"},
{"value": "30", "label": "30 days"},
],
"default": "14",
"help_text": "How many days of schedule to generate ahead. Used by both Fill EPG and SiriusXM Fill.",
},
{
"id": "_section_siriusxm",
"label": "── SiriusXM Channels Only ──────────────────────",
"type": "info",
"description": (
"The settings and actions below apply exclusively to SiriusXM channels "
"and use the SiriusXM Channel Group setting below — completely separate from "
"Fill Groups above. Channel data (names, descriptions, lineup order) is fetched "
"from the official SiriusXM API and cached locally. Cache auto-refreshes every 7 days — use "
"'Refresh Channel Data' to force an immediate update. Channel names are matched "
"case-insensitively with fuzzy fallbacks for common variations (leading quotes, "
"'The ' prefix, '&' vs 'and')."
),
},
{
"id": "sxm_groups",
"label": "SiriusXM Channel Group",
"type": "text",
"default": "",
"placeholder": "e.g. SiriusXM",
"help_text": (
"Comma-separated channel group name(s) that contain your SiriusXM channels. "
"All SiriusXM actions (Sort, Fill, Rename, Logos) operate exclusively on these groups."
),
},
{
"id": "fill_sxm_enrich",
"label": "Enable SiriusXM Enrichment",
"type": "boolean",
"default": False,
"help_text": (
"SiriusXM only — matches channel names against the official SiriusXM channel database and adds real "
"descriptions to generated EPG entries."
),
},
{
"id": "sort_start_number",
"label": "Sort Start Number",
"type": "text",
"default": "",
"placeholder": "Auto-detect from current channel range",
"help_text": (
"SiriusXM only — channel number assigned to the first sorted channel. "
"Leave blank to automatically use the lowest channel number in your SiriusXM Channel Group."
),
},
]
# Regex patterns used by _action_sample — one section per category shown
_SAMPLE_PATTERNS = {
"episode": r"S\d+E\d+|\bE\d{2,3}\b|\b\d+x\d+\b",
"broadcast": r"\((New|Live|Rerun|Re-run|Repeat|Encore|Premiere|Finale|Special)\)|\[LIVE\]",
"quality": r"\[(HD|4K|UHD|FHD|SD|HDR)\]",
"technical": r"\((CC|SAP|DVS|Stereo|Widescreen|Subtitled)\)",
"year": r"\((19|20)\d{2}\)",
"gracenote": r"\(INFO\)|\(Censored\)|\[as\]",
"unicode": r"ᴺᵉʷ|ᴸᶦᵛᵉ|ᴾʳᵉ|ᴿᵉᵖ|ᴵⁿᶠᵒ|ᴼᵛᵉʳ",
"any": r"[\(\[]",
}
def _build_fields(self):
sources = []
try:
from apps.epg.models import EPGSource
sources = list(EPGSource.objects.exclude(source_type="dummy").order_by("name"))
except Exception as e:
LOGGER.debug(f"EPGeditARR: could not load sources for field generation: {e}")
# ── Source rule sections ──
fields = [
{
"id": "_section_sources",
"label": "EPG Sources",
"type": "info",
"description": (
"Each non-dummy EPG source configured in Dispatcharr appears "
"below as its own section. Enable the sources you want to "
"transform and add rules for each field you want to modify.\n\n"
+ _RULE_FORMAT_HELP
),
}
]
if sources:
for source in sources:
sid = source.id
fields += [
{
"id": f"_section_src_{sid}",
"label": source.name,
"type": "info",
"description": (
f"Virtual EPG will be named '{VIRTUAL_PREFIX}{source.name}'. "
f"Enable the toggle below to activate transformation for this source."
),
},
{
"id": f"src_{sid}_enabled",
"label": "Enable transformation",
"type": "boolean",
"default": False,
"help_text": (
f"Create and keep a virtual transformed copy of "
f"'{source.name}' in sync after each refresh."
),
},
{
"id": f"src_{sid}_title_rules",
"label": "Title Rules",
"type": "text",
"default": "",
"placeholder": "regex::S\\d+E\\d+\\s*::\nreplace::[HD]::",
"help_text": "Rules applied to the program title. One per line.",
},
{
"id": f"src_{sid}_subtitle_rules",
"label": "Sub-Title Rules",
"type": "text",
"default": "",
"placeholder": "replace::(New)::",
"help_text": "Rules applied to the episode sub-title. One per line.",
},
{
"id": f"src_{sid}_description_rules",
"label": "Description Rules",
"type": "text",
"default": "",
"placeholder": "regex::^\\[.*?\\]\\s*::",
"help_text": "Rules applied to the program description. One per line.",
},
]
else:
fields.append({
"id": "_no_sources_info",
"label": "Sources unavailable",
"type": "info",
"description": (
"EPG sources could not be loaded from the database. "
"Ensure sources are configured in M3U & EPG Manager, "
"then reload the plugin."
),
})
# ── Rule Tester (dynamic: source dropdown built from live DB) ──
source_options = [{"value": str(s.id), "label": s.name} for s in sources]
default_source = str(sources[0].id) if sources else ""
tester_fields = [
{
"id": "_section_tester",
"label": "Rule Tester",
"type": "info",
"description": (
"Test a rule against live data from any source before adding it to the rules list. "
"Select a source and field, enter a pattern, then click 'Test Rule'. "
"A diverse sample of real values will be pulled automatically — "
"or paste your own text into 'Test Text' to test against that instead."
),
},
{
"id": "test_source_id",
"label": "Test Source",
"type": "select",
"options": source_options,
"default": default_source,
"help_text": "Which EPG source to pull live test data from.",
},
{
"id": "test_field",
"label": "Test Field",
"type": "select",
"options": [
{"value": "title", "label": "Title"},
{"value": "sub_title", "label": "Sub-Title"},
{"value": "description", "label": "Description"},
],
"default": "title",
"help_text": "Which program field to test the rule against.",
},
{
"id": "test_type",
"label": "Use Regex (OFF = literal find/replace)",
"type": "boolean",
"default": True,
"help_text": "ON = regex pattern, OFF = literal text find/replace.",
},
{
"id": "test_pattern",
"label": "Pattern / Find",
"type": "text",
"default": "",
"placeholder": "e.g. S\\d+E\\d+\\s*",
"help_text": "The regex pattern or literal text to find.",
},
{
"id": "test_replacement",
"label": "Replacement",
"type": "text",
"default": "",
"placeholder": "Leave empty to strip the match",
"help_text": "What to replace the match with. Leave empty to remove it entirely.",
},
{
"id": "test_input",
"label": "Test Text (optional)",
"type": "text",
"default": "",
"placeholder": "Leave empty to use live source data automatically",
"help_text": (
"Optional. Paste specific text to test against. "
"If empty, real values are sampled automatically from the selected source and field."
),
},
]
return fields + self._channel_scope_fields + self._fill_fields + tester_fields
# ── Signal management ─────────────────────────────────────────────────
# One signal watches all EPGSources. On each successful refresh it reads
# current settings from the DB (so rule changes take effect immediately
# without re-running Setup) and transforms the matching source.
def _connect_signal(self):
from apps.epg.models import EPGSource
from django.db.models.signals import post_save
def _on_epg_refresh(sender, instance, **kwargs):
if instance.source_type == "dummy":
return
update_fields = kwargs.get("update_fields")
status_saved = update_fields is None or "status" in (update_fields or [])
if not status_saved or instance.status != "success":
return
try:
from apps.plugins.models import PluginConfig
cfg = PluginConfig.objects.filter(key=PLUGIN_KEY, enabled=True).first()
if not cfg:
return
settings = cfg.settings
except Exception as e:
LOGGER.debug(f"EPGeditARR: signal could not read settings: {e}")
return
if settings.get(f"src_{instance.id}_enabled", False):
LOGGER.info(f"EPGeditARR: '{instance.name}' refreshed — transforming")
try:
self._do_transform_source(instance, settings)
except Exception as e:
LOGGER.error(f"EPGeditARR: transform failed for '{instance.name}': {e}")
if settings.get("fill_groups", "").strip():
LOGGER.info(f"EPGeditARR: running Fill EPG after '{instance.name}' refresh")
try:
self._action_fill_epg(settings, LOGGER)
except Exception as e:
LOGGER.error(f"EPGeditARR: auto Fill EPG failed: {e}")
if settings.get("sxm_groups", "").strip() and settings.get("fill_sxm_enrich"):
import time as _time
_now = _time.monotonic()
if _now - self._sxm_fill_last_run >= SXM_FILL_COOLDOWN_SECS:
self._sxm_fill_last_run = _now
LOGGER.info(f"EPGeditARR: running SiriusXM Fill after '{instance.name}' refresh")
try:
self._action_sxm_fill_epg(settings, LOGGER)
except Exception as e:
LOGGER.error(f"EPGeditARR: auto SiriusXM Fill EPG failed: {e}")
else:
LOGGER.info(
f"EPGeditARR: SiriusXM Fill cooldown active — skipping auto-run "
f"after '{instance.name}' (runs at most every 4 h)"
)
post_save.connect(
_on_epg_refresh,
sender=EPGSource,
weak=False,
dispatch_uid=self._signal_uid,
)
LOGGER.info("EPGeditARR: refresh signal connected")
def _disconnect_signal(self):
from apps.epg.models import EPGSource
from django.db.models.signals import post_save
post_save.disconnect(sender=EPGSource, dispatch_uid=self._signal_uid)
LOGGER.info("EPGeditARR: signal disconnected")
def stop(self, context):
self._disconnect_signal()
# ── Rule engine ───────────────────────────────────────────────────────
def _parse_rules(self, text):
rules = []
for line in (text or "").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("::")
if len(parts) < 3:
LOGGER.warning(f"EPGeditARR: malformed rule skipped: {line!r}")
continue
kind, arg1, arg2 = parts[0].strip().lower(), parts[1], parts[2]
if kind == "regex":
try:
# Convert $1 $2 capture-group syntax → Python's \1 \2
replacement = re.sub(r'\$(\d+)', r'\\\1', arg2)
rules.append({
"type": "regex",
"pattern": re.compile(arg1),
"replacement": replacement,
"raw": arg1,
})
except re.error as e:
LOGGER.warning(f"EPGeditARR: bad regex '{arg1}': {e}")
elif kind in ("replace", "find_replace"):
rules.append({"type": "replace", "find": arg1, "replacement": arg2})
else:
LOGGER.warning(f"EPGeditARR: unknown rule type '{kind}' — skipping")
return rules
def _apply_rules(self, value, rules):
if not value or not rules:
return value
for rule in rules:
if rule["type"] == "regex":
value = rule["pattern"].sub(rule["replacement"], value)
else:
value = value.replace(rule["find"], rule["replacement"])
return value.strip() if value else value
def _get_source_field_rules(self, source_id, settings):
return {
"title": self._parse_rules(settings.get(f"src_{source_id}_title_rules", "")),
"sub_title": self._parse_rules(settings.get(f"src_{source_id}_subtitle_rules", "")),
"description": self._parse_rules(settings.get(f"src_{source_id}_description_rules", "")),
}
def _rule_summary_for_source(self, source_id, settings):
lines = []
for label, key in [
("Title", f"src_{source_id}_title_rules"),
("Sub-Title", f"src_{source_id}_subtitle_rules"),
("Description", f"src_{source_id}_description_rules"),
]:
rules = self._parse_rules(settings.get(key, ""))
if rules:
descs = []
for r in rules:
if r["type"] == "regex":
descs.append(f"regex({r['raw']!r} → {r['replacement']!r})")
else:
descs.append(f"replace({r['find']!r} → {r['replacement']!r})")
lines.append(f" {label}: " + ", ".join(descs))
return "\n".join(lines) if lines else " (no rules configured)"
# ── EPG helpers ───────────────────────────────────────────────────────
def _get_enabled_sources(self, settings):
"""Return list of EPGSource instances that have been enabled in settings."""
from apps.epg.models import EPGSource
results = []
for source in EPGSource.objects.exclude(source_type="dummy").order_by("name"):
if settings.get(f"src_{source.id}_enabled", False):
results.append(source)
return results
def _get_or_create_virtual(self, source):
from apps.epg.models import EPGSource
virtual_name = f"{VIRTUAL_PREFIX}{source.name}"
virtual, created = EPGSource.objects.get_or_create(
name=virtual_name,
defaults={
"source_type": "dummy",
"custom_properties": {"epgeditarr_source_id": source.id},
},
)
if not created:
props = dict(virtual.custom_properties or {})
props["epgeditarr_source_id"] = source.id
virtual.custom_properties = props
virtual.save(update_fields=["custom_properties"])
return virtual, created
def _sync_epgdata(self, source, virtual):
"""Ensure virtual EPGSource has an EPGData entry for every entry in source."""
from apps.epg.models import EPGData
source_entries = list(EPGData.objects.filter(epg_source=source))
existing = {e.tvg_id: e for e in EPGData.objects.filter(epg_source=virtual)}
to_create = [
EPGData(tvg_id=se.tvg_id, name=se.name, icon_url=se.icon_url, epg_source=virtual)
for se in source_entries
if se.tvg_id not in existing
]
if to_create:
EPGData.objects.bulk_create(to_create, ignore_conflicts=True)
return {e.tvg_id: e for e in EPGData.objects.filter(epg_source=virtual)}
def _channel_qs(self, source, settings):
from apps.channels.models import Channel
qs = Channel.objects.filter(epg_data__epg_source=source)
include = [g.strip() for g in (settings.get("include_groups") or "").split(",") if g.strip()]
exclude = [g.strip() for g in (settings.get("exclude_groups") or "").split(",") if g.strip()]
if include:
qs = qs.filter(channel_group__name__in=include)
if exclude:
qs = qs.exclude(channel_group__name__in=exclude)
return qs
@staticmethod
def _normalize_channel_name(name):
"""Return a consistent lowercase key for channel name matching.
Handles leading curly/straight quotes (e.g. Wikipedia ‘'40s Junction’),
trailing parentheticals, and Wikipedia footnote markers.
"""
name = re.sub(r"^[\'\"‘’“”\s]+", '', name)
name = re.sub(r'\s*\[[^\]]{1,5}\]', '', name)
name = re.sub(r'\s*\(.*', '', name)
return name.lower().strip()
@staticmethod
def _fuzzy_channel_keys(name):
"""Return normalized lookup keys to try for a channel name (most specific first).
Generates prefix variants (strip/add 'the '/'siriusxm ') and suffix variants
(strip/add ' radio'/' channel'/' network'/' live') so names like 'Holly' match
'SiriusXM Holly', 'Grateful Dead' matches 'The Grateful Dead Channel', etc.
Also strips trailing lone digits so 'Limited Edition 1' matches 'Limited Edition'.
"""
base = Plugin._normalize_channel_name(name)
seen, keys = {base}, [base]
def add(k):
if k and len(k) >= 2 and k not in seen:
seen.add(k)
keys.append(k)
# Prefix variants: strip or add 'the ' / 'siriusxm ' / 'sirius xm '
no_the = base[4:] if base.startswith('the ') else None
no_sxm = base[9:] if base.startswith('siriusxm ') else None
no_sxm2 = base[10:] if base.startswith('sirius xm ') else None
# Core = base with any SXM prefix stripped, used to build cross-variants
_core = no_sxm if no_sxm is not None else (no_sxm2 if no_sxm2 is not None else base)
with_the = None if base.startswith('the ') else 'the ' + base
with_sxm = None if base.startswith('siriusxm ') else 'siriusxm ' + _core
with_sxm2 = None if base.startswith('sirius xm ') else 'sirius xm ' + _core
for v in (no_the, no_sxm, no_sxm2, with_the, with_sxm, with_sxm2):
if v: add(v)
# Suffix variants for each prefix variant
SUFFIXES = (' radio', ' channel', ' network', ' live')
for b in (base, no_the, no_sxm, no_sxm2, with_the, with_sxm, with_sxm2):
if not b:
continue
for sfx in SUFFIXES:
if b.endswith(sfx):
add(b[:-len(sfx)])
else:
add(b + sfx)
# & ↔ and for all variants collected so far
for k in list(keys):
amp = re.sub(r'\s+&\s+', ' and ', k)
if amp != k: add(amp)
andd = re.sub(r'\band\b', '&', k)
if andd != k: add(andd)
return keys
@staticmethod
def _official_channel_name(enrich):
"""Return a clean display name from a channels.json entry, fixing Wikipedia formatting artifacts."""
name = enrich.get("name", "")
name = re.sub(r'\s*\(.*', '', name) # strip "(formerly ...)" parentheticals
name = re.sub(r"(\w) ' (\w)", r"\1' \2", name) # "Valdes ' Cuba" → "Valdes' Cuba"
name = re.sub(r" 's\b", "'s", name) # "Cohen 's" → "Cohen's"
return name.strip()
def _lookup_enrich(self, cache, name):
"""Try multiple normalized variants of name against cache; return first hit or {}."""
normalized = self._normalize_channel_name(name)
alias_key = _CHANNEL_ALIASES.get(normalized)
if alias_key:
hit = cache.get(alias_key)
if hit:
return hit
for key in self._fuzzy_channel_keys(name):
hit = cache.get(key)
if hit:
return hit
return {}
def _channel_tvg_id(self, channel_name):
slug = re.sub(r'[^a-z0-9]+', '-', channel_name.lower()).strip('-')
return f"epgeditarr-fill-{slug}"
def _get_fill_channels(self, settings):
"""Return Channel objects eligible for fill EPG (in fill groups, no EPG or on a dummy source)."""
from django.db.models import Q
from apps.channels.models import Channel
from apps.epg.models import EPGSource
fill_group_names = [g.strip() for g in (settings.get('fill_groups') or '').split(',') if g.strip()]
if not fill_group_names:
return []
# Include channels with no EPG, already on our fill, or on any dummy source
# (covers Dispatcharr's built-in dummy fill so we can replace it)
qs = Channel.objects.filter(channel_group__name__in=fill_group_names).filter(
Q(epg_data__isnull=True) | Q(epg_data__epg_source__source_type='dummy')
)
skip = {n.strip().lower() for n in (settings.get('fill_skip_channels') or '').splitlines() if n.strip()}
return [c for c in qs.select_related('channel_group') if c.name.lower() not in skip]
def _get_sxm_channels(self, settings):
"""Return Channel objects eligible for SiriusXM fill EPG (in sxm_groups, no EPG or on a dummy/SXM source)."""
from django.db.models import Q
from apps.channels.models import Channel
sxm_group_names = [g.strip() for g in (settings.get('sxm_groups') or '').split(',') if g.strip()]
if not sxm_group_names:
return []
# Include channels with no EPG, on any dummy source (Dispatcharr built-in),
# or already on our SXM XMLTV source (so they can be re-matched)
qs = Channel.objects.filter(channel_group__name__in=sxm_group_names).filter(
Q(epg_data__isnull=True)
| Q(epg_data__epg_source__source_type='dummy')
| Q(epg_data__epg_source__name=SXM_SOURCE_NAME)
)
return list(qs.select_related('channel_group'))
def _load_sxm_cache(self, settings):
"""Return (cache_dict, was_refreshed). Auto-refreshes if stale or missing.
Always reads from the database — frontend-provided settings may carry a
stale cached blob that pre-dates a recent Refresh Channel Data call.
"""
from datetime import datetime
from apps.plugins.models import PluginConfig
cfg = PluginConfig.objects.filter(key=PLUGIN_KEY).first()
db_settings = cfg.settings or {} if cfg else {}
cache = db_settings.get(FILL_CACHE_KEY) or {}
updated_str = db_settings.get(FILL_CACHE_UPDATED_KEY) or ''
has_sxm = any(v.get('sxm_number') is not None for v in cache.values())
if cache and updated_str and has_sxm:
try:
updated = datetime.fromisoformat(updated_str)
if (datetime.utcnow() - updated).days < FILL_CACHE_TTL_DAYS:
return cache, False
except Exception:
pass
fresh = self._fetch_sxm_data()
self._save_fill_cache(fresh)
return fresh, True
def _save_fill_cache(self, data):
from datetime import datetime
from apps.plugins.models import PluginConfig
cfg = PluginConfig.objects.filter(key=PLUGIN_KEY).first()
if not cfg:
return
s = dict(cfg.settings or {})
s[FILL_CACHE_KEY] = data
s[FILL_CACHE_UPDATED_KEY] = datetime.utcnow().isoformat()
cfg.settings = s
cfg.save(update_fields=['settings'])
def _append_unmatched_log(self, names):
"""Add channel names that failed SXM matching to a persistent log for alias review."""
if not names:
return
try:
from apps.plugins.models import PluginConfig
cfg = PluginConfig.objects.filter(key=PLUGIN_KEY).first()
if not cfg:
return
s = dict(cfg.settings or {})
existing = list(s.get(UNMATCHED_LOG_KEY) or [])
seen = {n.lower() for n in existing}
added = False
for n in names:
if n.strip() and n.lower() not in seen:
existing.append(n)
seen.add(n.lower())
added = True
if added:
s[UNMATCHED_LOG_KEY] = sorted(existing, key=str.lower)
cfg.settings = s
cfg.save(update_fields=['settings'])
except Exception:
pass
def _fetch_sxm_data(self):
"""Fetch SiriusXM channel data. Tries GitHub Pages pre-built cache first, falls back to Wikipedia."""
import urllib.request
import json
headers = {"User-Agent": "EPGeditARR-Plugin/2.0 (Dispatcharr plugin; github.com/jstevenscl/epgeditarr)"}
# Primary: GitHub Pages pre-built cache (Wikipedia + siriusxm.com merged)
cache_url = "https://jstevenscl.github.io/epgeditarr/channels.json"
try:
req = urllib.request.Request(cache_url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
if data:
has_numbers = sum(1 for v in data.values() if v.get("sxm_number") is not None)
LOGGER.info(f"EPGeditARR: fetched {len(data)} channels from GitHub cache ({has_numbers} with lineup positions)")
return data
except Exception as e:
LOGGER.warning(f"EPGeditARR: GitHub cache unavailable ({e}), falling back to Wikipedia")
# Fallback: fetch Wikipedia directly
return self._fetch_from_wikipedia()
def _fetch_from_wikipedia(self):
"""Fetch SiriusXM channel data directly from Wikipedia (fallback)."""
import urllib.request
import json
headers = {"User-Agent": "EPGeditARR-Plugin/2.0 (Dispatcharr plugin; github.com/jstevenscl/epgeditarr)"}
candidate_pages = [
"List_of_SiriusXM_Radio_channels",
"List_of_SiriusXM_channels",
"List_of_Sirius_XM_channels",
]
last_error = "no candidates tried"
for page in candidate_pages:
url = (
f"https://en.wikipedia.org/w/api.php"
f"?action=parse&page={page}&prop=text&format=json&redirects=1"
)
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
raw = json.loads(resp.read().decode("utf-8"))
except Exception as e:
last_error = f"network error fetching '{page}': {e}"
continue
if "error" in raw:
last_error = f"Wikipedia API error for '{page}': {raw['error'].get('info', raw['error'])}"
LOGGER.debug(f"EPGeditARR: {last_error}")
continue
html = raw.get("parse", {}).get("text", {}).get("*", "")
if not html:
last_error = f"empty HTML for '{page}' (keys: {list(raw.get('parse', {}).keys())})"
continue
result = self._parse_wiki_tables(html)
if result:
LOGGER.info(f"EPGeditARR: fetched {len(result)} SiriusXM channels from Wikipedia '{page}'")
return result
last_error = f"no parseable channel tables found in '{page}'"
raise RuntimeError(f"Could not fetch SiriusXM data — {last_error}")
def _parse_wiki_tables(self, html):
"""Parse MediaWiki HTML tables → dict of lowercased_name → {name, description, genre, sxm_number, seasonal}."""
channels = {}
def clean(text):
text = re.sub(r'<[^>]+>', ' ', text)
for ent, rep in [
('&', '&'), ('<', '<'), ('>', '>'),
(' ', ' '), (' ', ' '), (''', "'"), ('"', '"'),
]:
text = text.replace(ent, rep)
return re.sub(r'\s+', ' ', text).strip()
_MONTH = {
'january': 1, 'february': 2, 'march': 3, 'april': 4,
'may': 5, 'june': 6, 'july': 7, 'august': 8,
'september': 9, 'october': 10, 'november': 11, 'december': 12,
}
def _parse_season(heading):
"""Return [start_month, end_month] from a heading like 'early November – early January', or None."""
months = re.findall(
r'(january|february|march|april|may|june|july|august|'
r'september|october|november|december)',
heading.lower()
)
if len(months) >= 2:
return [_MONTH[months[0]], _MONTH[months[1]]]
return None
# Split the HTML by heading tags so we can track which section each table belongs to.
# sections alternates: content_chunk, heading_tag, content_chunk, heading_tag, ...
parts = re.split(r'(<h[234][^>]*>.*?</h[234]>)', html, flags=re.DOTALL | re.IGNORECASE)
current_season = None
def _process_tables_in(chunk, seasonal):
for table_m in re.finditer(
r'<table[^>]+class="[^"]*wikitable[^"]*"[^>]*>(.*?)</table>',
chunk, re.DOTALL | re.IGNORECASE
):
table = table_m.group(1)
rows = re.findall(r'<tr[^>]*>(.*?)</tr>', table, re.DOTALL | re.IGNORECASE)
if len(rows) < 2:
continue
headers = []
for row in rows:
ths = re.findall(r'<th[^>]*>(.*?)</th>', row, re.DOTALL | re.IGNORECASE)
if ths:
headers = [clean(h).lower() for h in ths]
break
if not headers:
continue
name_idx = next((i for i, h in enumerate(headers) if 'name' in h), None)
desc_idx = next((i for i, h in enumerate(headers) if 'descri' in h or ('format' in h and 'name' not in h)), None)
genre_idx = next((i for i, h in enumerate(headers) if 'genre' in h), None)
num_idx = next((
i for i, h in enumerate(headers)
if h in ('channel', 'ch', 'ch.', '#', 'no.', 'no', 'number',
'siriusxm', 'sirius xm', 'sirius',
'siriusxm #', 'xm #', 'sirius #') and 'name' not in h
), None)
if name_idx is None:
continue
for row in rows:
tds = re.findall(r'<td[^>]*>(.*?)</td>', row, re.DOTALL | re.IGNORECASE)
if not tds or name_idx >= len(tds):
continue
name = clean(tds[name_idx])
name_key = self._normalize_channel_name(name)
if not name_key or len(name_key) < 2 or name_key in ('tba', 'tbd', 'vacant', 'n/a', '—', '-'):
continue
desc = clean(tds[desc_idx]) if desc_idx is not None and desc_idx < len(tds) else ''
genre = clean(tds[genre_idx]) if genre_idx is not None and genre_idx < len(tds) else ''
sxm_number = None
if num_idx is not None and num_idx < len(tds):
num_raw = re.sub(r'\[.*?\]', '', clean(tds[num_idx])).strip()
m = re.match(r'\d+', num_raw)
if m:
sxm_number = int(m.group())
channels[name_key] = {
'name': name, 'description': desc, 'genre': genre,