-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathxtream_server_routes.py
More file actions
2034 lines (1770 loc) · 78.9 KB
/
xtream_server_routes.py
File metadata and controls
2034 lines (1770 loc) · 78.9 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
from fastapi import APIRouter, Depends, HTTPException, Query, Form, Request
from fastapi.responses import JSONResponse, StreamingResponse, RedirectResponse, Response, FileResponse
from sqlalchemy.orm import Session
from models import get_db, Item
from hdhomerun_routes import register_extra_channels, _active_streams, _active_streams_lock, _SESSION_STALE_SECONDS, get_active_stream_count, is_ip_blocked, auto_replace_ip_session, KILL_BLOCK_SECONDS
import asyncio
import collections
import config
import gc
import hashlib
import json
import logging
import os
import re
import fnmatch
import sqlite3
import time
import queue as _queue
import threading
import uuid
import unicodedata
import requests
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Optional
from hls_utils import resolve_hls_variant
logger = logging.getLogger(__name__)
router = APIRouter()
M3U_DIR = config.M3U_DIR
# ---------------------------------------------------------------------------
# Credentials
# ---------------------------------------------------------------------------
def verify_credentials(username: str, password: str, item: Item) -> bool:
expected_user = item.proxy_username or "iptv"
expected_pass = item.proxy_password or "iptv"
return username == expected_user and password == expected_pass
def _get_item_by_credentials(username: str, password: str, db: Session):
"""Look up provider by proxy credentials. Returns first match or None."""
items = db.query(Item).all()
matches = [
i for i in items
if i.enabled
and (i.proxy_username or "iptv") == username
and (i.proxy_password or "iptv") == password
]
if not matches:
return None
if len(matches) > 1:
logger.warning(
f"Multiple providers share credentials '{username}' — using '{matches[0].name}'. "
"Set unique proxy credentials per provider in Settings."
)
return matches[0]
def _item_id_from_stream_id(stream_id: int) -> int:
"""Extract provider item_id from a namespaced stream_id."""
if stream_id >= 1_000_000_000:
return stream_id // 1_000_000_000 # episode namespace: item_id * 1e9 + ep_id
return stream_id // 100_000_000 # live/VOD/series namespace: item_id * 1e8 + offset
def _get_item_by_stream_id(stream_id: int, db: Session):
"""Look up provider by extracting item_id from namespaced stream_id."""
item_id = _item_id_from_stream_id(stream_id)
return db.query(Item).filter(Item.id == item_id).first()
def _unauthorized() -> JSONResponse:
return JSONResponse({"user_info": {"auth": 0}}, status_code=401)
def _get_base_url() -> str:
return config.ADVERTISED_BASE_URL
async def get_item_for_slug(provider_slug: str, db: Session = Depends(get_db)) -> Item:
item = db.query(Item).filter(Item.slug == provider_slug).first()
if not item or not item.enabled:
all_items = db.query(Item).all()
available = [f"/{i.slug}/" for i in all_items if i.slug and i.enabled]
raise HTTPException(
status_code=404,
detail={"error": "Provider not found", "available_providers": available},
)
return item
# ---------------------------------------------------------------------------
# Data models
# ---------------------------------------------------------------------------
@dataclass(slots=True)
class StreamEntry:
stream_id: int
name: str
logo: str
category_name: str
category_id: str
url: str # actual upstream URL — never exposed to clients
stream_type: str # "live" only (VOD/series are in SQLite)
guide_number: str
tvg_id: str
item_id: int = 0
@dataclass(slots=True)
class XtreamCache:
fingerprint: tuple
live_streams: list # StreamEntry list — live channels only (~100–200 entries)
live_stream_map: dict # stream_id -> StreamEntry (live only)
live_categories: list
vod_categories: list
series_categories: list
live_id_to_guide: dict
extra_channel_urls: dict
extra_channel_names: dict
db_path: str # SQLite catalog (VOD + Series rows)
vod_json_path: str # pre-built JSON array for get_vod_streams
series_json_path: str # pre-built JSON array for get_series
item_id: int # primary provider item id
# Per-item cache: item_id -> XtreamCache
_cache: dict[int, XtreamCache] = {}
_cache_lock = asyncio.Lock()
def invalidate_xtream_cache(item_id: int) -> None:
"""Drop cached catalog for a provider so the next request rebuilds it."""
_cache.pop(item_id, None)
# Tracks last build failure time per item_id to prevent tight rebuild loops
_build_failures: dict[int, float] = {}
_BUILD_RETRY_COOLDOWN = 60.0 # seconds before retrying after a failed build
# ---------------------------------------------------------------------------
# Stream ID helpers
# ---------------------------------------------------------------------------
def _make_id(item_id: int, tvg_id_str: str, type_offset: int) -> int:
base = item_id * 100_000_000 + type_offset
try:
return base + int(tvg_id_str)
except (ValueError, TypeError):
return base + (int(hashlib.md5(tvg_id_str.encode()).hexdigest(), 16) % 9_000_000)
def _live_id(item_id: int, tvg_id: str) -> int:
return _make_id(item_id, tvg_id, 0)
def _vod_id(item_id: int, tvg_id: str) -> int:
return _make_id(item_id, tvg_id, 10_000_000)
def _series_id(item_id: int, tvg_id: str) -> int:
return _make_id(item_id, tvg_id, 20_000_000)
def _episode_id(item_id: int, upstream_ep_id: int) -> int:
return item_id * 1_000_000_000 + upstream_ep_id
# ---------------------------------------------------------------------------
# Lazy URL caches (populated on first play)
# ---------------------------------------------------------------------------
_episode_cache: dict = {}
_episode_cache_lock = threading.Lock()
_vod_url_cache: dict = {}
_vod_url_cache_lock = threading.Lock()
_CACHE_MAX = 10_000
_UPSTREAM_HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/129.0.0.0 Safari/537.36"
),
"Accept": "application/json, text/plain, */*",
}
# ---------------------------------------------------------------------------
# M3U parsing helpers
# ---------------------------------------------------------------------------
def _normalize(s: str) -> str:
s = (s or "").lower().strip()
s = unicodedata.normalize("NFKD", s)
s = "".join(c for c in s if not unicodedata.combining(c))
return " ".join(s.split())
def _strict_norm(s: str) -> str:
return re.sub(r"[^a-z0-9]+", "", _normalize(s))
def _split_extinf(line: str):
"""Split #EXTINF line into (attrs_str, display_name) respecting quoted values."""
in_quotes = False
for idx, c in enumerate(line):
if c == '"':
in_quotes = not in_quotes
elif c == ',' and not in_quotes:
return line[:idx], line[idx + 1:].strip()
return line, ""
_ATTR_RE = re.compile(r'(tvg-id|tvg-name|tvg-logo|group-title|tvg-chno)="([^"]*)"')
def _stream_m3u_file(path: str):
"""Stream M3U entries one at a time — O(1) memory regardless of file size."""
try:
f = open(path, "r", encoding="utf-8", errors="ignore")
except FileNotFoundError:
return
try:
prev_extinf = None
first = True
for raw in f:
line = raw.rstrip("\n")
if first:
first = False
if line.strip() == "#EXTM3U":
continue
if line.startswith("#EXTINF"):
prev_extinf = line
elif prev_extinf is not None:
url = line.strip()
attrs_str, display_name = _split_extinf(prev_extinf)
attrs = dict(_ATTR_RE.findall(attrs_str))
yield {
"tvg_id": attrs.get("tvg-id", ""),
"tvg_name": attrs.get("tvg-name", ""),
"logo": attrs.get("tvg-logo", ""),
"group_title": attrs.get("group-title", ""),
"tvg_chno": attrs.get("tvg-chno", ""),
"display_name": display_name,
"url": url,
}
prev_extinf = None
finally:
f.close()
def _xi_display_norm(s: str) -> str:
s = unicodedata.normalize("NFKD", (s or ""))
s = "".join(c for c in s if not unicodedata.combining(c))
s = s.lower()
return re.sub(r"[^a-z0-9]+", " ", s).strip()
# ---------------------------------------------------------------------------
# SQLite catalog helpers
# ---------------------------------------------------------------------------
_CATALOG_SCHEMA = """
CREATE TABLE IF NOT EXISTS streams (
stream_id INTEGER PRIMARY KEY,
tvg_id TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL DEFAULT '',
logo TEXT NOT NULL DEFAULT '',
category_name TEXT NOT NULL DEFAULT '',
category_id TEXT NOT NULL DEFAULT '1',
url TEXT NOT NULL DEFAULT '',
stream_type TEXT NOT NULL,
item_id INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_item_type ON streams(item_id, stream_type);
"""
@contextmanager
def _catalog_conn(db_path: str):
conn = sqlite3.connect(db_path, check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def _catalog_lookup(db_path: str, stream_id: int):
with _catalog_conn(db_path) as conn:
return conn.execute(
"SELECT * FROM streams WHERE stream_id=?", (stream_id,)
).fetchone()
# ---------------------------------------------------------------------------
# Cache fingerprint + build
# ---------------------------------------------------------------------------
def _compute_fingerprint(items: list) -> tuple:
parts = []
for item in items:
for fname in (f"xtream_playlist_{item.id}.m3u", f"filtered_playlist_{item.id}.m3u"):
path = os.path.join(M3U_DIR, fname)
try:
st = os.stat(path)
parts.append((path, st.st_mtime, st.st_size))
except FileNotFoundError:
parts.append((path, 0, 0))
parts.append(("xtream_includes", item.id, getattr(item, "xtream_includes", None) or ""))
return tuple(parts)
def _build_categories(streams: list) -> tuple:
"""Return (category_list, name_to_id_map). IDs assigned alphabetically."""
seen = {}
for s in streams:
if s.category_name not in seen:
seen[s.category_name] = str(len(seen) + 1)
cat_list = [
{"category_id": cid, "category_name": name, "parent_id": 0}
for name, cid in sorted(seen.items())
]
return cat_list, seen
def _build_cache(items: list, fingerprint: tuple) -> XtreamCache: # noqa: C901
primary_item_id = items[0].id
db_key = "_".join(str(i.id) for i in items)
db_path = os.path.join(M3U_DIR, f"catalog_{db_key}.db")
vod_json_path = os.path.join(M3U_DIR, f"vod_cache_{db_key}.json")
series_json_path = os.path.join(M3U_DIR, f"series_cache_{db_key}.json")
# ---- Live channels: stream filtered playlists (small files) ----
used_guide_numbers: set = set()
next_available = 1
channels_by_name: dict = {}
for item in items:
filtered_path = os.path.join(M3U_DIR, f"filtered_playlist_{item.id}.m3u")
for e in _stream_m3u_file(filtered_path):
display = (e["tvg_name"] or e["display_name"]).replace("_", " ").strip()
norm = _strict_norm(display)
tvg_chno = e["tvg_chno"]
if tvg_chno:
guide_num = tvg_chno
explicit = True
else:
while str(next_available) in used_guide_numbers:
next_available += 1
guide_num = str(next_available)
next_available += 1
explicit = False
sid = _live_id(item.id, e["tvg_id"])
entry = StreamEntry(
stream_id=sid,
name=display,
logo=e["logo"],
category_name=e["group_title"] or "Live",
category_id="",
url=e["url"],
stream_type="live",
guide_number=guide_num,
tvg_id=e["tvg_id"],
item_id=item.id,
)
existing = channels_by_name.get(norm)
if existing is None:
channels_by_name[norm] = (entry, explicit)
used_guide_numbers.add(guide_num)
elif not existing[1] and explicit:
used_guide_numbers.discard(existing[0].guide_number)
channels_by_name[norm] = (entry, explicit)
used_guide_numbers.add(guide_num)
# ---- Pre-build extra channel pattern matchers (one per item) ----
def _make_matcher(compiled_patterns):
def _matches(display: str) -> bool:
norm_d = _xi_display_norm(display)
for kind, matcher in compiled_patterns:
if kind == "word":
if matcher.search(norm_d):
return True
else:
if fnmatch.fnmatch(re.sub(r"\s+", "", norm_d), matcher):
return True
return False
return _matches
item_matchers = [] # list of (item, has_patterns, match_fn)
for item in items:
raw_xi = getattr(item, "xtream_includes", None) or ""
patterns = [p.strip() for p in raw_xi.split(",") if p.strip()]
if not patterns:
item_matchers.append((item, False, None))
continue
compiled = []
for p in patterns:
# Behavior:
# - If user supplies '*' wildcards, treat as fnmatch on normalized alphanum.
# - If no '*', treat as a word/phrase match (more user-friendly than exact match).
if "*" in p:
if p.startswith("*") and p.endswith("*") and p.count("*") == 2:
inner = _xi_display_norm(p[1:-1])
if inner:
words = inner.split()
rx = re.compile(r"\b" + r"\s+".join(re.escape(w) for w in words) + r"\b")
compiled.append(("word", rx))
else:
compiled.append(("fnmatch", re.sub(r"[^a-z0-9*]+", "", p.lower())))
else:
inner = _xi_display_norm(p)
if inner:
words = inner.split()
rx = re.compile(r"\b" + r"\s+".join(re.escape(w) for w in words) + r"\b")
compiled.append(("word", rx))
item_matchers.append((item, bool(compiled), _make_matcher(compiled)))
# ---- Single-pass streaming: VOD + Series → SQLite + JSON; live → extra channels ----
vod_tmp = vod_json_path + ".tmp"
series_tmp = series_json_path + ".tmp"
conn = sqlite3.connect(db_path, check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.executescript(_CATALOG_SCHEMA)
conn.execute("DELETE FROM streams")
batch: list = []
BATCH_SIZE = 2000
def _flush():
if batch:
conn.executemany(
"INSERT OR REPLACE INTO streams "
"(stream_id,tvg_id,name,logo,category_name,category_id,url,stream_type,item_id) "
"VALUES (?,?,?,?,?,?,?,?,?)",
batch,
)
batch.clear()
extra_channel_urls: dict = {}
extra_channel_names: dict = {}
with open(vod_tmp, "w", encoding="utf-8") as vod_f, \
open(series_tmp, "w", encoding="utf-8") as series_f:
vod_f.write("[")
series_f.write("[")
vod_first = series_first = True
for item, has_patterns, _matches in item_matchers:
full_path = os.path.join(M3U_DIR, f"xtream_playlist_{item.id}.m3u")
for e in _stream_m3u_file(full_path):
gt = e["group_title"]
display = (e["tvg_name"] or e["display_name"]).strip()
if not display:
continue
if gt == "VOD":
sid = _vod_id(item.id, e["tvg_id"])
batch.append((sid, e["tvg_id"], display, e["logo"] or "",
"VOD", "1", e["url"] or "", "movie", item.id))
if len(batch) >= BATCH_SIZE:
_flush()
obj = {
"num": sid, "name": display, "stream_type": "movie",
"stream_id": sid, "stream_icon": e["logo"] or "",
"rating": "0", "added": "0",
"category_id": "1", "category_name": "VOD",
"container_extension": "mp4", "custom_sid": "",
"direct_source": "",
}
if not vod_first:
vod_f.write(",")
vod_f.write(json.dumps(obj, ensure_ascii=False))
vod_first = False
elif gt == "Series":
sid = _series_id(item.id, e["tvg_id"])
batch.append((sid, e["tvg_id"], display, e["logo"] or "",
"Series", "1", e["url"] or "", "series", item.id))
if len(batch) >= BATCH_SIZE:
_flush()
obj = {
"num": sid, "name": display, "series_id": sid,
"stream_icon": e["logo"] or "",
"rating": "0", "added": "0",
"category_id": "1", "category_name": "Series",
"cover": e["logo"] or "", "plot": "", "cast": "",
"director": "", "genre": "", "release_date": "",
"last_modified": "0", "episode_run_time": "0",
"youtube_trailer": "",
}
if not series_first:
series_f.write(",")
series_f.write(json.dumps(obj, ensure_ascii=False))
series_first = False
elif has_patterns:
# Extra channel candidate — live channel not in filtered playlist
disp = display.replace("_", " ").strip()
norm_name = _strict_norm(disp)
if norm_name in channels_by_name:
continue
if not _matches(disp):
continue
sid = _live_id(item.id, e["tvg_id"])
guide_num = e["tvg_id"]
entry = StreamEntry(
stream_id=sid,
name=disp,
logo=e["logo"],
category_name=gt or "Live",
category_id="",
url=e["url"],
stream_type="live",
guide_number=guide_num,
tvg_id=e["tvg_id"],
item_id=item.id,
)
channels_by_name[norm_name] = (entry, False)
used_guide_numbers.add(guide_num)
extra_channel_urls[guide_num] = e["url"]
extra_channel_names[guide_num] = disp
vod_f.write("]")
series_f.write("]")
_flush()
conn.commit()
conn.close()
os.replace(vod_tmp, vod_json_path)
os.replace(series_tmp, series_json_path)
# ---- Assemble live streams ----
live_streams = []
live_stream_map = {}
live_id_to_guide = {}
for entry, _ in channels_by_name.values():
live_streams.append(entry)
live_stream_map[entry.stream_id] = entry
live_id_to_guide[entry.stream_id] = entry.guide_number
live_cats, live_cat_map = _build_categories(live_streams)
for s in live_streams:
s.category_id = live_cat_map.get(s.category_name, "1")
vod_cats = [{"category_id": "1", "category_name": "VOD", "parent_id": 0}]
series_cats = [{"category_id": "1", "category_name": "Series", "parent_id": 0}]
gc.collect()
try:
with _catalog_conn(db_path) as conn:
vod_count = conn.execute(
"SELECT COUNT(*) FROM streams WHERE stream_type='movie'"
).fetchone()[0]
series_count = conn.execute(
"SELECT COUNT(*) FROM streams WHERE stream_type='series'"
).fetchone()[0]
except Exception:
vod_count = series_count = 0
provider_label = ", ".join(f"'{i.name}'" for i in items)
logger.info(
f"Xtream cache built [{provider_label}]: {len(live_streams)} live, "
f"{vod_count} VOD, {series_count} series → {db_path}"
)
return XtreamCache(
fingerprint=fingerprint,
live_streams=live_streams,
live_stream_map=live_stream_map,
live_categories=live_cats,
vod_categories=vod_cats,
series_categories=series_cats,
live_id_to_guide=live_id_to_guide,
extra_channel_urls=extra_channel_urls,
extra_channel_names=extra_channel_names,
db_path=db_path,
vod_json_path=vod_json_path,
series_json_path=series_json_path,
item_id=primary_item_id,
)
async def get_xtream_cache(db: Session, item: Item) -> XtreamCache:
global _cache
fingerprint = _compute_fingerprint([item])
async with _cache_lock:
cached = _cache.get(item.id)
if cached and cached.fingerprint == fingerprint:
# Verify catalog files still exist (could be deleted externally)
if (os.path.exists(cached.db_path)
and os.path.exists(cached.vod_json_path)
and os.path.exists(cached.series_json_path)):
return cached
# Enforce cooldown after build failures to prevent tight rebuild loops
last_fail = _build_failures.get(item.id, 0.0)
if time.time() - last_fail < _BUILD_RETRY_COOLDOWN:
logger.warning(
f"Xtream cache build cooldown active for item {item.id} "
f"({_BUILD_RETRY_COOLDOWN - (time.time() - last_fail):.0f}s remaining) — "
f"returning {'stale cache' if cached else 'error'}"
)
if cached:
return cached
raise HTTPException(status_code=503, detail="Cache unavailable — build failed recently, try again shortly")
try:
new_cache = await asyncio.to_thread(_build_cache, [item], fingerprint)
except Exception as exc:
_build_failures[item.id] = time.time()
logger.error(f"Xtream cache build failed for item {item.id}: {exc}", exc_info=True)
if cached:
logger.warning(f"Xtream cache: returning stale cache for item {item.id} after build failure")
return cached
raise HTTPException(status_code=503, detail=f"Cache build failed: {exc}")
_build_failures.pop(item.id, None)
_cache[item.id] = new_cache
if new_cache.extra_channel_urls:
register_extra_channels(new_cache.extra_channel_urls, new_cache.extra_channel_names)
return new_cache
# ---------------------------------------------------------------------------
# JSON serialization helpers
# ---------------------------------------------------------------------------
def _stream_to_json(entry: StreamEntry) -> dict:
"""Used for live streams only."""
return {
"num": entry.stream_id,
"name": entry.name,
"stream_type": "live",
"stream_id": entry.stream_id,
"stream_icon": entry.logo,
"epg_channel_id": entry.tvg_id,
"added": "0",
"category_id": entry.category_id,
"category_name": entry.category_name,
"custom_sid": "",
"tv_archive": 0,
"direct_source": "",
}
def _auth_response(base_url: str, item: Item) -> dict:
try:
from urllib.parse import urlparse
parsed = urlparse(base_url)
srv_host = parsed.hostname or "127.0.0.1"
srv_port = str(parsed.port or 5005)
srv_scheme = parsed.scheme or "http"
except Exception:
srv_host, srv_port, srv_scheme = "127.0.0.1", "5005", "http"
return {
"user_info": {
"username": item.proxy_username or "iptv",
"password": item.proxy_password or "iptv",
"message": "",
"auth": 1,
"status": "Active",
"exp_date": "9999999999",
"is_trial": "0",
"active_cons": "0",
"created_at": "0",
"max_connections": "10",
"allowed_output_formats": ["ts", "m3u8", "rtmp"],
},
"server_info": {
"url": srv_host,
"port": srv_port,
"https_port": "443",
"server_protocol": srv_scheme,
"rtmp_port": "1935",
"timezone": "UTC",
"timestamp_now": int(time.time()),
"time_now": time.strftime("%Y-%m-%d %H:%M:%S"),
},
}
def _vod_info_response_from_row(row) -> dict:
return {
"info": {
"name": row["name"],
"o_name": row["name"],
"cover_big": row["logo"],
"movie_image": row["logo"],
"release_date": "",
"episode_run_time": "",
"rating": "0",
"description": "",
"genre": "",
"cast": "",
"director": "",
"youtube_trailer": "",
},
"movie_data": {
"stream_id": row["stream_id"],
"name": row["name"],
"added": "0",
"category_id": row["category_id"],
"container_extension": "mp4",
"custom_sid": "",
"direct_source": "",
},
}
# ---------------------------------------------------------------------------
# Upstream fetch helpers (lazy VOD URL resolution + series info)
# ---------------------------------------------------------------------------
def _fetch_vod_url(stream_id: int, tvg_id: str, item_id: int, db: Session) -> Optional[str]:
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
return None
base = item.server_url.rstrip("/")
try:
resp = requests.get(
f"{base}/player_api.php",
params={
"username": item.username,
"password": item.user_pass,
"action": "get_vod_info",
"vod_id": tvg_id,
},
headers={**_UPSTREAM_HEADERS, "Referer": base},
timeout=15,
)
resp.raise_for_status()
data = resp.json()
except Exception as exc:
logger.warning(f"Upstream get_vod_info failed for vod {tvg_id}: {exc}")
return None
ext = (data.get("movie_data") or {}).get("container_extension") or "mp4"
url = f"{base}/movie/{item.username}/{item.user_pass}/{tvg_id}.{ext}"
with _vod_url_cache_lock:
if len(_vod_url_cache) >= _CACHE_MAX:
for k in list(_vod_url_cache)[: _CACHE_MAX // 2]:
del _vod_url_cache[k]
_vod_url_cache[stream_id] = url
return url
def _series_info_fallback_from_row(row) -> dict:
return {
"info": {
"name": row["name"],
"cover": row["logo"],
"plot": "",
"cast": "",
"director": "",
"genre": "",
"release_date": "",
"rating": "0",
"backdrop_path": [],
"youtube_trailer": "",
"episode_run_time": "0",
"category_id": row["category_id"],
},
"episodes": {},
}
def _fetch_series_info_from_row(row, db: Session) -> dict:
item = db.query(Item).filter(Item.id == row["item_id"]).first()
if not item:
return _series_info_fallback_from_row(row)
try:
base = item.server_url.rstrip("/")
resp = requests.get(
f"{base}/player_api.php",
params={
"username": item.username,
"password": item.user_pass,
"action": "get_series_info",
"series_id": row["tvg_id"],
},
headers={**_UPSTREAM_HEADERS, "Referer": base},
timeout=15,
)
resp.raise_for_status()
data = resp.json()
except Exception as exc:
logger.warning(f"Upstream get_series_info failed for series {row['tvg_id']}: {exc}")
return _series_info_fallback_from_row(row)
episodes_out = {}
episodes_data = data.get("episodes", {})
def _cache_episode(upstream_ep_id: int, ep_ext: str) -> int:
local_id = _episode_id(row["item_id"], upstream_ep_id)
upstream_url = f"{base}/series/{item.username}/{item.user_pass}/{upstream_ep_id}.{ep_ext}"
with _episode_cache_lock:
if len(_episode_cache) >= _CACHE_MAX:
for k in list(_episode_cache)[: _CACHE_MAX // 2]:
del _episode_cache[k]
_episode_cache[local_id] = upstream_url
return local_id
def _process_ep(ep: dict) -> dict | None:
if not isinstance(ep, dict):
return None
try:
upstream_ep_id = int(ep.get("id", 0))
except (ValueError, TypeError):
return None
ep_ext = ep.get("container_extension", "mp4")
local_id = _cache_episode(upstream_ep_id, ep_ext)
ep_out = dict(ep)
ep_out["id"] = str(local_id)
ep_out["direct_source"] = ""
return ep_out
if isinstance(episodes_data, list):
if episodes_data and isinstance(episodes_data[0], list):
# List-of-seasons: [[ep, ep, ...], [ep, ep, ...], ...]
for season_idx, season_episodes in enumerate(episodes_data):
season_list = [r for ep in season_episodes
if (r := _process_ep(ep)) is not None]
if season_list:
episodes_out[str(season_idx + 1)] = season_list
else:
# Flat list of episodes — all belong to season 1
season_list = [r for ep in episodes_data
if (r := _process_ep(ep)) is not None]
if season_list:
episodes_out["1"] = season_list
else:
# Standard dict format: {"1": [ep, ...], "2": [ep, ...]}
for season_num, episodes in episodes_data.items():
season_list = [r for ep in episodes
if (r := _process_ep(ep)) is not None]
if season_list:
episodes_out[season_num] = season_list
info = data.get("info", {})
info.setdefault("name", row["name"])
info.setdefault("cover", row["logo"])
return {"info": info, "episodes": episodes_out}
# ---------------------------------------------------------------------------
# Xtream API endpoint
# ---------------------------------------------------------------------------
async def _handle_player_api(
username: str,
password: str,
action: Optional[str],
vod_id: Optional[str],
series_id: Optional[str],
db: Session,
item: Item,
) -> Response:
if not verify_credentials(username, password, item):
return _unauthorized()
base_url = _get_base_url()
cache = await get_xtream_cache(db, item)
if action is None:
return JSONResponse(_auth_response(base_url, item))
if action == "get_live_categories":
return JSONResponse(cache.live_categories)
if action == "get_vod_categories":
return JSONResponse(cache.vod_categories)
if action == "get_series_categories":
return JSONResponse(cache.series_categories)
if action == "get_live_streams":
return JSONResponse([_stream_to_json(s) for s in cache.live_streams])
# VOD and series lists are served directly from pre-built JSON files — zero RAM cost
if action == "get_vod_streams":
if not os.path.exists(cache.vod_json_path):
return JSONResponse([])
return FileResponse(cache.vod_json_path, media_type="application/json")
if action == "get_series":
if not os.path.exists(cache.series_json_path):
return JSONResponse([])
return FileResponse(cache.series_json_path, media_type="application/json")
if action == "get_vod_info" and vod_id:
try:
sid = int(vod_id)
except (ValueError, TypeError):
return JSONResponse({"info": {}, "movie_data": {}})
row = await asyncio.to_thread(_catalog_lookup, cache.db_path, sid)
if not row or row["stream_type"] != "movie":
return JSONResponse({"info": {}, "movie_data": {}})
return JSONResponse(_vod_info_response_from_row(row))
if action == "get_series_info" and series_id:
try:
sid = int(series_id)
except (ValueError, TypeError):
return JSONResponse({"info": {}, "episodes": {}})
row = await asyncio.to_thread(_catalog_lookup, cache.db_path, sid)
if not row or row["stream_type"] != "series":
return JSONResponse({"info": {}, "episodes": {}})
return JSONResponse(await asyncio.to_thread(_fetch_series_info_from_row, row, db))
return JSONResponse({"error": "Unknown action"}, status_code=400)
@router.get("/{provider_slug}/player_api.php")
async def player_api_get(
provider_slug: str,
username: str = Query(...),
password: str = Query(...),
action: Optional[str] = Query(None),
vod_id: Optional[str] = Query(None),
series_id: Optional[str] = Query(None),
db: Session = Depends(get_db),
item: Item = Depends(get_item_for_slug),
):
return await _handle_player_api(username, password, action, vod_id, series_id, db, item)
@router.post("/{provider_slug}/player_api.php")
async def player_api_post(
provider_slug: str,
username: str = Form(...),
password: str = Form(...),
action: Optional[str] = Form(None),
vod_id: Optional[str] = Form(None),
series_id: Optional[str] = Form(None),
db: Session = Depends(get_db),
item: Item = Depends(get_item_for_slug),
):
return await _handle_player_api(username, password, action, vod_id, series_id, db, item)
# ---------------------------------------------------------------------------
# M3U playlist endpoints
# ---------------------------------------------------------------------------
async def _m3u_generator(cache: XtreamCache, base_url: str, username: str, password: str, slug: str):
"""Async generator — yields M3U lines without holding full catalog in RAM."""
yield "#EXTM3U\n"
for s in cache.live_streams:
url = f"{base_url}/{slug}/live/{username}/{password}/{s.stream_id}.ts"
yield (
f'#EXTINF:-1 tvg-id="{s.tvg_id}" tvg-name="{s.name}" '
f'tvg-logo="{s.logo}" group-title="{s.category_name}",{s.name}\n'
f"{url}\n"
)
# Stream VOD/series from SQLite via thread (avoids blocking the event loop)
def _fetch_rows(stream_type: str) -> list:
with _catalog_conn(cache.db_path) as conn:
conn.row_factory = None # return plain tuples for speed
return conn.execute(
"SELECT stream_id, tvg_id, name, logo, category_name "
"FROM streams WHERE item_id=? AND stream_type=?",
(cache.item_id, stream_type),
).fetchall()
for sid, tvg_id, name, logo, cat in await asyncio.to_thread(_fetch_rows, "movie"):
url = f"{base_url}/{slug}/movie/{username}/{password}/{sid}.mp4"
yield (
f'#EXTINF:-1 tvg-id="{tvg_id}" tvg-name="{name}" '
f'tvg-logo="{logo}" group-title="{cat}",{name}\n'
f"{url}\n"
)
# Series: serve individual episode entries from raw upstream M3U (so M3U-mode apps can browse episodes).
# The raw M3U has one entry per episode; our generated M3U has one per series (wrong for M3U mode).
raw_path = os.path.join(M3U_DIR, f"raw_playlist_{cache.item_id}.m3u")
def _read_raw_series_episodes() -> list:
"""Extract series episode entries from raw upstream M3U, rewriting stream URLs to our proxy."""
rows = []
proxy_series_base = f"{base_url}/{slug}/series/{username}/{password}/"
for e in _stream_m3u_file(raw_path):