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"
@app.after_request
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
@app.route('/test_bot')
def test_bot():
if not GOOGLE_PROXY_URL:
return "โ ERROR: GOOGLE_PROXY_URL Secret missing!", 400
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": "๐ System B Proxy Test!", "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
@app.route('//manifest.json')
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"}
]
})
@app.route('//catalog//.json')
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"๐ฌ {meta['title']}" + (f" ({meta['s_e']})" if meta['is_series'] else "")
msg_id = None
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": f"๐ Igniting Cluster\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"๐ All Engines Vaulting Done!\n{file_label}\n\nNode Status:\n{final_breakdown}"
elif nodes_finished == 0: status_msg = f"โ All Engines Failed!\n{file_label}\n\nAction: Check Engine logs!\n\nNode Status:\n{final_breakdown}"
else: status_msg = f"โ ๏ธ Partial Vaulting Complete\n{file_label}\n\nStatus: Some pieces failed.\n\nNode Status:\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"โณ Cluster Status: {combined_prog}%\n{file_label}\n\n"
f"๐ Combined Speed: {round(total_speed/1024**2, 2)} MB/s\n"
f"๐ฆ Total Size: {round(total_wanted/1024**3, 2)} GB\n"
f"โฑ๏ธ ETA: {format_eta(max_eta)}\n\n"
f"Node Status:\n{final_breakdown}\n\n"
f"โ Kill Task: /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
@app.route('//stream//.json')
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})
@app.route('//traffic_cop/')
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")
@app.route('/kill/', methods=['POST'])
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)
# ==========================================
@app.route('/telegram_webhook', methods=['POST'])
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("๐ค Swarm is Idle. No active downloads.")
return jsonify({"ok": True}), 200
msg = "๐ข ACTIVE SWARM\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"๐ฌ {label}\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("๐งน Emptying Trash...\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("โ
Trash Emptied! Storage space permanently freed.")
except Exception as e:
send_tg(f"โ Trash Error: {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"๐ Node Aborted: Task {u_id[:10]} killed across all engines.")
else:
send_tg("โ ๏ธ Task not found in active swarm.")
except Exception as e:
send_tg(f"โ Bot Error: {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": "๐ฆ Vault is Empty.", "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 = "๐ฆ MY CLOUD VAULT\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"๐ฌ {meta['title']}\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"๐บ {meta['title']}\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"๐บ {meta['title']} - {s_label}\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)