forked from jvdillon/netv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·3990 lines (3508 loc) · 149 KB
/
Copy pathmain.py
File metadata and controls
executable file
·3990 lines (3508 loc) · 149 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["fastapi", "uvicorn[standard]", "jinja2", "python-multipart", "cryptography", "defusedxml"]
# ///
"""IPTV Web App.
Usage:
./main.py [--port PORT] [--https] [--cert FILE --key FILE]
Options:
--port PORT Port to listen on (default: 8000)
--https Enable HTTPS using Let's Encrypt certs (auto-detect domain)
--cert FILE SSL certificate file (overrides --https)
--key FILE SSL private key file (overrides --https)
Examples:
./main.py # HTTP on port 8000
./main.py --https # HTTPS with auto-detected Let's Encrypt certs
./main.py --cert c.pem --key k.pem # HTTPS with custom certs
"""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Annotated, Any
from xml.sax.saxutils import escape as xml_escape
import asyncio
import concurrent.futures
import contextlib
import json
import logging
import os
import pathlib
import re
import signal
import subprocess
import threading
import time
import urllib.error
import urllib.parse
from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.responses import StreamingResponse
from auth import create_token, verify_password, verify_token
from cache import (
AVAILABLE_ENCODERS,
CACHE_DIR,
LOGO_BROWSER_TTL,
LOGO_MAX_SIZE,
Source,
clear_all_caches,
clear_all_file_caches,
get_cache,
get_cache_lock,
get_cached_info,
get_cached_logo,
get_sources,
get_watch_position,
load_file_cache,
load_server_settings,
load_user_settings,
refresh_encoders,
save_file_cache,
save_logo,
save_server_settings,
save_user_settings,
save_watch_position,
update_source_epg_url,
)
from epg import fetch_epg
from m3u import (
fetch_m3u,
fetch_m3u_all,
fetch_source_live_data,
fetch_source_vod_data,
get_first_xtream_client,
get_refresh_in_progress,
get_xtream_client_by_source,
load_all_live_data,
load_series_data,
load_vod_data,
parse_epg_urls,
)
from xtream import XtreamClient
import auth
import epg
import ffmpeg_command
import ffmpeg_session
log = logging.getLogger()
# SSE subscribers for EPG ready notifications (limit to prevent DoS)
_epg_subscribers: set[asyncio.Queue[str]] = set()
_shutdown_event: asyncio.Event | None = None # Set during shutdown to close SSE
_MAX_SSE_SUBSCRIBERS = 100
# Login rate limiting: track failed attempts per IP
_login_attempts: dict[str, list[float]] = {}
_LOGIN_WINDOW = 300 # 5 minutes
_LOGIN_MAX_ATTEMPTS = 10
# Category filter limits
_MAX_FILTER_CATEGORIES = 10000
# =============================================================================
# App Setup
# =============================================================================
APP_DIR = pathlib.Path(__file__).parent
TEMPLATES = Jinja2Templates(directory=APP_DIR / "templates")
TEMPLATES.env.auto_reload = True
# Super-resolution engine directory (TensorRT engines for different resolutions)
SR_ENGINE_DIR = pathlib.Path(
os.environ.get("SR_ENGINE_DIR", pathlib.Path.home() / "ffmpeg_build/models")
)
def get_sr_models() -> list[str]:
"""Get available AI Upscale models (unique model names from engine files)."""
if not SR_ENGINE_DIR.exists():
return []
# Engine files are named: {model}_{height}p_fp16.engine
# e.g., 4x-compact_1080p_fp16.engine, 2x-liveaction-span_720p_fp16.engine
models = set()
for engine in SR_ENGINE_DIR.glob("*_*p_fp16.engine"):
# Extract model name by removing _{height}p_fp16.engine suffix
name = engine.stem # e.g., "2x-liveaction-span_1080p_fp16"
# Remove _fp16 and _{height}p
parts = name.rsplit("_", 2) # ["2x-liveaction-span", "1080p", "fp16"]
if len(parts) >= 3:
models.add(parts[0])
# Sort with 4x-compact first (recommended), then alphabetically
def sort_key(m: str) -> tuple[int, str]:
if m == "4x-compact":
return (0, m)
return (1, m)
return sorted(models, key=sort_key)
def is_sr_available() -> bool:
"""Check if AI Upscale is available (at least one TensorRT engine exists)."""
return len(get_sr_models()) > 0
def _logo_url_filter(url: str) -> str:
"""Wrap external logo URLs through /api/logo proxy."""
if not url or url.startswith("/") or url.startswith("data:"):
return url # Already local or data URL
# Use hostname as source for organization
parsed = urllib.parse.urlparse(url)
source = parsed.netloc.split(":")[0] if parsed.netloc else "external"
return f"/api/logo?source={urllib.parse.quote(source)}&url={urllib.parse.quote(url)}"
TEMPLATES.env.filters["logo_url"] = _logo_url_filter
def _safe_float(value: float | str | None, default: float = 0.0) -> float:
"""Safely convert value to float, returning default on failure."""
if value is None:
return default
try:
return float(value)
except (ValueError, TypeError):
return default
# Thread locks for fetch operations
_fetch_locks: dict[str, threading.Lock] = {
"live": threading.Lock(),
"vod": threading.Lock(),
"series": threading.Lock(),
"epg": threading.Lock(),
}
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Clean up orphaned transcodes and preload data on startup."""
# Initialize EPG database
epg.init(CACHE_DIR)
# Prune expired EPG data (keep 24h buffer for "what was just on")
cutoff = datetime.now(UTC) - timedelta(hours=24)
pruned = epg.prune_old_programs(cutoff)
if pruned:
log.info("Pruned %d expired EPG programs", pruned)
# Initialize transcoding module with settings callback
ffmpeg_command.init(
load_server_settings,
sr_engine_dir=str(SR_ENGINE_DIR) if is_sr_available() else "",
)
# Kill orphaned ffmpeg processes
try:
result = subprocess.run(
["pgrep", "-f", "ffmpeg.*iptv_transcode"],
check=False,
capture_output=True,
text=True,
)
for pid in result.stdout.strip().split("\n"):
if pid:
try:
os.kill(int(pid), signal.SIGKILL)
log.info("Killed orphaned ffmpeg pid %s", pid)
except (ProcessLookupError, ValueError):
pass
except Exception:
pass
# Clean up orphaned dirs and recover valid VOD sessions
ffmpeg_session.cleanup_and_recover_sessions()
# Preload all data in background threads (parallel)
def load_live():
get_refresh_in_progress().add("guide_load")
try:
log.info("Preloading live data")
cats, streams, epg_urls = load_all_live_data()
with get_cache_lock():
get_cache()["live_categories"] = cats
get_cache()["live_streams"] = streams
get_cache()["epg_urls"] = epg_urls
log.info("Live data loaded")
finally:
get_refresh_in_progress().discard("guide_load")
def load_epg_data():
try:
epg_urls = get_cache().get("epg_urls", [])
if epg_urls:
load_all_epg(epg_urls)
log.info("EPG data loaded: %d programs", epg.get_program_count())
# Notify SSE subscribers
for q in list(_epg_subscribers):
with contextlib.suppress(Exception):
q.put_nowait("epg_ready")
except Exception as e:
log.error("EPG load error: %s", e)
def load_vod():
vod_cats, vod_streams = load_vod_data()
with get_cache_lock():
get_cache()["vod_categories"] = vod_cats
get_cache()["vod_streams"] = vod_streams
log.info("VOD data loaded")
def load_series():
series_cats, series_list = load_series_data()
with get_cache_lock():
get_cache()["series_categories"] = series_cats
get_cache()["series"] = series_list
log.info("Series data loaded")
# Start all preloads in parallel (EPG waits for live data internally)
def load_all():
load_live()
# EPG needs epg_urls from live data, so run after
load_epg_data()
threading.Thread(target=load_all, daemon=True).start()
threading.Thread(target=load_vod, daemon=True).start()
threading.Thread(target=load_series, daemon=True).start()
log.info("Preload started: live+EPG, VOD, series loading in parallel")
# Periodic cleanup of expired sessions (VOD and live)
cleanup_stop = threading.Event()
def cleanup_loop():
while not cleanup_stop.wait(60): # Check every minute
ffmpeg_session.cleanup_expired_sessions()
cleanup_thread = threading.Thread(target=cleanup_loop, daemon=True)
cleanup_thread.start()
# EPG scheduler
scheduler_stop = threading.Event()
_last_triggered: dict[str, str] = {} # source_id -> last triggered time
def scheduler_loop():
while not scheduler_stop.wait(30): # Check every 30 seconds
now = datetime.now()
current_time = now.strftime("%H:%M")
for source in get_sources():
if current_time in source.epg_schedule:
key = f"{source.id}_epg"
# Only trigger once per scheduled time
if (
_last_triggered.get(source.id) != current_time
and key not in get_refresh_in_progress()
):
log.info("Scheduled EPG refresh for %s at %s", source.name, current_time)
_last_triggered[source.id] = current_time
get_refresh_in_progress().add(key)
def do_refresh(src: Source = source, k: str = key):
try:
epg_url = None
if src.type == "xtream":
client = XtreamClient(src.url, src.username, src.password)
epg_url = client.epg_url
elif src.type == "m3u":
_, _, epg_url = fetch_m3u(src.url, src.id)
elif src.type == "epg":
epg_url = src.url
if epg_url:
_fetch_all_epg([(epg_url, src.epg_timeout, src.id)])
log.info("Scheduled EPG refresh complete for %s", src.name)
except Exception as e:
log.error("Scheduled EPG refresh failed for %s: %s", src.name, e)
finally:
get_refresh_in_progress().discard(k)
threading.Thread(target=do_refresh, daemon=True).start()
scheduler_thread = threading.Thread(target=scheduler_loop, daemon=True)
scheduler_thread.start()
yield
# Shutdown - signal SSE connections to close
global _shutdown_event
_shutdown_event = asyncio.Event()
_shutdown_event.set()
cleanup_stop.set()
scheduler_stop.set()
ffmpeg_session.shutdown()
app = FastAPI(title="neTV", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=APP_DIR / "static"), name="static")
class AuthRequired(Exception):
"""Raised when authentication is required."""
@app.exception_handler(AuthRequired)
async def auth_required_handler(request: Request, _exc: AuthRequired):
return RedirectResponse("/login", status_code=303)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""Show nice HTML error pages for HTTP errors."""
# Only handle HTML requests, let API requests get JSON
accept = request.headers.get("accept", "")
if "text/html" not in accept:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
return TEMPLATES.TemplateResponse(
request,
"error.html",
{"title": f"Error {exc.status_code}", "message": exc.detail},
status_code=exc.status_code,
)
def get_current_user(request: Request) -> dict | None:
token = request.cookies.get("token")
if not token:
return None
return verify_token(token)
def require_auth(request: Request) -> dict:
if os.environ.get("NETV_NO_AUTH"):
return {"sub": "admin"}
user = get_current_user(request)
if not user:
raise AuthRequired
return user
def require_admin(request: Request) -> dict:
user = require_auth(request)
username = user.get("sub", "")
if not auth.is_admin(username):
raise HTTPException(403, "Admin access required")
return user
# =============================================================================
# Auth Routes
# =============================================================================
@app.get("/setup", response_class=HTMLResponse)
async def setup_page(request: Request):
"""Initial setup page - create first admin user."""
if not auth.is_setup_required():
return RedirectResponse("/login", status_code=303)
return TEMPLATES.TemplateResponse(request, "setup.html", {"error": None})
@app.post("/setup")
async def setup_create_user(
request: Request,
username: Annotated[str, Form()],
password: Annotated[str, Form()],
confirm: Annotated[str, Form()],
):
"""Create the initial admin user."""
if not auth.is_setup_required():
return RedirectResponse("/login", status_code=303)
# Validate
if len(username) < 3:
return TEMPLATES.TemplateResponse(
request, "setup.html", {"error": "Username must be at least 3 characters"}
)
if len(password) < 8:
return TEMPLATES.TemplateResponse(
request, "setup.html", {"error": "Password must be at least 8 characters"}
)
if password != confirm:
return TEMPLATES.TemplateResponse(
request, "setup.html", {"error": "Passwords do not match"}
)
auth.create_user(username, password)
return RedirectResponse("/login", status_code=303)
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request, error: str | None = None):
"""Login page - redirects to setup if no users exist."""
if auth.is_setup_required():
return RedirectResponse("/setup", status_code=303)
last_user = request.cookies.get("last_user", "")
return TEMPLATES.TemplateResponse(
request, "login.html", {"error": error, "last_user": last_user}
)
def _check_rate_limit(ip: str) -> None:
"""Check login rate limit. Raises HTTPException if exceeded."""
now = time.time()
attempts = _login_attempts.get(ip, [])
# Clean old attempts for this IP
attempts = [t for t in attempts if now - t < _LOGIN_WINDOW]
if attempts:
_login_attempts[ip] = attempts
elif ip in _login_attempts:
del _login_attempts[ip]
# Periodically clean stale IPs (when dict is large)
if len(_login_attempts) > 1000:
stale = [k for k, v in _login_attempts.items() if not v or now - max(v) > _LOGIN_WINDOW]
for k in stale[:100]:
del _login_attempts[k]
if len(attempts) >= _LOGIN_MAX_ATTEMPTS:
raise HTTPException(429, "Too many login attempts, try again later")
@app.post("/login")
async def login(
request: Request,
username: Annotated[str, Form()],
password: Annotated[str, Form()],
):
"""Authenticate user and create session."""
ip = request.client.host if request.client else "unknown"
_check_rate_limit(ip)
if not verify_password(username, password):
_login_attempts.setdefault(ip, []).append(time.time())
return RedirectResponse("/login?error=invalid", status_code=303)
token = create_token({"sub": username})
response = RedirectResponse("/", status_code=303)
is_secure = request.url.scheme == "https" or request.headers.get("x-forwarded-proto") == "https"
response.set_cookie(
"token", token, httponly=True, samesite="strict", max_age=86400 * 7, secure=is_secure
)
response.set_cookie("last_user", username, max_age=86400 * 365, secure=is_secure)
return response
@app.get("/logout")
async def logout():
response = RedirectResponse("/login", status_code=303)
response.delete_cookie("token")
return response
# =============================================================================
# Main Pages
# =============================================================================
@app.get("/favicon.ico")
async def favicon():
return Response(status_code=204)
@app.get("/", response_class=HTMLResponse)
async def index(request: Request, _user: Annotated[dict, Depends(require_auth)]):
host = request.headers.get("host", "")
if "cams." in host:
return await cams_grid(request, _user)
return RedirectResponse("/guide", status_code=303)
@app.get("/frontdoor", response_class=HTMLResponse)
async def frontdoor_player(request: Request, _user: Annotated[dict, Depends(require_auth)]):
"""Direct player for the Front Door doorbell camera."""
cameras = _load_cameras()
cam = next((c for c in cameras if c["id"] == "front_door"), None)
if not cam:
raise HTTPException(404, "Front door camera not configured")
return TEMPLATES.TemplateResponse(
request,
"player.html",
{
"raw_url": cam.get("rtsp_sub") or cam["rtsp_main"],
"transcode_mode": "always",
"captions_enabled": False,
"stream_type": "cam",
"stream_id": "front_door",
"ext": "",
"resume_position": 0,
"series_id": None,
"episode_id": None,
"series_name": "",
"channel_name": "Front Door",
"program_title": "",
"program_desc": "",
"next_episode_url": None,
"cc_style": "",
"cc_lang": "",
"cast_host": "",
"deinterlace_fallback": False,
"source_id": "cameras",
},
)
def _fetch_all_epg(epg_urls: list[tuple[str, int, str]]) -> int:
"""Fetch EPG from all URLs into sqlite (in parallel). Returns total program count."""
user_agent = ffmpeg_command.get_user_agent()
def fetch_one(url_timeout_source: tuple[str, int, str]) -> tuple[str, int]:
url, timeout, source_id = url_timeout_source
try:
log.info("Fetching EPG (timeout=%ds): %s", timeout, url[:80])
count = fetch_epg(url, CACHE_DIR, timeout=timeout, source_id=source_id, user_agent=user_agent)
log.info("EPG done: %d programs from %s", count, url[:50])
return url, count
except Exception as e:
log.error("EPG failed: %s - %s", url[:50], e)
return url, 0
total = 0
max_workers = min(len(epg_urls) or 1, 8) # Cap at 8 concurrent fetches
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
futures = [ex.submit(fetch_one, u) for u in epg_urls]
for future in concurrent.futures.as_completed(futures):
_, count = future.result()
total += count
# Prune expired programs (keep 24h buffer)
cutoff = datetime.now(UTC) - timedelta(hours=24)
pruned = epg.prune_old_programs(cutoff)
if pruned:
log.info("Pruned %d expired EPG programs", pruned)
log.info("EPG fetch complete: %d programs total", total)
return total
def load_all_epg(epg_urls: list[tuple[str, int, str]]) -> None:
"""Load EPG into sqlite database if empty.
Args:
epg_urls: List of (url, timeout, source_id) tuples
"""
if epg.has_programs():
log.info("EPG database has %d programs", epg.get_program_count())
return
# No data - fetch synchronously
with _fetch_locks["epg"]:
if epg.has_programs():
return
log.info("No EPG data, fetching")
try:
_fetch_all_epg(epg_urls)
except Exception as e:
log.error("EPG fetch failed: %s", e)
get_cache()["epg_error"] = str(e)
def _start_guide_background_load() -> None:
"""Start background loading of guide data if not already in progress."""
if "guide_load" in get_refresh_in_progress():
return
get_refresh_in_progress().add("guide_load")
def load():
try:
log.info("Loading guide data in background")
cats, streams, epg_urls = load_all_live_data()
with get_cache_lock():
get_cache()["live_categories"] = cats
get_cache()["live_streams"] = streams
get_cache()["epg_urls"] = epg_urls
try:
_fetch_all_epg(epg_urls)
except Exception as e:
with get_cache_lock():
get_cache()["epg_error"] = str(e)
log.info("Guide data loaded")
finally:
get_refresh_in_progress().discard("guide_load")
threading.Thread(target=load, daemon=True).start()
@app.get("/events/epg")
async def epg_events(_user: Annotated[dict, Depends(require_auth)]):
"""SSE endpoint - notifies when EPG is ready."""
if len(_epg_subscribers) >= _MAX_SSE_SUBSCRIBERS:
raise HTTPException(503, "Too many subscribers")
queue: asyncio.Queue[str] = asyncio.Queue()
_epg_subscribers.add(queue)
async def event_stream():
try:
# If EPG already loaded, send immediately
if epg.has_programs():
yield "data: epg_ready\n\n"
return
# Wait for EPG ready event or shutdown
while True:
if _shutdown_event and _shutdown_event.is_set():
return
try:
event = await asyncio.wait_for(queue.get(), timeout=1)
yield f"data: {event}\n\n"
return
except TimeoutError:
continue
except TimeoutError:
yield "data: timeout\n\n"
finally:
_epg_subscribers.discard(queue)
return StreamingResponse(event_stream(), media_type="text/event-stream")
@app.get("/guide", response_class=HTMLResponse)
async def guide_page(
request: Request,
user: Annotated[dict, Depends(require_auth)],
offset: int = 0, # hours offset from now
cats: str = "", # comma-separated category IDs
):
username = user.get("sub", "")
# Check if cats was explicitly in URL (even if empty)
cats_in_url = "cats" in request.query_params
# If no channel data in memory, try file cache first (async to avoid blocking)
if "live_categories" not in get_cache() or "live_streams" not in get_cache():
cached = await asyncio.to_thread(load_file_cache, "live_data")
if cached:
data, _ = cached
with get_cache_lock():
get_cache()["live_categories"] = data["cats"]
get_cache()["live_streams"] = data["streams"]
get_cache()["epg_urls"] = parse_epg_urls(data.get("epg_urls", []))
else:
# No cache at all - start background load and show loading page
_start_guide_background_load()
return TEMPLATES.TemplateResponse(
request,
"guide.html",
{
"grid_data": [],
"selected_cats": [],
"cats_param": cats,
"time_markers": [],
"offset": offset,
"window_start": "",
"loading_message": "Loading channel data...",
"channel_count": 0,
"loading": True,
},
)
categories = get_cache()["live_categories"]
# EPG is optional - check sqlite db for data
epg_loading = not epg.has_programs()
# Get the full saved filter for dropdown (not just current URL filter)
user_settings = load_user_settings(username)
saved_filter_list = user_settings.get("guide_filter", [])
saved_filter = set(saved_filter_list) # For fast lookup
# Build ordered list of category objects matching user's saved order
cat_by_id = {str(c["category_id"]): c for c in categories}
ordered_filter_cats = [cat_by_id[cid] for cid in saved_filter_list if cid in cat_by_id]
# Get saved VIEW selection (separate from Settings filter)
saved_view_cats = user_settings.get("guide_selected_cats") # None = show all
# Determine effective cats: URL param (if present) > saved view > all from filter
if cats_in_url:
# URL explicitly has cats param (could be empty for "none")
effective_cats = cats
elif saved_view_cats is not None:
# Use saved view selection (could be [] for "none")
effective_cats = ",".join(saved_view_cats)
else:
# Default: show all from settings filter
effective_cats = ",".join(saved_filter_list)
# Use helper to get filtered/sorted streams
streams, ordered_cats, selected_cats = _get_guide_streams(effective_cats, username)
total_count = len(streams)
# Time window: 3 hours starting from offset
now = datetime.now(UTC)
window_start = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=offset)
window_end = window_start + timedelta(hours=3)
# Virtual scrolling: only render first batch, JS fetches rest on scroll
# When disabled, render all rows server-side
virtual_scroll_enabled = user_settings.get("virtual_scroll", True)
initial_batch_size = 500 if virtual_scroll_enabled else total_count
grid_data = _build_guide_rows(streams, 0, initial_batch_size, window_start, window_end)
# Time markers (every 30 min) - convert to local time for display
time_markers = []
for i in range(7): # 0, 30, 60, 90, 120, 150, 180 minutes
t = window_start + timedelta(minutes=i * 30)
t_local = t.astimezone() # Convert to local timezone
time_markers.append(
{
"label": t_local.strftime("%H:%M"),
"left_pct": (i * 30 / 180) * 100,
}
)
# Mobile time markers (2 hour window instead of 3)
time_markers_mobile = []
for i in range(5): # 0, 30, 60, 90, 120 minutes
t = window_start + timedelta(minutes=i * 30)
t_local = t.astimezone()
time_markers_mobile.append(
{
"label": t_local.strftime("%H:%M"),
"left_pct": (i * 30 / 120) * 100,
}
)
return TEMPLATES.TemplateResponse(
request,
"guide.html",
{
"categories": categories,
"selected_cats": selected_cats,
"saved_filter": saved_filter, # Full saved filter for dropdown (set)
"ordered_filter_cats": ordered_filter_cats, # Ordered list for dropdown
"cats_param": cats,
"effective_cats": effective_cats, # What's actually being used
"grid_data": grid_data,
"time_markers": time_markers,
"time_markers_mobile": time_markers_mobile,
"offset": offset,
"window_start": window_start.strftime("%Y-%m-%d %H:%M"),
"epg_error": get_cache().get("epg_error"),
"epg_loading": epg_loading,
"channel_count": len(grid_data),
"total_count": total_count, # For virtual scrolling
"virtual_scroll": virtual_scroll_enabled,
"loading": False,
"content_access": _get_content_access(username),
},
)
def _get_guide_streams(cats: str, username: str) -> tuple[list[dict], list[str], set[str]]:
"""Get filtered and sorted streams for guide.
Returns:
Tuple of (filtered_streams, ordered_cat_ids, selected_cat_set)
"""
all_streams = get_cache().get("live_streams", [])
# Parse selected category IDs (ordered list)
ordered_cats: list[str] = []
if cats:
ordered_cats = [c.strip() for c in cats.split(",") if c.strip()]
selected_cats = set(ordered_cats)
if not selected_cats:
return [], ordered_cats, selected_cats
# Get user's unavailable groups for filtering
user_limits = auth.get_user_limits(username)
unavailable_groups = set(user_limits.get("unavailable_groups", []))
cat_order = {c: i for i, c in enumerate(ordered_cats)}
def stream_sort_key(s: dict) -> int:
for c in s.get("category_ids") or []:
if str(c) in cat_order:
return cat_order[str(c)]
return len(ordered_cats)
def stream_allowed(s: dict) -> bool:
cat_ids = s.get("category_ids") or []
return not any(f"cat:{c}" in unavailable_groups for c in cat_ids)
streams = [
s
for s in all_streams
if any(str(c) in selected_cats for c in (s.get("category_ids") or [])) and stream_allowed(s)
]
streams.sort(key=stream_sort_key)
return streams, ordered_cats, selected_cats
def _build_guide_rows(
streams: list[dict],
start_idx: int,
count: int,
window_start: datetime,
window_end: datetime,
) -> list[dict]:
"""Build guide grid rows for a range of streams.
Returns:
List of row dicts with channel info and programs.
"""
end_idx = min(start_idx + count, len(streams))
slice_streams = streams[start_idx:end_idx]
if not slice_streams:
return []
# Collect EPG IDs for batch query
epg_ids = [s.get("epg_channel_id") or "" for s in slice_streams]
epg_ids_set = [e for e in epg_ids if e]
# Batch fetch icons and programs
icons_map = epg.get_icons_batch(epg_ids_set) if epg_ids_set else {}
# Build preferred_sources for EPG matching
preferred_sources = {
epg_id: s.get("source_id", "")
for s, epg_id in zip(slice_streams, epg_ids, strict=False)
if epg_id and s.get("source_id")
}
programs_map = (
epg.get_programs_batch(epg_ids_set, window_start, window_end, preferred_sources)
if epg_ids_set
else {}
)
# Build rows
window_end_mobile = window_start + timedelta(hours=2)
grid_data = []
for idx, (s, epg_id) in enumerate(zip(slice_streams, epg_ids, strict=False), start=start_idx):
icon = s.get("stream_icon", "") or icons_map.get(epg_id, "")
ch = {
"stream_id": s["stream_id"],
"name": s["name"],
"icon": icon,
"epg_id": epg_id,
}
row = {"channel": ch, "programs": [], "programs_mobile": [], "index": idx}
for p in programs_map.get(epg_id, []):
p_start = max(p.start, window_start)
p_end = min(p.stop, window_end)
start_mins = (p_start - window_start).total_seconds() / 60
duration_mins = (p_end - p_start).total_seconds() / 60
left_pct = (start_mins / 180) * 100
width_pct = (duration_mins / 180) * 100
row["programs"].append(
{
"title": p.title,
"desc": p.desc,
"start": p.start.strftime("%H:%M"),
"end": p.stop.strftime("%H:%M"),
"left_pct": left_pct,
"width_pct": width_pct,
}
)
# Mobile: 2-hour window
if p.start < window_end_mobile:
p_end_m = min(p.stop, window_end_mobile)
duration_mins_m = (p_end_m - p_start).total_seconds() / 60
left_pct_m = (start_mins / 120) * 100
width_pct_m = (duration_mins_m / 120) * 100
row["programs_mobile"].append(
{
"title": p.title,
"desc": p.desc,
"start": p.start.strftime("%H:%M"),
"end": p.stop.strftime("%H:%M"),
"left_pct": left_pct_m,
"width_pct": width_pct_m,
}
)
grid_data.append(row)
return grid_data
@app.get("/api/guide/rows")
async def guide_rows_api(
user: Annotated[dict, Depends(require_auth)],
start: int = Query(default=0, ge=0, description="Starting row index"),
count: int = Query(default=130, ge=1, le=500, description="Number of rows to fetch"),
offset: int = Query(default=0, ge=-168, le=168, description="Hours offset from now"),
cats: str = "",
):
"""API endpoint for virtual scrolling - returns guide rows as JSON."""
username = user.get("sub", "")
# Use saved filter if no cats provided
if not cats:
user_settings = load_user_settings(username)
saved = user_settings.get("guide_filter", [])
if saved:
cats = ",".join(saved)
# Ensure data is loaded
if "live_streams" not in get_cache():
cached = await asyncio.to_thread(load_file_cache, "live_data")
if cached:
data, _ = cached
with get_cache_lock():
get_cache()["live_categories"] = data["cats"]
get_cache()["live_streams"] = data["streams"]
get_cache()["epg_urls"] = parse_epg_urls(data.get("epg_urls", []))
streams, _, _ = _get_guide_streams(cats, username)
total_count = len(streams)
if total_count == 0:
return JSONResponse({"rows": [], "total": 0, "start": start})
# Time window
now = datetime.now(UTC)
window_start = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=offset)
window_end = window_start + timedelta(hours=3)
rows = _build_guide_rows(streams, start, count, window_start, window_end)
return JSONResponse(
{"rows": rows, "total": total_count, "start": start},
headers={"Cache-Control": "no-store"},
)
def _start_vod_background_load() -> None:
"""Start background loading of VOD data if not already in progress."""
if "vod_load" in get_refresh_in_progress():
return
get_refresh_in_progress().add("vod_load")
def load():
try:
log.info("Loading VOD data in background")
vod_cats, vod_streams = load_vod_data()
with get_cache_lock():
get_cache()["vod_categories"] = vod_cats
get_cache()["vod_streams"] = vod_streams
log.info("VOD data loaded")
finally:
get_refresh_in_progress().discard("vod_load")
threading.Thread(target=load, daemon=True).start()
@app.get("/vod", response_class=HTMLResponse)
async def vod_page(
request: Request,
user: Annotated[dict, Depends(require_auth)],
category: str | None = None,
sort: str = "rating",
):
# Load from file cache if not in memory (async to avoid blocking)