Spaces:
Paused
Paused
Download app.py from amri12310/sys-b-addon: direct link, hf CLI and curl.
- Browser
- Download file 33.6 kB
-
https://huggingface.co/spaces/amri12310/sys-b-addon/resolve/main/app.py
- Command line
-
hf download hf://spaces/amri12310/sys-b-addon/app.py
-
curl -L -o app.py https://huggingface.co/spaces/amri12310/sys-b-addon/resolve/main/app.py
33.6 kB
| import os, requests, urllib.parse, threading, re, time | |
| import concurrent.futures | |
| from flask import Flask, request, jsonify, redirect | |
| from huggingface_hub import HfApi, CommitOperationDelete | |
| app = Flask(__name__) | |
| api = HfApi() | |
| # --- CONFIG (ORCHESTRATOR) --- | |
| REPO_ID = "amri12310/hf-vault-99281-xk9-p02-mlq8-r4x-v9928-zb-v2-alpha-sync" | |
| SYS_B_URL = "https://amri12310-sys-b-engine.hf.space" | |
| SYS_C_URL = "https://amri123510-sys-c-engine.hf.space" | |
| SYS_D_URL = "https://amri123410-sys-d-engine.hf.space" | |
| SYS_E_URL = "https://amri123410-sys-e-engine.hf.space" | |
| ADDON_DOMAIN = "https://amri12310-sys-b-addon.hf.space" | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| GH_TOKEN = os.environ.get("GH_PAT") | |
| ADMIN_KEY = os.environ.get("ADMIN_KEY") | |
| # β‘ TELEGRAM & PROXY SECRETS | |
| TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") | |
| TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID") | |
| GOOGLE_PROXY_URL = os.environ.get("GOOGLE_PROXY_URL") | |
| recent_launches = {} | |
| ignited_uids = set() | |
| cached_vault_folders = set() | |
| last_tree_fetch = 0 | |
| ignition_lock = threading.Lock() | |
| # ========================================== | |
| # β‘ GOOGLE PROXY HELPER | |
| # ========================================== | |
| def send_via_proxy(tg_method, payload): | |
| if not GOOGLE_PROXY_URL or not TELEGRAM_BOT_TOKEN: | |
| return None | |
| proxy_payload = { | |
| "url": f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{tg_method}", | |
| "payload": payload | |
| } | |
| try: | |
| r = requests.post(GOOGLE_PROXY_URL, json=proxy_payload, timeout=15) | |
| return r.json() | |
| except Exception as e: | |
| print(f"β [PROXY CRITICAL FAIL] {e}", flush=True) | |
| return None | |
| # ========================================== | |
| # METADATA & UTILS | |
| # ========================================== | |
| cinemeta_cache = {} | |
| def fetch_cinemeta(u_id): | |
| if u_id in cinemeta_cache: return cinemeta_cache[u_id] | |
| parts = u_id.split('_') | |
| imdb_id = parts[0] | |
| is_series = len(parts) > 2 and parts[1].startswith('S') | |
| meta = { | |
| "title": imdb_id, | |
| "poster": "https://via.placeholder.com/150x225/1e293b/94a3b8?text=Vault", | |
| "ep_name": "", | |
| "is_series": is_series, | |
| "s_e": f"{parts[1]}{parts[2]}" if is_series else "" | |
| } | |
| try: | |
| m_type = "series" if is_series else "movie" | |
| r = requests.get(f"https://v3-cinemeta.strem.io/meta/{m_type}/{imdb_id}.json", timeout=3) | |
| if r.status_code == 200: | |
| data = r.json().get("meta") or {} | |
| if data: | |
| meta["title"] = data.get("name", imdb_id) | |
| meta["poster"] = data.get("poster", meta["poster"]) | |
| if is_series: | |
| s, e = int(parts[1][1:]), int(parts[2][1:]) | |
| for vid in data.get("videos", []): | |
| if vid.get("season") == s and vid.get("episode") == e: | |
| meta["ep_name"] = vid.get("name", "") | |
| break | |
| except: pass | |
| meta["title"] = str(meta["title"]).replace('<', '').replace('>', '').replace('&', '&') | |
| meta["ep_name"] = str(meta["ep_name"]).replace('<', '').replace('>', '').replace('&', '&') | |
| cinemeta_cache[u_id] = meta | |
| return meta | |
| def format_eta(seconds): | |
| if seconds >= 86400: return "> 1 Day" | |
| h, m, s = seconds // 3600, (seconds % 3600) // 60, seconds % 60 | |
| if h > 0: return f"{h}h {m}m" | |
| if m > 0: return f"{m}m {s}s" | |
| return f"{s}s" | |
| def format_size(size_bytes): | |
| if size_bytes >= 1024**3: return f"{size_bytes / 1024**3:.2f} GB" | |
| if size_bytes >= 1024**2: return f"{size_bytes / 1024**2:.2f} MB" | |
| return f"{size_bytes / 1024:.2f} KB" | |
| def after_request(response): | |
| response.headers.add('Access-Control-Allow-Origin', '*') | |
| response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') | |
| response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') | |
| return response | |
| def test_bot(): | |
| if not GOOGLE_PROXY_URL: | |
| return "β ERROR: GOOGLE_PROXY_URL Secret missing!", 400 | |
| payload = {"chat_id": TELEGRAM_CHAT_ID, "text": "π <b>System B Proxy Test!</b>", "parse_mode": "HTML"} | |
| res = send_via_proxy("sendMessage", payload) | |
| if res and res.get("ok"): | |
| return f"β SUCCESS! Proxy forwarded message (ID: {res.get('result', {}).get('message_id')})", 200 | |
| return f"β PROXY REJECTED: {res}", 400 | |
| def manifest(access_key): | |
| if access_key != ADMIN_KEY: | |
| return "Unauthorized", 403 | |
| return jsonify({ | |
| "id": "com.systemb.vault.final", | |
| "version": "10.0.0", | |
| "name": "System B Vault π", | |
| "description": "Enterprise Cloud Torrent Cluster", | |
| "resources": ["stream", "catalog"], | |
| "types": ["movie", "series"], | |
| "idPrefixes": ["tt"], | |
| "catalogs": [ | |
| {"type": "movie", "id": "hf_vault_movies", "name": "βοΈ My Vault"}, | |
| {"type": "series", "id": "hf_vault_series", "name": "βοΈ My Vault"} | |
| ] | |
| }) | |
| def catalog(access_key, ctype, catalog_id): | |
| if access_key != ADMIN_KEY: | |
| return jsonify({"metas": []}) # Return empty catalog | |
| try: | |
| url = f"https://huggingface.co/api/datasets/{REPO_ID}/tree/main" | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {} | |
| r = requests.get(url, headers=headers, timeout=5) | |
| tree = r.json() | |
| metas = [] | |
| seen_ids = set() | |
| for item in tree: | |
| if item.get("type") == "directory": | |
| folder_name = item.get("path", "") | |
| parts = folder_name.split('_') | |
| if not parts[0].startswith("tt"): continue | |
| imdb_id = parts[0] | |
| if imdb_id in seen_ids: continue | |
| is_series = len(parts) > 2 and parts[1].startswith("S") and parts[2].startswith("E") | |
| if (ctype == "series" and is_series) or (ctype == "movie" and not is_series): | |
| meta_data = fetch_cinemeta(folder_name) | |
| metas.append({ | |
| "id": imdb_id, | |
| "type": ctype, | |
| "name": meta_data.get("title", imdb_id), | |
| "poster": meta_data.get("poster"), | |
| "description": "Ready to stream from your System B Vault." | |
| }) | |
| seen_ids.add(imdb_id) | |
| return jsonify({"metas": metas}) | |
| except Exception as e: | |
| print(f"Catalog Error: {e}", flush=True) | |
| return jsonify({"metas": []}) | |
| def fire_missiles(u_id, info_hash, size_bytes, is_series, p_idx): | |
| global recent_launches | |
| current_time = time.time() | |
| if info_hash in recent_launches and (current_time - recent_launches[info_hash] < 60): | |
| return | |
| recent_launches[info_hash] = current_time | |
| targets = [(SYS_B_URL, 1, 3), (SYS_C_URL, 2, 3), (SYS_D_URL, 3, 3)] | |
| for url, part, total in targets: | |
| try: | |
| requests.get(f"{url}/archive", params={ | |
| "id": u_id, "hash": info_hash, "part": part, | |
| "total": total, "key": ADMIN_KEY, "is_series": is_series, | |
| "priority_idx": p_idx | |
| }, timeout=5) | |
| except: pass | |
| time.sleep(5) | |
| def trigger_scout(): | |
| if not GH_TOKEN: return | |
| url = "https://api.github.com/repos/amrit123101/Scout/actions/workflows/peer_radar.yml/dispatches" | |
| headers = {"Authorization": f"Bearer {GH_TOKEN}", "Accept": "application/vnd.github+json"} | |
| payload = {"ref": "main", "inputs": {"info_hash": info_hash, "u_id": u_id}} | |
| try: requests.post(url, headers=headers, json=payload, timeout=5) | |
| except: pass | |
| threading.Thread(target=trigger_scout).start() | |
| # ========================================== | |
| # β‘ FULLY DECOUPLED BACKGROUND TELEGRAM MONITOR (VIA PROXY) | |
| # ========================================== | |
| def monitor_cluster_thread(u_id): | |
| if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID or not GOOGLE_PROXY_URL: return | |
| meta = fetch_cinemeta(u_id) | |
| file_label = f"π¬ <b>{meta['title']}</b>" + (f" ({meta['s_e']})" if meta['is_series'] else "") | |
| msg_id = None | |
| payload = {"chat_id": TELEGRAM_CHAT_ID, "text": f"π <b>Igniting Cluster</b>\n{file_label}\n\nStatus: Communicating with nodes...", "parse_mode": "HTML"} | |
| for attempt in range(3): | |
| res = send_via_proxy("sendMessage", payload) | |
| if res and res.get("ok"): | |
| msg_id = res.get("result", {}).get("message_id") | |
| break | |
| print(f"β οΈ [PROXY SEND TIMEOUT] Attempt {attempt+1}", flush=True) | |
| time.sleep(2) | |
| if not msg_id: return | |
| while u_id in ignited_uids: | |
| time.sleep(15) | |
| def check_engine(url): | |
| try: return requests.get(f"{url}/status/{u_id}?detailed=1", timeout=10).json() | |
| except: return {"status": "offline"} | |
| with concurrent.futures.ThreadPoolExecutor() as executor: | |
| results = list(executor.map(check_engine, [SYS_B_URL, SYS_C_URL, SYS_D_URL])) | |
| nodes_active, nodes_finished, nodes_failed = 0, 0, 0 | |
| total_wanted, total_done, total_speed, max_eta = 0, 0, 0, 0 | |
| engine_breakdown = [] | |
| for i, res in enumerate(results): | |
| node_name = ["B", "C", "D"][i] | |
| status = res.get("status") | |
| if status == "active": | |
| nodes_active += 1 | |
| e_w, e_d, e_s, e_eta = res.get("wanted_bytes", 0), res.get("done_bytes", 0), res.get("speed_bytes", 0), res.get("eta_seconds", 0) | |
| e_seeds = res.get("seeds", "?") | |
| e_peers = res.get("peers", "?") | |
| e_avail = res.get("availability") | |
| swarm_text = f" | Seeds: {e_seeds} | Peers: {e_peers}" | |
| if e_avail is not None: | |
| swarm_text = f" | Avail: {round(e_avail, 2)}" + swarm_text | |
| total_wanted += e_w; total_done += e_d; total_speed += e_s; max_eta = max(max_eta, e_eta) | |
| engine_breakdown.append(f"β’ Engine {node_name}: {res.get('progress', 0)}% ({round(e_d/1024**3,1)}/{round(e_w/1024**3,1)} GB) @ {round(e_s/1024**2,1)} MB/s | ETA: {format_eta(e_eta)}{swarm_text}") | |
| elif status == "finished": | |
| nodes_finished += 1 | |
| engine_breakdown.append(f"β’ Engine {node_name}: β Vaulting Done") | |
| else: | |
| nodes_failed += 1 | |
| engine_breakdown.append(f"β’ Engine {node_name}: β Failed") | |
| final_breakdown = "\n".join(engine_breakdown) | |
| status_msg = "" | |
| if nodes_active == 0: | |
| if nodes_finished == 3: status_msg = f"π <b>All Engines Vaulting Done!</b>\n{file_label}\n\n<b>Node Status:</b>\n{final_breakdown}" | |
| elif nodes_finished == 0: status_msg = f"β <b>All Engines Failed!</b>\n{file_label}\n\n<b>Action:</b> Check Engine logs!\n\n<b>Node Status:</b>\n{final_breakdown}" | |
| else: status_msg = f"β οΈ <b>Partial Vaulting Complete</b>\n{file_label}\n\n<b>Status:</b> Some pieces failed.\n\n<b>Node Status:</b>\n{final_breakdown}" | |
| ignited_uids.discard(u_id) | |
| else: | |
| combined_prog = int((total_done / total_wanted) * 100) if total_wanted > 0 else 0 | |
| status_msg = (f"β³ <b>Cluster Status: {combined_prog}%</b>\n{file_label}\n\n" | |
| f"π <b>Combined Speed:</b> {round(total_speed/1024**2, 2)} MB/s\n" | |
| f"π¦ <b>Total Size:</b> {round(total_wanted/1024**3, 2)} GB\n" | |
| f"β±οΈ <b>ETA:</b> {format_eta(max_eta)}\n\n" | |
| f"<b>Node Status:</b>\n{final_breakdown}\n\n" | |
| f"β <b>Kill Task:</b> /kill_{u_id}") | |
| edit_payload = {"chat_id": TELEGRAM_CHAT_ID, "message_id": msg_id, "text": status_msg, "parse_mode": "HTML"} | |
| send_via_proxy("editMessageText", edit_payload) | |
| if nodes_active == 0: break | |
| def stream(access_key, type, id): | |
| if access_key != ADMIN_KEY: | |
| return jsonify({"streams": []}) # Return no | |
| global cached_vault_folders, last_tree_fetch | |
| raw_id = urllib.parse.unquote(id) | |
| id_parts = raw_id.split(':') | |
| is_series_flag = "true" if type == "series" else "false" | |
| headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", | |
| "Accept": "application/json" | |
| } | |
| # β‘ 1. ONLY TORRENTIO AND COMET (Switched BACK to feels.legal so Hugging Face doesn't get blocked!) | |
| scraper_urls = [ | |
| f"https://torrentio.strem.fun/stream/{type}/{id}.json", | |
| f"https://comet.feels.legal/e30=/stream/{type}/{id}.json" | |
| ] | |
| def fetch_scraper(url): | |
| try: | |
| r = requests.get(url, headers=headers, timeout=12) | |
| if r.status_code == 200: | |
| return r.json().get('streams', []) | |
| except: pass | |
| return [] | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: | |
| results = list(executor.map(fetch_scraper, scraper_urls)) | |
| seen_hashes = {} | |
| smart_streams = [] | |
| # β‘ 2. DEDUPLICATE, MERGE SOURCES, AND PREPARE SORTING | |
| for stream_list in results: | |
| if not stream_list: continue | |
| for orig_idx, s in enumerate(stream_list): | |
| info_hash = s.get('infoHash') | |
| if not info_hash: continue | |
| info_hash = info_hash.lower() | |
| orig_name = s.get('name', '').lower() | |
| if 'torrentio' in orig_name: source_name = 'Torrentio' | |
| elif 'comet' in orig_name: source_name = 'Comet' | |
| else: source_name = 'Web' | |
| if info_hash in seen_hashes: | |
| existing_stream = seen_hashes[info_hash] | |
| if source_name not in existing_stream['_source']: | |
| existing_stream['_source'] += f" + {source_name}" | |
| continue | |
| orig_title = s.get('title', '') | |
| orig_desc = s.get('description', '') | |
| display_text = orig_title if orig_title else orig_desc | |
| size_bytes = s.get('behaviorHints', {}).get('videoSize', 0) | |
| if not size_bytes: | |
| match_gb = re.search(r'(\d+(?:\.\d+)?)\s*GB', display_text) | |
| match_mb = re.search(r'(\d+(?:\.\d+)?)\s*MB', display_text) | |
| if match_gb: size_bytes = int(float(match_gb.group(1)) * 1024**3) | |
| elif match_mb: size_bytes = int(float(match_mb.group(1)) * 1024**2) | |
| else: size_bytes = 0 | |
| s['_parsed_size'] = size_bytes | |
| s['_display_text'] = display_text | |
| s['_source'] = source_name | |
| combined_text = f"{orig_name} {display_text}".lower() | |
| quality = "" | |
| if '2160p' in combined_text or '4k' in combined_text: | |
| quality = "4k" | |
| res_rank = 1 | |
| if 'dv' in combined_text or 'dolby vision' in combined_text: quality += " DV" | |
| elif 'hdr' in combined_text: quality += " HDR" | |
| elif '1080p' in combined_text: | |
| quality = "1080p" | |
| res_rank = 2 | |
| elif '720p' in combined_text: | |
| quality = "720p" | |
| res_rank = 3 | |
| elif '480p' in combined_text or 'cam' in combined_text: | |
| quality = "SD" | |
| res_rank = 4 | |
| else: | |
| quality = "Unknown" | |
| res_rank = 5 | |
| s['_quality'] = quality | |
| source_rank = 1 if source_name == 'Torrentio' else (2 if source_name == 'Comet' else 3) | |
| s['_sort_tuple'] = (res_rank, source_rank, orig_idx) | |
| seen_hashes[info_hash] = s | |
| smart_streams.append(s) | |
| # β‘ 3. SMART SORT: Groups by Res -> Then by Scraper -> Preserves Native Order | |
| smart_streams.sort(key=lambda x: x['_sort_tuple']) | |
| smart_streams = smart_streams[:90] | |
| custom_streams = [] | |
| auth_header = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {} | |
| if time.time() - last_tree_fetch > 60 or not cached_vault_folders: | |
| try: | |
| r_tree = requests.get(f"https://huggingface.co/api/datasets/{REPO_ID}/tree/main", headers=auth_header, timeout=3) | |
| if r_tree.status_code == 200: | |
| cached_vault_folders = set(item.get("path") for item in r_tree.json() if item.get("type") == "directory") | |
| last_tree_fetch = time.time() | |
| except Exception as e: print(f"Tree fetch error: {e}", flush=True) | |
| for s in smart_streams: | |
| info_hash = s.get('infoHash') | |
| file_idx = s.get('fileIdx', -1) | |
| size_bytes = s.get('_parsed_size', 45 * 1024**3) | |
| source_tag = s.get('_source', 'Web') | |
| quality_tag = s.get('_quality', '') | |
| display_text = s.get('_display_text', 'Unknown File') | |
| if len(id_parts) > 2: | |
| u_id = f"{id_parts[0]}_S{id_parts[1].zfill(2)}_E{id_parts[2].zfill(2)}_{info_hash[:10]}" | |
| else: | |
| u_id = f"{id_parts[0]}_{info_hash[:10]}" | |
| is_ready = (u_id in cached_vault_folders) | |
| # β‘ DEFAULT STATE | |
| label = "" | |
| title_prefix = "π Send to Vault\n" | |
| stream_url = f"{ADDON_DOMAIN}/{access_key}/traffic_cop/{u_id}?h={info_hash}&sz={size_bytes}&series={is_series_flag}&pidx={file_idx}" | |
| binge_id = "" | |
| if is_ready: | |
| # βοΈ STATE 1: VAULTED (Plays instantly from System E) | |
| stream_obj = { | |
| "name": f"βοΈ Vaulted\n{source_tag} {quality_tag}", | |
| "title": f"βοΈ Ready to Play\n{display_text}", | |
| "url": f"{SYS_E_URL}/stream/{u_id}/video.mkv", | |
| "behaviorHints": {"bingeGroup": binge_id, "videoSize": size_bytes, "videoHash": str(u_id)} | |
| } | |
| if s.get('_orig_title'): stream_obj["title"] = f"βοΈ Ready to Play\n{s['_orig_title']}" | |
| elif u_id in ignited_uids: | |
| # β³ STATE 2: DOWNLOADING (Plays natively via P2P while cluster vaults) | |
| def check_engine(url): | |
| try: return requests.get(f"{url}/status/{u_id}?detailed=1", timeout=2).json() | |
| except: return {"status": "offline"} | |
| with concurrent.futures.ThreadPoolExecutor() as executor: | |
| engine_results = list(executor.map(check_engine, [SYS_B_URL, SYS_C_URL, SYS_D_URL])) | |
| active_count, total_prog, max_eta = 0, 0, 0 | |
| for res in engine_results: | |
| if res.get("status") == "active": | |
| active_count += 1 | |
| total_prog += res.get("progress", 0) | |
| max_eta = max(max_eta, res.get("eta_seconds", 0)) | |
| avg_prog = int(total_prog / active_count) if active_count > 0 else 0 | |
| eta_str = format_eta(max_eta) if active_count > 0 else "Starting..." | |
| stream_obj = { | |
| "name": f"β³ Vaulting (P2P)\n{source_tag} {quality_tag}", | |
| "title": f"β³ Downloading: π [{avg_prog}%] - ETA: {eta_str}\n{display_text}", | |
| "infoHash": info_hash, # β‘ NATIVE P2P PLAYBACK | |
| "fileIdx": int(file_idx), | |
| "behaviorHints": {"bingeGroup": binge_id, "videoSize": size_bytes, "videoHash": str(u_id)} | |
| } | |
| if s.get('_orig_title'): stream_obj["title"] = f"β³ Downloading: π [{avg_prog}%] - ETA: {eta_str}\n{s['_orig_title']}" | |
| else: | |
| # π§² STATE 3: UNCACHED (Click sends to Traffic Cop -> Bumper Video) | |
| stream_obj = { | |
| "name": f"βΆοΈ Stream & Vault\n{source_tag} {quality_tag}", | |
| "title": f"Click to start Cloud Download...\n{display_text}", | |
| "url": f"{ADDON_DOMAIN}/{access_key}/traffic_cop/{u_id}?h={info_hash}&sz={size_bytes}&series={is_series_flag}&pidx={file_idx}", | |
| "behaviorHints": {"bingeGroup": binge_id, "videoSize": size_bytes, "videoHash": str(u_id)} | |
| } | |
| if s.get('_orig_title'): stream_obj["title"] = f"Downloading to Cloud...\n{s['_orig_title']}" | |
| if s.get('_orig_desc'): | |
| stream_obj["description"] = s['_orig_desc'] | |
| custom_streams.append(stream_obj) | |
| # β‘ 4-LINE VAULT RESCUE β‘ | |
| prefix = f"{id_parts[0]}_S{id_parts[1].zfill(2)}_E{id_parts[2].zfill(2)}_" if len(id_parts) > 2 else f"{id_parts[0]}_" | |
| for f in cached_vault_folders: | |
| if f.startswith(prefix) and not any(f in s.get('url', '') for s in custom_streams): | |
| custom_streams.append({"name": "βοΈ Vault", "title": "βοΈ Ready\nDirect Play", "url": f"{SYS_E_URL}/stream/{f}/video.mkv"}) | |
| # β‘ Keep Vaulted items at the very top by checking for the cloud icon! | |
| custom_streams.sort(key=lambda x: 0 if "βοΈ Ready" in x.get("title", "") else 1) | |
| return jsonify({"streams": custom_streams}) | |
| def traffic_cop(access_key, u_id): | |
| if access_key != ADMIN_KEY: | |
| return "Unauthorized", 403 | |
| info_hash = request.args.get('h') | |
| size_bytes = int(request.args.get('sz', 0)) | |
| is_series = request.args.get('series', 'false') | |
| p_idx = request.args.get('pidx', '-1') | |
| if not info_hash: return "No Hash", 400 | |
| with ignition_lock: | |
| if u_id not in ignited_uids: | |
| ignited_uids.add(u_id) | |
| threading.Thread(target=fire_missiles, args=(u_id, info_hash, size_bytes, is_series, p_idx)).start() | |
| threading.Thread(target=monitor_cluster_thread, args=(u_id,)).start() | |
| return redirect("http://127.0.0.1:65535/igniting.mp4") | |
| def kill_task(u_id): | |
| key = request.args.get('key') | |
| if key != ADMIN_KEY: return "Unauthorized", 403 | |
| def blast_kill(): | |
| for target in [SYS_B_URL, SYS_C_URL, SYS_D_URL]: | |
| try: requests.post(f"{target}/internal_kill/{u_id}?key={ADMIN_KEY}", timeout=3) | |
| except: pass | |
| threading.Thread(target=blast_kill).start() | |
| referer = request.headers.get("Referer") | |
| if referer: return redirect(referer) | |
| return "Kill broadcast sent.", 200 | |
| # ========================================== | |
| # β‘ 2-WAY TELEGRAM COMMAND CENTER (3-LEVEL DRILL DOWN) | |
| # ========================================== | |
| def telegram_webhook(): | |
| data = request.json | |
| if not data: return jsonify({"ok": True}), 200 | |
| # 1. HANDLE BUTTON CLICKS (Callback Queries) | |
| if 'callback_query' in data: | |
| callback = data['callback_query'] | |
| chat_id = callback['message']['chat']['id'] | |
| cb_data = callback['data'] | |
| msg_id = callback['message']['message_id'] | |
| if str(chat_id) != str(TELEGRAM_CHAT_ID): return jsonify({"ok": True}), 200 | |
| try: | |
| # Level 2: Open Show Menu | |
| if cb_data.startswith("open_"): | |
| imdb_id = cb_data.replace("open_", "") | |
| update_vault_menu(chat_id, msg_id, open_imdb=imdb_id) | |
| # Level 3: Open Season Menu | |
| elif cb_data.startswith("openseason_"): | |
| parts = cb_data.replace("openseason_", "").split("_") | |
| imdb_id, season = parts[0], parts[1] | |
| update_vault_menu(chat_id, msg_id, open_imdb=imdb_id, open_season=season) | |
| # Return to Level 1 | |
| elif cb_data == "vault_main": | |
| update_vault_menu(chat_id, msg_id) | |
| # Delete Entire Show | |
| elif cb_data.startswith("cbdelshow_"): | |
| imdb_id = cb_data.replace("cbdelshow_", "") | |
| files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN) | |
| ops = [CommitOperationDelete(path_in_repo=f) for f in files if f.startswith(f"{imdb_id}_")] | |
| if ops: | |
| api.create_commit(repo_id=REPO_ID, repo_type="dataset", operations=ops, commit_message=f"TG Bulk delete show {imdb_id}", token=HF_TOKEN) | |
| send_via_proxy("answerCallbackQuery", {"callback_query_id": callback['id'], "text": "𧨠Show Wiped!"}) | |
| update_vault_menu(chat_id, msg_id) # Refresh to main | |
| # Delete Entire Season | |
| elif cb_data.startswith("cbdelseason_"): | |
| parts = cb_data.replace("cbdelseason_", "").split("_") | |
| imdb_id, season = parts[0], parts[1] | |
| files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN) | |
| season_prefix = f"{imdb_id}_{season}_" | |
| ops = [CommitOperationDelete(path_in_repo=f) for f in files if f.startswith(season_prefix)] | |
| if ops: | |
| api.create_commit(repo_id=REPO_ID, repo_type="dataset", operations=ops, commit_message=f"TG Bulk delete {season}", token=HF_TOKEN) | |
| send_via_proxy("answerCallbackQuery", {"callback_query_id": callback['id'], "text": f"π Season {season} Wiped!"}) | |
| update_vault_menu(chat_id, msg_id, open_imdb=imdb_id) # Refresh to Show Level | |
| # Delete Single File | |
| elif cb_data.startswith("cbdel_"): | |
| folder = cb_data.replace("cbdel_", "") | |
| api.delete_folder(path_in_repo=folder, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN) | |
| send_via_proxy("answerCallbackQuery", {"callback_query_id": callback['id'], "text": "β Deleted!"}) | |
| imdb = folder.split('_')[0] | |
| parts = folder.split('_') | |
| season = parts[1] if len(parts) > 2 and parts[1].startswith('S') else None | |
| update_vault_menu(chat_id, msg_id, open_imdb=imdb, open_season=season) | |
| except Exception as e: | |
| print(f"Callback Error: {e}") | |
| return jsonify({"ok": True}), 200 | |
| # 2. HANDLE TEXT COMMANDS | |
| if 'message' in data: | |
| chat_id = data['message']['chat']['id'] | |
| text = data['message'].get('text', '') | |
| if str(chat_id) != str(TELEGRAM_CHAT_ID): return jsonify({"ok": True}), 200 | |
| def send_tg(msg): | |
| send_via_proxy("sendMessage", {"chat_id": chat_id, "text": msg, "parse_mode": "HTML"}) | |
| try: | |
| if text == '/status': | |
| if not ignited_uids: | |
| send_tg("π€ <b>Swarm is Idle.</b> No active downloads.") | |
| return jsonify({"ok": True}), 200 | |
| msg = "π’ <b>ACTIVE SWARM</b>\n\n" | |
| for u_id in list(ignited_uids): | |
| meta = fetch_cinemeta(u_id) | |
| label = f"{meta['title']} {meta['s_e']}" if meta['is_series'] else meta['title'] | |
| msg += f"π¬ <b>{label}</b>\n" | |
| msg += f"β Kill Task: /kill_{u_id}\n\n" | |
| send_tg(msg) | |
| elif text == '/vault': | |
| update_vault_menu(chat_id) | |
| elif text == '/trash': | |
| send_tg("π§Ή <b>Emptying Trash...</b>\nSquashing Git history to permanently destroy deleted LFS files. This takes a moment.") | |
| try: | |
| # β‘ This command forcefully rewrites history and deletes the physical LFS blobs | |
| api.super_squash_history(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN) | |
| send_tg("β <b>Trash Emptied!</b> Storage space permanently freed.") | |
| except Exception as e: | |
| send_tg(f"β <b>Trash Error:</b> {e}") | |
| elif text.startswith('/kill_'): | |
| u_id = text.replace('/kill_', '').strip() | |
| if u_id in ignited_uids: | |
| ignited_uids.discard(u_id) | |
| for url in [SYS_B_URL, SYS_C_URL, SYS_D_URL]: | |
| try: requests.post(f"{url}/internal_kill/{u_id}?key={ADMIN_KEY}", timeout=2) | |
| except: pass | |
| send_tg(f"π <b>Node Aborted:</b> Task {u_id[:10]} killed across all engines.") | |
| else: | |
| send_tg("β οΈ Task not found in active swarm.") | |
| except Exception as e: | |
| send_tg(f"β <b>Bot Error:</b> {e}") | |
| return jsonify({"ok": True}), 200 | |
| def update_vault_menu(chat_id, msg_id=None, open_imdb=None, open_season=None): | |
| """Main UI Engine for Interactive 3-Level Keyboards""" | |
| info = api.dataset_info(repo_id=REPO_ID, files_metadata=True, token=HF_TOKEN) | |
| folder_data = {} | |
| for f in info.siblings: | |
| if '/' in f.rfilename and f.size: | |
| folder = f.rfilename.split('/')[0] | |
| imdb = folder.split('_')[0] | |
| if not any(d['path'] == folder for d in folder_data.get(imdb, [])): | |
| folder_data.setdefault(imdb, []).append({"path": folder, "size": f.size}) | |
| else: | |
| for d in folder_data[imdb]: | |
| if d['path'] == folder: d['size'] += f.size | |
| keyboard = [] | |
| if not folder_data: | |
| payload = {"chat_id": chat_id, "text": "π¦ <b>Vault is Empty.</b>", "parse_mode": "HTML"} | |
| if msg_id: | |
| payload["message_id"] = msg_id | |
| send_via_proxy("editMessageText", payload) | |
| else: | |
| send_via_proxy("sendMessage", payload) | |
| return | |
| # LEVEL 1: MAIN VAULT MENU | |
| if not open_imdb: | |
| text = "π¦ <b>MY CLOUD VAULT</b>\nSelect a show to manage content:" | |
| for imdb, items in folder_data.items(): | |
| meta = fetch_cinemeta(items[0]['path']) | |
| total_size = sum(i['size'] for i in items) | |
| keyboard.append([{"text": f"π¬ {meta['title']} ({format_size(total_size)})", "callback_data": f"open_{imdb}"}]) | |
| # LEVEL 2 & 3: DRILL-DOWN MENUS | |
| elif open_imdb: | |
| items = folder_data.get(open_imdb, []) | |
| if not items: | |
| update_vault_menu(chat_id, msg_id) | |
| return | |
| meta = fetch_cinemeta(items[0]['path']) | |
| # Group items by season | |
| seasons = {} | |
| for item in items: | |
| parts = item['path'].split('_') | |
| s_name = parts[1] if len(parts) > 2 and parts[1].startswith('S') else "Movie" | |
| seasons.setdefault(s_name, []).append(item) | |
| # LEVEL 2: SEASON VIEW (or Movie View) | |
| if not open_season: | |
| # If it's just a Movie, skip the Season list and go straight to Delete | |
| if "Movie" in seasons and len(seasons) == 1: | |
| text = f"π¬ <b>{meta['title']}</b>\nManage Movie:" | |
| for item in seasons["Movie"]: | |
| keyboard.append([ | |
| {"text": f"β«οΈ Movie File ({format_size(item['size'])})", "callback_data": "ignore_click"}, | |
| {"text": "π Delete", "callback_data": f"cbdel_{item['path']}"} | |
| ]) | |
| keyboard.append([{"text": "𧨠Delete Entire Title", "callback_data": f"cbdelshow_{open_imdb}"}]) | |
| keyboard.append([{"text": "β¬ οΈ Back to Vault", "callback_data": "vault_main"}]) | |
| # If it's a TV Show, list the Seasons | |
| else: | |
| text = f"πΊ <b>{meta['title']}</b>\nSelect a Season:" | |
| for s_name, s_items in sorted(seasons.items()): | |
| s_size = sum(i['size'] for i in s_items) | |
| s_label = s_name.replace('S', 'Season ') | |
| keyboard.append([{"text": f"π {s_label} ({format_size(s_size)})", "callback_data": f"openseason_{open_imdb}_{s_name}"}]) | |
| keyboard.append([{"text": "𧨠Delete Entire Show", "callback_data": f"cbdelshow_{open_imdb}"}]) | |
| keyboard.append([{"text": "β¬ οΈ Back to Vault", "callback_data": "vault_main"}]) | |
| # LEVEL 3: EPISODE VIEW | |
| elif open_season: | |
| s_items = seasons.get(open_season, []) | |
| s_label = open_season.replace('S', 'Season ') | |
| text = f"πΊ <b>{meta['title']} - {s_label}</b>\nManage Episodes:" | |
| for item in sorted(s_items, key=lambda x: x['path']): | |
| parts = item['path'].split('_') | |
| label = f"{parts[1]}{parts[2]}" if len(parts) > 2 else "File" | |
| keyboard.append([ | |
| {"text": f"β«οΈ {label} ({format_size(item['size'])})", "callback_data": "ignore_click"}, | |
| {"text": "β Del", "callback_data": f"cbdel_{item['path']}"} | |
| ]) | |
| keyboard.append([{"text": f"π Delete Entire {s_label}", "callback_data": f"cbdelseason_{open_imdb}_{open_season}"}]) | |
| keyboard.append([{"text": "β¬ οΈ Back to Seasons", "callback_data": f"open_{open_imdb}"}]) | |
| payload = { | |
| "chat_id": chat_id, | |
| "text": text, | |
| "parse_mode": "HTML", | |
| "reply_markup": {"inline_keyboard": keyboard} | |
| } | |
| if msg_id: | |
| payload["message_id"] = msg_id | |
| send_via_proxy("editMessageText", payload) | |
| else: | |
| send_via_proxy("sendMessage", payload) | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) |