Files
Kronic-Krusaders/iptv.py
T
2026-11-25 20:20:09 -06:00

1099 lines
40 KiB
Python

from __future__ import annotations
import json
import os
import re
import sqlite3
import subprocess
import threading
import time
import urllib.request
import urllib.error
import hashlib
import ipaddress
import socket
from urllib.parse import urlsplit
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
DB_PATH = Path(os.getenv("DB_PATH", BASE_DIR / "media_library.db")).expanduser().resolve()
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg")
FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe")
IPTV_FETCH_TIMEOUT = max(3, int(os.getenv("IPTV_FETCH_TIMEOUT", "15")))
IPTV_MAX_PLAYLIST_BYTES = max(1024 * 1024, int(os.getenv("IPTV_MAX_PLAYLIST_MB", "20")) * 1024 * 1024)
IPTV_USER_AGENT = os.getenv(
"IPTV_USER_AGENT",
"Mozilla/5.0 (Kronic Media Server IPTV)",
)
IPTV_TRANSCODE_MODE = os.getenv("IPTV_TRANSCODE_MODE", "auto").strip().lower()
IPTV_X264_PRESET = os.getenv("IPTV_X264_PRESET", "veryfast")
IPTV_X264_CRF = str(int(os.getenv("IPTV_X264_CRF", "22")))
IPTV_AUDIO_BITRATE = os.getenv("IPTV_AUDIO_BITRATE", "160k")
IPTV_AUDIO_CHANNELS = max(1, min(6, int(os.getenv("IPTV_AUDIO_CHANNELS", "2"))))
IPTV_AUDIO_MODE = os.getenv("IPTV_AUDIO_MODE", "normalize").strip().lower()
IPTV_PROBE_TIMEOUT = max(3, int(os.getenv("IPTV_PROBE_TIMEOUT", "8")))
IPTV_SNAPSHOT_DIR = Path(os.getenv("IPTV_SNAPSHOT_DIR", BASE_DIR / "iptv-snapshots")).expanduser().resolve()
IPTV_SNAPSHOT_TTL_MINUTES = max(1, int(os.getenv("IPTV_SNAPSHOT_TTL_MINUTES", "180")))
IPTV_SNAPSHOT_TIMEOUT = max(3, int(os.getenv("IPTV_SNAPSHOT_TIMEOUT", "12")))
IPTV_SNAPSHOT_WIDTH = max(240, int(os.getenv("IPTV_SNAPSHOT_WIDTH", "640")))
IPTV_SNAPSHOT_CONCURRENCY = max(1, min(4, int(os.getenv("IPTV_SNAPSHOT_CONCURRENCY", "2"))))
_SNAPSHOT_SEMAPHORE = threading.BoundedSemaphore(IPTV_SNAPSHOT_CONCURRENCY)
# Explicit LAN exceptions: comma-separated hostnames or literal IPs, for trusted
# local IPTV receivers. Only admins configuring deployment should set this.
IPTV_TRUSTED_HOSTS = {
host.strip().lower().rstrip('.') for host in
os.getenv("IPTV_TRUSTED_HOSTS", "").split(",") if host.strip()
}
def validate_iptv_url(url: str) -> str:
"""Reject local files, unsafe protocols and internal network targets by default.
Note: validation at resolution time cannot completely defeat hostile DNS rebinding.
For internet-facing multi-tenant instances, isolate FFmpeg/playlist fetchers at
the network layer as well.
"""
value = str(url or "").strip()
if not value or len(value) > 4096 or any(ord(c) < 32 for c in value):
raise ValueError("Invalid IPTV URL.")
parsed = urlsplit(value)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname:
raise ValueError("IPTV URLs must use HTTP or HTTPS.")
if parsed.username is not None or parsed.password is not None:
raise ValueError("Credentials embedded in IPTV URLs are not supported.")
try:
port = parsed.port
except ValueError as exc:
raise ValueError("Invalid IPTV port.") from exc
if port is not None and port not in {80, 443, 8080, 8000, 8443}:
raise ValueError("IPTV URL port is not permitted.")
host = parsed.hostname.rstrip('.').lower()
if host in IPTV_TRUSTED_HOSTS:
return value
try:
addresses = socket.getaddrinfo(host, port or (443 if parsed.scheme.lower() == 'https' else 80), type=socket.SOCK_STREAM)
except OSError as exc:
raise ValueError("Unable to resolve IPTV hostname.") from exc
if not addresses:
raise ValueError("Unable to resolve IPTV hostname.")
for info in addresses:
ip = ipaddress.ip_address(info[4][0])
if not ip.is_global:
raise ValueError("IPTV URL resolves to a private or reserved address.")
return value
class _SafePlaylistRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
validate_iptv_url(newurl)
return super().redirect_request(req, fp, code, msg, headers, newurl)
_SAFE_PLAYLIST_OPENER = urllib.request.build_opener(_SafePlaylistRedirect())
_ATTR_RE = re.compile(r'''([A-Za-z0-9_.-]+)=(?:"([^"]*)"|'([^']*)'|([^\s,]+))''')
def _db() -> sqlite3.Connection:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH, timeout=15)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA busy_timeout = 15000")
return conn
def init_iptv_db() -> None:
with _db() as db:
db.executescript(
"""
CREATE TABLE IF NOT EXISTS iptv_collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_user_id INTEGER NOT NULL,
name TEXT NOT NULL,
is_public INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
UNIQUE(owner_user_id, name COLLATE NOCASE)
);
CREATE TABLE IF NOT EXISTS iptv_sources (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_user_id INTEGER NOT NULL,
collection_id INTEGER REFERENCES iptv_collections(id) ON DELETE SET NULL,
name TEXT NOT NULL,
source_type TEXT NOT NULL CHECK(source_type IN ('upload','url','channel')),
source_value TEXT NOT NULL DEFAULT '',
source_payload TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
is_public INTEGER NOT NULL DEFAULT 0,
last_refresh_at INTEGER,
last_error TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_iptv_sources_owner ON iptv_sources(owner_user_id);
CREATE TABLE IF NOT EXISTS iptv_channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_id INTEGER NOT NULL REFERENCES iptv_sources(id) ON DELETE CASCADE,
stable_key TEXT NOT NULL,
name TEXT NOT NULL,
stream_url TEXT NOT NULL,
tvg_id TEXT NOT NULL DEFAULT '',
tvg_name TEXT NOT NULL DEFAULT '',
tvg_logo TEXT NOT NULL DEFAULT '',
group_name TEXT NOT NULL DEFAULT '',
channel_number TEXT NOT NULL DEFAULT '',
referrer TEXT NOT NULL DEFAULT '',
user_agent TEXT NOT NULL DEFAULT '',
raw_options_json TEXT NOT NULL DEFAULT '{}',
selected INTEGER NOT NULL DEFAULT 0,
hidden INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
UNIQUE(source_id, stable_key)
);
CREATE INDEX IF NOT EXISTS idx_iptv_channels_source ON iptv_channels(source_id);
CREATE INDEX IF NOT EXISTS idx_iptv_channels_selected ON iptv_channels(selected, hidden);
CREATE TABLE IF NOT EXISTS iptv_channel_preferences (
user_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL REFERENCES iptv_channels(id) ON DELETE CASCADE,
hidden INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
PRIMARY KEY(user_id, channel_id)
);
CREATE INDEX IF NOT EXISTS idx_iptv_channel_preferences_user
ON iptv_channel_preferences(user_id, hidden);
"""
)
collection_columns = {
row["name"]
for row in db.execute("PRAGMA table_info(iptv_collections)").fetchall()
}
if "is_public" not in collection_columns:
db.execute(
"ALTER TABLE iptv_collections ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0"
)
source_columns = {
row["name"]
for row in db.execute("PRAGMA table_info(iptv_sources)").fetchall()
}
if "is_public" not in source_columns:
db.execute(
"ALTER TABLE iptv_sources ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0"
)
# Older builds stored Hide directly on the channel row. Preserve those
# choices as owner-specific preferences, then clear the global flag.
now = int(time.time())
db.execute(
"""
INSERT OR IGNORE INTO iptv_channel_preferences
(user_id, channel_id, hidden, updated_at)
SELECT s.owner_user_id, ch.id, 1, ?
FROM iptv_channels ch
JOIN iptv_sources s ON s.id=ch.source_id
WHERE ch.hidden=1
""",
(now,),
)
db.execute("UPDATE iptv_channels SET hidden=0 WHERE hidden<>0")
db.commit()
def _row(row: sqlite3.Row | None) -> dict[str, Any] | None:
return dict(row) if row is not None else None
def list_collections(user_id: int) -> list[dict[str, Any]]:
with _db() as db:
rows = db.execute(
"""SELECT c.*,
(SELECT COUNT(*) FROM iptv_sources s WHERE s.collection_id=c.id) AS source_count,
(SELECT COUNT(*) FROM iptv_channels ch JOIN iptv_sources s ON s.id=ch.source_id
WHERE s.collection_id=c.id AND ch.selected=1) AS channel_count
FROM iptv_collections c
WHERE c.owner_user_id=?
ORDER BY c.name COLLATE NOCASE""",
(int(user_id),),
).fetchall()
return [dict(r) for r in rows]
def create_collection(user_id: int, name: str, is_public: bool = False) -> dict[str, Any]:
name = str(name or "").strip()
if not name:
raise ValueError("Playlist name is required.")
now = int(time.time())
try:
with _db() as db:
cur = db.execute(
"INSERT INTO iptv_collections(owner_user_id,name,is_public,created_at) VALUES(?,?,?,?)",
(int(user_id), name, 1 if is_public else 0, now),
)
db.commit()
collection_id = int(cur.lastrowid)
except sqlite3.IntegrityError as exc:
raise ValueError("A playlist with that name already exists.") from exc
return {"id": collection_id, "name": name, "is_public": 1 if is_public else 0}
def delete_collection(user_id: int, collection_id: int) -> None:
with _db() as db:
result = db.execute(
"DELETE FROM iptv_collections WHERE id=? AND owner_user_id=?",
(int(collection_id), int(user_id)),
)
if result.rowcount == 0:
raise KeyError("Playlist not found.")
db.commit()
def set_collection_public(user_id: int, collection_id: int, is_public: bool) -> None:
with _db() as db:
result = db.execute(
"UPDATE iptv_collections SET is_public=? WHERE id=? AND owner_user_id=?",
(1 if is_public else 0, int(collection_id), int(user_id)),
)
if result.rowcount == 0:
raise KeyError("Playlist not found.")
db.commit()
def set_source_public(user_id: int, source_id: int, is_public: bool) -> None:
with _db() as db:
result = db.execute(
"UPDATE iptv_sources SET is_public=? WHERE id=? AND owner_user_id=?",
(1 if is_public else 0, int(source_id), int(user_id)),
)
if result.rowcount == 0:
raise KeyError("IPTV source not found.")
db.commit()
def list_sources(user_id: int) -> list[dict[str, Any]]:
with _db() as db:
rows = db.execute(
"""SELECT s.*, c.name AS collection_name,
(SELECT COUNT(*) FROM iptv_channels ch WHERE ch.source_id=s.id) AS channel_count,
(SELECT COUNT(*) FROM iptv_channels ch WHERE ch.source_id=s.id AND ch.selected=1) AS selected_count
FROM iptv_sources s
LEFT JOIN iptv_collections c ON c.id=s.collection_id
WHERE s.owner_user_id=?
ORDER BY COALESCE(c.name,''), s.name COLLATE NOCASE""",
(int(user_id),),
).fetchall()
return [dict(r) for r in rows]
def _validate_collection(db: sqlite3.Connection, user_id: int, collection_id: int | None) -> int | None:
if collection_id in (None, "", 0, "0"):
return None
collection_id = int(collection_id)
row = db.execute(
"SELECT id FROM iptv_collections WHERE id=? AND owner_user_id=?",
(collection_id, int(user_id)),
).fetchone()
if not row:
raise ValueError("Playlist does not belong to this user.")
return collection_id
def create_source(
user_id: int,
*,
name: str,
source_type: str,
source_value: str = "",
source_payload: str = "",
collection_id: int | None = None,
channel_name: str = "",
is_public: bool = False,
) -> dict[str, Any]:
name = str(name or "").strip()
source_type = str(source_type or "").strip().lower()
source_value = str(source_value or "").strip()
source_payload = str(source_payload or "")
if source_type not in {"upload", "url", "channel"}:
raise ValueError("Invalid IPTV source type.")
if not name:
raise ValueError("A name is required.")
if source_type in {"url", "channel"}:
source_value = validate_iptv_url(source_value)
if source_type == "upload" and not source_payload.strip():
raise ValueError("The uploaded M3U file is empty.")
if len(source_payload.encode("utf-8", "ignore")) > IPTV_MAX_PLAYLIST_BYTES:
raise ValueError("The uploaded playlist is too large.")
now = int(time.time())
with _db() as db:
collection_id = _validate_collection(db, user_id, collection_id)
cur = db.execute(
"""INSERT INTO iptv_sources
(owner_user_id,collection_id,name,source_type,source_value,source_payload,enabled,is_public,created_at)
VALUES(?,?,?,?,?,?,1,?,?)""",
(
int(user_id),
collection_id,
name,
source_type,
source_value,
source_payload,
1 if is_public else 0,
now,
),
)
source_id = int(cur.lastrowid)
db.commit()
if source_type == "channel":
channel_display = str(channel_name or name).strip() or name
channels = [{
"name": channel_display,
"stream_url": source_value,
"tvg_id": "",
"tvg_name": channel_display,
"tvg_logo": "",
"group_name": "",
"channel_number": "",
"referrer": "",
"user_agent": "",
"raw_options": {},
}]
_replace_source_channels(user_id, source_id, channels, direct_default_selected=True)
_mark_source_refresh(source_id, error="")
else:
refresh_source(user_id, source_id)
return get_source(user_id, source_id) or {"id": source_id, "name": name}
def get_source(user_id: int, source_id: int) -> dict[str, Any] | None:
with _db() as db:
row = db.execute(
"""SELECT s.*, c.name AS collection_name FROM iptv_sources s
LEFT JOIN iptv_collections c ON c.id=s.collection_id
WHERE s.id=? AND s.owner_user_id=?""",
(int(source_id), int(user_id)),
).fetchone()
return _row(row)
def delete_source(user_id: int, source_id: int) -> None:
with _db() as db:
result = db.execute(
"DELETE FROM iptv_sources WHERE id=? AND owner_user_id=?",
(int(source_id), int(user_id)),
)
if result.rowcount == 0:
raise KeyError("IPTV source not found.")
db.commit()
def move_source_to_collection(user_id: int, source_id: int, collection_id: int | None) -> None:
with _db() as db:
collection_id = _validate_collection(db, user_id, collection_id)
result = db.execute(
"UPDATE iptv_sources SET collection_id=? WHERE id=? AND owner_user_id=?",
(collection_id, int(source_id), int(user_id)),
)
if result.rowcount == 0:
raise KeyError("IPTV source not found.")
db.commit()
def _fetch_playlist(url: str) -> str:
url = validate_iptv_url(url)
request = urllib.request.Request(
url,
headers={
"User-Agent": IPTV_USER_AGENT,
"Accept": "application/x-mpegURL, application/vnd.apple.mpegurl, text/plain, */*",
},
)
try:
with _SAFE_PLAYLIST_OPENER.open(request, timeout=IPTV_FETCH_TIMEOUT) as response:
data = response.read(IPTV_MAX_PLAYLIST_BYTES + 1)
if len(data) > IPTV_MAX_PLAYLIST_BYTES:
raise ValueError("Remote playlist is too large.")
encoding = response.headers.get_content_charset() or "utf-8"
return data.decode(encoding, "replace")
except urllib.error.HTTPError as exc:
raise ValueError(f"Playlist HTTP error {exc.code}.") from exc
except urllib.error.URLError as exc:
raise ValueError(f"Could not fetch playlist: {exc.reason}") from exc
def refresh_source(user_id: int, source_id: int) -> dict[str, Any]:
source = get_source(user_id, source_id)
if not source:
raise KeyError("IPTV source not found.")
source_type = source["source_type"]
if source_type == "channel":
_mark_source_refresh(source_id, error="")
return {"ok": True, "channels": 1}
try:
if source_type == "upload":
text = source["source_payload"]
else:
text = _fetch_playlist(source["source_value"])
channels = parse_m3u(text)
_replace_source_channels(user_id, source_id, channels, direct_default_selected=False)
_mark_source_refresh(source_id, error="")
return {"ok": True, "channels": len(channels)}
except Exception as exc:
_mark_source_refresh(source_id, error=str(exc))
raise
def _mark_source_refresh(source_id: int, *, error: str) -> None:
with _db() as db:
db.execute(
"UPDATE iptv_sources SET last_refresh_at=?, last_error=? WHERE id=?",
(int(time.time()), str(error or ""), int(source_id)),
)
db.commit()
def parse_m3u(text: str) -> list[dict[str, Any]]:
lines = [line.strip() for line in str(text or "").replace("\ufeff", "").splitlines()]
channels: list[dict[str, Any]] = []
pending: dict[str, Any] | None = None
pending_options: dict[str, str] = {}
for line in lines:
if not line:
continue
if line.startswith("#EXTINF:"):
body = line.split(":", 1)[1]
attrs = {}
for match in _ATTR_RE.finditer(body):
attrs[match.group(1).lower()] = next(
value for value in match.groups()[1:] if value is not None
)
comma_index = body.rfind(",")
name = body[comma_index + 1:].strip() if comma_index >= 0 else "Channel"
pending = {
"name": name or attrs.get("tvg-name") or "Channel",
"tvg_id": attrs.get("tvg-id", ""),
"tvg_name": attrs.get("tvg-name", ""),
"tvg_logo": attrs.get("tvg-logo", ""),
"group_name": attrs.get("group-title", ""),
"channel_number": attrs.get("tvg-chno", attrs.get("channel-number", "")),
"referrer": "",
"user_agent": "",
"raw_options": {},
}
pending_options = {}
continue
if line.startswith("#EXTVLCOPT:"):
key_value = line[len("#EXTVLCOPT:"):]
key, sep, value = key_value.partition("=")
if sep:
key = key.strip().lower()
value = value.strip()
pending_options[key] = value
if pending is not None:
if key in {"http-referrer", "http-referrer-url", "referrer"}:
pending["referrer"] = value
elif key in {"http-user-agent", "user-agent"}:
pending["user_agent"] = value
continue
if line.startswith("#EXTHTTP:"):
payload = line[len("#EXTHTTP:"):].strip()
try:
headers = json.loads(payload)
if isinstance(headers, dict):
for key, value in headers.items():
pending_options[f"header:{key}"] = str(value)
if pending is not None:
if str(key).lower() == "referer":
pending["referrer"] = str(value)
if str(key).lower() == "user-agent":
pending["user_agent"] = str(value)
except Exception:
pass
continue
if line.startswith("#"):
continue
if "://" not in line:
continue
entry = pending or {
"name": line,
"tvg_id": "",
"tvg_name": "",
"tvg_logo": "",
"group_name": "",
"channel_number": "",
"referrer": "",
"user_agent": "",
"raw_options": {},
}
entry = dict(entry)
entry["stream_url"] = line
entry["raw_options"] = dict(pending_options)
channels.append(entry)
pending = None
pending_options = {}
return channels
def _stable_key(channel: dict[str, Any]) -> str:
tvg_id = str(channel.get("tvg_id") or "").strip().lower()
stream_url = str(channel.get("stream_url") or "").strip()
name = str(channel.get("name") or "").strip().lower()
seed = f"{tvg_id}\0{name}\0{stream_url}"
return hashlib.sha1(seed.encode("utf-8", "ignore")).hexdigest()
def _replace_source_channels(
user_id: int,
source_id: int,
channels: list[dict[str, Any]],
*,
direct_default_selected: bool,
) -> None:
now = int(time.time())
with _db() as db:
source = db.execute(
"SELECT id FROM iptv_sources WHERE id=? AND owner_user_id=?",
(int(source_id), int(user_id)),
).fetchone()
if not source:
raise KeyError("IPTV source not found.")
existing = {
row["stable_key"]: (int(row["selected"]), int(row["hidden"]))
for row in db.execute(
"SELECT stable_key,selected,hidden FROM iptv_channels WHERE source_id=?",
(int(source_id),),
).fetchall()
}
seen = set()
for index, channel in enumerate(channels):
# A playlist may contain local file paths or arbitrary FFmpeg protocols.
# Do not store those as executable playback sources.
try:
validate_iptv_url(channel.get("stream_url"))
except ValueError:
continue
stable_key = _stable_key(channel)
seen.add(stable_key)
selected, hidden = existing.get(
stable_key,
(1 if direct_default_selected else 0, 0),
)
db.execute(
"""INSERT INTO iptv_channels
(source_id,stable_key,name,stream_url,tvg_id,tvg_name,tvg_logo,group_name,
channel_number,referrer,user_agent,raw_options_json,selected,hidden,sort_order,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(source_id,stable_key) DO UPDATE SET
name=excluded.name,
stream_url=excluded.stream_url,
tvg_id=excluded.tvg_id,
tvg_name=excluded.tvg_name,
tvg_logo=excluded.tvg_logo,
group_name=excluded.group_name,
channel_number=excluded.channel_number,
referrer=excluded.referrer,
user_agent=excluded.user_agent,
raw_options_json=excluded.raw_options_json,
sort_order=excluded.sort_order,
updated_at=excluded.updated_at""",
(
int(source_id), stable_key, str(channel.get("name") or "Channel"),
str(channel.get("stream_url") or ""), str(channel.get("tvg_id") or ""),
str(channel.get("tvg_name") or ""), str(channel.get("tvg_logo") or ""),
str(channel.get("group_name") or ""), str(channel.get("channel_number") or ""),
str(channel.get("referrer") or ""), str(channel.get("user_agent") or ""),
json.dumps(channel.get("raw_options") or {}, ensure_ascii=False),
selected, hidden, index, now,
),
)
if seen:
placeholders = ",".join("?" for _ in seen)
db.execute(
f"DELETE FROM iptv_channels WHERE source_id=? AND stable_key NOT IN ({placeholders})",
(int(source_id), *seen),
)
else:
db.execute("DELETE FROM iptv_channels WHERE source_id=?", (int(source_id),))
db.commit()
def list_channels(
user_id: int,
*,
source_id: int | None = None,
selected_only: bool = False,
collection_id: int | None = None,
) -> list[dict[str, Any]]:
user_id = int(user_id)
# Source chooser/management is owner-only. The general selected-channel
# listing includes the user's own channels plus anything explicitly shared.
if source_id is not None:
access_clause = "s.owner_user_id=?"
else:
access_clause = "(s.owner_user_id=? OR s.is_public=1 OR COALESCE(c.is_public,0)=1)"
clauses = [access_clause]
values: list[Any] = [user_id]
if source_id is not None:
clauses.append("s.id=?")
values.append(int(source_id))
if collection_id is not None:
clauses.append("s.collection_id=?")
values.append(int(collection_id))
if selected_only:
clauses.extend([
"ch.selected=1",
"s.enabled=1",
"COALESCE(pref.hidden,0)=0",
])
with _db() as db:
rows = db.execute(
f"""SELECT
ch.*,
s.name AS source_name,
s.owner_user_id,
s.collection_id,
s.is_public AS source_is_public,
c.name AS collection_name,
COALESCE(c.is_public,0) AS collection_is_public,
COALESCE(pref.hidden,0) AS user_hidden,
CASE
WHEN s.owner_user_id=? THEN 0
ELSE 1
END AS is_shared,
CASE
WHEN s.owner_user_id=? THEN 'owned'
WHEN COALESCE(c.is_public,0)=1 THEN 'playlist'
WHEN s.is_public=1 THEN 'source'
ELSE ''
END AS public_via,
CASE
WHEN s.owner_user_id=? THEN COALESCE(c.name,'My Channels')
WHEN COALESCE(c.is_public,0)=1 THEN c.name
ELSE 'Shared Channels'
END AS display_collection_name
FROM iptv_channels ch
JOIN iptv_sources s ON s.id=ch.source_id
LEFT JOIN iptv_collections c ON c.id=s.collection_id
LEFT JOIN iptv_channel_preferences pref
ON pref.channel_id=ch.id AND pref.user_id=?
WHERE {' AND '.join(clauses)}
ORDER BY
CASE WHEN s.owner_user_id=? THEN 0 ELSE 1 END,
CASE
WHEN s.owner_user_id=? THEN COALESCE(c.name,'')
WHEN COALESCE(c.is_public,0)=1 THEN COALESCE(c.name,'')
ELSE 'Shared Channels'
END COLLATE NOCASE,
COALESCE(NULLIF(ch.group_name,''), s.name) COLLATE NOCASE,
ch.sort_order,
ch.name COLLATE NOCASE""",
(
user_id,
user_id,
user_id,
user_id,
*values,
user_id,
user_id,
),
).fetchall()
return [dict(r) for r in rows]
def get_channel(user_id: int, channel_id: int) -> dict[str, Any] | None:
user_id = int(user_id)
with _db() as db:
row = db.execute(
"""SELECT
ch.*,
s.name AS source_name,
s.owner_user_id,
s.enabled AS source_enabled,
s.is_public AS source_is_public,
s.collection_id,
c.name AS collection_name,
COALESCE(c.is_public,0) AS collection_is_public,
CASE WHEN s.owner_user_id=? THEN 0 ELSE 1 END AS is_shared
FROM iptv_channels ch
JOIN iptv_sources s ON s.id=ch.source_id
LEFT JOIN iptv_collections c ON c.id=s.collection_id
WHERE ch.id=?
AND (
s.owner_user_id=?
OR (
ch.selected=1
AND s.enabled=1
AND (s.is_public=1 OR COALESCE(c.is_public,0)=1)
)
)""",
(user_id, int(channel_id), user_id),
).fetchone()
return _row(row)
def set_channel_selection(user_id: int, source_id: int, channel_ids: list[int]) -> int:
channel_ids = sorted({int(x) for x in channel_ids})
with _db() as db:
source = db.execute(
"SELECT id FROM iptv_sources WHERE id=? AND owner_user_id=?",
(int(source_id), int(user_id)),
).fetchone()
if not source:
raise KeyError("IPTV source not found.")
db.execute(
"UPDATE iptv_channels SET selected=0 WHERE source_id=?",
(int(source_id),),
)
if channel_ids:
placeholders = ",".join("?" for _ in channel_ids)
db.execute(
f"UPDATE iptv_channels SET selected=1 WHERE source_id=? AND id IN ({placeholders})",
(int(source_id), *channel_ids),
)
db.commit()
return len(channel_ids)
def set_channel_hidden(user_id: int, channel_id: int, hidden: bool) -> None:
user_id = int(user_id)
channel_id = int(channel_id)
# Users may hide any channel they can currently access, including a
# shared/public channel. This never changes the owner's master selection.
channel = get_channel(user_id, channel_id)
if not channel:
raise KeyError("Channel not found.")
now = int(time.time())
with _db() as db:
db.execute(
"""INSERT INTO iptv_channel_preferences(user_id,channel_id,hidden,updated_at)
VALUES(?,?,?,?)
ON CONFLICT(user_id,channel_id)
DO UPDATE SET hidden=excluded.hidden, updated_at=excluded.updated_at""",
(user_id, channel_id, 1 if hidden else 0, now),
)
db.commit()
def update_channel(user_id: int, channel_id: int, data: dict[str, Any]) -> None:
# Hide is a per-user preference and is allowed for shared channels.
if "hidden" in data:
set_channel_hidden(
user_id,
channel_id,
bool(data["hidden"]),
)
# Everything else changes the owner's master channel record and therefore
# remains owner-only.
allowed = {"name", "group_name", "selected"}
assignments = []
values: list[Any] = []
for key in allowed:
if key not in data:
continue
value = data[key]
if key == "selected":
value = 1 if bool(value) else 0
else:
value = str(value or "").strip()
assignments.append(f"{key}=?")
values.append(value)
if not assignments:
return
values.extend([
int(channel_id),
int(user_id),
])
with _db() as db:
result = db.execute(
f"""UPDATE iptv_channels SET {', '.join(assignments)}
WHERE id=? AND source_id IN
(SELECT id FROM iptv_sources WHERE owner_user_id=?)""",
tuple(values),
)
if result.rowcount == 0:
raise KeyError("Channel not found.")
db.commit()
def _header_string(channel: dict[str, Any]) -> str:
headers: list[str] = []
user_agent = str(channel.get("user_agent") or "").strip()
referrer = str(channel.get("referrer") or "").strip()
if user_agent:
headers.append(f"User-Agent: {user_agent}")
if referrer:
headers.append(f"Referer: {referrer}")
try:
options = json.loads(channel.get("raw_options_json") or "{}")
except Exception:
options = {}
if isinstance(options, dict):
for key, value in options.items():
if not str(key).startswith("header:"):
continue
header_name = str(key).split(":", 1)[1].strip()
if header_name and value:
headers.append(f"{header_name}: {value}")
return "\r\n".join(headers) + ("\r\n" if headers else "")
def channel_snapshot_path(channel_id: int) -> Path:
IPTV_SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
return IPTV_SNAPSHOT_DIR / f"channel-{int(channel_id)}.jpg"
def ensure_channel_snapshot(channel: dict[str, Any], *, force: bool = False) -> Path | None:
"""Return a cached still frame for a live channel, creating it on demand.
Snapshot generation is deliberately concurrency-limited so opening the IPTV
grid cannot launch dozens of FFmpeg processes at once.
"""
try:
channel_id = int(channel["id"])
except Exception:
return None
destination = channel_snapshot_path(channel_id)
ttl_seconds = IPTV_SNAPSHOT_TTL_MINUTES * 60
if not force and destination.is_file():
try:
if time.time() - destination.stat().st_mtime < ttl_seconds:
return destination
except OSError:
pass
with _SNAPSHOT_SEMAPHORE:
# Another request may have generated it while this request waited.
if not force and destination.is_file():
try:
if time.time() - destination.stat().st_mtime < ttl_seconds:
return destination
except OSError:
pass
temporary = destination.with_suffix('.part.jpg')
temporary.unlink(missing_ok=True)
command = [
FFMPEG_BIN,
'-nostdin',
'-hide_banner',
'-loglevel', 'error',
'-rw_timeout', '10000000',
'-reconnect', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '3',
]
headers = _header_string(channel)
if headers:
command.extend(['-headers', headers])
validate_iptv_url(channel['stream_url'])
command.extend([
'-i', channel['stream_url'],
'-map', '0:v:0?',
'-an', '-sn', '-dn',
'-frames:v', '1',
'-vf', f"scale='min({IPTV_SNAPSHOT_WIDTH},iw)':-2",
'-q:v', '4',
'-y', str(temporary),
])
try:
result = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
timeout=IPTV_SNAPSHOT_TIMEOUT,
)
if result.returncode != 0 or not temporary.is_file() or temporary.stat().st_size < 512:
temporary.unlink(missing_ok=True)
return destination if destination.is_file() else None
temporary.replace(destination)
return destination
except Exception:
temporary.unlink(missing_ok=True)
return destination if destination.is_file() else None
def probe_channel(channel: dict[str, Any]) -> dict[str, str]:
command = [
FFPROBE_BIN,
"-v", "error",
"-analyzeduration", "3000000",
"-probesize", "3000000",
]
headers = _header_string(channel)
if headers:
command.extend(["-headers", headers])
validate_iptv_url(channel["stream_url"])
command.extend([
"-show_entries", "stream=codec_type,codec_name",
"-of", "json",
channel["stream_url"],
])
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=IPTV_PROBE_TIMEOUT,
check=True,
)
payload = json.loads(result.stdout or "{}")
streams = payload.get("streams") or []
video = next((x for x in streams if x.get("codec_type") == "video"), {})
audio = next((x for x in streams if x.get("codec_type") == "audio"), {})
return {
"video_codec": str(video.get("codec_name") or "").lower(),
"audio_codec": str(audio.get("codec_name") or "").lower(),
}
except Exception:
return {"video_codec": "", "audio_codec": ""}
def iptv_ffmpeg_command(channel: dict[str, Any]) -> tuple[list[str], dict[str, str]]:
probe = probe_channel(channel)
vcodec = probe["video_codec"]
acodec = probe["audio_codec"]
mode = IPTV_TRANSCODE_MODE if IPTV_TRANSCODE_MODE in {"auto", "always", "copy"} else "auto"
if mode == "always":
copy_video = False
elif mode == "copy":
copy_video = True
else:
copy_video = vcodec in {"h264", "avc1"}
# Live HLS/MPEG-TS commonly carries AAC in ADTS framing. MP4 requires
# AudioSpecificConfig instead, and some feeds cause FFmpeg's MP4 muxer to
# abort when AAC is copied verbatim. Normalizing audio to fresh AAC is
# inexpensive compared with video transcoding and also cleans timestamps.
#
# Set IPTV_AUDIO_MODE=copy if you explicitly want stream-copy audio.
copy_audio = (
IPTV_AUDIO_MODE == "copy"
and acodec in {"aac", "mp3"}
)
command = [
FFMPEG_BIN,
"-nostdin",
"-hide_banner",
"-loglevel", "warning",
"-fflags", "+genpts+discardcorrupt",
"-rw_timeout", "15000000",
"-reconnect", "1",
"-reconnect_streamed", "1",
"-reconnect_delay_max", "5",
]
headers = _header_string(channel)
if headers:
command.extend(["-headers", headers])
validate_iptv_url(channel["stream_url"])
command.extend([
"-i", channel["stream_url"],
"-map", "0:v:0?",
"-map", "0:a:0?",
"-sn", "-dn",
])
if copy_video:
command.extend(["-c:v", "copy"])
else:
command.extend([
"-c:v", "libx264",
"-preset", IPTV_X264_PRESET,
"-crf", IPTV_X264_CRF,
"-profile:v", "high",
"-level:v", "4.1",
"-pix_fmt", "yuv420p",
])
if copy_audio:
command.extend(["-c:a", "copy"])
if acodec == "aac":
command.extend([
"-bsf:a",
"aac_adtstoasc",
])
else:
command.extend([
"-c:a", "aac",
"-b:a", IPTV_AUDIO_BITRATE,
"-ar", "48000",
"-ac", str(IPTV_AUDIO_CHANNELS),
"-af", "aresample=async=1:first_pts=0",
])
command.extend([
"-avoid_negative_ts", "make_zero",
"-map_metadata", "-1",
"-map_chapters", "-1",
"-movflags", "+frag_keyframe+empty_moov+default_base_moof+omit_tfhd_offset",
"-frag_duration", "2000000",
"-min_frag_duration", "1000000",
"-video_track_timescale", "90000",
"-max_interleave_delta", "0",
"-flush_packets", "1",
"-f", "mp4",
"pipe:1",
])
probe["video_action"] = "copy" if copy_video else "h264"
probe["audio_action"] = (
"copy+aac_adtstoasc"
if copy_audio and acodec == "aac"
else "copy"
if copy_audio
else "aac-normalize"
)
return command, probe