-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathgenerate_playlist.py
More file actions
973 lines (829 loc) · 31.7 KB
/
Copy pathgenerate_playlist.py
File metadata and controls
973 lines (829 loc) · 31.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
#########################
### Author: @imshakil ###
#########################
import os
import argparse
import base64
import hashlib
import hmac
import time
import re
import json
from urllib.parse import urlsplit, urlunsplit
from concurrent.futures import ThreadPoolExecutor
import requests
from cryptography.fernet import Fernet, InvalidToken
from dotenv import load_dotenv
PREMIUM_CHANNELS = [
{
"name": "DekhoPrime TSports",
"group": "Sports",
"logo": "https://raw.githubusercontent.com/imShakil/tvlink/refs/heads/main/dekho-prime-icon-192.webp",
"pin": True,
"streams": {
"server_1" : {
"url": "https://trs1.aynaott.com/tsports/index.m3u8",
"headers": {},
},
},
"name": "DekhoPrime CrazeTV",
"group": "Sports",
"logo": "https://raw.githubusercontent.com/imShakil/tvlink/refs/heads/main/dekho-prime-icon-192.webp",
"pin": True,
"streams": {
"server_1" : {
"url": "https://dfr80qz435crc.cloudfront.net/MNOP/Amagi/Caze/Caze_TV_BR/Caze_TV.m3u8",
"headers": {},
},
},
},
]
def normalize_source(source):
source = source.strip()
return source
def clean_channel_url(raw_url):
"""
Extract a usable URL from malformed lines like:
http://...m3u8#EXTINF:-1 ...
"""
value = raw_url.strip()
inline_extinf_pos = value.find("#EXTINF:")
if inline_extinf_pos > 0:
value = value[:inline_extinf_pos].strip()
return value
def split_extinf_metadata_and_name(extinf_line):
"""
Split an EXTINF line into metadata and channel name by the first comma
that is outside quoted segments.
"""
in_quotes = False
for idx, ch in enumerate(extinf_line):
if ch == '"':
in_quotes = not in_quotes
continue
if ch == "," and not in_quotes:
metadata = extinf_line[:idx]
channel_name = extinf_line[idx + 1 :].strip()
return metadata, channel_name
return extinf_line, "Unknown"
def dedupe_url_key(raw_url):
"""
Build a stable dedupe key for stream URLs.
- trims spaces
- strips query string and fragment (often used for cache-busting like ?v=1)
"""
cleaned = clean_channel_url(raw_url)
try:
parts = urlsplit(cleaned)
except ValueError:
return cleaned
return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
def is_channel_stream_url(raw_url):
"""
Keep live-stream style URLs and skip direct video-file links.
"""
cleaned = clean_channel_url(raw_url)
try:
parts = urlsplit(cleaned)
except ValueError:
return False
if parts.scheme not in {"http", "https"}:
return False
path = (parts.path or "").lower()
return path.endswith((".m3u8", ".m3u", ".ts", ".mpd"))
def _clean_group_text(value):
lowered = value.strip().lower()
lowered = lowered.replace("&", " and ")
lowered = lowered.replace("/", " ")
lowered = lowered.replace("-", " ")
lowered = re.sub(r"[^a-z0-9 ]+", " ", lowered)
lowered = re.sub(r"\s+", " ", lowered).strip()
return lowered
def load_group_normalization_rules(rules_file):
if not rules_file:
return {"exact": {}, "contains": []}
if not os.path.exists(rules_file):
print(f"Group normalization file not found: {rules_file} (using fallback normalization)")
return {"exact": {}, "contains": []}
try:
with open(rules_file, "r", encoding="utf-8") as f:
raw = json.load(f)
except (OSError, json.JSONDecodeError) as err:
print(f"Failed to load group normalization file: {rules_file} ({err})")
return {"exact": {}, "contains": []}
exact_map = {}
for raw_key, raw_value in (raw.get("exact") or {}).items():
key = _clean_group_text(str(raw_key))
value = str(raw_value).strip()
if key and value:
exact_map[key] = value
contains_rules = []
for item in (raw.get("contains") or []):
if not isinstance(item, dict):
continue
group = str(item.get("group", "")).strip()
raw_tokens = item.get("tokens", [])
if not group or not isinstance(raw_tokens, list):
continue
tokens = []
for token in raw_tokens:
cleaned_token = _clean_group_text(str(token))
if cleaned_token:
tokens.append(cleaned_token)
if tokens:
contains_rules.append({"tokens": tuple(tokens), "group": group})
return {"exact": exact_map, "contains": contains_rules}
def normalize_group_name(raw_group, rules):
cleaned = _clean_group_text(raw_group or "")
if not cleaned:
return "Live"
exact_map = (rules or {}).get("exact", {})
contains_rules = (rules or {}).get("contains", [])
if cleaned in exact_map:
return exact_map[cleaned]
for rule in contains_rules:
tokens = rule["tokens"]
if all(token in cleaned for token in tokens):
return rule["group"]
return "Live"
def encrypted_label(source, cipher_key):
full_source_url = normalize_source(source)
# Deterministic source ID to keep output stable across runs with same input.
digest = hmac.new(
cipher_key.encode("utf-8"),
full_source_url.encode("utf-8"),
hashlib.sha256,
).hexdigest()
return f"SRC-ID:{digest[:24]}"
def decode_encrypted_label(label, cipher_key):
if not label.startswith("SRC-ENC:"):
return None
token = label.split("SRC-ENC:", 1)[1]
try:
value = Fernet(cipher_key.encode("utf-8")).decrypt(token.encode("utf-8"))
return value.decode("utf-8")
except (InvalidToken, ValueError):
return None
def resolve_source_id_label(label, cipher_key, sources):
if not label.startswith("SRC-ID:"):
return None
target = label.split("SRC-ID:", 1)[1].strip()
for source in sources:
candidate = encrypted_label(source, cipher_key)
candidate_id = candidate.split("SRC-ID:", 1)[1]
if hmac.compare_digest(candidate_id, target):
return source
return None
def parse_sources(raw_sources):
if not raw_sources:
return []
sources = []
for part in raw_sources.replace(",", "\n").splitlines():
source = part.strip()
if source:
sources.append(normalize_source(source))
return sources
def parse_legacy_dotenv_sources(dotenv_path=".env"):
try:
with open(dotenv_path, "r", encoding="utf-8") as f:
raw_lines = f.readlines()
except OSError:
return []
lines = []
for line in raw_lines:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if "=" in stripped:
continue
lines.append(stripped)
return lines
def is_url_live(session, url, timeout_seconds=10, retries=3):
headers = {
"User-Agent": "Mozilla/5.0 (compatible; tvlink-liveness/1.0)",
"Accept": "*/*",
}
not_allowed_status = {404, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511}
for attempt in range(retries + 1):
response = None
try:
response = session.get(
url,
stream=True,
timeout=(8, timeout_seconds),
headers=headers,
allow_redirects=True,
)
if response.status_code not in not_allowed_status:
return {
"is_live": True,
"status_code": response.status_code,
"reason": "ok",
"attempts": attempt + 1,
"error": "",
}
if attempt < retries:
time.sleep(0.5 * (attempt + 1))
continue
return {
"is_live": False,
"status_code": response.status_code,
"reason": "http_status",
"attempts": attempt + 1,
"error": "",
}
except requests.RequestException as err:
if attempt < retries:
time.sleep(0.5 * (attempt + 1))
continue
return {
"is_live": False,
"status_code": None,
"reason": "request_exception",
"attempts": attempt + 1,
"error": err.__class__.__name__,
}
finally:
if response is not None:
response.close()
return {
"is_live": False,
"status_code": None,
"reason": "unknown",
"attempts": retries + 1,
"error": "unknown",
}
def validate_candidates(candidates, max_workers, timeout_seconds, retries, log_file=""):
if not candidates:
return []
def check(candidate):
session = requests.Session()
try:
return is_url_live(
session,
candidate["url"],
timeout_seconds=timeout_seconds,
retries=retries,
)
finally:
session.close()
accepted = []
logs = []
potentially_live = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = executor.map(check, candidates)
for candidate, result in zip(candidates, results):
if result["is_live"]:
accepted.append(candidate)
elif result["reason"] == "request_exception":
# Mark as potentially live, add a special group marker
new_candidate = candidate.copy()
new_candidate["group"] = (candidate.get("group", "") + "|potentially_live").strip("|")
potentially_live.append(new_candidate)
if log_file:
status_code = result["status_code"] if result["status_code"] is not None else "-"
logs.append(
(
f'{candidate["source_label"]}\t{candidate["channel_name"]}\t{candidate["url"]}\t'
f'{"LIVE" if result["is_live"] else "DEAD"}\t{status_code}\t{result["reason"]}\t'
f'{result["attempts"]}\t{result["error"]}\n'
)
)
if log_file and logs:
with open(log_file, "a", encoding="utf-8") as f:
f.writelines(logs)
# Combine accepted and potentially_live channels
return accepted + potentially_live
def load_validation_cache(cache_file):
if not cache_file:
return {}
if not os.path.exists(cache_file):
return {}
try:
with open(cache_file, "r", encoding="utf-8") as f:
raw = json.load(f)
if isinstance(raw, dict):
return raw
except (OSError, json.JSONDecodeError):
pass
return {}
def save_validation_cache(cache_file, cache):
if not cache_file:
return
try:
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(cache, f, separators=(",", ":"), sort_keys=True)
except OSError as err:
print(f"Failed to write validation cache {cache_file}: {err}")
def _cache_is_fresh(entry, now_ts, live_ttl_seconds, dead_ttl_seconds):
checked_at = int(entry.get("checked_at", 0))
if checked_at <= 0:
return False
age = now_ts - checked_at
if age < 0:
return False
is_live = bool(entry.get("is_live", False))
ttl = live_ttl_seconds if is_live else dead_ttl_seconds
return age <= ttl
def _candidate_from_cache(candidate, entry):
if entry.get("is_live", False):
return candidate
if entry.get("reason") == "request_exception":
new_candidate = candidate.copy()
new_candidate["group"] = (candidate.get("group", "") + "|potentially_live").strip("|")
return new_candidate
return None
def validate_candidates_with_cache(
candidates,
max_workers,
timeout_seconds,
retries,
log_file="",
cache_file="",
enable_cache=False,
live_ttl_hours=24,
dead_ttl_hours=6,
):
if not candidates:
return []
if not enable_cache:
return validate_candidates(candidates, max_workers, timeout_seconds, retries, log_file=log_file)
cache = load_validation_cache(cache_file)
now_ts = int(time.time())
live_ttl_seconds = max(0, int(live_ttl_hours)) * 3600
dead_ttl_seconds = max(0, int(dead_ttl_hours)) * 3600
accepted_from_cache = []
to_validate = []
for candidate in candidates:
key = dedupe_url_key(candidate["url"])
entry = cache.get(key)
if entry and _cache_is_fresh(entry, now_ts, live_ttl_seconds, dead_ttl_seconds):
cached_candidate = _candidate_from_cache(candidate, entry)
if cached_candidate is not None:
accepted_from_cache.append(cached_candidate)
continue
to_validate.append(candidate)
if log_file and to_validate:
with open(log_file, "w", encoding="utf-8") as f:
f.write("source_id\tchannel_name\turl\tresult\tstatus_code\treason\tattempts\terror\n")
validated = []
logs = []
if to_validate:
def check(candidate):
session = requests.Session()
try:
return is_url_live(
session,
candidate["url"],
timeout_seconds=timeout_seconds,
retries=retries,
)
finally:
session.close()
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = executor.map(check, to_validate)
for candidate, result in zip(to_validate, results):
key = dedupe_url_key(candidate["url"])
cache[key] = {
"is_live": bool(result["is_live"]),
"checked_at": now_ts,
"reason": result.get("reason", ""),
}
if result["is_live"]:
validated.append(candidate)
elif result["reason"] == "request_exception":
new_candidate = candidate.copy()
new_candidate["group"] = (candidate.get("group", "") + "|potentially_live").strip("|")
validated.append(new_candidate)
if log_file:
status_code = result["status_code"] if result["status_code"] is not None else "-"
logs.append(
(
f'{candidate["source_label"]}\t{candidate["channel_name"]}\t{candidate["url"]}\t'
f'{"LIVE" if result["is_live"] else "DEAD"}\t{status_code}\t{result["reason"]}\t'
f'{result["attempts"]}\t{result["error"]}\n'
)
)
if log_file and logs:
with open(log_file, "a", encoding="utf-8") as f:
f.writelines(logs)
save_validation_cache(cache_file, cache)
print(
f"Validation cache reused {len(accepted_from_cache)} channels, checked {len(to_validate)} channels."
)
return accepted_from_cache + validated
def load_source_content(session, source):
if source.startswith("http://") or source.startswith("https://"):
try:
response = session.get(source, timeout=10)
response.raise_for_status()
return response.text
except requests.RequestException as err:
print(f"Skipping source (unreachable): {source} ({err})")
return None
try:
with open(source, "r", encoding="utf-8") as f:
return f.read()
except OSError as err:
print(f"Skipping source (read failed): {source} ({err})")
return None
def parse_m3u(
content,
source_name,
source_cipher_key="",
):
candidates = []
lines = [line.strip() for line in content.splitlines()]
current_extinf = None
source_label = encrypted_label(source_name, source_cipher_key)
# Map of known sports channel keywords to proper names
sports_channel_keywords = {
"willow": "Willow",
"tsports": "T Sports",
"ptv": "PTV Sports",
"nagorik": "Nagorik TV",
"sharq": "Sharq Game TV",
"premierleagpl": "Premier League",
# Add more as needed
}
generic_sports_groups = {"sports", "live sports", "sport", "live sport"}
def extract_sports_channel_name_from_url(url):
url_lower = url.lower()
for keyword, proper_name in sports_channel_keywords.items():
if keyword in url_lower:
return proper_name
return None
for line in lines:
if not line:
continue
if line.startswith("#EXTINF:"):
current_extinf = line
continue
if line.startswith("#"):
continue
if current_extinf is None:
continue
channel_url = clean_channel_url(line)
metadata, channel_name = split_extinf_metadata_and_name(current_extinf)
group = ""
logo = ""
if 'group-title="' in metadata:
group = metadata.split('group-title="', 1)[1].split('"', 1)[0]
if 'tvg-logo="' in metadata:
logo = metadata.split('tvg-logo="', 1)[1].split('"', 1)[0]
# If group is generic sports and channel name is generic, try to extract from URL
if group.strip().lower() in generic_sports_groups:
# If channel_name is generic (e.g., contains 'live', 'sports', etc.)
if channel_name.strip().lower() in generic_sports_groups or channel_name.strip().lower() == "live sports":
detected = extract_sports_channel_name_from_url(channel_url)
if detected:
channel_name = detected
if is_channel_stream_url(channel_url):
candidates.append(
{
"logo": logo,
"group": group,
"channel_name": channel_name,
"url": channel_url,
"source": source_name,
"source_label": source_label,
}
)
current_extinf = None
return candidates
def parse_existing_all_m3u(content):
candidates = []
lines = [line.strip() for line in content.splitlines()]
current_extinf = None
current_source_label = "SRC-ID:UNKNOWN"
for line in lines:
if not line:
continue
if line.startswith("# Source:"):
current_source_label = line.replace("# Source:", "", 1).strip() or "SRC-ID:UNKNOWN"
continue
if line.startswith("#EXTINF:"):
current_extinf = line
continue
if line.startswith("#"):
continue
if current_extinf is None:
continue
channel_url = clean_channel_url(line)
metadata, channel_name = split_extinf_metadata_and_name(current_extinf)
group = ""
logo = ""
if 'group-title="' in metadata:
group = metadata.split('group-title="', 1)[1].split('"', 1)[0]
if 'tvg-logo="' in metadata:
logo = metadata.split('tvg-logo="', 1)[1].split('"', 1)[0]
if is_channel_stream_url(channel_url):
candidates.append(
{
"logo": logo,
"group": group,
"channel_name": channel_name,
"url": channel_url,
"source": "",
"source_label": current_source_label,
}
)
current_extinf = None
return candidates
def combine_playlists(
sources,
validate_streams=True,
source_cipher_key="",
liveness_workers=24,
liveness_timeout_seconds=6,
liveness_retries=3,
liveness_log_file="",
prevalidation_output_file="all.m3u",
enable_validation_cache=False,
validation_cache_file="validation_cache.json",
live_ttl_hours=24,
dead_ttl_hours=6,
):
combined = []
seen = set()
session = requests.Session()
try:
for source in sources:
content = load_source_content(session, source)
if content is None:
continue
entries = parse_m3u(
content,
source,
source_cipher_key=source_cipher_key,
)
log_label = entries[0]["source_label"] if entries else "EMPTY"
print(f"{log_label}: parsed {len(entries)} channels")
for channel in entries:
key = dedupe_url_key(channel["url"])
if key in seen:
continue
seen.add(key)
combined.append(channel)
finally:
session.close()
if prevalidation_output_file:
write_to_file(combined, prevalidation_output_file)
print(f"Pre-validation playlist written to {prevalidation_output_file} with {len(combined)} channels.")
if not validate_streams:
return combined
validated = validate_candidates_with_cache(
combined,
liveness_workers,
liveness_timeout_seconds,
liveness_retries,
log_file=liveness_log_file,
cache_file=validation_cache_file,
enable_cache=enable_validation_cache,
live_ttl_hours=live_ttl_hours,
dead_ttl_hours=dead_ttl_hours,
)
print(f"Validation accepted {len(validated)} / {len(combined)} channels.")
return validated
def premium_candidates(source_cipher_key=""):
"""
Build candidate dicts from the static PREMIUM_CHANNELS list so they can be
prepended to the final playlist (and survive the same dedupe/validation
pipeline as source-derived channels).
"""
candidates = []
source_label = encrypted_label("PREMIUM", source_cipher_key) if source_cipher_key else "SRC-ID:PREMIUM"
for entry in PREMIUM_CHANNELS:
for stream in (entry.get("streams") or {}).values():
url = (stream or {}).get("url", "").strip()
if not url:
continue
candidates.append(
{
"logo": entry.get("logo", ""),
"group": entry.get("group", ""),
"channel_name": entry.get("name", "Unknown"),
"url": url,
"source": "PREMIUM",
"source_label": source_label,
}
)
return candidates
def prepend_premium(playlist, source_cipher_key=""):
"""
Ensure premium channels always appear at the very top of the playlist.
Existing premium entries (matched by URL) are removed to avoid duplicates.
"""
premium = premium_candidates(source_cipher_key=source_cipher_key)
if not premium:
return list(playlist)
premium_keys = {dedupe_url_key(p["url"]) for p in premium}
rest = [c for c in playlist if dedupe_url_key(c["url"]) not in premium_keys]
return premium + rest
def write_to_file(playlist, output_file, normalize_groups=False, group_rules=None):
with open(output_file, "w", encoding="utf-8") as f:
f.write("#EXTM3U\n")
current_source = None
for item in playlist:
if item["source_label"] != current_source:
if current_source is not None:
f.write("\n")
current_source = item["source_label"]
f.write(f'# Source: {current_source}\n')
group_name = item["group"]
if normalize_groups:
group_name = normalize_group_name(group_name, group_rules)
f.write(
f'#EXTINF:-1 tvg-logo="{item["logo"]}" group-title="{group_name}",{item["channel_name"]}\n'
)
f.write(f'{item["url"]}\n')
# Default keywords used to flag a channel as a Football World Cup stream.
# Tokens are matched case-insensitively against the channel name, group,
# and (where helpful) the logo URL.
DEFAULT_WORLD_CUP_KEYWORDS = (
"world cup",
"fifawc",
"fifa wc",
"fifa world",
"fifa",
"wc 2026",
"wc2026",
"wc",
)
def is_world_cup_channel(channel, keywords=None):
"""
Return True when a parsed channel entry looks like a Football World Cup
stream. A channel qualifies if:
- its logo URL references the FIFA World Cup branding, OR
- any of the configured keywords appear in its name or group.
"""
if not isinstance(channel, dict):
return False
tokens = tuple(k.strip().lower() for k in (keywords or DEFAULT_WORLD_CUP_KEYWORDS) if k and k.strip())
if not tokens:
tokens = tuple(k.lower() for k in DEFAULT_WORLD_CUP_KEYWORDS)
logo = (channel.get("logo") or "").lower()
name = (channel.get("channel_name") or "").lower()
group = (channel.get("group") or "").lower()
if "fifa-world-cup" in logo or "fifa_world_cup" in logo:
return True
haystack = f"{name} {group}"
for token in tokens:
if token and token in haystack:
return True
return False
def filter_world_cup_channels(playlist, keywords=None):
"""Return only the channels from `playlist` that look like World Cup streams."""
if not playlist:
return []
return [c for c in playlist if is_world_cup_channel(c, keywords=keywords)]
def write_private_playlist(
playlist,
output_file="private.m3u",
keywords=None,
normalize_groups=True,
group_rules=None,
):
"""
Write a curated `private.m3u` containing only Football World Cup channels.
Uses the same M3U format as the main playlist and preserves the existing
group normalization pipeline.
"""
world_cup = filter_world_cup_channels(playlist, keywords=keywords)
print(
f"World Cup filter matched {len(world_cup)} / {len(playlist)} channels "
f"for {output_file}."
)
write_to_file(
world_cup,
output_file,
normalize_groups=normalize_groups,
group_rules=group_rules,
)
return world_cup
def decode_labels_from_file(input_file, cipher_key):
with open(input_file, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f.readlines()]
found = []
for line in lines:
if line.startswith("# Source: SRC-"):
label = line.replace("# Source: ", "", 1)
found.append(label)
if not found:
print("No encrypted source labels found.")
return
print("Decoded source labels:")
raw_sources = os.getenv("PLAYLIST_SOURCES", "")
if not raw_sources:
raw_sources = "\n".join(parse_legacy_dotenv_sources(".env"))
known_sources = parse_sources(raw_sources)
seen = set()
for label in found:
if label in seen:
continue
seen.add(label)
decoded = decode_encrypted_label(label, cipher_key)
if decoded is not None:
print(f"{label} => {decoded}")
continue
resolved = resolve_source_id_label(label, cipher_key, known_sources)
if resolved is not None:
print(f"{label} => {resolved}")
continue
print(f"{label} => [unresolved]")
def resolve_cipher_key():
passphrase = os.getenv("SOURCE_PASSPHRASE", "").strip()
if passphrase:
digest = hashlib.sha256(passphrase.encode("utf-8")).digest()
return base64.urlsafe_b64encode(digest).decode("utf-8")
return ""
if __name__ == "__main__":
load_dotenv()
parser = argparse.ArgumentParser()
parser.add_argument("--decode-file", help="Decode encrypted source labels from this playlist file.")
args = parser.parse_args()
source_cipher_key = resolve_cipher_key()
if args.decode_file:
if not source_cipher_key:
raise SystemExit("SOURCE_PASSPHRASE is required for decode mode.")
decode_labels_from_file(args.decode_file, source_cipher_key)
raise SystemExit(0)
raw_sources = os.getenv("PLAYLIST_SOURCES", "")
if not raw_sources:
raw_sources = "\n".join(parse_legacy_dotenv_sources(".env"))
validate_streams = os.getenv("VALIDATE_STREAMS", "true").lower() == "true"
output_file = os.getenv("OUTPUT_FILE", "iptv.m3u8")
liveness_workers = int(os.getenv("LIVENESS_WORKERS", "24"))
liveness_timeout_seconds = int(os.getenv("LIVENESS_TIMEOUT_SECONDS", "6"))
liveness_retries = int(os.getenv("LIVENESS_RETRIES", "3"))
liveness_log_file = os.getenv("LIVENESS_LOG_FILE", "liveness.log").strip()
enable_validation_cache = os.getenv("ENABLE_VALIDATION_CACHE", "true").lower() == "true"
validation_cache_file = os.getenv("VALIDATION_CACHE_FILE", "validation_cache.json").strip()
live_ttl_hours = int(os.getenv("LIVE_TTL_HOURS", "24"))
dead_ttl_hours = int(os.getenv("DEAD_TTL_HOURS", "6"))
prevalidation_output_file = os.getenv("ALL_OUTPUT_FILE", "all.m3u").strip()
validate_from_all_file = os.getenv("VALIDATE_FROM_ALL_FILE", "").strip()
group_normalization_file = os.getenv("GROUP_NORMALIZATION_FILE", "group_normalization.json").strip()
group_rules = load_group_normalization_rules(group_normalization_file)
private_output_file = os.getenv("PRIVATE_OUTPUT_FILE", "private.m3u").strip()
private_filter_keywords_raw = os.getenv("PRIVATE_FILTER_KEYWORDS", "").strip()
private_filter_keywords = (
[k.strip() for k in private_filter_keywords_raw.split(",") if k.strip()]
if private_filter_keywords_raw
else None
)
if not source_cipher_key:
raise SystemExit("SOURCE_PASSPHRASE is required.")
if validate_from_all_file:
try:
with open(validate_from_all_file, "r", encoding="utf-8") as f:
all_content = f.read()
except OSError as err:
raise SystemExit(f"Failed to read VALIDATE_FROM_ALL_FILE: {validate_from_all_file} ({err})")
combined_playlist = parse_existing_all_m3u(all_content)
print(
f"Loaded {len(combined_playlist)} channels from {validate_from_all_file} for validation-only mode."
)
if validate_streams:
combined_playlist = validate_candidates_with_cache(
combined_playlist,
liveness_workers,
liveness_timeout_seconds,
liveness_retries,
log_file=liveness_log_file,
cache_file=validation_cache_file,
enable_cache=enable_validation_cache,
live_ttl_hours=live_ttl_hours,
dead_ttl_hours=dead_ttl_hours,
)
print(f"Validation accepted {len(combined_playlist)} channels from {validate_from_all_file}.")
else:
sources = parse_sources(raw_sources)
if not sources:
raise SystemExit("No playlist sources found in PLAYLIST_SOURCES.")
combined_playlist = combine_playlists(
sources,
validate_streams=validate_streams,
source_cipher_key=source_cipher_key,
liveness_workers=liveness_workers,
liveness_timeout_seconds=liveness_timeout_seconds,
liveness_retries=liveness_retries,
liveness_log_file=liveness_log_file,
prevalidation_output_file=prevalidation_output_file,
enable_validation_cache=enable_validation_cache,
validation_cache_file=validation_cache_file,
live_ttl_hours=live_ttl_hours,
dead_ttl_hours=dead_ttl_hours,
)
combined_playlist = prepend_premium(combined_playlist, source_cipher_key=source_cipher_key)
write_to_file(combined_playlist, output_file, normalize_groups=True, group_rules=group_rules)
print(f"Combined playlist written to {output_file} with {len(combined_playlist)} channels.")
if private_output_file:
write_private_playlist(
combined_playlist,
output_file=private_output_file,
keywords=private_filter_keywords,
normalize_groups=True,
group_rules=group_rules,
)
print(f"Private World Cup playlist written to {private_output_file}.")