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 = ( "
" "{html_escape(error.detail)}
" "Contact your administrator.
" "" "" ).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('