From cb01da246f9fd02fcc9fdeec7b44593d42076cf6 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:18:58 -0600 Subject: [PATCH] Upload files to "/" --- admin_policies.py | 153 +++ history_scopes.py | 106 ++ media_accounts.py | 866 ++++++++++++ room_access_scope.py | 62 + stream_server.py | 3040 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 4227 insertions(+) create mode 100644 admin_policies.py create mode 100644 history_scopes.py create mode 100644 media_accounts.py create mode 100644 room_access_scope.py create mode 100644 stream_server.py diff --git a/admin_policies.py b/admin_policies.py new file mode 100644 index 0000000..a668d98 --- /dev/null +++ b/admin_policies.py @@ -0,0 +1,153 @@ +"""Instance-managed, additive media policies. Existing room denials remain in force.""" +import json +import re +from media_accounts import open_database, require_admin, AccountError, MEDIA_KEYS + +def init(db): + db.execute("CREATE TABLE IF NOT EXISTS instance_appearance (id INTEGER PRIMARY KEY CHECK(id=1), settings TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS room_appearance (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, settings TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS instance_media_policy (user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, policy TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS room_templates (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, policy TEXT NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS room_template_policy (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, policy TEXT NOT NULL)") + +def validate(data): + from library_index import get_media_sources + if not isinstance(data,dict) or not isinstance(data.get('types'),list) or not isinstance(data.get('libraries'),list): + raise AccountError(400,'Invalid media policy') + types=data['types']; libraries=data['libraries'] + if any(not isinstance(x,str) or x not in MEDIA_KEYS for x in types) or any(type(x) is not int for x in libraries): + raise AccountError(400,'Invalid media type or library') + if not set(libraries)<= {s['id'] for s in get_media_sources()}: + raise AccountError(400,'Unknown library') + return {'types':sorted(set(types)), 'libraries':sorted(set(libraries))} + +def policies(uid): + from room_access_scope import current + rid=current(uid) + with open_database() as db: + init(db) + user=db.execute('SELECT is_platform_admin FROM users WHERE id=?',(uid,)).fetchone() + if user and user['is_platform_admin']: return [] + rows=db.execute('SELECT policy FROM instance_media_policy WHERE user_id=?',(uid,)).fetchall() + rows+=db.execute('SELECT p.policy FROM room_template_policy p JOIN room_memberships m ON m.room_id=p.room_id JOIN managed_rooms r ON r.id=m.room_id WHERE m.user_id=? AND r.enabled=1 AND (? IS NULL OR r.id=?)',(uid,rid,rid)).fetchall() + return [json.loads(r['policy']) for r in rows] + +def source_allowed(uid,source, rules=None): + if not source: return False + rules=policies(uid) if rules is None else rules + key='tv' if source['library_type']=='shows' else 'movies' + return all(source['id'] in r['libraries'] and key in r['types'] for r in rules) + +def enforce_source(uid,source): + from media_accounts import enforce_media_library + if not source or not source_allowed(uid,source): raise AccountError(403,'Library access denied') + enforce_media_library(uid,'tv' if source['library_type']=='shows' else 'movies') + +def snapshot(token): + from library_index import get_media_sources + require_admin(token) + with open_database() as db: + init(db) + return {'users':[dict(r) for r in db.execute('SELECT id,username,is_platform_admin FROM users ORDER BY username')], 'sources':[{k:s[k] for k in ('id','name','library_type')} for s in get_media_sources()], 'policies':{str(r['user_id']):json.loads(r['policy']) for r in db.execute('SELECT * FROM instance_media_policy')}, 'rooms':[dict(r) for r in db.execute('SELECT id,room_name,display_name FROM managed_rooms ORDER BY display_name')], 'room_policies':{str(r['room_id']):json.loads(r['policy']) for r in db.execute('SELECT * FROM room_template_policy')}, 'templates':[{'id':r['id'],'name':r['name'],'policy':json.loads(r['policy'])} for r in db.execute('SELECT * FROM room_templates ORDER BY name')]} + +def save_user(token,data): + require_admin(token) + uid=data.get('user_id') + if type(uid) is not int: raise AccountError(400,'Invalid user') + with open_database() as db: + init(db) + u=db.execute('SELECT is_platform_admin FROM users WHERE id=?',(uid,)).fetchone() + if not u or u['is_platform_admin']: raise AccountError(400,'Select a non-platform-admin account') + if data.get('inherit') is True: db.execute('DELETE FROM instance_media_policy WHERE user_id=?',(uid,)) + else: db.execute('INSERT INTO instance_media_policy VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET policy=excluded.policy',(uid,json.dumps(validate(data)))) + return {'ok':True} + +def save_template(token,data): + require_admin(token) + name=str(data.get('name') or '').strip() + if not name or len(name)>100: raise AccountError(400,'Enter a template name') + policy=validate(data) + actions=('media_access','user_permissions','room_permissions','password_resets','account_approvals') + roles=data.get('roles',{}) + if not isinstance(roles,dict) or any(r not in ('member','moderator','admin','owner') or not isinstance(v,list) or any(a not in actions for a in v) for r,v in roles.items()): + raise AccountError(400,'Invalid role policy') + from history_scopes import validate as validate_history + policy['history']=validate_history(data.get('history',{})) + policy['roles']=roles + policy['ai_chat']=data.get('ai_chat') is True + policy['ai_tools']=policy['ai_chat'] and data.get('ai_tools') is True + with open_database() as db: + init(db) + db.execute('INSERT INTO room_templates(name,policy) VALUES(?,?) ON CONFLICT(name) DO UPDATE SET policy=excluded.policy',(name,json.dumps(policy))) + return {'ok':True} + +def copy_template(db,room_id,template_id): + if template_id in (None,''): return + init(db) + row=db.execute('SELECT policy FROM room_templates WHERE id=?',(template_id,)).fetchone() + if not row: raise AccountError(400,'Unknown room template') + db.execute('INSERT INTO room_template_policy VALUES(?,?)',(room_id,row['policy'])) + history=json.loads(row['policy']).get('history') + if history is not None: + from history_scopes import put + put(db,room_id,history) + + +def enforce_external_owner(uid,media): + from room_access_scope import current + rid=current(uid) + from library_index import get_media_source + import time + with open_database() as db: + user=db.execute('SELECT status,is_platform_admin FROM users WHERE id=?',(uid,)).fetchone() + if not user or user['status']!='active': raise AccountError(403,'External link owner inactive') + if not user['is_platform_admin'] and not db.execute("SELECT 1 FROM groups g JOIN group_memberships m ON m.group_id=g.id WHERE m.user_id=? AND g.status='active' AND g.media_enabled=1 AND g.subscription_status IN ('active','trial','free') AND (g.expires_at IS NULL OR g.expires_at>?) AND (? IS NULL OR g.id=(SELECT group_id FROM managed_rooms WHERE id=?))",(uid,int(time.time()),rid,rid)).fetchone(): + raise AccountError(403,'External link owner lacks media access') + enforce_source(uid,get_media_source(media.get('source_id'))) + + +def apply_template(token,data): + require_admin(token) + rid=data.get('room_id') + if type(rid) is not int: raise AccountError(400,'Invalid room') + with open_database() as db: + init(db) + db.execute('BEGIN IMMEDIATE') + if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') + db.execute('DELETE FROM room_template_policy WHERE room_id=?',(rid,)) + copy_template(db,rid,data.get('template_id')) + return {'ok':True} + +DEFAULT_BRAND={'name':'','login_title':'Welcome','login_subtitle':'Sign in to your private hangout','powered_by':False,'allow_owner_rename':True} +def appearance(room_id=None): + with open_database() as db: + init(db) + row=db.execute('SELECT settings FROM instance_appearance WHERE id=1').fetchone() + result={**DEFAULT_BRAND,**(json.loads(row['settings']) if row else {})} + if room_id is not None: + room=db.execute('SELECT settings FROM room_appearance WHERE room_id=?',(room_id,)).fetchone() + result['room']=json.loads(room['settings']) if room else {} + return result + +def save_appearance(token,data): + require_admin(token) + result={} + for key in ('name','login_title','login_subtitle'): + value=data.get(key,DEFAULT_BRAND[key]) + if not isinstance(value,str) or len(value)>120 or any(ord(c)<32 for c in value): raise AccountError(400,'Invalid branding text') + result[key]=value.strip() + result.update(powered_by=data.get('powered_by') is True,allow_owner_rename=data.get('allow_owner_rename') is True) + with open_database() as db: + init(db) + db.execute('INSERT INTO instance_appearance VALUES(1,?) ON CONFLICT(id) DO UPDATE SET settings=excluded.settings',(json.dumps(result),)) + return {'ok':True} + +def save_room_appearance(token,data): + require_admin(token) + rid=data.get('room_id');accent=data.get('accent','');icon=data.get('icon','') + if type(rid) is not int or not isinstance(accent,str) or (accent and not re.fullmatch(r'#[0-9a-fA-F]{6}',accent)) or not isinstance(icon,str) or len(icon)>12 or any(ord(c)<32 for c in icon): raise AccountError(400,'Invalid room appearance') + with open_database() as db: + init(db) + if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') + db.execute('INSERT INTO room_appearance VALUES(?,?) ON CONFLICT(room_id) DO UPDATE SET settings=excluded.settings',(rid,json.dumps({'accent':accent,'icon':icon}))) + return {'ok':True} diff --git a/history_scopes.py b/history_scopes.py new file mode 100644 index 0000000..80180c9 --- /dev/null +++ b/history_scopes.py @@ -0,0 +1,106 @@ +"""Room-aware history. Scope is derived on the server, never supplied as a storage key.""" +import json +from contextlib import contextmanager +from media_accounts import open_database, require_admin, assigned_rooms, session_user, AccountError +from datetime import datetime +import library_index as li + +KINDS=('tube','movies','tv') +MODES=('shared','group','room','user','off') +DEFAULT={k:'shared' for k in KINDS} + +def validate(data): + if not isinstance(data,dict) or any(k not in KINDS or v not in MODES for k,v in data.items()): + raise AccountError(400,'Invalid history settings') + return {**DEFAULT,**data} + +def init(db): + db.execute('CREATE TABLE IF NOT EXISTS room_history_settings (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, settings TEXT NOT NULL)') + +def settings(db,rid): + init(db) + row=db.execute('SELECT settings FROM room_history_settings WHERE room_id=?',(rid,)).fetchone() + return {**DEFAULT,**(json.loads(row[0]) if row else {})} + +def put(db,rid,data): + init(db) + db.execute('INSERT INTO room_history_settings VALUES(?,?) ON CONFLICT(room_id) DO UPDATE SET settings=excluded.settings',(rid,json.dumps(validate(data)))) + +def admin_get(token,rid): + require_admin(token) + with open_database() as db: + if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') + return settings(db,rid) + +def admin_save(token,data): + require_admin(token) + rid=data.get('room_id') + if type(rid) is not int: raise AccountError(400,'Invalid room') + with open_database() as db: + if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found') + put(db,rid,data.get('history')) + return {'ok':True} + +def resolve(token,room_header,kind): + user=session_user(token) + if not room_header or not str(room_header).isdigit(): raise AccountError(400,'Select a room and refresh the page to use media history') + rid=int(room_header) + if rid not in {r['id'] for r in assigned_rooms(token)}: raise AccountError(403,'Room history access denied') + with open_database() as db: + mode=settings(db,rid)[kind] + if mode=='shared': return 'shared' + if mode=='off': return None + if mode=='room': return f'room:{rid}' + if mode=='user': return f'user:{user["id"]}' + group=db.execute('SELECT group_id FROM managed_rooms WHERE id=?',(rid,)).fetchone() + if not group: raise AccountError(403,'Room history unavailable') + return f'group:{group[0]}' + +@contextmanager +def connect(): + db=li.get_db() + db.execute('CREATE TABLE IF NOT EXISTS scoped_progress (scope TEXT NOT NULL, kind TEXT NOT NULL, item TEXT NOT NULL, position_seconds REAL NOT NULL, duration_seconds REAL, completed INTEGER NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(scope,kind,item))') + db.execute('CREATE TABLE IF NOT EXISTS scoped_tube_history (scope TEXT NOT NULL, video_id TEXT NOT NULL, title TEXT NOT NULL, channel_name TEXT, thumbnail_url TEXT, duration_seconds REAL, first_played_at TEXT NOT NULL, last_played_at TEXT NOT NULL, watch_count INTEGER NOT NULL, PRIMARY KEY(scope,video_id))') + try: + with db: + yield db + finally: + db.close() + +def get_progress(scope,kind,item): + if scope=='shared': return li.get_youtube_playback_progress(item) if kind=='tube' else li.get_playback_progress(item) + result={'position_seconds':0.0,'duration_seconds':None,'completed':False,'updated_at':None} + if scope is None: return result + with connect() as db: + row=db.execute('SELECT position_seconds,duration_seconds,completed,updated_at FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item))).fetchone() + if row: result.update(dict(row));result['completed']=bool(result['completed']) + return result + +def save_progress(scope,kind,item,position,duration=None,completed=False): + if scope is None: return + if scope=='shared': + return (li.save_youtube_playback_progress if kind=='tube' else li.save_playback_progress)(item,position,duration,completed) + position=max(0.,float(position or 0));duration=max(0.,float(duration)) if duration not in (None,'') else None + with connect() as db: + db.execute('''INSERT INTO scoped_progress VALUES(?,?,?,?,?,?,?) ON CONFLICT(scope,kind,item) DO UPDATE SET position_seconds=excluded.position_seconds,duration_seconds=COALESCE(excluded.duration_seconds,scoped_progress.duration_seconds),completed=excluded.completed,updated_at=excluded.updated_at''',(scope,kind,str(item),position,duration,int(bool(completed)),datetime.now().isoformat())) + +def reset_progress(scope,kind,item): + if scope is None: return + if scope=='shared': return (li.reset_youtube_playback_progress if kind=='tube' else li.reset_playback_progress)(item) + with connect() as db: db.execute('DELETE FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item))) + +def record_watch(scope,video_id,title,channel_name=None,thumbnail_url=None,duration_seconds=None): + if scope is None: return + if scope=='shared': return li.record_youtube_watch(video_id,title,channel_name,thumbnail_url,duration_seconds) + try: duration=float(duration_seconds) if duration_seconds not in (None,'') else None + except (ValueError,TypeError): duration=None + now=datetime.now().isoformat() + with connect() as db: + db.execute('''INSERT INTO scoped_tube_history VALUES(?,?,?,?,?,?,?,?,1) ON CONFLICT(scope,video_id) DO UPDATE SET title=excluded.title,channel_name=COALESCE(excluded.channel_name,scoped_tube_history.channel_name),thumbnail_url=COALESCE(excluded.thumbnail_url,scoped_tube_history.thumbnail_url),duration_seconds=COALESCE(excluded.duration_seconds,scoped_tube_history.duration_seconds),last_played_at=excluded.last_played_at,watch_count=scoped_tube_history.watch_count+1''',(scope,video_id,title or video_id,channel_name,thumbnail_url,duration,now,now)) + +def history(scope,limit=50): + if scope is None: return [] + if scope=='shared': return li.get_youtube_history(limit) + with connect() as db: + rows=db.execute('''SELECT h.video_id,h.title,h.channel_name,h.thumbnail_url,COALESCE(p.duration_seconds,h.duration_seconds) duration_seconds,h.first_played_at,h.last_played_at,h.watch_count,COALESCE(p.position_seconds,0) position_seconds,COALESCE(p.completed,0) completed,c.video_id IS NOT NULL cached,c.size_bytes cache_size_bytes FROM scoped_tube_history h LEFT JOIN scoped_progress p ON p.scope=h.scope AND p.kind='tube' AND p.item=h.video_id LEFT JOIN youtube_video_cache c ON c.video_id=h.video_id WHERE h.scope=? ORDER BY h.last_played_at DESC LIMIT ?''',(scope,max(1,min(int(limit),500)))).fetchall() + return [{**dict(r),'completed':bool(r['completed']),'cached':bool(r['cached'])} for r in rows] diff --git a/media_accounts.py b/media_accounts.py new file mode 100644 index 0000000..52cc281 --- /dev/null +++ b/media_accounts.py @@ -0,0 +1,866 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import re +import secrets +import sqlite3 +import time +from pathlib import Path +from typing import Any + +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError +from dotenv import load_dotenv + +BASE_DIR = Path(__file__).resolve().parent +load_dotenv(BASE_DIR / "config.env") + +SESSION_COOKIE = "kronick_media_session" +SESSION_TTL_SECONDS = int(os.getenv("KRONICK_SESSION_TTL_HOURS", "168")) * 3600 +COOKIE_SECURE = os.getenv("KRONICK_COOKIE_SECURE", "false").strip().lower() in { + "1", "true", "yes", "on" +} +SESSION_SECRET = os.getenv( + "KRONICK_SESSION_SECRET", + "change-this-media-server-session-secret", +).encode("utf-8") + +PASSWORD_MIN_LENGTH = 8 +USERNAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{2,31}$") +SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{2,47}$") + +ROLE_PERMISSIONS = { + "owner": {"view_media", "play_media", "manage_media", "manage_members", "manage_group"}, + "admin": {"view_media", "play_media", "manage_media", "manage_members"}, + "moderator": {"view_media", "play_media", "manage_media"}, + "member": {"view_media", "play_media"}, +} + +DATABASE_PATH = Path( + os.getenv( + "KRONICK_ACCOUNT_DB", + str(BASE_DIR / "kronick_accounts.sqlite3"), + ) +).expanduser().resolve() + +password_hasher = PasswordHasher() + + +class AccountError(Exception): + def __init__(self, status: int, detail: str): + super().__init__(detail) + self.status = int(status) + self.detail = str(detail) + + +def configure_accounts(database_path: str | Path | None = None) -> None: + global DATABASE_PATH + if database_path: + DATABASE_PATH = Path(database_path).expanduser().resolve() + + +def open_database() -> sqlite3.Connection: + DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True) + db = sqlite3.connect(DATABASE_PATH, timeout=15) + db.row_factory = sqlite3.Row + db.execute("PRAGMA foreign_keys = ON") + db.execute("PRAGMA busy_timeout = 15000") + return db + + +def _session_hash(token: str) -> str: + return hmac.new( + SESSION_SECRET, + token.encode("utf-8"), + hashlib.sha256, + ).hexdigest() + + +def public_user(row: sqlite3.Row | dict[str, Any]) -> dict[str, Any]: + return { + "id": row["id"], + "username": row["username"], + "email": row["email"], + "status": row["status"], + "isPlatformAdmin": bool(row["is_platform_admin"]), + "createdAt": row["created_at"], + "approvedAt": row["approved_at"], + "lastLoginAt": row["last_login_at"], + } + + +def initialize_account_database() -> None: + with open_database() as db: + db.execute("PRAGMA journal_mode = WAL") + db.executescript( + """ + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + email TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' + CHECK(status IN ('pending','active','disabled','banned','denied')), + is_platform_admin INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + approved_at INTEGER, + last_login_at INTEGER + ); + + CREATE TABLE IF NOT EXISTS user_sessions ( + token_hash TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions(user_id); + CREATE INDEX IF NOT EXISTS idx_user_sessions_expiry ON user_sessions(expires_at); + + CREATE TABLE IF NOT EXISTS groups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + slug TEXT NOT NULL UNIQUE COLLATE NOCASE, + status TEXT NOT NULL DEFAULT 'active', + owner_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + max_users INTEGER NOT NULL DEFAULT 10, + max_rooms INTEGER NOT NULL DEFAULT 10, + storage_limit_mb INTEGER NOT NULL DEFAULT 1024, + media_enabled INTEGER NOT NULL DEFAULT 1, + subscription_status TEXT NOT NULL DEFAULT 'active', + expires_at INTEGER, + custom_branding_json TEXT NOT NULL DEFAULT '{}', + custom_domain TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS group_memberships ( + group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role TEXT NOT NULL DEFAULT 'member' + CHECK(role IN ('owner','admin','moderator','member')), + created_at INTEGER NOT NULL, + PRIMARY KEY(group_id, user_id) + ); + CREATE INDEX IF NOT EXISTS idx_memberships_user ON group_memberships(user_id); + + CREATE TABLE IF NOT EXISTS managed_rooms ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + room_name TEXT NOT NULL UNIQUE COLLATE NOCASE, + display_name TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_managed_rooms_group ON managed_rooms(group_id); + CREATE TABLE IF NOT EXISTS role_permissions ( + role TEXT NOT NULL CHECK(role IN ('member','moderator','admin','owner')), + action TEXT NOT NULL CHECK(action IN ('media_access','user_permissions','room_permissions','password_resets','account_approvals')), + allowed INTEGER NOT NULL CHECK(allowed IN (0,1)), + PRIMARY KEY(role,action) + ); + + CREATE TABLE IF NOT EXISTS room_memberships ( + room_id INTEGER NOT NULL REFERENCES managed_rooms(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role TEXT NOT NULL DEFAULT 'member' + CHECK(role IN ('owner','admin','moderator','member')), + created_at INTEGER NOT NULL, + PRIMARY KEY(room_id,user_id) + ); + CREATE INDEX IF NOT EXISTS idx_room_memberships_user ON room_memberships(user_id); + """ + ) + now = int(time.time()) + db.execute("DELETE FROM user_sessions WHERE expires_at <= ?", (now,)) + db.commit() + + bootstrap_admin() + + +def bootstrap_admin() -> None: + username = os.getenv("KRONICK_ADMIN_USERNAME", "").strip() + email = os.getenv("KRONICK_ADMIN_EMAIL", "").strip().lower() + password = os.getenv("KRONICK_ADMIN_PASSWORD", "") + if not username or not email or not password: + return + if len(password) < PASSWORD_MIN_LENGTH: + raise RuntimeError("KRONICK_ADMIN_PASSWORD must be at least 8 characters") + + now = int(time.time()) + with open_database() as db: + row = db.execute( + "SELECT id FROM users WHERE username = ? OR email = ?", + (username, email), + ).fetchone() + if row: + db.execute( + "UPDATE users SET status='active', is_platform_admin=1 WHERE id=?", + (row["id"],), + ) + else: + db.execute( + """INSERT INTO users + (username,email,password_hash,status,is_platform_admin,created_at,approved_at) + VALUES (?,?,?,?,?,?,?)""", + (username, email, password_hasher.hash(password), "active", 1, now, now), + ) + db.commit() + + +def signup_account(data: dict[str, Any]) -> dict[str, Any]: + username = str(data.get("username") or "").strip() + email = str(data.get("email") or "").strip().lower() + password = str(data.get("password") or "") + + if "@" not in email or len(email) > 254: + raise AccountError(400, "Enter a valid email address.") + if not USERNAME_RE.fullmatch(username): + raise AccountError( + 400, + "Username must be 3-32 characters and use letters, numbers, dot, dash, or underscore.", + ) + if len(password) < PASSWORD_MIN_LENGTH: + raise AccountError(400, "Password must be at least 8 characters.") + + now = int(time.time()) + try: + with open_database() as db: + db.execute( + """INSERT INTO users(username,email,password_hash,status,created_at) + VALUES (?,?,?,?,?)""", + (username, email, password_hasher.hash(password), "pending", now), + ) + db.commit() + except sqlite3.IntegrityError as exc: + raise AccountError(409, "That username or email is already registered.") from exc + + return { + "ok": True, + "status": "pending", + "message": "Account request submitted for administrator approval.", + } + + +def login_account(data: dict[str, Any]) -> tuple[dict[str, Any], str]: + login_value = str(data.get("login") or "").strip() + password = str(data.get("password") or "") + + with open_database() as db: + user = db.execute( + "SELECT * FROM users WHERE username=? OR email=?", + (login_value, login_value), + ).fetchone() + + if not user: + raise AccountError(401, "Incorrect username/email or password.") + + try: + valid = password_hasher.verify(user["password_hash"], password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + valid = False + + if not valid: + raise AccountError(401, "Incorrect username/email or password.") + + if user["status"] != "active": + messages = { + "pending": "Your account is waiting for administrator approval.", + "disabled": "Your account is disabled.", + "banned": "Your account is banned.", + "denied": "Your account request was denied.", + } + raise AccountError(403, messages.get(user["status"], "Your account is not active.")) + + if 'must_change_password' in user.keys() and user['must_change_password']: + raise AccountError(403,'Password change required. Sign in through Kronic Chat to set your new password.') + + token = secrets.token_urlsafe(48) + token_hash = _session_hash(token) + now = int(time.time()) + + with open_database() as db: + db.execute( + "INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) VALUES (?,?,?,?,?)", + (token_hash, user["id"], now, now + SESSION_TTL_SECONDS, now), + ) + db.execute("UPDATE users SET last_login_at=? WHERE id=?", (now, user["id"])) + db.commit() + + refreshed = session_user(token) + return {"ok": True, "user": public_user(refreshed)}, token + + +def logout_account(token: str | None) -> None: + if not token: + return + with open_database() as db: + db.execute("DELETE FROM user_sessions WHERE token_hash=?", (_session_hash(token),)) + db.commit() + + +def session_user(token: str | None, *, require_active: bool = True) -> sqlite3.Row: + if not token: + raise AccountError(401, "Login required.") + + now = int(time.time()) + token_hash = _session_hash(token) + with open_database() as db: + row = db.execute( + """SELECT u.* FROM user_sessions s + JOIN users u ON u.id=s.user_id + WHERE s.token_hash=? AND s.expires_at>?""", + (token_hash, now), + ).fetchone() + if not row: + raise AccountError(401, "Session expired. Please log in again.") + if require_active and row["status"] != "active": + raise AccountError(403, f"Account is {row['status']}.") + db.execute("UPDATE user_sessions SET last_seen_at=? WHERE token_hash=?", (now, token_hash)) + db.commit() + return row + + +def media_context(token: str | None) -> dict[str, Any]: + user = session_user(token) + now = int(time.time()) + from room_access_scope import current + room_id = current(user["id"]) + + with open_database() as db: + groups = db.execute( + """SELECT g.*, gm.role + FROM groups g + JOIN group_memberships gm ON gm.group_id=g.id + WHERE gm.user_id=? + AND g.status='active' + AND g.media_enabled=1 + AND g.subscription_status IN ('active','trial','free') + AND (g.expires_at IS NULL OR g.expires_at > ?) + AND (? IS NULL OR g.id=(SELECT group_id FROM managed_rooms WHERE id=?)) + ORDER BY g.name""", + (user["id"], now, room_id, room_id), + ).fetchall() + + permissions: set[str] = set() + if user["is_platform_admin"]: + permissions.update({ + "view_media", "play_media", "manage_media", + "manage_members", "manage_group", "platform_admin", + }) + else: + for group in groups: + permissions.update(ROLE_PERMISSIONS.get(group["role"], {"view_media", "play_media"})) + + has_media_access = bool(user["is_platform_admin"] or groups) + allowed = allowed_media_libraries(int(user['id'])) if has_media_access else {key:False for key in MEDIA_KEYS} + can_manage = 'manage_media' in permissions and not global_media_restricted(int(user['id'])) + + return { + "user": public_user(user), + "groups": [dict(row) for row in groups], + "permissions": sorted(permissions), + "hasMediaAccess": has_media_access, + "allowedLibraries": allowed, + "canManageMedia": can_manage, + "selectedRoomId": room_id, + "isPlatformAdmin": bool(user["is_platform_admin"]), + } + + +MEDIA_KEYS = ('movies','tv','music','iptv','tube','twitch') + + +def allowed_media_libraries(user_id: int) -> dict[str,bool]: + # Scoped requests only consider the selected room. Legacy internal calls remain conservative. + from room_access_scope import current + room_id=current(user_id) + from admin_policies import policies + rules=policies(user_id) + result={key:all(key in r['types'] for r in rules) for key in MEDIA_KEYS} + with open_database() as db: + user=db.execute("SELECT is_platform_admin FROM users WHERE id=?",(user_id,)).fetchone() + if user and user["is_platform_admin"]: + return {key:True for key in MEDIA_KEYS} + if not db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='room_media_permissions'").fetchone(): + return result + rows=db.execute('''SELECT library_key,enabled FROM room_media_permissions p + JOIN room_memberships rm ON rm.user_id=p.user_id AND rm.room_id=p.room_id + WHERE p.user_id=? AND (? IS NULL OR p.room_id=?)''',(user_id,room_id,room_id)).fetchall() + for row in rows: + if row['library_key'] in result and not row['enabled']: + result[row['library_key']]=False + return result + + +def enforce_media_library(user_id:int,key:str)->None: + if key in MEDIA_KEYS and not allowed_media_libraries(user_id)[key]: + raise AccountError(403,f'Access to {key} is disabled by your room administrator.') + + +def require_media_access(token: str | None) -> dict[str, Any]: + context = media_context(token) + if not context["hasMediaAccess"]: + raise AccountError( + 403, + "Your account is active but is not assigned to a media-enabled group.", + ) + return context + + +def global_media_restricted(user_id: int) -> bool: + """Unscoped tools can alter shared state, so preserve their conservative gate.""" + from admin_policies import policies + from room_access_scope import clear, restore + scope=clear() + try: + return bool(policies(user_id)) or not all(allowed_media_libraries(user_id).values()) + finally: restore(scope) + + +def require_manage_media(token: str | None) -> dict[str, Any]: + context = require_media_access(token) + if not context["canManageMedia"] or not all(context["allowedLibraries"].values()): + raise AccountError(403, "Media management permission required.") + return context + + +def require_admin(token: str | None) -> sqlite3.Row: + user = session_user(token) + if not user["is_platform_admin"]: + raise AccountError(403, "Platform administrator access required.") + return user + + +# These role rules apply to chat-room administration, NOT the right to play media. +# The platform-admin account has an unconditional instance-level override. +ROOM_PERMISSION_ACTIONS = ('media_access', 'user_permissions', 'room_permissions', 'password_resets', 'account_approvals') +ROOM_PERMISSION_ROLES = ('member', 'moderator', 'admin', 'owner') +DEFAULT_ROOM_ROLE_POLICY = { + 'member': (False, False, False, False, False), + 'moderator': (False, False, False, False, False), + 'admin': (True, True, True, True, True), + 'owner': (True, True, True, True, True), +} + + +def admin_get_role_permissions(token: str | None) -> dict[str, Any]: + require_admin(token) + with open_database() as db: + rows = db.execute('SELECT role,action,allowed FROM role_permissions').fetchall() + policy = {role: dict(zip(ROOM_PERMISSION_ACTIONS, defaults)) + for role, defaults in DEFAULT_ROOM_ROLE_POLICY.items()} + for row in rows: + if row['role'] in policy and row['action'] in ROOM_PERMISSION_ACTIONS: + policy[row['role']][row['action']] = bool(row['allowed']) + return {'roles': policy, 'actions': list(ROOM_PERMISSION_ACTIONS)} + + +def admin_set_role_permissions(token: str | None, payload: dict[str, Any]) -> dict[str, Any]: + require_admin(token) + values = payload.get('roles') + if not isinstance(values, dict) or set(values) != set(ROOM_PERMISSION_ROLES): + raise AccountError(400, 'All room roles must be provided.') + items = [] + for role in ROOM_PERMISSION_ROLES: + options = values[role] + if not isinstance(options, dict) or set(options) != set(ROOM_PERMISSION_ACTIONS): + raise AccountError(400, f'Invalid actions for {role}.') + for action, allowed in options.items(): + if type(allowed) is not bool: + raise AccountError(400, 'Permission values must be true or false.') + items.append((role, action, int(allowed))) + # Prevent any admin-panel misconfiguration from removing all room policy authority. + if not all(values['owner'].values()): + raise AccountError(400, 'Room owners must retain every management capability.') + with open_database() as db: + db.execute('BEGIN IMMEDIATE') + db.executemany('''INSERT INTO role_permissions(role,action,allowed) VALUES (?,?,?) + ON CONFLICT(role,action) DO UPDATE SET allowed=excluded.allowed''', items) + db.commit() + return admin_get_role_permissions(token) + + +def admin_overview(token: str | None) -> dict[str, Any]: + require_admin(token) + with open_database() as db: + users = db.execute("SELECT * FROM users ORDER BY created_at DESC").fetchall() + groups = db.execute( + """SELECT g.*, + (SELECT COUNT(*) FROM group_memberships gm WHERE gm.group_id=g.id) AS user_count, + (SELECT COUNT(*) FROM managed_rooms mr WHERE mr.group_id=g.id) AS room_count + FROM groups g ORDER BY g.name""" + ).fetchall() + memberships = db.execute( + """SELECT gm.group_id,gm.user_id,gm.role,u.username,u.email,g.name AS group_name + FROM group_memberships gm + JOIN users u ON u.id=gm.user_id + JOIN groups g ON g.id=gm.group_id + ORDER BY g.name,u.username""" + ).fetchall() + + rooms = db.execute("""SELECT mr.*,g.name AS group_name FROM managed_rooms mr + JOIN groups g ON g.id=mr.group_id ORDER BY mr.room_name""").fetchall() + return { + "rooms": [dict(row) for row in rooms], + "users": [public_user(row) for row in users], + "groups": [dict(row) for row in groups], + "memberships": [dict(row) for row in memberships], + "roles": {key: sorted(value) for key, value in ROLE_PERMISSIONS.items()}, + } + + + +def admin_room_memberships(token: str | None) -> dict[str, Any]: + require_admin(token) + with open_database() as db: + rows = db.execute("""SELECT rm.room_id,rm.user_id,rm.role,u.username, + u.is_platform_admin,mr.room_name,mr.display_name,g.name AS group_name + FROM room_memberships rm JOIN users u ON u.id=rm.user_id + JOIN managed_rooms mr ON mr.id=rm.room_id + JOIN groups g ON g.id=mr.group_id ORDER BY mr.room_name,u.username""").fetchall() + return {"memberships": [dict(row) for row in rows]} + + +def admin_assign_room_member(token: str | None, room_id: int, payload: dict) -> dict[str, bool]: + require_admin(token) + try: + user_id = int(payload.get('user_id')) + except (TypeError,ValueError): + raise AccountError(400,'Invalid user ID') + role = str(payload.get('role','')).strip().lower() + if role not in ('member','moderator','admin','owner'): + raise AccountError(400,'Invalid room role') + with open_database() as db: + db.execute('BEGIN IMMEDIATE') + room = db.execute('SELECT id,group_id FROM managed_rooms WHERE id=?',(room_id,)).fetchone() + user = db.execute('SELECT status FROM users WHERE id=?',(user_id,)).fetchone() + if not room: + raise AccountError(404,'Room not found') + if not user or user['status']!='active': + raise AccountError(400,'An active user is required') + member = db.execute('SELECT 1 FROM group_memberships WHERE group_id=? AND user_id=?', + (room['group_id'],user_id)).fetchone() + if not member: + group = db.execute('SELECT max_users FROM groups WHERE id=?',(room['group_id'],)).fetchone() + count = db.execute('SELECT COUNT(*) FROM group_memberships WHERE group_id=?', + (room['group_id'],)).fetchone()[0] + if count >= group['max_users']: + raise AccountError(409,'Parent group is full') + db.execute('INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES(?,?,?,?)', + (room['group_id'],user_id,'member',int(time.time()))) + # An owner can hand ownership to another member, but may not leave a room ownerless. + existing = db.execute('SELECT role FROM room_memberships WHERE room_id=? AND user_id=?', + (room_id,user_id)).fetchone() + if existing and existing['role'] == 'owner' and role != 'owner': + owners = db.execute("SELECT COUNT(*) FROM room_memberships WHERE room_id=? AND role='owner'", + (room_id,)).fetchone()[0] + if owners <= 1: + raise AccountError(409, 'Assign another room owner before demoting the last owner.') + db.execute("""INSERT INTO room_memberships(room_id,user_id,role,created_at) + VALUES(?,?,?,?) ON CONFLICT(room_id,user_id) DO UPDATE SET role=excluded.role""", + (room_id,user_id,role,int(time.time()))) + db.commit() + return {'ok':True} + + +def admin_remove_room_member(token: str | None, room_id: int, user_id: int) -> dict[str, bool]: + require_admin(token) + with open_database() as db: + db.execute('BEGIN IMMEDIATE') + old_role = db.execute('SELECT role FROM room_memberships WHERE room_id=? AND user_id=?', + (room_id,user_id)).fetchone() + if old_role and old_role['role'] == 'owner': + owners = db.execute("SELECT COUNT(*) FROM room_memberships WHERE room_id=? AND role='owner'", + (room_id,)).fetchone()[0] + if owners <= 1: + raise AccountError(409, 'Assign another room owner before removing the last owner.') + cur = db.execute('DELETE FROM room_memberships WHERE room_id=? AND user_id=?', + (room_id,user_id)) + if not cur.rowcount: + raise AccountError(404,'Room membership not found') + db.commit() + return {'ok':True} + +def admin_set_user_status(token: str | None, user_id: int, status: str) -> dict[str, Any]: + admin = require_admin(token) + status = str(status or "").strip().lower() + if status not in {"pending", "active", "disabled", "banned", "denied"}: + raise AccountError(400, "Invalid account status.") + if admin["id"] == user_id and status != "active": + raise AccountError(400, "You cannot disable your own administrator account.") + + now = int(time.time()) + with open_database() as db: + result = db.execute( + "UPDATE users SET status=?, approved_at=CASE WHEN ?='active' THEN COALESCE(approved_at,?) ELSE approved_at END WHERE id=?", + (status, status, now, user_id), + ) + if result.rowcount == 0: + raise AccountError(404, "User not found.") + if status != "active": + db.execute("DELETE FROM user_sessions WHERE user_id=?", (user_id,)) + db.commit() + return {"ok": True, "status": status} + + + +def admin_delete_user(token: str | None, user_id: int) -> dict[str, Any]: + """Permanently delete a non-platform-admin account and dependent account rows.""" + actor = require_admin(token) + if actor["id"] == user_id: + raise AccountError(400, "You cannot delete your own account.") + with open_database() as db: + db.execute("BEGIN IMMEDIATE") + target = db.execute("SELECT id,username,is_platform_admin FROM users WHERE id=?", (user_id,)).fetchone() + if target is None: + raise AccountError(404, "Account not found.") + if target["is_platform_admin"]: + raise AccountError(403, "Platform administrator accounts cannot be deleted from this interface.") + # Database FK cascades remove sessions, memberships, room requests, + # invitation redemptions, and password reset state. References in + # authored/owned objects are ON DELETE SET NULL. + db.execute("DELETE FROM users WHERE id=?", (user_id,)) + db.commit() + return {"ok": True, "deletedUserId": user_id} + +def admin_create_group(token: str | None, data: dict[str, Any]) -> dict[str, Any]: + admin = require_admin(token) + name = str(data.get("name") or "").strip() + slug = str(data.get("slug") or "").strip().lower() + max_users = max(1, min(int(data.get("max_users") or 10), 10000)) + media_enabled = bool(data.get("media_enabled", True)) + + if not name: + raise AccountError(400, "Group name is required.") + if not SLUG_RE.fullmatch(slug): + raise AccountError(400, "Group slug must be 3-48 lowercase letters/numbers/dash/underscore.") + + now = int(time.time()) + try: + with open_database() as db: + cursor = db.execute( + """INSERT INTO groups + (name,slug,status,owner_user_id,max_users,max_rooms,storage_limit_mb,media_enabled,subscription_status,custom_domain,created_at) + VALUES (?,?,?,?,?,?,?,?,?,?,?)""", + (name, slug, "active", admin["id"], max_users, 1, 1024, int(media_enabled), "active", "", now), + ) + group_id = cursor.lastrowid + db.execute( + "INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES (?,?,?,?)", + (group_id, admin["id"], "owner", now), + ) + db.commit() + except sqlite3.IntegrityError as exc: + raise AccountError(409, "That group slug already exists.") from exc + + return {"ok": True, "groupId": group_id} + + +def admin_create_managed_room(token: str | None, group_id: int, data: dict[str, Any]) -> dict[str, Any]: + """Explicitly create a chat room within an existing media group. + + Room creation is separate from group creation; avoid creating implicit + rooms or approving accounts as a side effect. + """ + admin = require_admin(token) + room_name = str(data.get("room_name") or "").strip().lower() + display_name = str(data.get("display_name") or "").strip() or room_name + if not SLUG_RE.fullmatch(room_name): + raise AccountError(400, "Room name must be 3-48 lowercase letters, digits, hyphens or underscores.") + if len(display_name) > 100: + raise AccountError(400, "Display name is too long.") + now = int(time.time()) + try: + with open_database() as db: + group = db.execute("SELECT id,max_rooms,status FROM groups WHERE id=?", (group_id,)).fetchone() + if group is None or group["status"] != "active": + raise AccountError(404, "Active group not found.") + used = db.execute("SELECT COUNT(*) FROM managed_rooms WHERE group_id=?", (group_id,)).fetchone()[0] + if used >= group["max_rooms"]: + raise AccountError(409, "This group has reached its room limit.") + cursor = db.execute( + """INSERT INTO managed_rooms(group_id,room_name,display_name,enabled,created_by_user_id,created_at) + VALUES (?,?,?,?,?,?)""", + (group_id, room_name, display_name, 1, admin["id"], now), + ) + room_id = cursor.lastrowid + from admin_policies import copy_template + copy_template(db,room_id,data.get("template_id")) + db.execute( + """INSERT INTO room_memberships(room_id,user_id,role,created_at) + SELECT ?,user_id,role,? FROM group_memberships WHERE group_id=?""", + (room_id,now,group_id), + ) + db.commit() + except sqlite3.IntegrityError as exc: + raise AccountError(409, "That room name already exists.") from exc + return {"ok": True, "roomId": room_id, "room": room_name} + + +def admin_toggle_group_media(token: str | None, group_id: int, enabled: bool) -> dict[str, Any]: + require_admin(token) + with open_database() as db: + result = db.execute( + "UPDATE groups SET media_enabled=? WHERE id=?", + (int(bool(enabled)), group_id), + ) + if result.rowcount == 0: + raise AccountError(404, "Group not found.") + db.commit() + return {"ok": True, "media_enabled": bool(enabled)} + + +def admin_assign_member(token: str | None, group_id: int, data: dict[str, Any]) -> dict[str, Any]: + require_admin(token) + user_id = int(data.get("user_id")) + role = str(data.get("role") or "member").strip().lower() + if role not in ROLE_PERMISSIONS: + raise AccountError(400, "Invalid role.") + + now = int(time.time()) + with open_database() as db: + group = db.execute("SELECT max_users FROM groups WHERE id=?", (group_id,)).fetchone() + user = db.execute("SELECT status FROM users WHERE id=?", (user_id,)).fetchone() + if not group: + raise AccountError(404, "Group not found.") + if not user: + raise AccountError(404, "User not found.") + if user["status"] != "active": + raise AccountError(400, "Only active users can be assigned to groups.") + existing = db.execute( + "SELECT 1 FROM group_memberships WHERE group_id=? AND user_id=?", + (group_id, user_id), + ).fetchone() + count = db.execute( + "SELECT COUNT(*) AS n FROM group_memberships WHERE group_id=?", + (group_id,), + ).fetchone()["n"] + if not existing and count >= group["max_users"]: + raise AccountError(409, "This group has reached its user limit.") + + db.execute( + """INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES (?,?,?,?) + ON CONFLICT(group_id,user_id) DO UPDATE SET role=excluded.role""", + (group_id, user_id, role, now), + ) + db.commit() + return {"ok": True} + + +def admin_remove_member(token: str | None, group_id: int, user_id: int) -> dict[str, Any]: + require_admin(token) + with open_database() as db: + db.execute( + "DELETE FROM group_memberships WHERE group_id=? AND user_id=?", + (group_id, user_id), + ) + db.commit() + return {"ok": True} + + +def create_sso_session(identity: dict[str, Any]) -> str: + """Create a short-lived Media session after Chat's server validates its cookie. + + Matching local accounts are preserved. Chat groups become non-privileged + Media groups with isolated 'sso-' slugs to avoid overriding existing ACLs. + """ + user = identity.get("user") or {} + username = str(user.get("username") or "") + email = str(user.get("email") or "").lower() + if (not USERNAME_RE.fullmatch(username) or "@" not in email or + user.get("status") != "active"): + raise AccountError(403, "Invalid or inactive Chat account") + groups = identity.get("mediaGroups") or [] + if not groups and not bool(user.get("isPlatformAdmin")): + raise AccountError(403, "No media-enabled Chat group assigned") + now = int(time.time()) + token = secrets.token_urlsafe(48) + with open_database() as db: + row = db.execute("SELECT * FROM users WHERE username=? OR email=?", (username, email)).fetchone() + if row and (row["username"].lower() != username.lower() or + row["email"].lower() != email): + raise AccountError(409, "Media account identity conflict; contact the administrator") + sso_marker = f"!sso-managed:{user.get('id')}" + if row and row["password_hash"] != sso_marker: + raise AccountError(409, "Existing Media account needs explicit SSO migration") + if row and row["status"] != "active": + raise AccountError(403, "Media account is disabled or pending") + if row: + user_id = row["id"] + else: + db.execute( + """INSERT INTO users(username,email,password_hash,status,created_at,approved_at) + VALUES (?,?,?,?,?,?)""", + (username, email, sso_marker, + "active", now, now), + ) + user_id = db.execute("SELECT last_insert_rowid()").fetchone()[0] + # Rebuild only SSO-controlled memberships, not local media permissions. + db.execute( + """DELETE FROM group_memberships WHERE user_id=? AND group_id IN + (SELECT id FROM groups WHERE slug LIKE 'sso-chat-%')""", (user_id,) + ) + for group in groups: + try: + remote_id = int(group["id"]) + except (TypeError, ValueError, KeyError): + continue + if remote_id <= 0: + continue + slug = f"sso-chat-{remote_id}" + name = "Chat: " + str(group.get("name") or slug)[:100] + db.execute( + """INSERT OR IGNORE INTO groups(name,slug,status,media_enabled, + subscription_status,created_at) VALUES (?,?,'active',1,'active',?)""", + (name, slug, now), + ) + media_group_id = db.execute("SELECT id FROM groups WHERE slug=?", (slug,)).fetchone()[0] + db.execute( + """INSERT OR IGNORE INTO group_memberships + (group_id,user_id,role,created_at) VALUES (?,?,'member',?)""", + (media_group_id, user_id, now), + ) + db.execute( + """INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) + VALUES (?,?,?,?,?)""", + (_session_hash(token), user_id, now, now + 3600, now), + ) + db.commit() + return token + + +# Room selection is based on explicit active room memberships, not group roles. +def assigned_rooms(token): + user = session_user(token) + with open_database() as db: + rows = db.execute("""SELECT mr.id,mr.room_name,mr.display_name,rm.role + FROM managed_rooms mr JOIN groups g ON g.id=mr.group_id + JOIN room_memberships rm ON rm.room_id=mr.id + WHERE rm.user_id=? AND mr.enabled=1 AND g.status='active' + ORDER BY mr.display_name COLLATE NOCASE,mr.room_name""", (user['id'],)).fetchall() + return [dict(row) for row in rows] + + +def rename_room_display(token, room_id, data, *, instance_only=False): + user = session_user(token) + from admin_policies import appearance + if not user['is_platform_admin'] and not appearance()['allow_owner_rename']: + raise AccountError(403,'Room title customization disabled by instance administrator') + title = data.get('display_name') + if not isinstance(title, str) or not title.strip() or len(title.strip()) > 100 or any(ord(c)<32 for c in title): + raise AccountError(400, 'Enter a display title of 1–100 characters.') + with open_database() as db: + db.execute('BEGIN IMMEDIATE') + room = db.execute("""SELECT mr.id,rm.role FROM managed_rooms mr + JOIN groups g ON g.id=mr.group_id + LEFT JOIN room_memberships rm ON rm.room_id=mr.id AND rm.user_id=? + WHERE mr.id=? AND mr.enabled=1 AND g.status='active'""",(user['id'],room_id)).fetchone() + if not room or not (user['is_platform_admin'] or (not instance_only and room['role']=='owner')): + raise AccountError(403, 'Room owner or instance administrator required.') + db.execute('UPDATE managed_rooms SET display_name=? WHERE id=?',(title.strip(),room_id)) + db.commit() + return {'ok':True,'display_name':title.strip()} diff --git a/room_access_scope.py b/room_access_scope.py new file mode 100644 index 0000000..50f0d0d --- /dev/null +++ b/room_access_scope.py @@ -0,0 +1,62 @@ +"""Request-local, verified room identity; never use a global last-room cookie.""" +from contextvars import ContextVar +from functools import wraps +from urllib.parse import urlsplit, parse_qs + +_current = ContextVar('kronic_room_access', default=None) + +def current(uid): + scope = _current.get() + return scope[1] if scope and scope[0] == int(uid) else None + +def clear(): + return _current.set(None) + +def restore(token): + _current.reset(token) + +def bind(uid, room_id): + from media_accounts import open_database, AccountError + with open_database() as db: + row = db.execute('''SELECT r.id FROM managed_rooms r JOIN groups g ON g.id=r.group_id + JOIN room_memberships m ON m.room_id=r.id + WHERE r.id=? AND m.user_id=? AND r.enabled=1 AND g.status='active' ''', (room_id,uid)).fetchone() + if not row: raise AccountError(403,'Selected room is not assigned to this account') + _current.set((int(uid),int(row['id']))) + return int(row['id']) + +def bind_request(handler): + from media_accounts import session_user, assigned_rooms, AccountError + # A handler can call the same authorization guard more than once. + # The enclosing HTTP-method decorator resets this context for every request. + if _current.get() is not None: return _current.get()[1] + token=handler.get_session_token(); user=session_user(token); uid=int(user['id']) + rooms=assigned_rooms(token) + raw=handler.headers.get('X-Kronic-Room') + url_room=parse_qs(urlsplit(handler.path).query,keep_blank_values=True).get('kronic_room',[]) + if len(url_room)>1 or (url_room and raw is not None and raw!=url_room[0]): raise AccountError(400,'Conflicting room selectors') + if url_room: raw=url_room[0] + ref=urlsplit(handler.headers.get('Referer','')) + name=None + if ref.path in ('/','/app','/m','/m/','/desktop','/desktop/') and ref.netloc.lower()==(handler.headers.get('Host') or '').lower(): + name=parse_qs(ref.query).get('room',[None])[0] + if raw is not None: + if not raw.isascii() or not raw.isdigit() or len(raw)>19 or not 0=3 and parts[:2]==['api','sources']: + try: source_id=int(parts[2]) + except ValueError: raise AccountError(400,'Invalid library ID') + enforce_source(user_id,get_media_source(source_id)) + if path in ('/api/media','/api/search'): + sid = parse_qs(urlparse(self.path).query).get('source_id',[None])[0] + if sid is not None: + source=get_media_source(int(sid)) + enforce_source(user_id,source) + return + parts=path.strip('/').split('/') + if parts and parts[0] in ('play','stream','thumbnail','external') and len(parts)>=2: + raw=parts[1].removesuffix('.m3u') + try: media_id=int(raw) + except ValueError: raise AccountError(400,'Invalid media ID') + media=get_media_by_id(media_id) + if media: + source=get_media_source(media['source_id']) + enforce_source(user_id,source) + if len(parts)>=3 and parts[:2]==['api','media'] and parts[2]!='move': + try: media_id=int(parts[2]) + except ValueError: raise AccountError(400,'Invalid media ID') + media=get_media_by_id(media_id) + if media: + source=get_media_source(media['source_id']) + enforce_source(user_id,source) + + + def require_manage_session(self): + ras.bind_request(self) + return require_manage_media(self.get_session_token()) + + def require_admin_session(self): + return require_admin(self.get_session_token()) + + def api_auth_me(self): + user = session_user(self.get_session_token()) + return self.send_json({ + "user": { + "id": user["id"], + "username": user["username"], + "email": user["email"], + "status": user["status"], + "isPlatformAdmin": bool(user["is_platform_admin"]), + "createdAt": user["created_at"], + "approvedAt": user["approved_at"], + "lastLoginAt": user["last_login_at"], + } + }) + + def api_media_context(self): + ras.bind_request(self) + return self.send_json(media_context(self.get_session_token())) + + def api_auth_login(self): + payload, token = login_account(self.read_json()) + secure = "; Secure" if COOKIE_SECURE else "" + cookie = ( + f"{SESSION_COOKIE}={token}; Path=/; Max-Age={SESSION_TTL_SECONDS}; " + f"HttpOnly; SameSite=Lax{secure}" + ) + return self.send_json(payload, extra_headers={"Set-Cookie": cookie}) + + def api_auth_signup(self): + return self.send_json(signup_account(self.read_json())) + + def api_auth_logout(self): + logout_account(self.get_session_token()) + # Signing out of Media also ends the embedded Chat session. + borg_chat_gateway.logout_chat(self) + secure = "; Secure" if COOKIE_SECURE else "" + cookie = f"{SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax{secure}" + return self.send_json( + {"ok": True}, + extra_headers={"Set-Cookie": [cookie, borg_chat_gateway.expired_chat_cookie()]}, + ) + + def use_mobile_interface(self, path): + # Explicit URLs override the browser preference without changing it. + if path in {"/m", "/m/"}: + return True + if path in {"/desktop", "/desktop/"}: + return False + try: + cookies = SimpleCookie() + cookies.load(self.headers.get("Cookie", "")) + preference = cookies.get("kronic_interface") + mode = preference.value if preference else "auto" + except Exception: + mode = "auto" + if mode in {"desktop", "mobile"}: + return mode == "mobile" + ua = self.headers.get("User-Agent", "").lower() + return (self.headers.get("Sec-CH-UA-Mobile", "").strip() == "?1" + or any(marker in ua for marker in ( + "android", "iphone", "ipad", "ipod", "windows phone", + "mobile", "kindle", "silk/", "blackberry", "opera mini"))) + + def serve_room_picker(self, rooms, base): + from admin_policies import appearance + cards = ''.join('' + html_escape((appearance(r['id']).get('room',{}).get('icon','')+' '+(r['display_name'] or r['room_name'])).strip()) + '›' for r in rooms) + message = 'Select a room to continue.' if rooms else 'No rooms are assigned to your account. Contact your administrator.' + admin_link = 'Administration' if session_user(self.get_session_token())['is_platform_admin'] else '' + body = (HTML_DIR / 'rooms.html').read_text(encoding='utf-8').replace('@@ROOM_MESSAGE@@', message).replace('@@ADMIN_LINK@@', admin_link).replace('@@ROOM_CARDS@@', cards) + return self.send_room_html(body) + + def send_room_html(self, body): + data = body.encode('utf-8') + self.send_response(200) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.send_header('Cache-Control', 'private, no-store') + self.send_header('Vary', 'User-Agent, Sec-CH-UA-Mobile, Cookie') + self.send_header('Referrer-Policy', 'same-origin') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def serve_media_app(self, mobile=False): + try: + session_user(self.get_session_token()) + except AccountError as error: + if error.status == 401: + return self.send_redirect("/login") + body = ( + "" + "Account access" + "" + "

