import room_access_scope as ras import history_scopes as hs from media_accounts import admin_get_role_permissions, admin_set_role_permissions import json import urllib.request import urllib.error import borg_chat_gateway import balroc_kronic_bridge # Kronic AI Command permission patch v1 import ai_command_access # kronic-ai-media-v1 import hashlib import hmac import re import mimetypes import os import subprocess import threading import time from pathlib import Path from urllib.parse import urlparse, parse_qs, unquote, urlencode from html import escape as html_escape from media_accounts import assigned_rooms, rename_room_display from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler from http.cookies import SimpleCookie from dotenv import load_dotenv from library_index import ( init_db, get_sorted_media, get_media_by_id, get_media_samples, update_sorted_media, search_media, get_media_sources, get_media_source, get_media_source_paths, add_media_source, add_media_source_path, remove_media_source_path, remove_media_source, set_media_source_enabled, set_media_source_type, set_media_source_artwork_preference, move_media, remove_media_index_by_current_path, save_metadata_overrides, reset_metadata_overrides, get_playback_progress, save_playback_progress, reset_playback_progress, get_youtube_metadata_cache, save_youtube_metadata_cache, set_media_title_override, update_media_after_youtube_rename, record_youtube_watch, get_youtube_playback_progress, save_youtube_playback_progress, reset_youtube_playback_progress, get_youtube_history, get_youtube_video_cache, media_needs_probe, touch_media_scan_state, apply_sidecar_to_item, ) from thumbnail_worker import generate_thumbnail, get_thumbnail_path from mediainfo import get_full_mediainfo, inspect_media_file from youtube_metadata import extract_youtube_id, fetch_youtube_metadata, build_youtube_filename from youtube_stream import youtube_search, serve_youtube_video, serve_youtube_audio, music_audio_cache_status, cache_status, resolver_status from twitch_stream import start_browser_pipeline from twitch_jobs import ( init_twitch_db, start_twitch_watcher, add_channel as twitch_add_channel, get_channel as twitch_get_channel, list_channels as twitch_list_channels, delete_channel as twitch_delete_channel, refresh_channel as twitch_refresh_channel, set_auto_record as twitch_set_auto_record, set_quality as twitch_set_quality, enqueue_recording as twitch_enqueue_recording, stop_recording as twitch_stop_recording, list_recordings as twitch_list_recordings, clear_finished_recordings as twitch_clear_finished_recordings, ) from recording_schedule import start as start_recording_scheduler, schedule as schedule_recording, list_jobs as list_scheduled_recordings, cancel as cancel_scheduled_recording from cache_jobs import ( init_cache_jobs_db, start_cache_worker, enqueue_cache_job, list_cache_jobs, clear_cache_jobs, remove_cache_job, retry_cache_job, cancel_cache_job, ) from resolver_manager import start_resolver, stop_resolver from music import ( init_music_db, import_music, list_tracks as music_list_tracks, delete_track as music_delete_track, get_track as music_get_track, reconcile_music_files, start_music_reconciler, ) from music_import_jobs import ( init_music_import_jobs, start_music_import_worker, enqueue_music_import, list_music_import_jobs, clear_music_import_jobs, ) from playback_planner import ( plan_playback, quality_options, compatibility_cache_status, ensure_remux_cache, remux_stream_command, transcode_stream_command, probe_media, ) from media_accounts import ( AccountError, SESSION_COOKIE, SESSION_TTL_SECONDS, COOKIE_SECURE, initialize_account_database, signup_account, login_account, logout_account, session_user, media_context, require_media_access, require_manage_media, allowed_media_libraries, enforce_media_library, create_sso_session, require_admin, admin_overview, admin_room_memberships, admin_assign_room_member, admin_remove_room_member, admin_set_user_status, admin_create_group, admin_create_managed_room, admin_toggle_group_media, admin_assign_member, admin_remove_member, admin_delete_user, ) from kronic.cast import bridge as cast_bridge from kronic.cast.service import get_cast_service, start_cast_service, stop_cast_service from iptv import ( init_iptv_db, list_collections as iptv_list_collections, create_collection as iptv_create_collection, delete_collection as iptv_delete_collection, set_collection_public as iptv_set_collection_public, list_sources as iptv_list_sources, create_source as iptv_create_source, get_source as iptv_get_source, delete_source as iptv_delete_source, move_source_to_collection as iptv_move_source_to_collection, set_source_public as iptv_set_source_public, refresh_source as iptv_refresh_source, list_channels as iptv_list_channels, get_channel as iptv_get_channel, set_channel_selection as iptv_set_channel_selection, update_channel as iptv_update_channel, iptv_ffmpeg_command, ensure_channel_snapshot as iptv_ensure_channel_snapshot, ) BASE_DIR = Path(__file__).resolve().parent HTML_DIR = BASE_DIR / "html" CSS_DIR = BASE_DIR / "CSS" JS_DIR = BASE_DIR / "JS" load_dotenv(BASE_DIR / "config.env") HOST = os.getenv("HOST", "0.0.0.0") PORT = int(os.getenv("PORT", "7060")) CHAT_SSO_URL = os.getenv("KRONICK_SSO_INTROSPECT_URL", "").strip() CHAT_SSO_SECRET = os.getenv("KRONICK_SSO_SHARED_SECRET", "").strip() CHAT_LOGIN_URL = "https://kronickrusaders.ca/login" LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper() FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg") EXTERNAL_STREAM_SECRET = os.getenv( "EXTERNAL_STREAM_SECRET", os.getenv("KRONICK_SESSION_SECRET", ""), ).encode("utf-8") EXTERNAL_STREAM_TTL_SECONDS = max( 60, int(os.getenv("EXTERNAL_STREAM_TTL_MINUTES", "360")) * 60, ) FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe") init_db() initialize_account_database() init_iptv_db() init_music_db() init_cache_jobs_db() start_cache_worker() start_music_reconciler() init_music_import_jobs() start_music_import_worker() init_twitch_db() start_twitch_watcher() start_recording_scheduler() start_cast_service() THUMBNAIL_FAILURE_LOCK = threading.Lock() THUMBNAIL_FAILURES = {} def _thumbnail_fingerprint(path): try: stat = Path(path).stat() return (int(stat.st_size), int(stat.st_mtime_ns)) except OSError: return None SCAN_LOCK = threading.Lock() SCAN_STATE = {"running": False, "started_at": None, "completed_at": None, "selected_source_ids": [], "libraries": {}} def get_scan_state(): with SCAN_LOCK: return json.loads(json.dumps(SCAN_STATE)) def update_scan_library(source_id, **values): source_id = str(source_id) with SCAN_LOCK: SCAN_STATE["libraries"].setdefault(source_id, {}).update(values) YOUTUBE_LOCK = threading.Lock() YOUTUBE_STATE = { "running": False, "phase": "idle", "source_id": None, "source_name": None, "mode": None, "started_at": None, "completed_at": None, "total": 0, "processed": 0, "percent": 0, "found": 0, "skipped": 0, "errors": 0, "current_item": "", "results": [], "message": "", } def get_youtube_state(): with YOUTUBE_LOCK: return json.loads(json.dumps(YOUTUBE_STATE)) def update_youtube_state(**values): with YOUTUBE_LOCK: YOUTUBE_STATE.update(values) def youtube_preview_worker(source_id, force_refresh=False): source = next((s for s in get_media_sources() if s["id"] == source_id), None) media_items = get_sorted_media(source_id) update_youtube_state( running=True, phase="preview", source_id=source_id, source_name=source["name"] if source else str(source_id), mode=None, started_at=time.time(), completed_at=None, total=len(media_items), processed=0, percent=0, found=0, skipped=0, errors=0, current_item="", results=[], message="Reading YouTube IDs and metadata...", ) results = [] found = skipped = errors = 0 try: for index, media in enumerate(media_items, start=1): path = Path(media.get("current_path") or media.get("original_path") or "") current_filename = path.name update_youtube_state(current_item=current_filename) video_id = extract_youtube_id(current_filename) if not video_id: skipped += 1 processed = index update_youtube_state( processed=processed, percent=int(processed * 100 / max(1, len(media_items))), skipped=skipped, ) continue try: metadata = None if force_refresh else get_youtube_metadata_cache(video_id) cached = metadata is not None if metadata is None: metadata = fetch_youtube_metadata(video_id) save_youtube_metadata_cache( video_id, metadata["title"], metadata.get("channel_name"), metadata.get("channel_url"), ) proposed_filename = build_youtube_filename( metadata["title"], video_id, path.suffix, ) current_title = media.get("effective_title") or media.get("title") or "" result = { "media_id": media["id"], "video_id": video_id, "current_title": current_title, "proposed_title": metadata["title"], "channel_name": metadata.get("channel_name"), "channel_url": metadata.get("channel_url"), "current_filename": current_filename, "proposed_filename": proposed_filename, "title_changed": current_title != metadata["title"], "filename_changed": current_filename != proposed_filename, "cached": cached, "status": "ready", "error": None, } results.append(result) found += 1 except Exception as exc: results.append({ "media_id": media["id"], "video_id": video_id, "current_title": media.get("effective_title") or media.get("title") or "", "current_filename": current_filename, "status": "error", "error": str(exc), }) errors += 1 processed = index update_youtube_state( processed=processed, percent=int(processed * 100 / max(1, len(media_items))), found=found, skipped=skipped, errors=errors, results=results, ) update_youtube_state( running=False, phase="preview_complete", completed_at=time.time(), processed=len(media_items), percent=100, found=found, skipped=skipped, errors=errors, current_item="", results=results, message=f"Preview complete: {found} YouTube items found, {skipped} without a video ID, {errors} errors.", ) except Exception as exc: update_youtube_state( running=False, phase="error", completed_at=time.time(), current_item="", message=str(exc), ) def youtube_apply_worker(source_id, mode): state = get_youtube_state() results = list(state.get("results") or []) source_name = state.get("source_name") update_youtube_state( running=True, phase="apply", source_id=source_id, source_name=source_name, mode=mode, started_at=time.time(), completed_at=None, total=len(results), processed=0, percent=0, errors=0, current_item="", message="Applying YouTube metadata...", ) applied = 0 errors = 0 applied_results = [] try: for index, preview in enumerate(results, start=1): item = dict(preview) update_youtube_state(current_item=item.get("current_filename", "")) if item.get("status") != "ready": applied_results.append(item) processed = index update_youtube_state( processed=processed, percent=int(processed * 100 / max(1, len(results))), errors=errors, results=applied_results + results[index:], ) continue try: media = get_media_by_id(item["media_id"]) if not media or media.get("source_id") != source_id: raise ValueError("Media is no longer in the selected library") title = item["proposed_title"] current_path = Path(media.get("current_path") or media.get("original_path")).resolve() if mode == "rename": if not current_path.is_file(): raise FileNotFoundError(current_path) target_path = current_path.with_name( build_youtube_filename(title, item["video_id"], current_path.suffix) ) if target_path != current_path: if target_path.exists(): raise FileExistsError(f"Destination already exists: {target_path.name}") current_path.rename(target_path) try: update_media_after_youtube_rename(item["media_id"], title, target_path) except Exception: try: target_path.rename(current_path) except Exception: pass raise item["applied_filename"] = target_path.name else: set_media_title_override(item["media_id"], title) item["applied_filename"] = current_path.name else: set_media_title_override(item["media_id"], title) item["apply_status"] = "applied" item["error"] = None applied += 1 except Exception as exc: item["apply_status"] = "error" item["error"] = str(exc) errors += 1 applied_results.append(item) processed = index update_youtube_state( processed=processed, percent=int(processed * 100 / max(1, len(results))), errors=errors, results=applied_results + results[index:], ) update_youtube_state( running=False, phase="apply_complete", completed_at=time.time(), processed=len(results), percent=100, errors=errors, current_item="", results=applied_results, message=f"Applied YouTube metadata to {applied} items with {errors} errors.", ) except Exception as exc: update_youtube_state( running=False, phase="error", completed_at=time.time(), current_item="", message=str(exc), ) def _probe_fields(path): probe = probe_media(path) return { "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, } def scan_worker(selected_source_ids=None, scan_mode="quick"): from mediainfo import list_media_files scan_mode = "deep" if str(scan_mode).lower() == "deep" else "quick" deep = scan_mode == "deep" all_sources = get_media_sources(enabled_only=True) if selected_source_ids is None: sources = all_sources else: selected = {int(x) for x in selected_source_ids} sources = [x for x in all_sources if x["id"] in selected] with SCAN_LOCK: SCAN_STATE.update({ "running": True, "started_at": time.time(), "completed_at": None, "selected_source_ids": [x["id"] for x in sources], "mode": scan_mode, "libraries": {}, }) existing_all = get_sorted_media() existing_by_path = {} existing_by_source = {} for existing in existing_all: p = existing.get("current_path") or existing.get("original_path") if p: try: existing_by_path[str(Path(p).resolve())] = existing except Exception: pass existing_by_source.setdefault(existing.get("source_id"), []).append(existing) try: for source in sources: source_id = source["id"] update_scan_library(source_id, name=source["name"], status="scanning", stage=f"{scan_mode.title()} scan: discovering files", current_path="", total=0, processed=0, percent=0, mode=scan_mode, new=0, changed=0, unchanged=0, removed=0, errors=0, unavailable_paths=[]) work_items = [] available_roots = [] unavailable_roots = [] seen_paths = set() for source_path in get_media_source_paths(source_id, enabled_only=True): root = Path(source_path["path"]).resolve() update_scan_library(source_id, current_path=str(root)) if not root.is_dir(): unavailable_roots.append(str(root)) print(f"[SCAN] Storage unavailable; preserving index: {root}", flush=True) continue available_roots.append(root) try: files = list_media_files(root) except Exception as exc: unavailable_roots.append(str(root)) print(f"[SCAN] Failed {root}; preserving index: {exc}", flush=True) continue for media_file in files: path = Path(media_file).resolve() canonical = str(path) seen_paths.add(canonical) work_items.append({"file": path, "root": root, "source_path_id": source_path["id"]}) total = len(work_items) update_scan_library(source_id, total=total, unavailable_paths=unavailable_roots, stage=f"{scan_mode.title()} scan: checking media") counters = {"new":0, "changed":0, "unchanged":0, "removed":0, "errors":0} for index, work in enumerate(work_items, 1): path, root = work["file"], work["root"] source_path_id = work["source_path_id"] canonical = str(path) existing = existing_by_path.get(canonical) needs_probe = media_needs_probe(existing, path, deep=deep) try: if not needs_probe and existing: counters["unchanged"] += 1 touch_media_scan_state(existing["id"], source_id=source_id, source_path_id=source_path_id, relative_path=str(path.relative_to(root)), current_path=canonical) else: update_scan_library(source_id, stage="Deep probing" if deep else "Probing new/changed media", current_path=canonical) item = inspect_media_file(path) item.update(_probe_fields(path)) item = apply_sidecar_to_item(item, path) if item.get("is_short_media"): remove_media_index_by_current_path(path) else: item["original_path"] = existing["original_path"] if existing else canonical item["current_path"] = canonical item["source_id"] = source_id item["source_path_id"] = source_path_id item["relative_path"] = str(path.relative_to(root)) item["sorted_path"] = None update_sorted_media(item) if existing: counters["changed"] += 1 else: counters["new"] += 1 thumb = get_thumbnail_path(item["original_path"]) if (source.get("artwork_preference", "generated_first") == "generated_first" or not item.get("artwork_path")) and (deep or not thumb.is_file()): generate_thumbnail(canonical, key_path=item["original_path"]) refreshed = get_media_by_id(existing["id"]) if existing else None existing_by_path[canonical] = refreshed or item except Exception as exc: counters["errors"] += 1 print(f"[SCAN] {path}: {exc}", flush=True) percent = int(index * 100 / max(1,total)) update_scan_library(source_id, processed=index, total=total, percent=percent, **counters) # Remove stale DB records ONLY for roots that are confirmed online. if available_roots: for existing in existing_by_source.get(source_id, []): ptext = existing.get("current_path") or existing.get("original_path") if not ptext: continue try: ep = Path(ptext).resolve() except Exception: continue belongs_to_online_root = any(ep == root or root in ep.parents for root in available_roots) if belongs_to_online_root and str(ep) not in seen_paths: counters["removed"] += remove_media_index_by_current_path(ep) status = "complete" stage = "Complete" if unavailable_roots: stage = "Complete — some storage unavailable; indexed items preserved" update_scan_library(source_id, status=status, stage=stage, current_path="", processed=total, total=total, percent=100, unavailable_paths=unavailable_roots, **counters) finally: with SCAN_LOCK: SCAN_STATE["running"] = False SCAN_STATE["completed_at"] = time.time() class StreamingHandler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, format_string, *args): if LOG_LEVEL == "DEBUG": super().log_message(format_string, *args) def get_session_token(self): raw_cookie = self.headers.get("Cookie", "") if not raw_cookie: return None cookie = SimpleCookie() try: cookie.load(raw_cookie) except Exception: return None morsel = cookie.get(SESSION_COOKIE) return morsel.value if morsel else None def start_chat_sso(self): """Exchange parent-domain Chat cookie for a host-only Media cookie.""" if not (CHAT_SSO_URL and CHAT_SSO_SECRET): return False raw = SimpleCookie() try: raw.load(self.headers.get("Cookie", "")) except Exception: return False chat_cookie = raw.get("kronick_session") if not chat_cookie: return False payload = json.dumps({"token": chat_cookie.value}).encode("utf-8") req = urllib.request.Request( CHAT_SSO_URL, data=payload, method="POST", headers={"Content-Type": "application/json", "X-Kronick-SSO-Secret": CHAT_SSO_SECRET}, ) try: with urllib.request.urlopen(req, timeout=5) as response: identity = json.load(response) token = create_sso_session(identity) except AccountError as exc: self.send_error(exc.status, exc.detail) return True except urllib.error.HTTPError as exc: # The Chat session is missing, invalid or revoked. if exc.code in (401, 403): return False self.send_error(502, "Chat authentication service returned an error") return True except (urllib.error.URLError, OSError, ValueError) as exc: print("[SSO] Chat authentication unavailable:", type(exc).__name__) self.send_error(502, "Chat authentication service unavailable") return True self.send_response(302) self.send_header("Location", urlparse(self.path).path if urlparse(self.path).path in {"/m", "/m/", "/desktop", "/desktop/"} else "/") self.send_header( "Set-Cookie", f"{SESSION_COOKIE}={token}; Path=/; Max-Age=3600; " "HttpOnly; Secure; SameSite=Lax", ) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", "0") self.end_headers() return True def send_redirect(self, location, status=302): self.send_response(status) self.send_header("Location", location) self.send_header("Cache-Control", "private, no-store") self.send_header("Content-Length", "0") self.end_headers() def send_account_error(self, error): self.send_json({"detail": error.detail, "error": error.detail}, status=error.status) def require_media_session(self): ras.bind_request(self) context = require_media_access(self.get_session_token()) self.check_media_path_access(int(context['user']['id'])) return context def globally_restricted(self, uid): from admin_policies import policies scope=ras.clear() try: return bool(policies(uid)) or not all(allowed_media_libraries(uid).values()) finally: ras.restore(scope) def check_media_path_access(self, user_id): from admin_policies import enforce_source, policies # Deny known library read and playback endpoints. path = urlparse(self.path).path categories = { '/api/music/':'music', '/api/iptv/':'iptv', '/api/youtube/':'tube','/api/cache/':'tube', '/api/twitch/':'twitch','/api/recordings/':'twitch', } for prefix, key in categories.items(): if path.startswith(prefix): enforce_media_library(user_id,key) return if (path.startswith('/api/cast/') or path == '/api/scan/status') and self.globally_restricted(user_id): raise AccountError(403,'Global media controls unavailable for restricted accounts') parts=path.strip('/').split('/') if len(parts)>=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()