import os import sys # Enforce zero shard/chunk disk cache on HuggingFace Xet to prevent 10GB+ cache accumulation os.environ.setdefault("HF_XET_SHARD_CACHE_SIZE_LIMIT", "0") os.environ.setdefault("HF_XET_CHUNK_CACHE_SIZE_BYTES", "0") os.environ.setdefault("HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT", "33554432") os.environ.setdefault("HF_XET_LOG_DIR_MAX_SIZE", "10000000") os.environ.setdefault("HF_HUB_DISABLE_DISK_INTEGRITY_CHECK", "1") import logging import urllib.parse import httpx import time import collections import threading import re import zipfile import shutil import json from typing import Optional, Any from fastapi import FastAPI, HTTPException, Query, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import RedirectResponse, HTMLResponse # Store last 100 log lines in a thread-safe list/deque RECENT_LOGS = collections.deque(maxlen=100) FATAL_ERRORS = collections.deque(maxlen=10) class InMemoryLogHandler(logging.Handler): def emit(self, record): try: log_entry = self.format(record) RECENT_LOGS.append(log_entry) except Exception: self.handleError(record) # Setup logging LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper() # Create handlers stdout_handler = logging.StreamHandler(sys.stdout) file_handler = logging.FileHandler("stream_service.log", encoding="utf-8") log_handler = InMemoryLogHandler() # Set formatters formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s") stdout_handler.setFormatter(formatter) file_handler.setFormatter(formatter) log_handler.setFormatter(formatter) # Configure root logger root_logger = logging.getLogger() root_logger.setLevel(LOG_LEVEL) root_logger.addHandler(stdout_handler) root_logger.addHandler(file_handler) root_logger.addHandler(log_handler) log = logging.getLogger("stream-service") # Config DB_URL = os.environ.get("DB_URL", "") HF_TOKEN = os.environ.get("HFTOKEN") BUCKET_ID = "shashwatIDR/stream" import ipaddress def is_safe_domain_url(url: str) -> bool: """Strict security check: ensures 0 direct IP access. Returns False if target is an IPv4 or IPv6.""" try: hostname = urllib.parse.urlparse(url).hostname or "" if not hostname: return False ipaddress.ip_address(hostname) return False # Target is a raw IP address! Block it. except ValueError: return True # Target is a valid domain name. # Zero Direct IP Access: Invidious queries & streams are routed strictly through Antideploy proxy layer INVIDIOUS_PROXY_URL = os.environ.get("INVIDIOUS_PROXY_URL", "https://noipaccess.antideploy.app").rstrip("/") raw_instances = [inst.strip() for inst in os.environ.get("INVIDIOUS_INSTANCES", "").split(",") if inst.strip()] if not raw_instances: raw_instances = [INVIDIOUS_PROXY_URL] # Filter out any raw IP addresses with zero tolerance INVIDIOUS_INSTANCES = [inst for inst in raw_instances if is_safe_domain_url(inst)] if not INVIDIOUS_INSTANCES: INVIDIOUS_INSTANCES = [INVIDIOUS_PROXY_URL] # Track stats in session STATS = { "total": 0, "done": 0, "progressing": 0, "failed": 0 } STREAM_JOBS = {} # video_id -> {"status": "fetching"|"progressing"|"done"|"failed", "error": str, "timestamp": float} UPLOAD_TIMESTAMPS = collections.deque() NETWORK_STATS = { "last_download_speed_kbps": 0.0, "last_upload_speed_kbps": 0.0, "total_downloaded_mb": 0.0, "total_uploaded_mb": 0.0 } # Base URL cache to avoid redundant database reads BASE_URL_CACHE = {} BASE_URL_CACHE_LOCK = threading.Lock() # In-memory database cache DB_CACHE = {} DB_CACHE_LOCK = threading.Lock() def load_db_cache(): """Load all records from SQL database or fallback HF db_backup.json.""" global DB_CACHE, BASE_URL_CACHE sql_loaded = False try: log.info("Syncing cache from MySQL database on startup...") conn = get_db_connection() with conn.cursor() as cursor: cursor.execute("SELECT id, url FROM base_urls") url_rows = cursor.fetchall() cursor.execute("SELECT id, name, artists, lyrics_sources, canvas_sources, stream_sources FROM songs") song_rows = cursor.fetchall() conn.close() with DB_CACHE_LOCK: DB_CACHE = {row["id"]: row for row in song_rows} with BASE_URL_CACHE_LOCK: BASE_URL_CACHE = {row["id"]: row["url"] for row in url_rows} BASE_URL_CACHE[2] = "https://velamhere-img.hf.space" log.info(f"Successfully synced {len(song_rows)} songs and {len(url_rows)} base URLs from MySQL.") sql_loaded = True except Exception as sql_ex: log.warning(f"Failed to sync from MySQL database: {sql_ex}") if not sql_loaded: try: url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/db_backup.json" headers = {} if HF_TOKEN: headers["Authorization"] = f"Bearer {HF_TOKEN}" log.info(f"Fallback: loading database cache from HF backup ({url})...") with httpx.Client(follow_redirects=True) as client: resp = client.get(url, headers=headers) if resp.status_code == 200: data = resp.json() songs_list = data.get("songs", []) if not songs_list: raise ValueError("HF backup JSON contains 0 songs") has_lyrics_metadata = any("lyrics_sources" in s for s in songs_list) if not has_lyrics_metadata: raise ValueError("HF backup JSON is missing lyrics_sources metadata (old schema)") with DB_CACHE_LOCK: DB_CACHE = {s["id"]: s for s in songs_list} base_urls_list = data.get("base_urls", []) with BASE_URL_CACHE_LOCK: BASE_URL_CACHE = {} for item in base_urls_list: if isinstance(item, dict): BASE_URL_CACHE[int(item["id"])] = item["url"] elif isinstance(item, (list, tuple)) and len(item) >= 2: BASE_URL_CACHE[int(item[0])] = item[1] BASE_URL_CACHE[2] = "https://velamhere-img.hf.space" log.info(f"Successfully loaded {len(DB_CACHE)} songs and {len(BASE_URL_CACHE)} base URLs from HF backup JSON.") else: log.warning(f"HF backup JSON not found (HTTP {resp.status_code}).") except Exception as e: log.error(f"Failed to load cache from HF backup fallback: {e}") # Regular expression to mask URLs URL_PATTERN = re.compile(r'https?://[^\s]+') def mask_urls(text: str) -> str: return URL_PATTERN.sub('[URL]', text) def get_avg_uploads_per_min() -> float: now = time.time() while UPLOAD_TIMESTAMPS and UPLOAD_TIMESTAMPS[0] < now - 120: UPLOAD_TIMESTAMPS.popleft() return len(UPLOAD_TIMESTAMPS) / 2.0 def get_ssl_config(): ca_paths = [ "/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/cert.pem", "/usr/local/etc/openssl/cert.pem", "/etc/pki/tls/certs/ca-bundle.crt", ] for path in ca_paths: if os.path.exists(path): return {"ca": path, "check_hostname": True} return {"check_hostname": True} def get_db_connection(): parsed = urllib.parse.urlparse(DB_URL) host = parsed.hostname port = parsed.port or 4000 user = parsed.username password = parsed.password db = parsed.path.lstrip('/') ssl_config = get_ssl_config() return pymysql.connect( host=host, port=port, user=user, password=password, database=db, ssl=ssl_config, cursorclass=pymysql.cursors.DictCursor ) def get_base_url(url_id: int) -> str: """Fetch base URL from cached storage or database lookup.""" with BASE_URL_CACHE_LOCK: if url_id in BASE_URL_CACHE: return BASE_URL_CACHE[url_id] try: conn = get_db_connection() with conn.cursor() as cursor: cursor.execute("SELECT url FROM base_urls WHERE id = %s", (url_id,)) row = cursor.fetchone() conn.close() if row: url = row["url"] with BASE_URL_CACHE_LOCK: BASE_URL_CACHE[url_id] = url return url except Exception as e: log.error(f"Failed to fetch base url for ID {url_id}: {e}") return "" def load_db_stats(): """Load stats from DB cache to know how many streams are already done and total songs.""" try: with DB_CACHE_LOCK: total_count = len(DB_CACHE) done_count = sum(1 for song in DB_CACHE.values() if song.get("stream_sources")) STATS["done"] = done_count STATS["total"] = total_count log.info(f"Loaded DB stats from cache: Total Songs = {total_count}, Cached Streams = {done_count}") except Exception as e: log.error(f"Failed to load DB stats: {e}") def init_db(): """Ensure the songs and base_urls tables exist, run migrations, and seed default URLs.""" try: conn = get_db_connection() with conn.cursor() as cursor: # 1. Create base_urls table cursor.execute(""" CREATE TABLE IF NOT EXISTS base_urls ( id INT AUTO_INCREMENT PRIMARY KEY, url VARCHAR(500) UNIQUE NOT NULL ) """) conn.commit() # 2. Seed default base_urls cursor.execute(""" INSERT INTO base_urls (id, url) VALUES (1, 'https://huggingface.co/buckets/allnewuser/lyrics/resolve'), (2, 'https://velamhere-img.hf.space'), (3, 'https://velamhere-img.hf.space/song'), (4, 'https://huggingface.co/buckets/shashwatIDR/lossless/resolve') ON DUPLICATE KEY UPDATE url = VALUES(url) """) conn.commit() # 3. Create songs table if not exists cursor.execute(""" CREATE TABLE IF NOT EXISTS songs ( id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), artists VARCHAR(500), lyrics_sources VARCHAR(50), canvas_sources VARCHAR(50), stream_sources VARCHAR(50), lossless VARCHAR(50) ) """) conn.commit() # Add stream_sources column if it does not exist cursor.execute("SHOW COLUMNS FROM songs LIKE 'stream_sources'") if not cursor.fetchone(): cursor.execute("ALTER TABLE songs ADD COLUMN stream_sources VARCHAR(50)") conn.commit() cursor.execute("SHOW COLUMNS FROM songs LIKE 'lossless'") if not cursor.fetchone(): cursor.execute("ALTER TABLE songs ADD COLUMN lossless VARCHAR(50)") conn.commit() log.info("Added lossless column to songs table.") else: log.info("Database schema verified.") conn.close() # Load database cache and stats load_db_cache() load_db_stats() except Exception as e: log.error(f"Database initialization failed: {e}") DB_BACKUP_INTERVAL = int(os.environ.get("DB_BACKUP_INTERVAL", "180")) def db_backup_loop(): log.info(f"Starting database backup daemon thread (interval: {DB_BACKUP_INTERVAL}s, dirty-checked)...") while True: try: time.sleep(DB_BACKUP_INTERVAL) try: import db_service if not getattr(db_service, "DB_CACHE_DIRTY", True): continue except Exception: pass # Read from memory cache instead of DB with DB_CACHE_LOCK: songs = list(DB_CACHE.values()) # SAFEGUARD: Never overwrite backup with empty data (prevents clearing backup if DB is down) if not songs: log.warning("DB backup skipped: DB_CACHE is empty. Refusing to overwrite db_backup.json.") continue with BASE_URL_CACHE_LOCK: base_urls = [{"id": k, "url": v} for k, v in BASE_URL_CACHE.items()] try: conn = get_db_connection() with conn.cursor() as cursor: cursor.execute("SELECT * FROM base_urls") db_base_urls = cursor.fetchall() if db_base_urls: base_urls = db_base_urls conn.close() except Exception as conn_err: log.warning(f"Database connection unavailable during backup, using in-memory base_urls: {conn_err}") backup_data = { "songs": songs, "base_urls": base_urls } json_bytes = json.dumps(backup_data, default=str, separators=(',', ':')).encode('utf-8') from db_service import safe_batch_bucket_files safe_batch_bucket_files( BUCKET_ID, add=[(json_bytes, "db_backup.json")], token=HF_TOKEN ) del json_bytes try: import db_service db_service.cleanup_upload_cache() db_service.DB_CACHE_DIRTY = False except Exception: pass log.info(f"Database backup ({len(songs)} songs) successfully uploaded to Hugging Face (db_backup.json).") except Exception as e: log.error(f"Failed to backup database to Hugging Face: {e}") # Initialize FastAPI App app = FastAPI(title="Muzo Stream Service", version="1.0.0") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") def startup_event(): init_db() # Start database backup loop in a separate daemon thread backup_thread = threading.Thread(target=db_backup_loop, daemon=True) backup_thread.start() def trigger_startup_sync(): log.info("Automatic startup sync disabled by configuration.") def db_get_song_stream(video_id: str) -> Optional[dict]: with DB_CACHE_LOCK: return DB_CACHE.get(video_id) def fetch_correct_metadata(video_id: str) -> tuple[str, str]: """Fetch track metadata (title, artist) using upstream metadata service API.""" worker_api = os.environ.get("METADATA_API_BASE", os.environ.get("WORKER_API_BASE", "https://beautiful-junie-scoder-53c5187c.koyeb.app")) url = f"{worker_api.rstrip('/')}/?id={video_id}" try: with httpx.Client(timeout=15.0, follow_redirects=True) as client: resp = client.get(url) if resp.status_code == 200: data = resp.json() matched = data.get("matched_track", {}) yt = data.get("ytmusic", {}) title = matched.get("title") or yt.get("title") or "" artist = matched.get("artist") or yt.get("artist") or "" if title: return title.strip(), artist.strip() except Exception as e: log.warning(f"Metadata API fetch failed for {video_id}: {e}") return "Unknown Song", "Unknown Artist" def db_save_stream_source(video_id: str, value: str = "m4a"): # Determine metadata from memory cache name = "" artists = "" with DB_CACHE_LOCK: existing = DB_CACHE.get(video_id) if existing: name = existing.get("name") or "" artists = existing.get("artists") or "" # Only fetch metadata if it is missing or invalid if not name or name == "Unknown Song" or not artists: name, artists = fetch_correct_metadata(video_id) # Update in-memory cache first with DB_CACHE_LOCK: if video_id in DB_CACHE: DB_CACHE[video_id]["stream_sources"] = value if name and name != "Unknown Song": DB_CACHE[video_id]["name"] = name if artists and artists != "Unknown Artist": DB_CACHE[video_id]["artists"] = artists else: DB_CACHE[video_id] = { "id": video_id, "name": name, "artists": artists, "stream_sources": value } try: # Update DB conn = get_db_connection() with conn.cursor() as cursor: # Query for existing metadata cursor.execute("SELECT id FROM songs WHERE id = %s", (video_id,)) row = cursor.fetchone() if row: cursor.execute(""" UPDATE songs SET name = %s, artists = %s, stream_sources = %s WHERE id = %s """, (name, artists, value, video_id)) else: cursor.execute(""" INSERT INTO songs (id, name, artists, stream_sources) VALUES (%s, %s, %s, %s) """, (video_id, name, artists, value)) conn.commit() conn.close() log.info(f"Updated stream_sources to {value} for {video_id}") except Exception as e: log.error(f"Failed to save stream source to DB for {video_id} (preserved in memory cache): {e}") # -------------------------------------------------------------------------- # Automatic Cache Clearance Logic # -------------------------------------------------------------------------- def check_and_clear_cache(): """Check if Hugging Face bucket streams size exceeds 20 GB, and if so, purge all streams and clear DB references.""" return def download_and_upload_loop(video_id: str) -> Optional[str]: """Loop through Invidious instances, fetch stream metadata, download (30s timeout), and upload to HF.""" STREAM_JOBS[video_id] = {"status": "progressing", "timestamp": time.time()} STATS["progressing"] = sum(1 for j in STREAM_JOBS.values() if j["status"] in ["fetching", "progressing"]) for instance in INVIDIOUS_INSTANCES: try: log.info(f"Attempting download/upload for {video_id} using {instance}") # Fetch metadata and download audio in one HTTP client context with 60s timeout with httpx.Client(timeout=30.0) as client: url = f"{instance.rstrip('/')}/api/v1/videos/{video_id}" if not is_safe_domain_url(url): log.error(f"SECURITY: Blocked attempt to contact direct IP: {url}") continue resp = client.get(url) if resp.status_code != 200: log.warning(f"Invidious API call to {instance} failed: HTTP {resp.status_code}") continue try: data = resp.json() except ValueError: log.warning(f"Failed to decode Invidious API JSON from {instance} for {video_id}") continue formats = data.get("adaptiveFormats", []) # Filter and prioritize m4a formats m4a_formats = [ f for f in formats if f.get("type", "").startswith("audio/") and ("mp4" in f.get("type", "") or f.get("container") == "m4a") ] if m4a_formats: m4a_formats.sort(key=lambda x: int(x.get("bitrate") or 0), reverse=True) selected_format = m4a_formats[0] else: other_formats = [f for f in formats if f.get("type", "").startswith("audio/")] if other_formats: other_formats.sort(key=lambda x: int(x.get("bitrate") or 0), reverse=True) selected_format = other_formats[0] else: selected_format = None if not selected_format: log.warning(f"No audio formats found on Invidious instance {instance}") continue original_url = selected_format.get("url") container = selected_format.get("container") if not container: mime_type = selected_format.get("type", "") container = "webm" if "webm" in mime_type else "m4a" ext = container or "m4a" # Reconstruct proxied URL using the same instance parsed = urllib.parse.urlparse(original_url) original_host = parsed.netloc proxied_url = f"{instance.rstrip('/')}/videoplayback?{parsed.query}&host={original_host}" if not is_safe_domain_url(proxied_url): log.error(f"SECURITY: Blocked attempt to stream from direct IP: {proxied_url}") continue t0 = time.time() log.info(f"Downloading stream via proxy {instance}...") stream_resp = client.get(proxied_url) if stream_resp.status_code != 200: log.warning(f"Stream download failed from proxy {instance}: HTTP {stream_resp.status_code}. Trying direct /stream endpoint...") stream_resp = client.get(f"{instance.rstrip('/')}/stream/{video_id}") if stream_resp.status_code != 200: continue if stream_resp.headers.get("x-audio-extension"): ext = stream_resp.headers.get("x-audio-extension") audio_bytes = stream_resp.content t1 = time.time() dl_duration = t1 - t0 if dl_duration > 0: dl_speed = len(audio_bytes) / dl_duration / 1024.0 NETWORK_STATS["last_download_speed_kbps"] = dl_speed NETWORK_STATS["total_downloaded_mb"] += len(audio_bytes) / (1024.0 * 1024.0) # Upload to HF log.info(f"Uploading {len(audio_bytes)} bytes to HF bucket for {video_id}.{ext}") t0 = time.time() from db_service import safe_batch_bucket_files safe_batch_bucket_files( BUCKET_ID, add=[(audio_bytes, f"{video_id}.{ext}")], token=HF_TOKEN ) t1 = time.time() ul_duration = t1 - t0 if ul_duration > 0: ul_speed = len(audio_bytes) / ul_duration / 1024.0 NETWORK_STATS["last_upload_speed_kbps"] = ul_speed NETWORK_STATS["total_uploaded_mb"] += len(audio_bytes) / (1024.0 * 1024.0) # Update DB with ext db_save_stream_source(video_id, ext) STREAM_JOBS[video_id] = {"status": "done", "timestamp": time.time()} STATS["done"] += 1 UPLOAD_TIMESTAMPS.append(time.time()) log.info(f"Stream upload successfully completed for {video_id}.{ext} using {instance}") # Post-upload check for cache limits check_and_clear_cache() return ext except Exception as e: log.warning(f"Exception using instance {instance} for {video_id}: {e}") if not isinstance(e, (httpx.HTTPError, httpx.NetworkError, httpx.TimeoutException, ValueError, KeyError)): err_msg = f"{type(e).__name__} during sync for {video_id}: {str(e)}" if err_msg not in FATAL_ERRORS: FATAL_ERRORS.append(err_msg) continue # All instances failed - Try ultimate fallback log.info(f"All Invidious instances failed. Attempting ultimate fallback for {video_id}...") try: fallback_url = f"https://effective-disco-3nfb.onrender.com/api/stream/{video_id}" with httpx.Client(timeout=60.0, follow_redirects=True) as client: t0 = time.time() resp = client.get(fallback_url) if resp.status_code == 200: audio_bytes = resp.content t1 = time.time() dl_duration = t1 - t0 if dl_duration > 0: dl_speed = len(audio_bytes) / dl_duration / 1024.0 NETWORK_STATS["last_download_speed_kbps"] = dl_speed NETWORK_STATS["total_downloaded_mb"] += len(audio_bytes) / (1024.0 * 1024.0) ext = "m4a" # default to m4a content_type = resp.headers.get("content-type", "") if "webm" in content_type: ext = "webm" elif "mp3" in content_type: ext = "mp3" log.info(f"Uploading fallback {len(audio_bytes)} bytes to HF bucket for {video_id}.{ext}") t0_up = time.time() from db_service import safe_batch_bucket_files safe_batch_bucket_files( BUCKET_ID, add=[(audio_bytes, f"{video_id}.{ext}")], token=HF_TOKEN ) t1_up = time.time() ul_duration = t1_up - t0_up if ul_duration > 0: ul_speed = len(audio_bytes) / ul_duration / 1024.0 NETWORK_STATS["last_upload_speed_kbps"] = ul_speed NETWORK_STATS["total_uploaded_mb"] += len(audio_bytes) / (1024.0 * 1024.0) db_save_stream_source(video_id, ext) STREAM_JOBS[video_id] = {"status": "done", "timestamp": time.time()} STATS["done"] += 1 UPLOAD_TIMESTAMPS.append(time.time()) log.info(f"Stream upload successfully completed for {video_id}.{ext} via ultimate fallback") return ext except Exception as fallback_ex: log.error(f"Ultimate fallback failed for {video_id}: {fallback_ex}") STREAM_JOBS[video_id] = {"status": "failed", "error": "All Invidious instances and ultimate fallback failed", "timestamp": time.time()} STATS["failed"] += 1 STATS["progressing"] = sum(1 for j in STREAM_JOBS.values() if j["status"] in ["fetching", "progressing"]) return None @app.get("/api/stream") async def get_stream(id: str = Query(..., description="YouTube videoId"), background_tasks: BackgroundTasks = None): # 1. Check if stream is already cached row = db_get_song_stream(id) name = "" artists = "" lossless_val = None if row: name = row.get("name") or "" artists = row.get("artists") or "" stream_src = row.get("stream_sources") or "" lossless_src = row.get("lossless") or "" if lossless_src: lossless_val = f"https://huggingface.co/buckets/shashwatIDR/lossless/resolve/{id}.flac" else: # Enqueue background lossless processing if not already present lossless_val = "processing in lossless" try: from queue_manager import trigger_lossless_backup if background_tasks: background_tasks.add_task(trigger_lossless_backup) except Exception: pass if stream_src: cached_url = f"https://velamhere-img.hf.space/song/{id}" log.info(f"Cache hit: returning stream URL for {id}") return {"id": id, "name": name, "artist": artists, "url": cached_url, "lossless": lossless_val} else: # Increment total count as this song ID is new to the DB STATS["total"] += 1 # 2. Cache miss: download and upload using the retry loop ext = download_and_upload_loop(id) if not ext: raise HTTPException(status_code=502, detail="Failed to fetch and cache stream from all Invidious instances") cached_url = f"https://velamhere-img.hf.space/song/{id}" row = db_get_song_stream(id) or {} lossless_src = row.get("lossless") or "" if lossless_src: lossless_val = f"https://huggingface.co/buckets/shashwatIDR/lossless/resolve/{id}.flac" else: lossless_val = "processing in lossless" log.info(f"Cache miss resolved: returning stream URL for {id}") return {"id": id, "name": name, "artist": artists, "url": cached_url, "lossless": lossless_val} def bulk_sync_worker(song_ids): from concurrent.futures import ThreadPoolExecutor log.info(f"Bulk sync worker started for {len(song_ids)} songs with 100 parallel threads") def sync_single_song(song_id): try: # Check if already processed while waiting row = db_get_song_stream(song_id) if row: stream_src = row.get("stream_sources") or "" if stream_src: return log.info(f"Syncing stream for {song_id}") download_and_upload_loop(song_id) except Exception as e: log.error(f"Error syncing {song_id}: {e}") with ThreadPoolExecutor(max_workers=50) as executor: executor.map(sync_single_song, song_ids) log.info("Bulk sync worker completed.") @app.post("/api/stream/sync") def sync_streams(background_tasks: BackgroundTasks): """Scan all songs in DB and cache streams for those that don't have it yet.""" try: with DB_CACHE_LOCK: song_ids = [song_id for song_id, song in DB_CACHE.items() if not song.get("stream_sources")] log.info(f"Sync triggered: found {len(song_ids)} songs to cache.") if song_ids: background_tasks.add_task(bulk_sync_worker, song_ids) return {"message": f"Sync started in background for {len(song_ids)} songs."} except Exception as e: log.error(f"Sync failed to start: {e}") raise HTTPException(status_code=502, detail=str(e)) @app.post("/api/lossless/sync") def sync_lossless_backup(background_tasks: BackgroundTasks): """Trigger background bulk sync for all songs missing lossless audio.""" try: from queue_manager import trigger_lossless_backup count = trigger_lossless_backup() return {"message": f"Lossless bulk backup started: queued {count} songs missing lossless audio."} except Exception as e: log.error(f"Lossless sync failed to start: {e}") raise HTTPException(status_code=500, detail=str(e)) # Internet Archive endpoints removed @app.get("/api/stats") def get_stats(): total, lyrics, canvas, stream, lossless_count = 0, 0, 0, 0, 0 try: with DB_CACHE_LOCK: total = len(DB_CACHE) for song in DB_CACHE.values(): if song.get("lyrics_sources"): lyrics += 1 if song.get("canvas_sources"): canvas += 1 if song.get("stream_sources"): stream += 1 lossless_val = str(song.get("lossless") or "").strip() if lossless_val and lossless_val != "0": lossless_count += 1 except Exception as e: log.error(f"Failed to calculate stats from cache: {e}") try: from queue_manager import LOSSLESS_STATS except ImportError: LOSSLESS_STATS = {"queued": 0, "progressing": 0, "done": 0, "failed": 0} return { "total": total, "lyrics": lyrics, "canvas": canvas, "stream": stream, "lossless": lossless_count, "lossless_stats": LOSSLESS_STATS, "stats": STATS, "avg_uploads_per_min": get_avg_uploads_per_min(), "network_stats": NETWORK_STATS, "fatal_errors": list(FATAL_ERRORS), "jobs": {jid: {"status": job["status"], "timestamp": job["timestamp"]} for jid, job in STREAM_JOBS.items()}, "logs": [mask_urls(line) for line in RECENT_LOGS] } @app.get("/api/search") def search_songs(q: Optional[str] = None, limit: int = 12): try: results = [] q_lower = q.lower() if q else None with DB_CACHE_LOCK: songs = list(DB_CACHE.values()) if q_lower: for s in songs: s_id = s.get("id") or "" s_name = s.get("name") or "" s_artists = s.get("artists") or "" if (q_lower in s_id.lower() or q_lower in s_name.lower() or q_lower in s_artists.lower()): results.append(s) if len(results) >= limit: break else: # Return last N songs results = songs[-limit:] results.reverse() return results except Exception as e: log.error(f"Search failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/lyrics/{video_id}") async def get_lyrics(video_id: str): try: with DB_CACHE_LOCK: row = DB_CACHE.get(video_id) if not row or not row.get("lyrics_sources"): raise HTTPException(status_code=404, detail="No cached lyrics for this videoId in fallback DB") lyrics_src = row["lyrics_sources"] url_id = 1 ext = "json" if ":" in lyrics_src: parts = lyrics_src.split(":") try: url_id = int(parts[0]) except ValueError: url_id = 1 if len(parts) > 1: ext = parts[1] with BASE_URL_CACHE_LOCK: url_base = BASE_URL_CACHE.get(url_id) if url_base: target_url = f"{url_base}/{video_id}.{ext}" else: target_url = f"https://huggingface.co/buckets/allnewuser/lyrics/resolve/{video_id}.{ext}" headers = {} if HF_TOKEN: headers["Authorization"] = f"Bearer {HF_TOKEN}" async with httpx.AsyncClient(follow_redirects=True) as client: resp = await client.get(target_url, headers=headers) if resp.status_code != 200: raise HTTPException(status_code=resp.status_code, detail="Failed to fetch lyrics from Hugging Face bucket/IA") try: return resp.json() except Exception: return HTMLResponse(content=resp.text, media_type="application/json") except HTTPException: raise except Exception as e: log.error(f"Lyrics fetch failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/canvas") def get_canvas(id: str): try: with DB_CACHE_LOCK: row = DB_CACHE.get(id) if not row or not row.get("canvas_sources"): raise HTTPException(status_code=404, detail="No cached canvas for this id in fallback DB") with BASE_URL_CACHE_LOCK: url_base = BASE_URL_CACHE.get(2) if not url_base or "huggingface.co/buckets" in str(url_base): url_base = "https://velamhere-img.hf.space" stream_url = f"{url_base}/{id}" return { "id": id, "name": row["name"], "artist": row["artists"], "url": stream_url } except HTTPException: raise except Exception as e: log.error(f"Canvas fetch failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/canvas/stream/{video_id}") def stream_canvas(video_id: str): try: with BASE_URL_CACHE_LOCK: url_base = BASE_URL_CACHE.get(2) if not url_base or "huggingface.co/buckets" in str(url_base): url_base = "https://velamhere-img.hf.space" redirect_url = f"{url_base}/{video_id}" return RedirectResponse(url=redirect_url, status_code=307) except Exception as e: log.error(f"Canvas stream redirect failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/stream/listen/{video_id}") def listen_stream(video_id: str): try: row = db_get_song_stream(video_id) url_id = 3 ext = None if row and row.get("stream_sources"): stream_src = row["stream_sources"] if ":" in stream_src: parts = stream_src.split(":") try: url_id = int(parts[0]) except ValueError: url_id = 3 if len(parts) > 1: ext = parts[1] else: ext = stream_src # If not cached yet, download and upload it first if not ext: log.info(f"Stream miss in listen_stream for {video_id}, downloading and uploading...") ext = download_and_upload_loop(video_id) if not ext: raise HTTPException(status_code=502, detail="Failed to fetch and cache stream") with BASE_URL_CACHE_LOCK: url_base = BASE_URL_CACHE.get(url_id) if url_base: redirect_url = f"{url_base}/{video_id}" else: redirect_url = f"https://velamhere-img.hf.space/song/{video_id}" return RedirectResponse(url=redirect_url, status_code=307) except HTTPException: raise except Exception as e: log.error(f"Stream listen redirect failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.api_route("/api/stream/add", methods=["GET", "POST"]) def add_stream_to_queue(id: str = Query(..., description="YouTube videoId or comma-separated videoIds"), background_tasks: BackgroundTasks = None): """Add video ID(s) to the stream processing queue (in-memory execution). Accepts comma-separated IDs.""" try: raw_ids = [v.strip() for v in id.split(",") if v.strip()] if not raw_ids: raise HTTPException(status_code=400, detail="No valid IDs provided") cached_ids = [] queued_ids = [] for vid in raw_ids: row = db_get_song_stream(vid) if row and row.get("stream_sources"): cached_ids.append(vid) else: queued_ids.append(vid) if background_tasks: background_tasks.add_task(download_and_upload_loop, vid) else: thread = threading.Thread(target=download_and_upload_loop, args=(vid,), daemon=True) thread.start() return { "message": f"Processed {len(raw_ids)} ID(s). {len(queued_ids)} queued, {len(cached_ids)} already cached.", "queued": queued_ids, "cached": cached_ids } except HTTPException: raise except Exception as e: log.error(f"Failed to add streams to queue: {e}") @app.get("/status") @app.get("/api/status") def get_service_status(): lossless_count = 0 m4a_count = 0 try: with DB_CACHE_LOCK: for song in DB_CACHE.values(): lossless_val = str(song.get("lossless") or "").strip() if lossless_val and lossless_val != "0": lossless_count += 1 stream_src = str(song.get("stream_sources") or "").strip().lower() if stream_src: ext = stream_src.split(":")[-1] if ":" in stream_src else stream_src if ext == "m4a": m4a_count += 1 except Exception as e: log.error(f"Failed to calculate status stats: {e}") try: from queue_manager import TASK_QUEUE, LOSSLESS_TASK_QUEUE, QUEUED_SET, LOSSLESS_QUEUED_SET, QUEUED_SET_LOCK, LOSSLESS_QUEUED_LOCK with QUEUED_SET_LOCK: stream_queued_ids = set(QUEUED_SET) with LOSSLESS_QUEUED_LOCK: lossless_queued_ids = set(LOSSLESS_QUEUED_SET) combined_queued = len(stream_queued_ids | lossless_queued_ids) sq_size = TASK_QUEUE.qsize() lq_size = LOSSLESS_TASK_QUEUE.qsize() except Exception: combined_queued = STATS.get("progressing", 0) sq_size = 0 lq_size = 0 return { "status": "online", "lossless": lossless_count, "m4a": m4a_count, "in_queue": combined_queued, "queue_details": { "stream_queue": sq_size, "lossless_queue": lq_size, "total_combined_queued": combined_queued } } @app.get("/admin", response_class=HTMLResponse) def get_admin_page(): try: import admin return HTMLResponse(content=admin.get_admin_html()) except Exception: import sys, os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import admin return HTMLResponse(content=admin.get_admin_html()) @app.get("/", response_class=HTMLResponse) def dashboard(): html_content = r"""
Fallback cache · synced lyrics & canvas loops