Account access unavailable

" + f"

{html_escape(error.detail)}

" + "

Contact your administrator.

" + "

Back to login

" + "" + ).encode("utf-8") + self.send_response(403) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + rooms = assigned_rooms(self.get_session_token()) + parsed = urlparse(self.path) + params = parse_qs(parsed.query) + base = parsed.path if parsed.path in ('/m','/m/','/desktop','/desktop/') else '/' + requested = params.get('room', [''])[0] + room = next((r for r in rooms if r['room_name'] == requested), None) + if not room: + if len(rooms) == 1 and not requested and 'choose' not in params: + return self.send_redirect(base + '?' + urlencode({'room': rooms[0]['room_name']})) + return self.serve_room_picker(rooms, base) + file_path = HTML_DIR / ('mobile.html' if mobile else 'index.html') + if not file_path.is_file(): + return self.send_error(404) + from admin_policies import appearance + branding=appearance(room['id']) + room_style=branding.get('room',{}) + title = html_escape((room_style.get('icon','')+' '+(room['display_name'] or room['room_name'])).strip(), quote=True) + # Only substitute explicit placeholders. Never inject user strings into JS. + body = file_path.read_text(encoding='utf-8').replace('@@ROOM_ID@@', str(int(room['id']))) + body = body.replace('@@ROOM_QUERY@@', html_escape(urlencode({'room': room['room_name']}), quote=True)).replace('@@ROOM_TITLE@@', title) + accent=room_style.get('accent','') + if re.fullmatch(r'#[0-9a-fA-F]{6}',accent): + body=body.replace('', '',1) + if branding['powered_by']: + body=body.replace('','Powered by Kronic',1) + return self.send_room_html(body) + + @ras.isolated_request + def do_GET(self): + + if borg_chat_gateway.proxy(self): + + return + parsed = urlparse(self.path) + path = parsed.path + try: + if path == "/login": + if CHAT_SSO_URL: + from urllib.parse import urlencode + query = parse_qs(parsed.query) + keep = {key: query[key][0] for key in ('invite', 'admin') if query.get(key)} + url = CHAT_LOGIN_URL + ('?' + urlencode(keep) if keep else '') + return self.send_redirect(url) + return self.serve_static_file(HTML_DIR / "login.html", "text/html; charset=utf-8") + if path == "/admin": + return self.serve_static_file(HTML_DIR / "admin.html", "text/html; charset=utf-8") + if path == "/mobile.webmanifest": + return self.serve_static_file(HTML_DIR / "mobile.webmanifest", "application/manifest+json") + if path in {"/", "/app", "/m", "/m/", "/desktop", "/desktop/"}: + if CHAT_SSO_URL: + try: + session_user(self.get_session_token()) + except AccountError: + if self.start_chat_sso(): + return + return self.serve_media_app(mobile=self.use_mobile_interface(path)) + if path.startswith("/CSS/"): + return self.serve_static_safe(CSS_DIR, path[len("/CSS/"):]) + if path.startswith("/css/"): + return self.serve_static_safe(CSS_DIR, path[len("/css/"):]) + if path.startswith("/JS/"): + return self.serve_static_safe(JS_DIR, path[len("/JS/"):]) + if path.startswith("/js/"): + return self.serve_static_safe(JS_DIR, path[len("/js/"):]) + if path == "/api/my/assigned-rooms": + return self.send_json({"rooms": assigned_rooms(self.get_session_token())}) + if path == "/api/auth/me": + return self.api_auth_me() + if path == "/api/auth/media-context": + return self.api_media_context() + if path == "/api/admin/role-permissions": + self.require_admin_session() + return self.send_json(admin_get_role_permissions(self.get_session_token())) + if path == '/api/public/branding': + from admin_policies import appearance + b=appearance() + return self.send_json({k:b[k] for k in ('name','login_title','login_subtitle','powered_by')}) + if path == '/api/admin/history-settings': + self.require_admin_session() + rid=parse_qs(parsed.query).get('room_id',[''])[0] + if not rid.isdigit(): raise AccountError(400,'Invalid room') + return self.send_json(hs.admin_get(self.get_session_token(),int(rid))) + if path == '/api/admin/appearance': + self.require_admin_session() + from admin_policies import appearance + rid=parse_qs(parsed.query).get('room_id',[None])[0] + return self.send_json(appearance(int(rid) if rid else None)) + if path == '/api/admin/media-policies': + from admin_policies import snapshot + return self.send_json(snapshot(self.get_session_token())) + if path == "/api/admin/overview": + self.require_admin_session() + return self.send_json(admin_overview(self.get_session_token())) + if path == "/api/admin/room-memberships": + self.require_admin_session() + return self.send_json(admin_room_memberships(self.get_session_token())) + + if path.startswith("/external-stream/"): + return self.handle_external_stream(parsed) + + if path == "/api/balroc/access": + ras.bind_request(self) + rights = ai_command_access.access_for_token(self.get_session_token()) + if not media_context(self.get_session_token())["hasMediaAccess"]: + rights.update(can_chat=False, can_use_tools=False) + return self.send_json(rights) + if path == "/api/admin/ai-access": + self.require_admin_session() + return self.send_json(ai_command_access.admin_list_ai_access(self.get_session_token())) + + # Everything below this point is protected media content/API. + self.require_media_session() + + # kronic-ai-destinations-v5: authenticated live Jellyfin player choices. + if path == "/api/balroc/clients": + ai_command_access.require_ai_access(self.get_session_token()) + from admin_policies import policies + uid=int(session_user(self.get_session_token())['id']) + if self.globally_restricted(uid): + return self.send_json({'clients':[],'can_approve':False}) + result=balroc_kronic_bridge.clients() + user=session_user(self.get_session_token()) + result['can_approve']=bool(user['is_platform_admin']) + return self.send_json(result) + if path == "/api/balroc/status": + ai_command_access.require_ai_access(self.get_session_token()) + return self.send_json(balroc_kronic_bridge.status()) + if path == "/api/sources": + return self.api_sources() + if path.startswith("/api/sources/") and path.endswith("/samples"): + source_id = int(path.strip("/").split("/")[2]) + params = parse_qs(parsed.query) + try: + limit = int(params.get("limit", ["6"])[0]) + except (TypeError, ValueError): + limit = 6 + candidates = get_media_samples( + source_id, + limit=min(12, max(limit * 3, limit)), + ) + samples = [] + for item in candidates: + key_path = item.get("original_path") + if key_path and get_thumbnail_path(key_path).is_file(): + samples.append(item) + if len(samples) >= limit: + break + return self.send_json(samples) + if path == "/api/media": + return self.api_media(parsed) + if path == "/api/search": + return self.api_search(parsed) + if path == "/api/browse": + self.require_manage_session() + return self.api_browse(parsed) + if path == "/api/scan/status": + return self.send_json(get_scan_state()) + if path == "/api/cast/status": + status = get_cast_service().status() + status["player"] = cast_bridge.player_state() + return self.send_json(status) + if path == "/api/cast/command": + params = parse_qs(parsed.query) + client_id = params.get("client_id", [""])[0] + try: + after = int(params.get("after", ["0"])[0]) + except (TypeError, ValueError): + after = 0 + try: + timeout = float(params.get("timeout", ["20"])[0]) + except (TypeError, ValueError): + timeout = 20.0 + return self.send_json( + cast_bridge.wait_for_command( + client_id=client_id, + after=after, + timeout=timeout, + ) + ) + if path == "/api/youtube/status": + return self.send_json(get_youtube_state()) + if path == "/api/youtube/search": + return self.api_youtube_search(parsed) + if path == "/api/youtube/history": + return self.api_youtube_history(parsed) + if path == "/api/youtube/cache/status": + return self.send_json(cache_status()) + if path == "/api/youtube/resolver/status": + return self.send_json(resolver_status()) + if path == "/api/recordings/scheduled": + context = self.require_media_session() + return self.send_json(list_scheduled_recordings(int(context['user']['id']))) + if path == "/api/twitch/overview": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + return self.send_json({ + "channels": twitch_list_channels(user_id), + "recordings": twitch_list_recordings(user_id, limit=50), + }) + if path.startswith("/api/twitch/live/") and path.endswith("/play"): + self.require_media_session() + slug = path[len("/api/twitch/live/"):-len("/play")].strip("/").lower() + if not re.fullmatch(r"[a-z0-9_]{1,25}", slug): + return self.send_error(400, "Invalid Twitch channel name") + return self.handle_twitch_play(None, None, parsed, channel_override={ + "url": f"https://www.twitch.tv/{slug}", "channel_name": slug, + "quality": "best", + }) + if path.startswith("/api/twitch/channels/") and path.endswith("/play"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + channel_id = int(path.strip("/").split("/")[3]) + return self.handle_twitch_play(user_id, channel_id, parsed) + if path == "/api/cache/jobs": + params = parse_qs(parsed.query) + try: + limit = int(params.get("limit", ["100"])[0]) + except (TypeError, ValueError): + limit = 100 + return self.send_json({"jobs": list_cache_jobs(limit=limit)}) + if path.startswith("/api/music/tracks/") and path.endswith("/audio"): + track_id = int(path.strip("/").split("/")[3]) + return self.handle_music_track_audio(track_id, parsed) + if path == "/api/music/import-jobs": + self.require_media_session() + return self.send_json({"jobs": list_music_import_jobs(limit=20)}) + if path == "/api/music/overview": + params = parse_qs(parsed.query) + try: + limit = int(params.get("limit", ["500"])[0]) + except (TypeError, ValueError): + limit = 500 + search = params.get("q", [""])[0] + tracks = music_list_tracks(limit=limit, search=search) + for item in tracks: + item["cached"] = music_audio_cache_status(item.get("youtube_id")).get("cached", False) + return self.send_json({"tracks": tracks, "cache": music_audio_cache_status()}) + if path == "/api/iptv/overview": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + return self.send_json({ + "collections": iptv_list_collections(user_id), + "sources": iptv_list_sources(user_id), + "channels": iptv_list_channels(user_id, selected_only=True), + }) + if path.startswith("/api/iptv/sources/") and path.endswith("/channels"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + source_id = int(path.strip("/").split("/")[3]) + return self.send_json({ + "source": iptv_get_source(user_id, source_id), + "channels": iptv_list_channels(user_id, source_id=source_id), + }) + if path.startswith("/api/iptv/channels/") and path.endswith("/snapshot"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + channel_id = int(path.strip("/").split("/")[3]) + channel = iptv_get_channel(user_id, channel_id) + if not channel: + return self.send_error(404) + snapshot = iptv_ensure_channel_snapshot(channel) + if not snapshot or not snapshot.is_file(): + return self.send_error(404) + return self.serve_static_file(snapshot, "image/jpeg") + if path.startswith("/api/iptv/channels/") and path.endswith("/play"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + channel_id = int(path.strip("/").split("/")[3]) + return self.handle_iptv_play(user_id, channel_id) + if path.startswith("/api/youtube/progress/"): + video_id = path[len("/api/youtube/progress/"):] + return self.api_get_youtube_playback_progress(video_id) + if path.startswith("/api/youtube/video/"): + video_id = path[len("/api/youtube/video/"):] + return self.handle_youtube_video(video_id, parsed) + if path.startswith("/api/music/audio/"): + video_id = path[len("/api/music/audio/"):] + return self.handle_music_audio(video_id, parsed) + if path.startswith("/api/media/") and path.endswith("/playback-options"): + media_id = int(path.strip("/").split("/")[2]) + return self.api_get_playback_options(media_id) + if path.startswith("/api/media/") and path.endswith("/playback-plan"): + media_id = int(path.strip("/").split("/")[2]) + return self.api_get_playback_plan(media_id, parsed) + if path.startswith("/api/media/") and path.endswith("/progress"): + media_id = int(path.strip("/").split("/")[2]) + return self.api_get_playback_progress(media_id) + if path.startswith("/api/media/") and path.endswith("/mediainfo"): + media_id = int(path.strip("/").split("/")[2]) + return self.api_get_mediainfo(media_id) + if path.startswith("/thumbnail/"): + return self.handle_thumbnail(path) + if path.startswith("/external/") and path.endswith(".m3u"): + return self.handle_external_playlist(path) + if path.startswith("/play/"): + return self.handle_play(path) + if path.startswith("/stream/"): + return self.handle_stream(path) + self.send_error(404) + except (BrokenPipeError, ConnectionResetError): + pass + except AccountError as exc: + try: + self.send_account_error(exc) + except Exception: + pass + except Exception as exc: + print(f"[ERROR] GET {path}: {exc}") + try: + self.send_json({"error": "Internal server error."}, status=500) + except Exception: + pass + + @ras.isolated_request + def do_POST(self): + + if borg_chat_gateway.proxy(self): + + return + path = urlparse(self.path).path + try: + if path == "/api/auth/login": + if CHAT_SSO_URL: + return self.send_json({"detail": "Sign in with Kronic Krusaders"}, status=403) + return self.api_auth_login() + if path == "/api/auth/signup": + if CHAT_SSO_URL: + return self.send_json({"detail": "Sign up with Kronic Krusaders"}, status=403) + return self.api_auth_signup() + if path == "/api/auth/logout": + return self.api_auth_logout() + + if path == "/api/admin/history-settings": + return self.send_json(hs.admin_save(self.get_session_token(),self.read_json())) + if path in ('/api/admin/apply-template','/api/admin/appearance','/api/admin/room-appearance'): + from admin_policies import apply_template,save_appearance,save_room_appearance + fn={'/api/admin/apply-template':apply_template,'/api/admin/appearance':save_appearance,'/api/admin/room-appearance':save_room_appearance}[path] + return self.send_json(fn(self.get_session_token(),self.read_json())) + if path in ("/api/admin/media-policies", "/api/admin/room-templates"): + from admin_policies import save_user,save_template + fn=save_user if path.endswith("media-policies") else save_template + return self.send_json(fn(self.get_session_token(),self.read_json())) + if path == "/api/admin/groups": + self.require_admin_session() + return self.send_json(admin_create_group(self.get_session_token(), self.read_json())) + if path.startswith("/api/admin/groups/") and path.endswith("/rooms"): + self.require_admin_session() + segments = path.strip("/").split("/") + if len(segments) != 5 or not segments[3].isdigit(): + return self.send_json({"error": "Invalid group path."}, status=400) + return self.send_json( + admin_create_managed_room( + self.get_session_token(), int(segments[3]), self.read_json() + ), + status=201, + ) + if path.startswith("/api/admin/groups/") and path.endswith("/members"): + self.require_admin_session() + group_id = int(path.strip("/").split("/")[3]) + return self.send_json(admin_assign_member(self.get_session_token(), group_id, self.read_json())) + + if path == "/api/admin/ai-access": + self.require_admin_session() + return self.send_json(ai_command_access.admin_set_ai_access(self.get_session_token(), self.read_json())) + + self.require_media_session() + + # kronic-ai-players-v6: approval is server-authorized, not a browser permission. + if path == '/api/balroc/approve-client': + self.require_admin_session() + body=self.read_json() + device_id=str(body.get('device_id') or '').strip() + try: + return self.send_json(balroc_kronic_bridge.approve_client(device_id)) + except balroc_kronic_bridge.BridgeError as error: + return self.send_json({'error':str(error)},status=error.status) + + if path in ("/api/balroc/chat", "/api/balroc/transcribe"): + rights = ai_command_access.require_ai_access(self.get_session_token()) + body = self.read_json() + if path.endswith("/chat"): + body["use_tools"] = bool(rights["can_use_tools"]) + try: + if path.endswith("/chat"): + from ai_command_sessions import get as get_ai_session, put as save_ai_session + from ai_command_context import resolve as resolve_ai_media + context = self.require_media_session() + user_id = int(context['user']['id']) + window_id = str(body.get('window_id') or '') + try: + if not re.fullmatch(r"[A-Za-z0-9_-]{12,80}", window_id): raise ValueError("Invalid AI window identifier") + scoped_window = hashlib.sha256(f"{ras.current(user_id)}:{window_id}".encode()).hexdigest() + previous = get_ai_session(user_id, scoped_window) + except ValueError as error: + return self.send_json({'error': str(error)}, status=400) + # Explicit Jellyfin destinations take priority over local Kronic media routing. + from ai_command_destinations import resolve as resolve_ai_destination + message = str(body.get('message') or '') + dest = str(body.get('destination') or 'kronic') + wants_remote = (dest not in ('kronic', 'local', '')) or bool( + __import__('re').search(r'\b(kodi|cody|jellyfin|firestick|fire tv|android tv|browser player)\b', message, __import__('re').I)) + from admin_policies import policies + restricted=self.globally_restricted(user_id) + if wants_remote and restricted: + return self.send_json({'reply':'Remote playback is unavailable for restricted media accounts.','window_id':window_id}) + if wants_remote: + try: + client_list = balroc_kronic_bridge.clients().get('clients', []) + except balroc_kronic_bridge.BridgeError as err: + return self.send_json({'reply':'Could not retrieve active Jellyfin players: '+str(err), + 'window_id':window_id}) + else: + client_list = [] + route = resolve_ai_destination(message, dest, client_list) + if route['mode'] == 'error': + return self.send_json({'reply':route['reply'], 'window_id':window_id}) + if route['mode'] == 'remote' and not rights['can_use_tools']: + return self.send_json({'reply':'Agent tools are disabled for this account.', 'window_id':window_id}) + response = None if route['mode'] == 'remote' else resolve_ai_media( + str(body.get('message') or ''), user_id, bool(rights['can_use_tools']), + youtube_search=youtube_search, music_list_tracks=music_list_tracks, + iptv_list_channels=iptv_list_channels, + window_id=scoped_window, + ) + if response is None: + if restricted: + return self.send_json({'reply':'Unrestricted agent tools are disabled for this account. Use a local media search.','window_id':window_id}) + if route['mode'] == 'remote': + body['message'] = route['message'] + body['session_id'] = previous + response = balroc_kronic_bridge.chat(body) + if response.get('session_id'): + save_ai_session(user_id, scoped_window, str(response['session_id'])) + response['window_id'] = window_id + else: + response = balroc_kronic_bridge.transcribe(body) + return self.send_json(response) + except balroc_kronic_bridge.BridgeError as error: + return self.send_json({"error": str(error)}, status=error.status) + + if path == "/api/sources": + self.require_manage_session() + return self.api_add_source() + if path.startswith("/api/sources/") and path.endswith("/paths"): + self.require_manage_session() + parts = path.strip("/").split("/") + return self.api_add_source_path(int(parts[2])) + if path == "/api/scan": + self.require_manage_session() + return self.api_start_scan() + if path == "/api/cast/player-state": + data = self.read_json() + result = cast_bridge.update_player_state( + client_id=str(data.get("client_id") or ""), + status=data.get("status") or "stopped", + position=data.get("position") or 0, + duration=data.get("duration") or 0, + volume=data.get("volume"), + muted=data.get("muted"), + video_id=data.get("video_id"), + ) + return self.send_json(result) + if path == "/api/recordings/scheduled": + context = self.require_media_session() + payload = self.read_json() + try: + job = schedule_recording(int(context['user']['id']), + str(payload.get('provider') or ''), + str(payload.get('media_key') or ''), + payload.get('start_at'), + str(payload.get('title') or '')) + return self.send_json(job, status=201) + except (ValueError, TypeError) as error: + return self.send_json({'error':str(error)},status=400) + if path == "/api/twitch/channels": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + data = self.read_json() + try: + channel = twitch_add_channel( + user_id, + data.get("url") or data.get("channel") or "", + quality=data.get("quality") or "best", + ) + return self.send_json(channel, status=201) + except ValueError as error: + return self.send_json({"error": str(error)}, status=400) + + if path.startswith("/api/twitch/channels/"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + parts = path.strip("/").split("/") + if len(parts) == 5 and parts[:3] == ["api", "twitch", "channels"]: + channel_id = int(parts[3]) + action = parts[4] + data = self.read_json() + try: + if action == "refresh": + return self.send_json(twitch_refresh_channel(user_id, channel_id)) + if action == "record": + return self.send_json(twitch_enqueue_recording(user_id, channel_id), status=202) + if action == "auto": + return self.send_json( + twitch_set_auto_record( + user_id, + channel_id, + bool(data.get("enabled")), + ) + ) + if action == "quality": + return self.send_json( + twitch_set_quality( + user_id, + channel_id, + str(data.get("quality") or "best"), + ) + ) + except ValueError as error: + return self.send_json({"error": str(error)}, status=400) + + if path.startswith("/api/twitch/recordings/"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + parts = path.strip("/").split("/") + if len(parts) == 5 and parts[:3] == ["api", "twitch", "recordings"]: + job_id = int(parts[3]) + action = parts[4] + try: + if action == "stop": + return self.send_json(twitch_stop_recording(user_id, job_id)) + except ValueError as error: + return self.send_json({"error": str(error)}, status=400) + + if path == "/api/twitch/recordings/clear": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + return self.send_json({ + "removed": twitch_clear_finished_recordings(user_id) + }) + + if path == "/api/youtube/preview": + self.require_manage_session() + return self.api_youtube_preview() + if path == "/api/youtube/apply": + self.require_manage_session() + return self.api_youtube_apply() + if path == "/api/youtube/watch": + return self.api_record_youtube_watch() + if path == "/api/music/import": + context = self.require_media_session() + return self.api_music_import(int(context["user"]["id"])) + if path == "/api/music/import-jobs/clear": + self.require_media_session() + removed = clear_music_import_jobs() + return self.send_json({"removed": removed}) + if path == "/api/youtube/cache-job": + context = self.require_media_session() + return self.api_youtube_cache_job(int(context["user"]["id"])) + if path == "/api/cache/jobs/clear": + self.require_media_session() + data = self.read_json() + statuses = data.get("statuses") or ["complete", "failed", "cancelled"] + removed = clear_cache_jobs(statuses) + return self.send_json({"removed": removed}) + if path.startswith("/api/cache/jobs/"): + self.require_media_session() + parts = path.strip("/").split("/") + # /api/cache/jobs// + # -> ["api", "cache", "jobs", "", ""] + if len(parts) == 5 and parts[:3] == ["api", "cache", "jobs"]: + try: + job_id = int(parts[3]) + except (TypeError, ValueError): + return self.send_json( + {"error": "Invalid cache job ID"}, + status=400, + ) + + action = parts[4] + try: + if action == "cancel": + return self.send_json(cancel_cache_job(job_id)) + if action == "retry": + return self.send_json(retry_cache_job(job_id)) + if action == "remove": + removed = remove_cache_job(job_id) + return self.send_json({"removed": bool(removed)}) + + return self.send_json( + {"error": f"Unknown cache job action: {action}"}, + status=404, + ) + except ValueError as error: + return self.send_json( + {"error": str(error)}, + status=400, + ) + if path == "/api/music/reconcile": + self.require_media_session() + return self.send_json(reconcile_music_files(limit=5000)) + if path.startswith("/api/youtube/progress/"): + video_id = path[len("/api/youtube/progress/"):] + return self.api_save_youtube_playback_progress(video_id) + if path == "/api/iptv/collections": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + data = self.read_json() + return self.send_json(iptv_create_collection(user_id, data.get("name"), bool(data.get("is_public", False))), status=201) + if path == "/api/iptv/sources": + context = self.require_media_session() + user_id = int(context["user"]["id"]) + data = self.read_json() + source = iptv_create_source( + user_id, + name=data.get("name"), + source_type=data.get("source_type"), + source_value=data.get("source_value", ""), + source_payload=data.get("source_payload", ""), + collection_id=data.get("collection_id"), + channel_name=data.get("channel_name", ""), + is_public=bool(data.get("is_public", False)), + ) + return self.send_json(source, status=201) + if path.startswith("/api/iptv/sources/") and path.endswith("/refresh"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + source_id = int(path.strip("/").split("/")[3]) + return self.send_json(iptv_refresh_source(user_id, source_id)) + if path.startswith("/api/iptv/sources/") and path.endswith("/selection"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + source_id = int(path.strip("/").split("/")[3]) + data = self.read_json() + count = iptv_set_channel_selection(user_id, source_id, data.get("channel_ids") or []) + return self.send_json({"ok": True, "selected": count}) + if path == "/api/media/move": + self.require_manage_session() + return self.api_move_media() + if path.startswith("/api/media/") and path.endswith("/progress"): + media_id = int(path.strip("/").split("/")[2]) + return self.api_save_playback_progress(media_id) + if path.startswith("/api/media/") and path.endswith("/reanalyze"): + self.require_manage_session() + media_id = int(path.strip("/").split("/")[2]) + return self.api_reanalyze(media_id) + self.send_error(404) + except AccountError as exc: + self.send_account_error(exc) + except Exception as exc: + self.send_json({"error": "Internal server error."}, status=500) + + @ras.isolated_request + def do_PUT(self): + # Room administration uses PUT. Without this handler BaseHTTPRequestHandler + # answers 501 before the Chat reverse proxy can forward the request. + if borg_chat_gateway.proxy(self): + return + path = urlparse(self.path).path + try: + if path == '/api/admin/role-permissions': + self.require_admin_session() + return self.send_json(admin_set_role_permissions(self.get_session_token(), self.read_json())) + if path.startswith('/api/admin/rooms/') and path.endswith('/members'): + self.require_admin_session() + room_id = int(path.strip('/').split('/')[3]) + return self.send_json(admin_assign_room_member(self.get_session_token(), room_id, self.read_json())) + self.send_error(404, 'Unknown PUT endpoint') + except AccountError as exc: + self.send_account_error(exc) + except Exception as exc: + self.send_json({'error': str(exc)}, status=500) + + @ras.isolated_request + def do_PATCH(self): + + if borg_chat_gateway.proxy(self): + + return + path = urlparse(self.path).path + try: + if re.fullmatch(r'/api/(?:admin|my)/rooms/\d+/display-name', path): + room_id = int(path.split('/')[4]) + return self.send_json(rename_room_display(self.get_session_token(), room_id, self.read_json(), instance_only=path.startswith('/api/admin/'))) + if path.startswith("/api/admin/users/") and path.endswith("/status"): + self.require_admin_session() + user_id = int(path.strip("/").split("/")[3]) + status = self.read_json().get("status") + return self.send_json(admin_set_user_status(self.get_session_token(), user_id, status)) + if path.startswith("/api/admin/groups/") and path.endswith("/media"): + self.require_admin_session() + group_id = int(path.strip("/").split("/")[3]) + enabled = bool(self.read_json().get("enabled", True)) + return self.send_json(admin_toggle_group_media(self.get_session_token(), group_id, enabled)) + + if path.startswith("/api/iptv/collections/") and path.endswith("/public"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + collection_id = int(path.strip("/").split("/")[3]) + data = self.read_json() + iptv_set_collection_public(user_id, collection_id, bool(data.get("is_public", False))) + return self.send_json({"ok": True}) + if path.startswith("/api/iptv/sources/") and path.endswith("/public"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + source_id = int(path.strip("/").split("/")[3]) + data = self.read_json() + iptv_set_source_public(user_id, source_id, bool(data.get("is_public", False))) + return self.send_json({"ok": True}) + if path.startswith("/api/iptv/channels/"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + channel_id = int(path.strip("/").split("/")[3]) + iptv_update_channel(user_id, channel_id, self.read_json()) + return self.send_json({"ok": True}) + if path.startswith("/api/iptv/sources/") and path.endswith("/collection"): + context = self.require_media_session() + user_id = int(context["user"]["id"]) + source_id = int(path.strip("/").split("/")[3]) + data = self.read_json() + iptv_move_source_to_collection(user_id, source_id, data.get("collection_id")) + return self.send_json({"ok": True}) + + self.require_manage_session() + + if path.startswith("/api/media/") and path.endswith("/metadata"): + media_id = int(path.strip("/").split("/")[2]) + save_metadata_overrides(media_id, self.read_json()) + return self.send_json({"success": True}) + if path.startswith("/api/sources/"): + source_id = int(path.split("/")[-1]) + data = self.read_json() + if "enabled" in data: + set_media_source_enabled(source_id, bool(data["enabled"])) + if "library_type" in data: + set_media_source_type(source_id, data["library_type"]) + if "artwork_preference" in data: + set_media_source_artwork_preference(source_id, data["artwork_preference"]) + return self.send_json({"success": True}) + self.send_error(404) + except AccountError as exc: + self.send_account_error(exc) + except Exception as exc: + self.send_json({"error": "Internal server error."}, status=500) + + @ras.isolated_request + def do_DELETE(self): + + if borg_chat_gateway.proxy(self): + + return + path = urlparse(self.path).path + try: + if path.startswith('/api/admin/rooms/') and '/members/' in path: + self.require_admin_session() + parts = path.strip('/').split('/') + if len(parts)==6 and parts[0:2]==['api','admin'] and parts[2]=='rooms' and parts[4]=='members': + return self.send_json(admin_remove_room_member(self.get_session_token(),int(parts[3]),int(parts[5]))) + + if path.startswith("/api/admin/users/") and path.count("/") == 4: + self.require_admin_session() + target_user_id = int(path.rsplit("/", 1)[-1]) + return self.send_json(admin_delete_user(self.get_session_token(), target_user_id)) + + if path.startswith("/api/admin/groups/") and "/members/" in path: + self.require_admin_session() + parts = path.strip("/").split("/") + group_id = int(parts[3]) + user_id = int(parts[5]) + return self.send_json(admin_remove_member(self.get_session_token(), group_id, user_id)) + + context = self.require_media_session() + user_id = int(context["user"]["id"]) + + if path.startswith("/api/twitch/channels/"): + channel_id = int(path.strip("/").split("/")[3]) + try: + removed = twitch_delete_channel(user_id, channel_id) + return self.send_json({"removed": bool(removed)}) + except ValueError as error: + return self.send_json({"error": str(error)}, status=400) + + if path.startswith("/api/iptv/sources/"): + source_id = int(path.strip("/").split("/")[3]) + iptv_delete_source(user_id, source_id) + return self.send_json({"ok": True}) + if path.startswith("/api/iptv/collections/"): + collection_id = int(path.strip("/").split("/")[3]) + iptv_delete_collection(user_id, collection_id) + return self.send_json({"ok": True}) + + if path.startswith('/api/recordings/scheduled/'): + context = self.require_media_session() + try: + result = cancel_scheduled_recording(int(context['user']['id']), int(path.rsplit('/',1)[-1])) + return self.send_json(result) + except ValueError as error: + return self.send_json({'error':str(error)}, status=400) + if path.startswith("/api/media/") and path.endswith("/progress"): + media_id = int(path.strip("/").split("/")[2]) + kind = self.media_history_kind(media_id) + hs.reset_progress(self.history_scope(kind), kind, media_id) + return self.send_json({"success": True}) + if path.startswith("/api/youtube/progress/"): + video_id = path[len("/api/youtube/progress/"):] + hs.reset_progress(self.history_scope("tube"), "tube", video_id) + return self.send_json({"success": True}) + if path.startswith("/api/music/tracks/"): + track_id = int(path[len("/api/music/tracks/"):]) + music_delete_track(track_id) + return self.send_json({"success": True}) + if path.startswith("/api/media/") and path.endswith("/metadata-overrides"): + self.require_manage_session() + media_id = int(path.strip("/").split("/")[2]) + reset_metadata_overrides(media_id) + return self.send_json({"success": True}) + if path.startswith("/api/source-paths/"): + self.require_manage_session() + remove_media_source_path(int(path.split("/")[-1])) + return self.send_json({"success": True}) + if path.startswith("/api/sources/"): + self.require_manage_session() + remove_media_source(int(path.split("/")[-1])) + return self.send_json({"success": True}) + self.send_error(404) + except AccountError as exc: + self.send_account_error(exc) + except Exception as exc: + self.send_json({"error": "Internal server error."}, status=500) + + def handle_twitch_play(self, user_id, channel_id, parsed, channel_override=None): + channel = channel_override or twitch_get_channel(user_id, channel_id) + if not channel: + return self.send_error(404, "Twitch channel not found") + + params = parse_qs(parsed.query) + quality = params.get( + "quality", + [channel.get("quality") or "best"], + )[0] + + try: + resolved, pipeline = start_browser_pipeline( + channel["url"], + quality=quality, + ) + except Exception as error: + return self.send_json( + {"error": str(error)}, + status=502, + ) + + print( + "[TWITCH] play", + { + "channel": resolved.channel, + "quality": resolved.quality, + "title": resolved.title, + "category": resolved.category, + }, + flush=True, + ) + + client_disconnected = False + try: + self.send_response(200) + self.send_header("Content-Type", "video/mp4") + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Cache-Control", "no-store") + self.send_header("X-Twitch-Channel", resolved.channel) + self.send_header("X-Twitch-Quality", resolved.quality) + self.end_headers() + + if pipeline.process is None or pipeline.process.stdout is None: + raise RuntimeError("Twitch FFmpeg stdout unavailable") + + while True: + chunk = pipeline.process.stdout.read(256 * 1024) + if not chunk: + break + self.wfile.write(f"{len(chunk):X}\r\n".encode("ascii")) + self.wfile.write(chunk) + self.wfile.write(b"\r\n") + self.wfile.flush() + + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + + except (BrokenPipeError, ConnectionResetError): + client_disconnected = True + finally: + pipeline.stop(graceful=False) + + if ( + not client_disconnected + and pipeline.process + and pipeline.process.returncode not in {None, 0, -15} + ): + error = pipeline.stderr_text() + if error: + print( + "[TWITCH] FFmpeg failed:", + error[-6000:], + flush=True, + ) + + def handle_iptv_play(self, user_id, channel_id): + channel = iptv_get_channel(user_id, channel_id) + if not channel: + return self.send_error(404, "IPTV channel not found") + if not bool(channel.get("source_enabled", 1)): + return self.send_error(403, "IPTV source is disabled") + + command, probe = iptv_ffmpeg_command(channel) + print( + "[IPTV]", + { + "channel_id": channel_id, + "name": channel.get("name"), + "video": probe.get("video_codec"), + "video_action": probe.get("video_action"), + "audio": probe.get("audio_codec"), + "audio_action": probe.get("audio_action"), + }, + flush=True, + ) + + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + + stderr_chunks = [] + client_disconnected = False + + def collect_stderr(): + if not process.stderr: + return + try: + while True: + chunk = process.stderr.read(8192) + if not chunk: + break + stderr_chunks.append(chunk) + if sum(len(part) for part in stderr_chunks) > 128 * 1024: + del stderr_chunks[:-8] + except Exception: + pass + + stderr_thread = threading.Thread( + target=collect_stderr, + daemon=True, + name=f"iptv-ffmpeg-{channel_id}", + ) + stderr_thread.start() + + try: + self.send_response(200) + self.send_header("Content-Type", "video/mp4") + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Cache-Control", "no-store") + self.send_header("X-IPTV-Video-Action", probe.get("video_action", "")) + self.send_header("X-IPTV-Audio-Action", probe.get("audio_action", "")) + self.end_headers() + + if process.stdout is None: + raise RuntimeError("FFmpeg IPTV stdout unavailable") + + while True: + chunk = process.stdout.read(256 * 1024) + if not chunk: + break + self.wfile.write(f"{len(chunk):X}\r\n".encode("ascii")) + self.wfile.write(chunk) + self.wfile.write(b"\r\n") + self.wfile.flush() + + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + + except (BrokenPipeError, ConnectionResetError): + client_disconnected = True + finally: + if process.stdout: + try: + process.stdout.close() + except Exception: + pass + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + process.kill() + try: + process.wait(timeout=2) + except Exception: + pass + try: + stderr_thread.join(timeout=1) + except Exception: + pass + if ( + not client_disconnected + and process.returncode not in {None, 0, -15} + and stderr_chunks + ): + stderr_text = b"".join(stderr_chunks).decode("utf-8", "replace") + print("[IPTV] FFmpeg failed:", stderr_text[-6000:], flush=True) + + def read_json(self): + raw = self.headers.get("Content-Length", "0") + try: + length = int(raw) + except (TypeError, ValueError): + raise ValueError("Invalid Content-Length.") + max_length = 24 * 1024 * 1024 if urlparse(self.path).path == "/api/iptv/sources" else 2 * 1024 * 1024 + if length < 0 or length > max_length: + raise ValueError("JSON request body exceeds endpoint limit or has invalid length.") + return json.loads(self.rfile.read(length).decode("utf-8")) if length else {} + + def send_json(self, data, status=200, extra_headers=None): + encoded = json.dumps(data, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("X-Frame-Options", "SAMEORIGIN") + self.send_header("Referrer-Policy", "same-origin") + if extra_headers: + for key, value in extra_headers.items(): + for item in (value if isinstance(value, (list, tuple)) else [value]): + self.send_header(str(key), str(item)) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def serve_static_safe(self, root, relative_name): + root = root.resolve() + requested = (root / unquote(relative_name)).resolve() + try: + requested.relative_to(root) + except ValueError: + self.send_error(403) + return + if not requested.is_file(): + self.send_error(404) + return + content_type, _ = mimetypes.guess_type(str(requested)) + self.serve_static_file(requested, content_type or "application/octet-stream") + + def serve_static_file(self, file_path, content_type): + if not file_path.is_file(): + self.send_error(404) + return + data = file_path.read_bytes() + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + if content_type.startswith('image/'): + self.send_header('Cache-Control','private, no-store') + self.end_headers() + self.wfile.write(data) + + def api_sources(self): + from admin_policies import source_allowed,policies + uid=int(self.require_media_session()['user']['id']) + rules=policies(uid) + allowed=allowed_media_libraries(uid) + sources = [src for src in get_media_sources() if allowed['tv' if src['library_type']=='shows' else 'movies'] and source_allowed(uid,src,rules)] + counts = {} + for item in get_sorted_media(): + sid = item.get("source_id") + if sid is not None: + counts[sid] = counts.get(sid, 0) + 1 + for source in sources: + source["media_count"] = counts.get(source["id"], 0) + self.send_json(sources) + + def api_add_source(self): + data = self.read_json() + sid = add_media_source(str(data.get("name", "")), str(data.get("path", "")), str(data.get("library_type", "movies"))) + self.send_json({"success": True, "source_id": sid}, status=201) + + def api_add_source_path(self, source_id): + data = self.read_json() + pid = add_media_source_path(source_id, str(data.get("path", ""))) + self.send_json({"success": True, "path_id": pid}, status=201) + + def api_media(self, parsed): + params = parse_qs(parsed.query) + sid = params.get("source_id", [None])[0] + items=get_sorted_media(int(sid) if sid is not None else None) + from admin_policies import source_allowed,policies + uid=int(self.require_media_session()['user']['id']) + rules=policies(uid) + allowed=allowed_media_libraries(uid) + source_types={src['id']:src['library_type'] for src in get_media_sources() if source_allowed(uid,src,rules)} + self.send_json([item for item in items if item.get('source_id') in source_types and allowed['tv' if source_types.get(item.get('source_id'))=='shows' else 'movies']]) + + def api_search(self, parsed): + params = parse_qs(parsed.query) + query = params.get("q", [""])[0].strip() + sid = params.get("source_id", [None])[0] + items=search_media(query, source_id=int(sid) if sid is not None else None) if query else [] + from admin_policies import source_allowed,policies + uid=int(self.require_media_session()['user']['id']) + rules=policies(uid) + allowed=allowed_media_libraries(uid) + source_types={src['id']:src['library_type'] for src in get_media_sources() if source_allowed(uid,src,rules)} + self.send_json([item for item in items if item.get('source_id') in source_types and allowed['tv' if source_types.get(item.get('source_id'))=='shows' else 'movies']]) + + def api_browse(self, parsed): + requested_path = parse_qs(parsed.query).get("path", ["/"])[0] + configured = os.getenv("MEDIA_BROWSE_ROOTS", "/mnt:/media:/srv") + roots = [Path(item).expanduser().resolve() for item in configured.split(os.pathsep) if item.strip()] + roots = [root for root in roots if root.is_dir()] + if requested_path == "/": + return self.send_json({"path": "/", "name": "Media roots", "parent": None, + "folders": [{"name": str(root), "path": str(root)} for root in roots]}) + path = Path(requested_path).expanduser().resolve() + if not any(path == root or root in path.parents for root in roots): + return self.send_json({"error": "Folder is outside allowed media roots."}, status=403) + if not path.is_dir(): + raise NotADirectoryError(path) + folders = [] + try: + for item in sorted(path.iterdir(), key=lambda x: x.name.lower()): + try: + if item.is_dir(): + folders.append({"name": item.name, "path": str(item.resolve())}) + except OSError: + pass + except PermissionError: + pass + self.send_json({"path": str(path), "name": path.name or "Library", "parent": str(path.parent) if path not in roots else "/", "folders": folders}) + + def api_start_scan(self): + data = self.read_json() + requested_ids = data.get("source_ids") + scan_mode = str(data.get("mode") or "quick").lower().strip() + if scan_mode not in {"quick", "deep"}: + return self.send_json({"error": "Scan mode must be quick or deep."}, status=400) + if requested_ids is not None: + if not isinstance(requested_ids, list) or not requested_ids: + return self.send_json({"error": "Select at least one library."}, status=400) + requested_ids = list(dict.fromkeys(int(x) for x in requested_ids)) + enabled_ids = {s["id"] for s in get_media_sources(enabled_only=True)} + if any(x not in enabled_ids for x in requested_ids): + return self.send_json({"error": "One or more selected libraries do not exist or are disabled."}, status=400) + with SCAN_LOCK: + if SCAN_STATE["running"]: + return self.send_json({"error": "A library scan is already running."}, status=409) + SCAN_STATE["running"] = True + threading.Thread(target=scan_worker, args=(requested_ids, scan_mode), daemon=True, name="media-library-scan").start() + self.send_json({"success": True, "started": True, "source_ids": requested_ids, "mode": scan_mode}, status=202) + + def api_youtube_preview(self): + data = self.read_json() + source_id = int(data.get("source_id", 0)) + force_refresh = bool(data.get("force_refresh", False)) + + source = next((s for s in get_media_sources() if s["id"] == source_id), None) + if not source: + return self.send_json({"error": "Select a valid media library."}, status=400) + + with YOUTUBE_LOCK: + if YOUTUBE_STATE["running"]: + return self.send_json({"error": "A YouTube metadata job is already running."}, status=409) + YOUTUBE_STATE["running"] = True + YOUTUBE_STATE["phase"] = "starting_preview" + + threading.Thread( + target=youtube_preview_worker, + args=(source_id, force_refresh), + daemon=True, + name="youtube-metadata-preview", + ).start() + self.send_json({"success": True, "started": True, "source_id": source_id}, status=202) + + def api_youtube_apply(self): + data = self.read_json() + source_id = int(data.get("source_id", 0)) + mode = str(data.get("mode", "metadata")).strip().lower() + if mode not in {"metadata", "rename"}: + return self.send_json({"error": "Mode must be metadata or rename."}, status=400) + + state = get_youtube_state() + if state.get("running"): + return self.send_json({"error": "A YouTube metadata job is already running."}, status=409) + if state.get("phase") not in {"preview_complete", "apply_complete"}: + return self.send_json({"error": "Run Preview first."}, status=400) + if int(state.get("source_id") or 0) != source_id: + return self.send_json({"error": "The preview belongs to a different library. Run Preview again."}, status=400) + if not any(item.get("status") == "ready" for item in state.get("results") or []): + return self.send_json({"error": "The preview contains no YouTube items to apply."}, status=400) + + with YOUTUBE_LOCK: + YOUTUBE_STATE["running"] = True + YOUTUBE_STATE["phase"] = "starting_apply" + YOUTUBE_STATE["mode"] = mode + + threading.Thread( + target=youtube_apply_worker, + args=(source_id, mode), + daemon=True, + name="youtube-metadata-apply", + ).start() + self.send_json({"success": True, "started": True, "source_id": source_id, "mode": mode}, status=202) + + def api_youtube_search(self, parsed): + params = parse_qs(parsed.query) + query = params.get("q", [""])[0].strip() + try: + limit = int(params.get("limit", ["20"])[0]) + except (TypeError, ValueError): + limit = 20 + self.send_json(youtube_search(query, limit=limit)) + + def history_scope(self, kind): + return hs.resolve(self.get_session_token(), str(ras.bind_request(self)), kind) + + def media_history_kind(self, media_id): + media = get_media_by_id(media_id) + if not media: raise AccountError(404, "Media not found") + source = get_media_source(media.get("source_id")) + from admin_policies import enforce_source + enforce_source(int(session_user(self.get_session_token())["id"]), source) + return "tv" if source["library_type"] == "shows" else "movies" + + def api_youtube_history(self, parsed): + params = parse_qs(parsed.query) + try: + limit = int(params.get("limit", ["50"])[0]) + except (TypeError, ValueError): + limit = 50 + self.send_json({"items": hs.history(self.history_scope("tube"), limit)}) + + def api_record_youtube_watch(self): + data = self.read_json() + video_id = str(data.get("video_id", "")).strip() + if not video_id: + return self.send_json({"error": "video_id is required"}, status=400) + hs.record_watch(self.history_scope("tube"), + video_id=video_id, + title=data.get("title") or video_id, + channel_name=data.get("channel_name") or data.get("artist"), + thumbnail_url=data.get("thumbnail_url") or data.get("thumbnail"), + duration_seconds=data.get("duration_seconds") or data.get("duration"), + ) + self.send_json({"success": True}) + + def api_get_youtube_playback_progress(self, video_id): + progress = hs.get_progress(self.history_scope("tube"), "tube", video_id) + cache = get_youtube_video_cache(video_id) + cached = False + if cache: + cache_path = Path(cache.get("cache_path") or "") + cached = cache_path.is_file() and cache_path.stat().st_size > 0 + progress["cached"] = cached + progress["seek_mode"] = "client" if cached else "server" + self.send_json(progress) + + def api_save_youtube_playback_progress(self, video_id): + data = self.read_json() + hs.save_progress(self.history_scope("tube"), "tube", video_id, + position=data.get("position_seconds", 0), + duration=data.get("duration_seconds"), + completed=bool(data.get("completed", False)), + ) + self.send_json({"success": True}) + + def handle_youtube_video(self, video_id, parsed): + params = parse_qs(parsed.query) + try: + start_seconds = max(0.0, float(params.get("start", ["0"])[0])) + except (TypeError, ValueError): + start_seconds = 0.0 + refresh = str(params.get("refresh", ["false"])[0]).lower() in {"1", "true", "yes", "on"} + bypass_cache = str(params.get('uncached', ['false'])[0]).lower() in {'1', 'true', 'yes'} + serve_youtube_video( + self, + video_id=video_id, + start_seconds=start_seconds, + refresh=refresh, + bypass_cache=bypass_cache, + ) + + def api_youtube_cache_job(self, user_id): + data = self.read_json() + try: + job = enqueue_cache_job( + user_id=user_id, + video_id=str(data.get("video_id") or "").strip(), + mode=str(data.get("mode") or "").strip(), + title=str(data.get("title") or ""), + artist=str(data.get("artist") or ""), + thumbnail=str(data.get("thumbnail") or ""), + duration_seconds=data.get("duration"), + ) + except ValueError as error: + return self.send_json({"error": str(error)}, status=400) + + return self.send_json(job, status=202) + + def handle_music_track_audio(self, track_id, parsed): + track = music_get_track(track_id) + if not track: + return self.send_json({"error": "Music track not found"}, status=404) + + local_path = Path(track.get("local_path") or "") + if local_path.is_file() and local_path.stat().st_size > 0: + return self.stream_file( + local_path, + content_type_override="audio/mp4", + ) + + video_id = str(track.get("youtube_id") or "").strip() + if not video_id: + return self.send_json( + {"error": "Track has no local file or YouTube source"}, + status=404, + ) + + params = parse_qs(parsed.query) + refresh = str(params.get("refresh", ["false"])[0]).lower() in {"1", "true", "yes", "on"} + return serve_youtube_audio( + self, + video_id=video_id, + start_seconds=0, + refresh=refresh, + ) + + def api_music_import(self, user_id): + data = self.read_json() + query = str(data.get("url") or data.get("query") or "").strip() + if not query: + return self.send_json( + {"error": "Spotify URL or music query is required"}, + status=400, + ) + job = enqueue_music_import( + query=query, + user_id=user_id, + ) + return self.send_json(job, status=202) + + def handle_music_audio(self, video_id, parsed): + params = parse_qs(parsed.query) + try: + start_seconds = max(0.0, float(params.get("start", ["0"])[0])) + except (TypeError, ValueError): + start_seconds = 0.0 + refresh = str(params.get("refresh", ["false"])[0]).lower() in {"1", "true", "yes", "on"} + return serve_youtube_audio(self, video_id=video_id, start_seconds=start_seconds, refresh=refresh) + + def api_move_media(self): + data = self.read_json() + result = move_media(int(data["media_id"]), int(data["target_source_id"]), data.get("target_subfolder")) + self.send_json({"success": True, "result": result}) + + def api_get_playback_options(self, media_id): + media = get_media_by_id(media_id) + if not media: + return self.send_json({"error": "Media not found"}, status=404) + + file_path = Path(media.get("current_path") or media.get("original_path")) + if not file_path.is_file(): + return self.send_json({"error": "Media file is unavailable"}, status=404) + + try: + probe = probe_media(file_path) + except Exception as error: + return self.send_json( + {"error": f"Could not inspect media streams: {error}"}, + status=500, + ) + + try: + refreshed = dict(media) + refreshed.update({ + "file_size": probe.get("size"), + "file_mtime_ns": probe.get("mtime_ns"), + "video_codec": probe.get("video_codec"), + "video_width": probe.get("width"), + "video_height": probe.get("height"), + "video_bitrate": probe.get("video_bitrate"), + "video_fps": probe.get("fps"), + "audio_tracks": probe.get("audio_tracks") or [], + "probe": probe, + }) + update_sorted_media(refreshed) + except Exception as error: + print( + "[PLAYBACK] Could not persist lazy stream metadata:", + {"media_id": media_id, "error": str(error)}, + flush=True, + ) + + return self.send_json({ + "media_id": media_id, + "video_codec": probe.get("video_codec"), + "width": probe.get("width"), + "height": probe.get("height"), + "quality_options": quality_options(probe), + "audio_tracks": probe.get("audio_tracks") or [], + }) + + def api_get_playback_plan(self, media_id, parsed): + media = get_media_by_id(media_id) + if not media: + return self.send_json( + {"error": "Media not found"}, + status=404, + ) + + file_path = Path( + media.get("current_path") + or media.get("original_path") + ) + + if not file_path.is_file(): + return self.send_json( + {"error": "Media file not found"}, + status=404, + ) + + params = parse_qs(parsed.query) + browser = params.get( + "browser", + ["unknown"], + )[0] + + capabilities = { + "h264": params.get( + "h264", + ["1"], + )[0], + "av1": params.get( + "av1", + ["0"], + )[0], + "hevc": params.get( + "hevc", + ["0"], + )[0], + "webm_vp9": params.get( + "webm_vp9", + ["0"], + )[0], + "webm_av1": params.get( + "webm_av1", + ["0"], + )[0], + } + + force_compat = ( + params.get( + "force_compat", + ["0"], + )[0] + in { + "1", + "true", + "yes", + "on", + } + ) + + quality = params.get("quality", ["original"])[0] + raw_audio = params.get("audio", [""])[0] + try: + audio_stream_index = int(raw_audio) if raw_audio != "" else None + except (TypeError, ValueError): + audio_stream_index = None + + plan = plan_playback( + file_path, + capabilities=capabilities, + browser=browser, + force_compat=force_compat, + quality=quality, + audio_stream_index=audio_stream_index, + ) + plan["selected_quality"] = quality + + plan["cache"] = { + "cached": False, + "path": None, + "size_bytes": 0, + } + + # Never expose server filesystem paths to the browser. + plan["source"].pop( + "path", + None, + ) + if plan["cache"].get("path"): + plan["cache"]["path"] = None + + plan["media_id"] = media_id + return self.send_json(plan) + + def api_get_playback_progress(self, media_id): + media = get_media_by_id(media_id) + if not media: + return self.send_json({"error": "Media not found"}, status=404) + kind = self.media_history_kind(media_id) + progress = hs.get_progress(self.history_scope(kind), kind, media_id) or {} + suffix = Path(media.get("current_path") or media.get("original_path")).suffix.lower() + self.send_json({ + "media_id": media_id, + "position_seconds": progress.get("position_seconds", 0), + "duration_seconds": progress.get("duration_seconds") or media.get("duration_seconds"), + "completed": bool(progress.get("completed", False)), + "seek_mode": "client", + }) + + def api_save_playback_progress(self, media_id): + data = self.read_json() + kind = self.media_history_kind(media_id) + hs.save_progress(self.history_scope(kind), kind, media_id, data.get("position_seconds", 0), data.get("duration_seconds"), bool(data.get("completed", False))) + self.send_json({"success": True}) + + def api_get_mediainfo(self, media_id): + media = get_media_by_id(media_id) + if not media: + return self.send_json({"error": "Media not found"}, status=404) + path = media.get("current_path") or media.get("original_path") + self.send_json(get_full_mediainfo(path)) + + def api_reanalyze(self, media_id): + media = get_media_by_id(media_id) + if not media: + return self.send_json({"error": "Media not found"}, status=404) + path = Path(media.get("current_path") or media.get("original_path")).resolve() + item = inspect_media_file(path) + item = apply_sidecar_to_item(item, path) + if item.get("is_short_media"): + remove_media_index_by_current_path(path) + return self.send_json({"success": True, "removed_short": True}) + item.update({ + "original_path": media["original_path"], "current_path": str(path), "source_id": media.get("source_id"), + "source_path_id": media.get("source_path_id"), "relative_path": media.get("relative_path"), "sorted_path": media.get("sorted_path") + }) + update_sorted_media(item) + self.send_json({"success": True, "removed_short": False}) + + def send_thumbnail_file(self, file_path): + """Jellyfin/poster images get browser caching for four hours.""" + path = Path(file_path) + if not path.is_file(): + return self.send_error(404) + mime = mimetypes.guess_type(str(path))[0] or "image/jpeg" + self.send_response(200) + self.send_header("Content-Type", mime) + self.send_header("Content-Length", str(path.stat().st_size)) + self.send_header("Cache-Control", "private, no-store") + self.end_headers() + with path.open("rb") as source: + while True: + block = source.read(128 * 1024) + if not block: break + self.wfile.write(block) + + def handle_thumbnail(self, request_path): + media_id = int(request_path[len("/thumbnail/"):]) + media = get_media_by_id(media_id) + if not media: + return self.send_error(404) + + key_path = media.get("original_path") + current_path = media.get("current_path") or key_path + # Library-specific choice: local FFmpeg frame or Jellyfin artwork first. + # A missing preferred image always falls back to the other source. + source = get_media_source(media.get("source_id")) if media.get("source_id") else None + preference = (source or {}).get("artwork_preference") or "jellyfin_first" + # Prefer existing Jellyfin artwork on previously indexed titles too; + # old database rows may not have artwork_path yet until the next scan. + from metadata_sidecar import find_artwork + current_sidecar = find_artwork(current_path) + if preference == "jellyfin_first" and current_sidecar and current_sidecar.is_file(): + self.send_thumbnail_file(current_sidecar) + return + sidecar_value = media.get("artwork_path") or "" + sidecar_art = Path(sidecar_value) if sidecar_value else None + # Existing database records may predate the NFO path validation fix. + # Check them at serve time too, resolving symlinks before containment. + if sidecar_art is not None: + try: + sidecar_art = sidecar_art.resolve(strict=True) + sidecar_art.relative_to(Path(current_path).resolve().parent) + if sidecar_art.suffix.lower() not in {".jpg", ".jpeg", ".png", ".webp"}: + sidecar_art = None + except (OSError, ValueError, RuntimeError): + sidecar_art = None + # Ignore previously indexed Jellyfin trickplay contact sheets. + # Old database rows can still point to them even after artwork discovery is fixed. + if sidecar_art is not None and any(part.endswith(".trickplay") for part in sidecar_art.parts): + sidecar_art = None + thumbnail = get_thumbnail_path(key_path) + + if preference == "jellyfin_first": + if sidecar_art is not None and sidecar_art.is_file(): + content_type = mimetypes.guess_type(str(sidecar_art))[0] or "image/jpeg" + return self.send_thumbnail_file(sidecar_art) + if thumbnail.is_file(): + return self.send_thumbnail_file(thumbnail) + else: + if thumbnail.is_file(): + return self.send_thumbnail_file(thumbnail) + # The original/generated image can be produced on demand below. + # Only use Jellyfin artwork if generation fails. + + fingerprint = _thumbnail_fingerprint(current_path) + with THUMBNAIL_FAILURE_LOCK: + previous_failure = THUMBNAIL_FAILURES.get(key_path) + + if previous_failure == fingerprint: + if sidecar_art is not None and sidecar_art.is_file(): + content_type = mimetypes.guess_type(str(sidecar_art))[0] or "image/jpeg" + return self.send_thumbnail_file(sidecar_art) + return self.send_error(404) + + thumbnail = generate_thumbnail( + current_path, + key_path=key_path, + ) + + if thumbnail is None or not thumbnail.is_file(): + with THUMBNAIL_FAILURE_LOCK: + THUMBNAIL_FAILURES[key_path] = fingerprint + if sidecar_art is not None and sidecar_art.is_file(): + content_type = mimetypes.guess_type(str(sidecar_art))[0] or "image/jpeg" + return self.send_thumbnail_file(sidecar_art) + return self.send_error(404) + + with THUMBNAIL_FAILURE_LOCK: + THUMBNAIL_FAILURES.pop(key_path, None) + + return self.send_thumbnail_file(thumbnail) + + def _external_stream_signature(self, media_id, expires_at, user_id, room_id=None): + if not EXTERNAL_STREAM_SECRET: + raise RuntimeError( + "Set EXTERNAL_STREAM_SECRET or KRONICK_SESSION_SECRET" + ) + message = f"policy-v3:{int(media_id)}:{int(expires_at)}:{int(user_id)}:{room_id}".encode("utf-8") + return hmac.new( + EXTERNAL_STREAM_SECRET, + message, + hashlib.sha256, + ).hexdigest() + + def _external_stream_authorized(self, media_id, expires_at, signature, user_id, room_id=None): + try: + expires_at = int(expires_at) + except (TypeError, ValueError): + return False + + if expires_at < int(time.time()): + return False + + expected = self._external_stream_signature(media_id, expires_at, user_id, room_id) + return hmac.compare_digest(expected, str(signature or "")) + + def handle_external_playlist(self, request_path): + user_id=int(self.require_media_session()["user"]["id"]) + name = request_path[len("/external/"):] + if not name.endswith(".m3u"): + return self.send_error(404) + + try: + media_id = int(name[:-4]) + except ValueError: + return self.send_error(404) + + media = get_media_by_id(media_id) + if not media: + return self.send_error(404) + + title = ( + media.get("title_override") + or media.get("title") + or Path( + media.get("current_path") + or media.get("original_path") + or str(media_id) + ).stem + ) + + expires_at = int(time.time()) + EXTERNAL_STREAM_TTL_SECONDS + room_id=ras.current(user_id) + signature = self._external_stream_signature(media_id, expires_at, user_id, room_id) + + host = self.headers.get("Host") or f"{HOST}:{PORT}" + forwarded_proto = self.headers.get("X-Forwarded-Proto", "") + scheme = "https" if forwarded_proto.lower() == "https" else "http" + + stream_url = ( + f"{scheme}://{host}/external-stream/{media_id}" + f"?exp={expires_at}&uid={user_id}&rid={room_id}&sig={signature}" + ) + + body = ( + "#EXTM3U\n" + f"#EXTINF:-1,{title}\n" + f"{stream_url}\n" + ).encode("utf-8") + + safe_title = re.sub( + r"[^A-Za-z0-9._ -]+", + "_", + str(title), + ).strip() or f"media-{media_id}" + + self.send_response(200) + self.send_header("Content-Type", "audio/x-mpegurl; charset=utf-8") + self.send_header( + "Content-Disposition", + f'attachment; filename="{safe_title}.m3u"', + ) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def handle_external_stream(self, parsed): + try: + media_id = int(parsed.path[len("/external-stream/"):]) + except ValueError: + return self.send_error(404) + + params = parse_qs(parsed.query) + expires_at = params.get("exp", [""])[0] + signature = params.get("sig", [""])[0] + + try: + user_id=int(params.get("uid",[""])[0]) + room_id=int(params.get("rid",[""])[0]) + except ValueError: + return self.send_error(403) + if not self._external_stream_authorized( + media_id, + expires_at, + signature, user_id, room_id, + ): + return self.send_error( + 403, + "External playback link expired or invalid", + ) + + media = get_media_by_id(media_id) + if not media: + return self.send_error(404) + + file_path = Path( + media.get("current_path") + or media.get("original_path") + ) + if not file_path.is_file(): + return self.send_error(404) + + from admin_policies import enforce_external_owner + ras.bind(user_id,room_id) + enforce_external_owner(user_id,media) + # VLC/mpv understand MKV and many codecs directly. Preserve the + # original file and let the external player do what it is good at. + return self.stream_file(file_path) + + def _playback_capabilities(self, params): + return { + "h264": params.get("h264", ["1"])[0], + "av1": params.get("av1", ["0"])[0], + "hevc": params.get("hevc", ["0"])[0], + "webm_vp9": params.get("webm_vp9", ["0"])[0], + "webm_av1": params.get("webm_av1", ["0"])[0], + } + + def handle_play(self, request_path): + parsed = urlparse(self.path) + media_id = int( + parsed.path[len("/play/"):] + ) + params = parse_qs(parsed.query) + + try: + start_seconds = max( + 0.0, + float( + params.get( + "start", + ["0"], + )[0] + ), + ) + except ( + TypeError, + ValueError, + ): + start_seconds = 0.0 + + browser = params.get( + "browser", + ["unknown"], + )[0] + + force_compat = ( + params.get( + "force_compat", + ["0"], + )[0] + in { + "1", + "true", + "yes", + "on", + } + ) + + media = get_media_by_id( + media_id + ) + if not media: + return self.send_error(404) + + file_path = Path( + media.get("current_path") + or media.get("original_path") + ) + if not file_path.is_file(): + return self.send_error(404) + + quality = params.get("quality", ["original"])[0] + raw_audio = params.get("audio", [""])[0] + try: + audio_stream_index = int(raw_audio) if raw_audio != "" else None + except (TypeError, ValueError): + audio_stream_index = None + + plan = plan_playback( + file_path, + capabilities=self._playback_capabilities( + params + ), + browser=browser, + force_compat=force_compat, + quality=quality, + audio_stream_index=audio_stream_index, + ) + + plan["selected_quality"] = quality + + print( + "[PLAYBACK]", + { + "media_id": media_id, + "browser": browser, + "mode": plan["mode"], + "video": plan["source"].get( + "video_codec" + ), + "audio": plan["source"].get( + "audio_codec" + ), + "source": file_path.name, + "reason": plan["reason"], + }, + flush=True, + ) + + if plan["mode"] == "direct": + return self.stream_file( + file_path + ) + + if plan["mode"] == "remux_stream": + return self.stream_ffmpeg_remux( + file_path, + start_seconds=start_seconds, + audio_stream_index=plan.get("selected_audio_stream_index"), + ) + + return self.stream_ffmpeg_compat( + file_path, + start_seconds=start_seconds, + audio_stream_index=plan.get("selected_audio_stream_index"), + target_height=plan.get("requested_height"), + video_bitrate=plan.get("video_bitrate"), + ) + + def stream_ffmpeg_remux( + self, + file_path, + start_seconds=0.0, + audio_stream_index=None, + ): + command = remux_stream_command( + file_path, + start_seconds=start_seconds, + audio_stream_index=audio_stream_index, + ) + return self._stream_ffmpeg_command( + command, + playback_mode="remux-stream", + ) + + def stream_ffmpeg_compat( + self, + file_path, + start_seconds=0.0, + audio_stream_index=None, + target_height=None, + video_bitrate=None, + ): + command = transcode_stream_command( + file_path, + start_seconds=start_seconds, + audio_stream_index=audio_stream_index, + target_height=target_height, + video_bitrate=video_bitrate, + ) + return self._stream_ffmpeg_command( + command, + playback_mode="transcode-stream", + ) + + def _stream_ffmpeg_command( + self, + command, + *, + playback_mode, + ): + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + + stderr_chunks = [] + client_disconnected = False + + def collect_stderr(): + if not process.stderr: + return + try: + while True: + chunk = process.stderr.read(8192) + if not chunk: + break + stderr_chunks.append(chunk) + if sum(len(part) for part in stderr_chunks) > 128 * 1024: + del stderr_chunks[:-8] + except Exception: + pass + + stderr_thread = threading.Thread( + target=collect_stderr, + daemon=True, + name="ffmpeg-playback-stderr", + ) + stderr_thread.start() + + try: + self.send_response(200) + self.send_header("Content-Type", "video/mp4") + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Cache-Control", "no-store") + self.send_header( + "X-Media-Playback-Mode", + playback_mode, + ) + self.end_headers() + + if process.stdout is None: + raise RuntimeError("FFmpeg stdout was not available") + + while True: + chunk = process.stdout.read(256 * 1024) + if not chunk: + break + self.wfile.write( + f"{len(chunk):X}\r\n".encode("ascii") + ) + self.wfile.write(chunk) + self.wfile.write(b"\r\n") + self.wfile.flush() + + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + + except (BrokenPipeError, ConnectionResetError): + client_disconnected = True + finally: + if process.stdout: + try: + process.stdout.close() + except Exception: + pass + + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + process.kill() + try: + process.wait(timeout=2) + except Exception: + pass + + try: + stderr_thread.join(timeout=1) + except Exception: + pass + + if ( + not client_disconnected + and process.returncode not in {None, 0, -15} + and stderr_chunks + ): + stderr_text = b"".join(stderr_chunks).decode( + "utf-8", + "replace", + ) + print( + f"[PLAYBACK] FFmpeg {playback_mode} failed:", + stderr_text[-6000:], + flush=True, + ) + + def handle_stream(self, request_path): + media_id = int(request_path[len("/stream/"):]) + media = get_media_by_id(media_id) + if not media: + return self.send_error(404) + file_path = Path(media.get("current_path") or media.get("original_path")) + if not file_path.is_file(): + return self.send_error(404) + self.stream_file(file_path) + + def stream_file(self, file_path, content_type_override=None): + file_size = file_path.stat().st_size + content_type, _ = mimetypes.guess_type(str(file_path)) + content_type = content_type_override or content_type or "application/octet-stream" + range_header = self.headers.get("Range") + try: + if range_header: + result = self.parse_range_header(range_header, file_size) + if result is None: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{file_size}") + self.send_header("Content-Length", "0") + self.end_headers() + return + start, end = result + length = end - start + 1 + self.send_response(206) + self.send_header("Content-Type", content_type) + self.send_header("Cache-Control", "private, no-store") + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Range", f"bytes {start}-{end}/{file_size}") + self.send_header("Content-Length", str(length)) + self.end_headers() + with open(file_path, "rb") as media_file: + media_file.seek(start) + remaining = length + while remaining > 0: + chunk = media_file.read(min(262144, remaining)) + if not chunk: break + self.wfile.write(chunk) + remaining -= len(chunk) + return + self.send_response(200) + self.send_header("Cache-Control", "private, no-store") + self.send_header("Content-Type", content_type) + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Length", str(file_size)) + self.end_headers() + with open(file_path, "rb") as media_file: + while True: + chunk = media_file.read(262144) + if not chunk: break + self.wfile.write(chunk) + except (BrokenPipeError, ConnectionResetError): + pass + + def parse_range_header(self, range_header, file_size): + try: + units, spec = range_header.split("=", 1) + if units.strip() != "bytes" or "," in spec: + return None + start_text, end_text = spec.strip().split("-", 1) + if not start_text: + suffix = int(end_text) + if suffix <= 0: return None + suffix = min(suffix, file_size) + return file_size - suffix, file_size - 1 + start = int(start_text) + if start >= file_size: return None + end = min(int(end_text), file_size - 1) if end_text else file_size - 1 + return None if end < start else (start, end) + except Exception: + return None + + +def _start_resolver_nonfatal(): + """ + Start the embedded Kronic resolver without blocking the media server. + + YouTube is optional. A resolver bind/startup/health-check problem should + never prevent local libraries, IPTV, auth, or the web UI from starting. + """ + try: + start_resolver() + print( + "[RESOLVER] Embedded Kronic resolver ready.", + flush=True, + ) + except Exception as error: + print( + "[RESOLVER] Embedded resolver failed to start; " + "continuing without Tube:", + repr(error), + flush=True, + ) + + +def run(): + from kronic_chat_manager import chat_manager + # Start the HTTP server first. The resolver startup helper may spend time + # waiting on its health check, so run it independently. + server = ThreadingHTTPServer( + (HOST, PORT), + StreamingHandler, + ) + + resolver_thread = threading.Thread( + target=_start_resolver_nonfatal, + daemon=True, + name="kronic-resolver-startup", + ) + resolver_thread.start() + + chat_manager.start() + + print("=====================================", flush=True) + print(f"Media Server: http://{HOST}:{PORT}", flush=True) + print( + "Kronic YouTube resolver: starting in background", + flush=True, + ) + print("=====================================", flush=True) + + try: + server.serve_forever() + + except KeyboardInterrupt: + print("\nStopping...", flush=True) + + finally: + chat_manager.stop() + server.server_close() + + try: + stop_resolver() + except Exception as error: + print( + "[RESOLVER] Error while stopping resolver:", + repr(error), + flush=True, + ) + + +if __name__ == "__main__": + run()