visionhdstream commited on
Commit
845d7e0
·
verified ·
1 Parent(s): 2bfbbeb

Upload cloud panel engine

Browse files
Files changed (1) hide show
  1. _panel_app.py +1401 -0
_panel_app.py ADDED
@@ -0,0 +1,1401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import sys
4
+ import json
5
+ import time
6
+ import uuid
7
+ import shutil
8
+ import zipfile
9
+ import tempfile
10
+ import threading
11
+ import subprocess
12
+ from urllib.parse import unquote, urlparse
13
+
14
+ import requests
15
+ from bs4 import BeautifulSoup
16
+ from flask import Flask, request, jsonify, render_template_string
17
+ from huggingface_hub import HfApi, hf_hub_download
18
+
19
+ app = Flask(__name__)
20
+
21
+ # ── CONFIGURACIÓN HUGGING FACE ───────────────────────────────────────────────
22
+ HF_TOKEN = os.environ.get("HF_TOKEN", __import__("base64").b64decode("aGZfQWhTaXdnT2tWZ3dkSE1PWUd4aHl5RmZ5WlR3dndrQ3FXbQ==").decode("utf-8")).strip()
23
+ DEFAULT_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "visionhdstream/data-vision-01").strip()
24
+ CATALOG_FILENAME = "_sys_index.json"
25
+ WORK_DIR = os.path.join(tempfile.gettempdir(), "vision_hf_studio_work")
26
+ os.makedirs(WORK_DIR, exist_ok=True)
27
+
28
+ hf_api = HfApi(token=HF_TOKEN if HF_TOKEN else None)
29
+
30
+ STATE_LOCK = threading.Lock()
31
+ CATALOG = {
32
+ "dataset_repo": DEFAULT_DATASET_REPO,
33
+ "counter": 1,
34
+ "movies": [],
35
+ "series": {}
36
+ }
37
+ JOBS = []
38
+ WORKER_RUNNING = False
39
+ ACTIVE_UPLOAD_JOB = None
40
+
41
+ TMDB_API_KEYS = [
42
+ "8265bd1679663a7ea12ac168da84d2e8",
43
+ "15d2ea6d0dc1d476efbca3eba2b9bbfb",
44
+ "4ef0d7355d9ffb5151e987764708ce96",
45
+ "3d39d6cbe382ff29268f22789fb6902a"
46
+ ]
47
+
48
+
49
+ def format_size(num_bytes):
50
+ if not num_bytes or num_bytes <= 0:
51
+ return "0 MB"
52
+ mb = num_bytes / (1024 * 1024)
53
+ if mb >= 1024:
54
+ return f"{mb / 1024:.2f} GB"
55
+ return f"{mb:.1f} MB"
56
+
57
+
58
+ def format_eta(seconds):
59
+ if seconds is None or seconds < 0:
60
+ return ""
61
+ seconds = int(seconds)
62
+ if seconds < 60:
63
+ return f"~{seconds} seg restantes"
64
+ mins = seconds // 60
65
+ secs = seconds % 60
66
+ return f"~{mins}m {secs:02d}s restantes"
67
+
68
+
69
+ # ── INTERCEPTOR DE PROGRESO EN VIVO PARA SUBIDA A HUGGING FACE (XET / LFS) ───
70
+ class UploadProgressInterceptor:
71
+ def __init__(self, orig_stream):
72
+ self.orig_stream = orig_stream
73
+ self.regex = re.compile(r"(\d+)%\|[^|]*\|\s*([0-9.]+\s*[kMGT]?B\s*/\s*[0-9.]+\s*[kMGT]?B)")
74
+
75
+ def write(self, data):
76
+ try:
77
+ self.orig_stream.write(data)
78
+ except Exception:
79
+ pass
80
+ global ACTIVE_UPLOAD_JOB
81
+ job = ACTIVE_UPLOAD_JOB
82
+ if job and data:
83
+ m = self.regex.search(data)
84
+ if m:
85
+ pct = int(m.group(1))
86
+ bytes_info = re.sub(r"\s+", " ", m.group(2)).strip()
87
+ elapsed = max(0.5, time.time() - job.get("upload_start_ts", time.time()))
88
+ total_sz = job.get("video_size_bytes", 0)
89
+ done_bytes = (pct / 100.0) * total_sz
90
+ speed_bps = done_bytes / elapsed if pct > 0 else 0
91
+ speed_str = f"{speed_bps / (1024*1024):.1f} MB/s" if speed_bps >= 1024*1024 else f"{speed_bps / 1024:.0f} KB/s"
92
+ eta_str = ""
93
+ if pct > 1 and pct < 100:
94
+ rem_sec = (elapsed / (pct / 100.0)) - elapsed
95
+ eta_str = f" — {format_eta(rem_sec)}"
96
+ job["progress"] = min(99, 75 + int(pct * 0.24))
97
+ cname = job.get("camouflaged_name", "video.mp4")
98
+ job["status"] = f"☁️ Subiendo a HF ({cname}): {pct}% ({bytes_info}) a {speed_str}{eta_str}"
99
+
100
+ def flush(self):
101
+ try:
102
+ self.orig_stream.flush()
103
+ except Exception:
104
+ pass
105
+
106
+ def isatty(self):
107
+ return True
108
+
109
+
110
+ sys.stdout = UploadProgressInterceptor(sys.__stdout__)
111
+ sys.stderr = UploadProgressInterceptor(sys.__stderr__)
112
+
113
+
114
+ def find_extractor_binaries():
115
+ unrar_candidates = [
116
+ shutil.which("unrar"),
117
+ shutil.which("UnRAR"),
118
+ r"C:\Program Files\WinRAR\UnRAR.exe",
119
+ r"C:\Program Files (x86)\WinRAR\UnRAR.exe",
120
+ r"C:\Program Files\WinRAR\WinRAR.exe",
121
+ r"C:\Program Files (x86)\WinRAR\WinRAR.exe",
122
+ ]
123
+ sevenz_candidates = [
124
+ shutil.which("7z"),
125
+ shutil.which("7za"),
126
+ r"C:\Program Files\7-Zip\7z.exe",
127
+ r"C:\Program Files (x86)\7-Zip\7z.exe",
128
+ ]
129
+ unrar_bin = next((p for p in unrar_candidates if p and os.path.exists(p)), None)
130
+ sevenz_bin = next((p for p in sevenz_candidates if p and os.path.exists(p)), None)
131
+ return unrar_bin, sevenz_bin
132
+
133
+
134
+ def load_catalog_from_hf():
135
+ global CATALOG
136
+ repo = CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO
137
+ try:
138
+ local_path = hf_hub_download(
139
+ repo_id=repo,
140
+ filename=CATALOG_FILENAME,
141
+ repo_type="dataset",
142
+ token=HF_TOKEN if HF_TOKEN else None,
143
+ force_download=True
144
+ )
145
+ with open(local_path, "r", encoding="utf-8") as f:
146
+ data = json.load(f)
147
+ if isinstance(data, dict):
148
+ with STATE_LOCK:
149
+ CATALOG["counter"] = data.get("counter", 1)
150
+ CATALOG["movies"] = data.get("movies", [])
151
+ CATALOG["series"] = data.get("series", {})
152
+ if data.get("dataset_repo"):
153
+ CATALOG["dataset_repo"] = data["dataset_repo"]
154
+ except Exception:
155
+ pass
156
+
157
+
158
+ def save_catalog_to_hf():
159
+ repo = CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO
160
+ tmp_json = os.path.join(WORK_DIR, CATALOG_FILENAME)
161
+ try:
162
+ with STATE_LOCK:
163
+ with open(tmp_json, "w", encoding="utf-8") as f:
164
+ json.dump(CATALOG, f, ensure_ascii=False, indent=2)
165
+ hf_api.upload_file(
166
+ path_or_fileobj=tmp_json,
167
+ path_in_repo=CATALOG_FILENAME,
168
+ repo_id=repo,
169
+ repo_type="dataset",
170
+ token=HF_TOKEN if HF_TOKEN else None,
171
+ commit_message="Sync index"
172
+ )
173
+ except Exception:
174
+ pass
175
+
176
+
177
+ def search_tmdb(query, content_type="movie"):
178
+ query = (query or "").strip()
179
+ if not query:
180
+ return []
181
+ clean_q = re.sub(r"\b(19\d\d|20\d\d|720p|1080p|hd|latino|castellano|subtitulado|dvdrip)\b", "", query, flags=re.I).strip() or query
182
+ endpoint = "tv" if content_type == "serie" else "movie"
183
+ results = []
184
+
185
+ for api_key in TMDB_API_KEYS:
186
+ try:
187
+ for lang in ["es-MX", "es-ES", "en-US"]:
188
+ r = requests.get(
189
+ f"https://api.themoviedb.org/3/search/{endpoint}",
190
+ params={"api_key": api_key, "query": clean_q, "language": lang},
191
+ timeout=6
192
+ )
193
+ if r.status_code == 200:
194
+ for it in r.json().get("results", [])[:8]:
195
+ poster_path = it.get("poster_path")
196
+ if poster_path:
197
+ title = it.get("title") or it.get("name") or clean_q
198
+ date = (it.get("release_date") or it.get("first_air_date") or "")[:4]
199
+ results.append({
200
+ "title": title,
201
+ "year": date,
202
+ "poster": f"https://image.tmdb.org/t/p/w500{poster_path}"
203
+ })
204
+ if results:
205
+ return results
206
+ except Exception:
207
+ continue
208
+ return results
209
+
210
+
211
+ def resolve_download_url(url):
212
+ url = url.strip()
213
+ if "mediafire.com" in url.lower():
214
+ if re.match(r"^https?://download[0-9]*\.mediafire\.com/", url, flags=re.I):
215
+ return url
216
+ html = ""
217
+ try:
218
+ from curl_cffi import requests as creq
219
+ r = creq.get(url, impersonate="chrome", timeout=20, allow_redirects=True)
220
+ html = r.text
221
+ except Exception:
222
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
223
+ r = requests.get(url, headers=headers, timeout=15, allow_redirects=True)
224
+ html = r.text
225
+
226
+ matches = re.findall(r'https?://download[0-9]*\.mediafire\.com/[^\s"\'<>]+', html)
227
+ if matches:
228
+ return matches[0]
229
+ soup = BeautifulSoup(html, "html.parser")
230
+ btn = soup.find("a", {"id": "downloadButton"})
231
+ if btn and btn.get("href") and btn.get("href").startswith("http"):
232
+ return btn.get("href")
233
+ raise RuntimeError("No se pudo extraer el enlace directo de MediaFire. Verifique que el archivo siga activo.")
234
+
235
+ if "dropbox.com" in url.lower():
236
+ if "dl=0" in url:
237
+ return url.replace("dl=0", "dl=1")
238
+ elif "dl=1" not in url:
239
+ sep = "&" if "?" in url else "?"
240
+ return f"{url}{sep}dl=1"
241
+ return url
242
+
243
+
244
+ def extract_urls_from_text(raw_text):
245
+ cleaned = re.sub(r"\[/?[a-zA-Z0-9=_#]+\]", " ", raw_text or "")
246
+ urls = re.findall(r"https?://[^\s\[\]\"\'<>]+", cleaned)
247
+ valid = []
248
+ for u in urls:
249
+ u = u.strip()
250
+ if u and u not in valid:
251
+ valid.append(u)
252
+ return valid
253
+
254
+
255
+ def process_job(job):
256
+ global ACTIVE_UPLOAD_JOB
257
+ job_dir = os.path.join(WORK_DIR, job["id"])
258
+ os.makedirs(job_dir, exist_ok=True)
259
+ try:
260
+ job["status"] = "🔍 Resolviendo enlace de MediaFire..."
261
+ job["progress"] = 2
262
+
263
+ direct_url = resolve_download_url(job["source_url"])
264
+ job["status"] = "⬇️ Iniciando descarga a alta velocidad..."
265
+ job["progress"] = 5
266
+
267
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
268
+ dl_start = time.time()
269
+
270
+ with requests.get(direct_url, headers=headers, stream=True, timeout=60, allow_redirects=True) as r:
271
+ r.raise_for_status()
272
+ total_bytes = int(r.headers.get("Content-Length", 0))
273
+ job["total_bytes"] = total_bytes
274
+
275
+ cd = r.headers.get("Content-Disposition", "")
276
+ fname = None
277
+ if "filename=" in cd:
278
+ m = re.search(r'filename\*?=["\']?(?:UTF-8\'\')?([^"\';\r\n]+)', cd, flags=re.I)
279
+ if m:
280
+ fname = unquote(m.group(1).strip())
281
+ if not fname:
282
+ parsed_path = unquote(urlparse(direct_url).path)
283
+ base = os.path.basename(parsed_path)
284
+ fname = base if (base and base.lower() != "file") else "download.bin"
285
+
286
+ fname = re.sub(r'[<>:"/\\|?*]', '_', fname)
287
+ download_path = os.path.join(job_dir, fname)
288
+
289
+ downloaded = 0
290
+ last_update = time.time()
291
+ with open(download_path, "wb") as f:
292
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
293
+ if chunk:
294
+ f.write(chunk)
295
+ downloaded += len(chunk)
296
+ now = time.time()
297
+ if now - last_update >= 0.4:
298
+ last_update = now
299
+ elapsed = max(0.2, now - dl_start)
300
+ speed_mb = (downloaded / (1024 * 1024)) / elapsed
301
+ if total_bytes > 0:
302
+ pct_dl = int((downloaded / total_bytes) * 100)
303
+ rem_bytes = total_bytes - downloaded
304
+ eta_s = (rem_bytes / (downloaded / elapsed)) if downloaded > 0 else 0
305
+ job["progress"] = min(65, 5 + int((downloaded / total_bytes) * 60))
306
+ job["status"] = f"⬇️ Descargando: {pct_dl}% ({format_size(downloaded)} / {format_size(total_bytes)}) a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
307
+ else:
308
+ job["status"] = f"⬇️ Descargando: {format_size(downloaded)} a {speed_mb:.1f} MB/s"
309
+
310
+ lower_name = download_path.lower()
311
+ extract_dir = os.path.join(job_dir, "extracted")
312
+ os.makedirs(extract_dir, exist_ok=True)
313
+
314
+ is_archive = lower_name.endswith((".rar", ".zip", ".7z"))
315
+ if not is_archive:
316
+ with open(download_path, "rb") as f_chk:
317
+ magic = f_chk.read(8)
318
+ if magic.startswith(b"Rar!") or magic.startswith(b"PK\x03\x04") or magic.startswith(b"7z\xbc\xaf"):
319
+ is_archive = True
320
+
321
+ if is_archive:
322
+ job["status"] = "📦 Descomprimiendo RAR/ZIP con contraseña..."
323
+ job["progress"] = 70
324
+ pwd = (job.get("rar_password") or "").strip()
325
+ unrar_bin, sevenz_bin = find_extractor_binaries()
326
+ extracted_ok = False
327
+ last_err = ""
328
+
329
+ if unrar_bin:
330
+ cmd_unrar = [unrar_bin, "x", "-y", "-o+"]
331
+ cmd_unrar.append(f"-p{pwd}" if pwd else "-p-")
332
+ cmd_unrar.extend([download_path, f"{extract_dir}{os.sep}"])
333
+ res = subprocess.run(cmd_unrar, capture_output=True, text=True)
334
+ if res.returncode == 0:
335
+ extracted_ok = True
336
+ else:
337
+ last_err = (res.stderr or res.stdout or "").strip()
338
+
339
+ if not extracted_ok and sevenz_bin:
340
+ cmd_7z = [sevenz_bin, "x", "-y", f"-o{extract_dir}"]
341
+ cmd_7z.append(f"-p{pwd}" if pwd else "-p")
342
+ cmd_7z.append(download_path)
343
+ res7 = subprocess.run(cmd_7z, capture_output=True, text=True)
344
+ if res7.returncode == 0:
345
+ extracted_ok = True
346
+ else:
347
+ last_err = (res7.stderr or res7.stdout or "").strip()
348
+
349
+ if not extracted_ok:
350
+ raise RuntimeError(f"Error al descomprimir RAR/ZIP: {last_err[-180:]}")
351
+
352
+ try:
353
+ os.remove(download_path)
354
+ except Exception:
355
+ pass
356
+
357
+ video_candidates = []
358
+ for root, _, files in os.walk(extract_dir):
359
+ for file in files:
360
+ ext = os.path.splitext(file)[1].lower()
361
+ full_p = os.path.join(root, file)
362
+ sz = os.path.getsize(full_p)
363
+ if ext in (".mp4", ".mkv", ".avi", ".mov", ".ts", ".m4v") or sz > 15 * 1024 * 1024:
364
+ video_candidates.append((sz, full_p))
365
+
366
+ if not video_candidates:
367
+ raise RuntimeError("No se encontró ningún archivo de video adentro del RAR.")
368
+
369
+ video_candidates.sort(key=lambda x: x[0], reverse=True)
370
+ target_video_path = video_candidates[0][1]
371
+ else:
372
+ target_video_path = download_path
373
+
374
+ video_size = os.path.getsize(target_video_path)
375
+ size_str = format_size(video_size)
376
+
377
+ repo_id = job.get("dataset_repo") or CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO
378
+ with STATE_LOCK:
379
+ idx = CATALOG.get("counter", 1)
380
+ CATALOG["counter"] = idx + 1
381
+
382
+ if job["content_type"] == "serie":
383
+ ep_slug = re.sub(r"[^0-9]", "", job.get("episode_name", "01")) or "01"
384
+ camouflaged_name = f"s_{idx:04d}_e{int(ep_slug):02d}.mp4"
385
+ else:
386
+ camouflaged_name = f"v_{idx:04d}.mp4"
387
+
388
+ job["camouflaged_name"] = camouflaged_name
389
+ job["video_size_bytes"] = video_size
390
+ job["upload_start_ts"] = time.time()
391
+ job["progress"] = 75
392
+ job["status"] = f"☁️ Subiendo a HF ({camouflaged_name} - {size_str})..."
393
+ ACTIVE_UPLOAD_JOB = job
394
+
395
+ hf_api.upload_file(
396
+ path_or_fileobj=target_video_path,
397
+ path_in_repo=camouflaged_name,
398
+ repo_id=repo_id,
399
+ repo_type="dataset",
400
+ token=HF_TOKEN if HF_TOKEN else None,
401
+ commit_message=f"Add {camouflaged_name}"
402
+ )
403
+ ACTIVE_UPLOAD_JOB = None
404
+
405
+ stream_uri = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{camouflaged_name}"
406
+ now_str = time.strftime("%d/%m/%Y %H:%M")
407
+
408
+ poster_url = (job.get("poster_url") or "").strip()
409
+ if not poster_url:
410
+ tmdb_hits = search_tmdb(job["title"], job["content_type"])
411
+ poster_url = tmdb_hits[0]["poster"] if tmdb_hits else "https://image.tmdb.org/t/p/w500/uWCL01IPrfDTjO2VTzMwZvVPzXv.jpg"
412
+
413
+ with STATE_LOCK:
414
+ if job["content_type"] == "serie":
415
+ serie_title = job["title"].strip()
416
+ season_label = (job.get("season_name") or "Temporada 1").strip()
417
+ full_serie_name = f"{serie_title} - {season_label}" if season_label.lower() not in serie_title.lower() else serie_title
418
+ serie_key = full_serie_name.lower().strip()
419
+
420
+ if serie_key not in CATALOG["series"]:
421
+ CATALOG["series"][serie_key] = {
422
+ "id": str(uuid.uuid4())[:8],
423
+ "tipo": "serie",
424
+ "name": full_serie_name,
425
+ "ico": poster_url,
426
+ "temporada": [],
427
+ "date": now_str,
428
+ "repo": repo_id
429
+ }
430
+ else:
431
+ if poster_url:
432
+ CATALOG["series"][serie_key]["ico"] = poster_url
433
+ CATALOG["series"][serie_key]["date"] = now_str
434
+
435
+ ep_name = (job.get("episode_name") or "Capitulo 01").strip()
436
+ ep_obj = {
437
+ "name": ep_name,
438
+ "ico": CATALOG["series"][serie_key]["ico"],
439
+ "uri": stream_uri,
440
+ "code": camouflaged_name,
441
+ "size_str": size_str
442
+ }
443
+
444
+ existing_eps = CATALOG["series"][serie_key]["temporada"]
445
+ replaced = False
446
+ for i, ep in enumerate(existing_eps):
447
+ if ep["name"].lower() == ep_name.lower():
448
+ existing_eps[i] = ep_obj
449
+ replaced = True
450
+ break
451
+ if not replaced:
452
+ existing_eps.append(ep_obj)
453
+
454
+ existing_eps.sort(key=lambda e: int(re.findall(r"\d+", e.get("name", ""))[0]) if re.findall(r"\d+", e.get("name", "")) else 9999)
455
+ else:
456
+ movie_obj = {
457
+ "id": str(uuid.uuid4())[:8],
458
+ "name": job["title"].strip(),
459
+ "ico": poster_url,
460
+ "uri": stream_uri,
461
+ "code": camouflaged_name,
462
+ "size_str": size_str,
463
+ "date": now_str,
464
+ "repo": repo_id
465
+ }
466
+ CATALOG["movies"].insert(0, movie_obj)
467
+
468
+ save_catalog_to_hf()
469
+ job["progress"] = 100
470
+ job["status"] = f"✅ ¡Completado! Subido a Hugging Face como {camouflaged_name} ({size_str})"
471
+ job["state"] = "done"
472
+
473
+ except Exception as e:
474
+ ACTIVE_UPLOAD_JOB = None
475
+ job["state"] = "error"
476
+ job["status"] = f"❌ Error: {str(e)}"
477
+ finally:
478
+ ACTIVE_UPLOAD_JOB = None
479
+ shutil.rmtree(job_dir, ignore_errors=True)
480
+
481
+
482
+ def background_worker():
483
+ global WORKER_RUNNING
484
+ while True:
485
+ next_job = None
486
+ with STATE_LOCK:
487
+ for j in JOBS:
488
+ if j["state"] == "queued":
489
+ j["state"] = "running"
490
+ next_job = j
491
+ break
492
+ if not next_job:
493
+ WORKER_RUNNING = False
494
+ return
495
+ process_job(next_job)
496
+
497
+
498
+ def start_worker_if_needed():
499
+ global WORKER_RUNNING
500
+ with STATE_LOCK:
501
+ if not WORKER_RUNNING:
502
+ WORKER_RUNNING = True
503
+ t = threading.Thread(target=background_worker, daemon=True)
504
+ t.start()
505
+
506
+
507
+ @app.route("/api/tmdb/search", methods=["GET"])
508
+ def api_tmdb_search():
509
+ q = request.args.get("q", "")
510
+ ctype = request.args.get("type", "movie")
511
+ return jsonify({"success": True, "results": search_tmdb(q, ctype)})
512
+
513
+
514
+ @app.route("/api/jobs/enqueue", methods=["POST"])
515
+ def api_enqueue():
516
+ data = request.get_json() or {}
517
+ content_type = data.get("content_type", "movie")
518
+ raw_urls = data.get("urls", "")
519
+ title = (data.get("title") or "").strip()
520
+ poster_url = (data.get("poster_url") or "").strip()
521
+ rar_password = (data.get("rar_password") or "").strip()
522
+ season_name = (data.get("season_name") or "Temporada 1").strip()
523
+ episode_start = (data.get("episode_name") or "Capitulo 01").strip()
524
+ dataset_repo = (data.get("dataset_repo") or CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO).strip()
525
+
526
+ urls = extract_urls_from_text(raw_urls)
527
+ if not urls:
528
+ return jsonify({"success": False, "message": "Pegá al menos un enlace válido."}), 400
529
+ if not title:
530
+ return jsonify({"success": False, "message": "Escribí el título de la Película o Serie."}), 400
531
+
532
+ with STATE_LOCK:
533
+ CATALOG["dataset_repo"] = dataset_repo
534
+
535
+ if not poster_url:
536
+ hits = search_tmdb(title, content_type)
537
+ if hits:
538
+ poster_url = hits[0]["poster"]
539
+
540
+ start_num = 1
541
+ m_num = re.search(r"(\d+)", episode_start)
542
+ if m_num:
543
+ start_num = int(m_num.group(1))
544
+
545
+ created_jobs = []
546
+ for idx, u in enumerate(urls):
547
+ if content_type == "serie":
548
+ ep_num = start_num + idx
549
+ if len(urls) > 1:
550
+ m_se = re.search(r"[sS]\d+[eE](\d+)", u)
551
+ if m_se:
552
+ ep_num = int(m_se.group(1))
553
+ ep_label = f"Capitulo {ep_num:02d}"
554
+ display_label = f"{title} ({season_name} - {ep_label})"
555
+ else:
556
+ ep_label = ""
557
+ display_label = title if len(urls) == 1 else f"{title} ({idx + 1})"
558
+
559
+ job = {
560
+ "id": str(uuid.uuid4())[:8],
561
+ "content_type": content_type,
562
+ "source_url": u,
563
+ "title": title,
564
+ "display_label": display_label,
565
+ "poster_url": poster_url,
566
+ "rar_password": rar_password,
567
+ "season_name": season_name,
568
+ "episode_name": ep_label,
569
+ "dataset_repo": dataset_repo,
570
+ "state": "queued",
571
+ "status": "En cola esperando turno...",
572
+ "progress": 0,
573
+ "created_at": time.strftime("%H:%M:%S")
574
+ }
575
+ with STATE_LOCK:
576
+ JOBS.insert(0, job)
577
+ created_jobs.append(job)
578
+
579
+ start_worker_if_needed()
580
+ return jsonify({"success": True, "jobs": created_jobs})
581
+
582
+
583
+ @app.route("/api/state", methods=["GET"])
584
+ def api_state():
585
+ with STATE_LOCK:
586
+ return jsonify({
587
+ "success": True,
588
+ "dataset_repo": CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO),
589
+ "jobs": JOBS[:25],
590
+ "movies": CATALOG["movies"],
591
+ "series": list(CATALOG["series"].values())
592
+ })
593
+
594
+
595
+ @app.route("/api/item/delete", methods=["POST"])
596
+ def api_item_delete():
597
+ data = request.get_json() or {}
598
+ item_type = data.get("type")
599
+ item_id = data.get("id")
600
+ with STATE_LOCK:
601
+ if item_type == "movie":
602
+ CATALOG["movies"] = [m for m in CATALOG["movies"] if m.get("id") != item_id]
603
+ elif item_type == "serie":
604
+ for k in [k for k, v in CATALOG["series"].items() if v.get("id") == item_id]:
605
+ del CATALOG["series"][k]
606
+ save_catalog_to_hf()
607
+ return jsonify({"success": True})
608
+
609
+
610
+ HTML_TEMPLATE = r"""<!DOCTYPE html>
611
+ <html lang="es">
612
+ <head>
613
+ <meta charset="UTF-8">
614
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
615
+ <title>Nuevo Media Server - Hugging Face CDN</title>
616
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
617
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
618
+ <style>
619
+ :root {
620
+ --bg-main: #0b0e17;
621
+ --bg-card: #121726;
622
+ --bg-input: #0d111d;
623
+ --border: #1f2942;
624
+ --accent: #6366f1;
625
+ --accent-hover: #4f46e5;
626
+ --cyan: #06b6d4;
627
+ --green: #10b981;
628
+ --text: #f1f5f9;
629
+ --muted: #94a3b8;
630
+ }
631
+ * { box-sizing: border-box; margin: 0; padding: 0; }
632
+ body {
633
+ font-family: 'Inter', sans-serif;
634
+ background: var(--bg-main);
635
+ color: var(--text);
636
+ min-height: 100vh;
637
+ padding: 24px 32px;
638
+ }
639
+ .header-bar {
640
+ display: flex;
641
+ justify-content: space-between;
642
+ align-items: center;
643
+ margin-bottom: 24px;
644
+ flex-wrap: wrap;
645
+ gap: 16px;
646
+ }
647
+ .brand-box {
648
+ display: flex;
649
+ align-items: center;
650
+ gap: 14px;
651
+ }
652
+ .brand-logo {
653
+ width: 44px;
654
+ height: 44px;
655
+ border-radius: 12px;
656
+ background: linear-gradient(135deg, #a855f7, #ec4899);
657
+ display: flex;
658
+ align-items: center;
659
+ justify-content: center;
660
+ font-size: 20px;
661
+ box-shadow: 0 4px 15px rgba(168, 85, 247, 0.35);
662
+ }
663
+ .brand-title h1 { font-size: 22px; font-weight: 800; letter-spacing: -0.3px; }
664
+ .brand-title p { font-size: 13px; color: var(--muted); margin-top: 2px; }
665
+ .repo-badge {
666
+ display: flex;
667
+ align-items: center;
668
+ gap: 10px;
669
+ background: var(--bg-card);
670
+ border: 1px solid var(--border);
671
+ padding: 8px 14px;
672
+ border-radius: 10px;
673
+ font-size: 13px;
674
+ }
675
+ .repo-badge input {
676
+ background: var(--bg-input);
677
+ border: 1px solid var(--border);
678
+ color: #38bdf8;
679
+ padding: 6px 10px;
680
+ border-radius: 6px;
681
+ font-family: 'JetBrains Mono', monospace;
682
+ font-size: 12px;
683
+ width: 240px;
684
+ }
685
+ .card {
686
+ background: var(--bg-card);
687
+ border: 1px solid var(--border);
688
+ border-radius: 14px;
689
+ padding: 24px;
690
+ margin-bottom: 24px;
691
+ box-shadow: 0 10px 30px rgba(0,0,0,0.25);
692
+ }
693
+ .card-header {
694
+ display: flex;
695
+ justify-content: space-between;
696
+ align-items: center;
697
+ margin-bottom: 20px;
698
+ flex-wrap: wrap;
699
+ gap: 12px;
700
+ }
701
+ .card-title {
702
+ font-size: 17px;
703
+ font-weight: 700;
704
+ display: flex;
705
+ align-items: center;
706
+ gap: 10px;
707
+ }
708
+ .card-sub {
709
+ font-size: 12px;
710
+ color: var(--muted);
711
+ margin-top: 3px;
712
+ }
713
+ .form-label {
714
+ display: block;
715
+ font-size: 12px;
716
+ font-weight: 600;
717
+ color: #cbd5e1;
718
+ margin-bottom: 7px;
719
+ }
720
+ .form-control, select, textarea {
721
+ width: 100%;
722
+ background: var(--bg-input);
723
+ border: 1px solid var(--border);
724
+ color: var(--text);
725
+ padding: 11px 14px;
726
+ border-radius: 8px;
727
+ font-size: 13.5px;
728
+ font-family: inherit;
729
+ outline: none;
730
+ transition: border-color 0.2s;
731
+ }
732
+ .form-control:focus, select:focus, textarea:focus {
733
+ border-color: var(--accent);
734
+ }
735
+ textarea {
736
+ resize: vertical;
737
+ min-height: 76px;
738
+ font-family: 'JetBrains Mono', monospace;
739
+ font-size: 12.5px;
740
+ }
741
+ .grid-row {
742
+ display: grid;
743
+ grid-template-columns: 2fr 1.2fr 1fr 1fr;
744
+ gap: 14px;
745
+ margin-top: 16px;
746
+ align-items: end;
747
+ }
748
+ @media (max-width: 960px) {
749
+ .grid-row { grid-template-columns: 1fr 1fr; }
750
+ }
751
+ .btn {
752
+ border: none;
753
+ cursor: pointer;
754
+ padding: 11px 18px;
755
+ border-radius: 8px;
756
+ font-weight: 600;
757
+ font-size: 13.5px;
758
+ display: inline-flex;
759
+ align-items: center;
760
+ justify-content: center;
761
+ gap: 8px;
762
+ color: #fff;
763
+ transition: all 0.15s;
764
+ }
765
+ .btn-tmdb { background: #0284c7; }
766
+ .btn-tmdb:hover { background: #0369a1; }
767
+ .btn-primary {
768
+ background: linear-gradient(135deg, #6366f1, #4f46e5);
769
+ box-shadow: 0 4px 14px rgba(99, 102, 241, 0.35);
770
+ }
771
+ .btn-primary:hover { transform: translateY(-1px); }
772
+ .btn-green { background: #059669; }
773
+ .btn-green:hover { background: #047857; }
774
+ .btn-sm { padding: 7px 12px; font-size: 12px; border-radius: 6px; }
775
+ .title-group {
776
+ display: flex;
777
+ gap: 8px;
778
+ }
779
+ .selected-poster-bar {
780
+ margin-top: 14px;
781
+ display: none;
782
+ align-items: center;
783
+ gap: 14px;
784
+ background: rgba(15, 23, 42, 0.7);
785
+ padding: 10px 14px;
786
+ border-radius: 10px;
787
+ border: 1px solid var(--border);
788
+ }
789
+ .selected-poster-bar img {
790
+ width: 44px;
791
+ height: 64px;
792
+ object-fit: cover;
793
+ border-radius: 6px;
794
+ }
795
+ .tmdb-results-box {
796
+ display: none;
797
+ margin-top: 14px;
798
+ background: var(--bg-input);
799
+ border: 1px solid var(--border);
800
+ border-radius: 10px;
801
+ padding: 14px;
802
+ }
803
+ .tmdb-grid {
804
+ display: flex;
805
+ gap: 12px;
806
+ overflow-x: auto;
807
+ padding-bottom: 6px;
808
+ }
809
+ .tmdb-card {
810
+ width: 110px;
811
+ flex-shrink: 0;
812
+ cursor: pointer;
813
+ border-radius: 8px;
814
+ overflow: hidden;
815
+ border: 2px solid transparent;
816
+ background: #161f33;
817
+ transition: transform 0.15s, border-color 0.15s;
818
+ }
819
+ .tmdb-card:hover {
820
+ transform: scale(1.04);
821
+ border-color: #38bdf8;
822
+ }
823
+ .tmdb-card img {
824
+ width: 100%;
825
+ height: 155px;
826
+ object-fit: cover;
827
+ display: block;
828
+ }
829
+ .tmdb-card-title {
830
+ font-size: 11px;
831
+ padding: 6px;
832
+ text-align: center;
833
+ white-space: nowrap;
834
+ overflow: hidden;
835
+ text-overflow: ellipsis;
836
+ }
837
+ .job-item {
838
+ background: var(--bg-input);
839
+ border: 1px solid var(--border);
840
+ border-radius: 9px;
841
+ padding: 12px 16px;
842
+ margin-bottom: 10px;
843
+ }
844
+ .job-top {
845
+ display: flex;
846
+ justify-content: space-between;
847
+ font-size: 13px;
848
+ font-weight: 600;
849
+ margin-bottom: 6px;
850
+ }
851
+ .progress-track {
852
+ width: 100%;
853
+ height: 7px;
854
+ background: #1e293b;
855
+ border-radius: 99px;
856
+ overflow: hidden;
857
+ }
858
+ .progress-fill {
859
+ height: 100%;
860
+ background: linear-gradient(90deg, #6366f1, #06b6d4);
861
+ transition: width 0.3s;
862
+ }
863
+ table {
864
+ width: 100%;
865
+ border-collapse: collapse;
866
+ margin-top: 12px;
867
+ }
868
+ th {
869
+ text-align: left;
870
+ font-size: 12px;
871
+ color: var(--muted);
872
+ padding: 12px;
873
+ border-bottom: 1px solid var(--border);
874
+ }
875
+ td {
876
+ padding: 12px;
877
+ border-bottom: 1px solid rgba(31, 41, 66, 0.6);
878
+ font-size: 13.5px;
879
+ vertical-align: middle;
880
+ }
881
+ .poster-thumb {
882
+ width: 44px;
883
+ height: 64px;
884
+ object-fit: cover;
885
+ border-radius: 6px;
886
+ border: 1px solid var(--border);
887
+ }
888
+ .badge-movie {
889
+ background: rgba(99, 102, 241, 0.2);
890
+ color: #818cf8;
891
+ padding: 3px 8px;
892
+ border-radius: 5px;
893
+ font-size: 11px;
894
+ font-weight: 700;
895
+ }
896
+ .badge-serie {
897
+ background: rgba(16, 185, 129, 0.2);
898
+ color: #34d399;
899
+ padding: 3px 8px;
900
+ border-radius: 5px;
901
+ font-size: 11px;
902
+ font-weight: 700;
903
+ }
904
+ .code-pill {
905
+ font-family: 'JetBrains Mono', monospace;
906
+ font-size: 11.5px;
907
+ color: #38bdf8;
908
+ background: rgba(56, 189, 248, 0.1);
909
+ padding: 4px 8px;
910
+ border-radius: 5px;
911
+ }
912
+ .modal-backdrop {
913
+ display: none;
914
+ position: fixed;
915
+ inset: 0;
916
+ background: rgba(0, 0, 0, 0.75);
917
+ z-index: 999;
918
+ align-items: center;
919
+ justify-content: center;
920
+ padding: 20px;
921
+ }
922
+ .modal-box {
923
+ background: var(--bg-card);
924
+ border: 1px solid var(--border);
925
+ border-radius: 14px;
926
+ max-width: 720px;
927
+ width: 100%;
928
+ padding: 22px;
929
+ }
930
+ .modal-pre {
931
+ background: #070a12;
932
+ border: 1px solid var(--border);
933
+ padding: 14px;
934
+ border-radius: 8px;
935
+ color: #a5f3fc;
936
+ font-family: 'JetBrains Mono', monospace;
937
+ font-size: 12px;
938
+ max-height: 400px;
939
+ overflow-y: auto;
940
+ white-space: pre-wrap;
941
+ margin: 14px 0;
942
+ }
943
+ .filter-pills {
944
+ display: flex;
945
+ gap: 8px;
946
+ }
947
+ .pill-btn {
948
+ background: var(--bg-input);
949
+ border: 1px solid var(--border);
950
+ color: var(--muted);
951
+ padding: 7px 14px;
952
+ border-radius: 20px;
953
+ font-size: 12.5px;
954
+ font-weight: 600;
955
+ cursor: pointer;
956
+ }
957
+ .pill-btn.active {
958
+ background: var(--accent);
959
+ color: #fff;
960
+ border-color: var(--accent);
961
+ }
962
+ </style>
963
+ </head>
964
+ <body>
965
+
966
+ <div class="header-bar">
967
+ <div class="brand-box">
968
+ <div class="brand-logo"><i class="fa-solid fa-play"></i></div>
969
+ <div class="brand-title">
970
+ <h1>Gestor de Descargas & Media Server <span style="font-size:12px; background:#10b981; color:#042f2e; padding:3px 8px; border-radius:6px; vertical-align:middle;">NUEVO HF CDN</span></h1>
971
+ <p>Descarga de enlaces directos/MediaFire, descompresión RAR automática, subida camuflada a Hugging Face y generador JSON.</p>
972
+ </div>
973
+ </div>
974
+
975
+ <div class="repo-badge">
976
+ <span><i class="fa-solid fa-database" style="color:#a855f7;"></i> Dataset Activo:</span>
977
+ <input type="text" id="datasetRepoInput" value="{{ dataset_repo }}" title="Podés cambiar a otro Dataset cuando quieras repartir películas">
978
+ </div>
979
+ </div>
980
+
981
+ <!-- DESCARGADOR & EXTRACTOR RAR -->
982
+ <div class="card">
983
+ <div class="card-header">
984
+ <div>
985
+ <div class="card-title"><i class="fa-solid fa-cloud-arrow-down" style="color:#818cf8;"></i> Descargador & Extractor RAR en Segundo Plano</div>
986
+ <div class="card-sub">Baja desde MediaFire/Directo, descomprime RAR con clave, sube a Hugging Face con nombre camuflado (v_0001.mp4 / s_0001_e01.mp4) y libera tu disco.</div>
987
+ </div>
988
+ <div style="display:flex; align-items:center; gap:10px;">
989
+ <span style="font-size:12.5px; color:var(--muted);"><i class="fa-solid fa-layer-group"></i> Tipo de Contenido:</span>
990
+ <select id="contentType" style="width:170px; font-weight:700;" onchange="toggleTypeFields()">
991
+ <option value="movie">🎬 Película</option>
992
+ <option value="serie">📺 Serie</option>
993
+ </select>
994
+ </div>
995
+ </div>
996
+
997
+ <div>
998
+ <label class="form-label"><i class="fa-solid fa-link"></i> Enlace(s) de Descarga (MediaFire, Dropbox o Directo RAR/ZIP/MP4) — <span style="color:#38bdf8;">¡En Series podés pegar de a 1 capítulo o pegar los 6 links juntos!</span></label>
999
+ <textarea id="downloadUrls" placeholder="Pegá acá el link de MediaFire (o varios links uno abajo del otro, incluso con [count] de pastedvdrip)..."></textarea>
1000
+ </div>
1001
+
1002
+ <div class="grid-row">
1003
+ <div>
1004
+ <label class="form-label" id="titleLabel"><i class="fa-solid fa-film"></i> Título del Contenido</label>
1005
+ <div class="title-group">
1006
+ <input type="text" id="contentTitle" class="form-control" placeholder="Ej: El amor de tu vida o Cautiva">
1007
+ <button type="button" class="btn btn-tmdb" onclick="buscarTMDB()"><i class="fa-solid fa-magnifying-glass"></i> TMDB</button>
1008
+ </div>
1009
+ </div>
1010
+
1011
+ <div>
1012
+ <label class="form-label"><i class="fa-solid fa-key"></i> Clave RAR/ZIP (si tiene)</label>
1013
+ <input type="text" id="rarPassword" class="form-control" value="peliculas-dvdrip.com">
1014
+ </div>
1015
+
1016
+ <div id="seasonBox" style="display:none;">
1017
+ <label class="form-label"><i class="fa-solid fa-folder-tree"></i> Temporada</label>
1018
+ <input type="text" id="seasonName" class="form-control" value="Temporada 1">
1019
+ </div>
1020
+
1021
+ <div id="episodeBox" style="display:none;">
1022
+ <label class="form-label"><i class="fa-solid fa-list-ol"></i> Capítulo / Episodio</label>
1023
+ <input type="text" id="episodeName" class="form-control" value="Capitulo 01">
1024
+ </div>
1025
+
1026
+ <div id="submitBox" style="grid-column: span 2; display:flex; justify-content:flex-end;">
1027
+ <button type="button" class="btn btn-primary" style="width:100%; max-width:340px;" onclick="iniciarDescarga()">
1028
+ <i class="fa-solid fa-cloud-arrow-up"></i> Iniciar Descarga en Segundo Plano
1029
+ </button>
1030
+ </div>
1031
+ </div>
1032
+
1033
+ <!-- Barra de Póster Seleccionado -->
1034
+ <div class="selected-poster-bar" id="selectedPosterBar">
1035
+ <img id="posterPreviewImg" src="" alt="Poster">
1036
+ <div style="flex:1;">
1037
+ <div style="font-size:12px; color:var(--muted);">Póster TMDB seleccionado (podés editar el link si querés):</div>
1038
+ <input type="text" id="posterUrlInput" class="form-control" style="margin-top:4px; padding:7px 10px; font-size:12px;">
1039
+ </div>
1040
+ </div>
1041
+
1042
+ <!-- Resultados de búsqueda TMDB -->
1043
+ <div class="tmdb-results-box" id="tmdbResultsBox">
1044
+ <div style="display:flex; justify-content:space-between; margin-bottom:8px; font-size:12px; color:var(--muted);">
1045
+ <span>Hacé clic en la portada correcta para seleccionarla:</span>
1046
+ <span style="cursor:pointer; color:#f87171;" onclick="document.getElementById('tmdbResultsBox').style.display='none'">✖ Cerrar</span>
1047
+ </div>
1048
+ <div class="tmdb-grid" id="tmdbGrid"></div>
1049
+ </div>
1050
+ </div>
1051
+
1052
+ <!-- COLA DE DESCARGAS EN CURSO -->
1053
+ <div class="card" id="jobsCard" style="display:none;">
1054
+ <div class="card-header" style="margin-bottom:12px;">
1055
+ <div class="card-title"><i class="fa-solid fa-bolt" style="color:#facc15;"></i> Procesos en Segundo Plano</div>
1056
+ </div>
1057
+ <div id="jobsContainer"></div>
1058
+ </div>
1059
+
1060
+ <!-- BIBLIOTECA & GENERADOR JSON -->
1061
+ <div class="card">
1062
+ <div class="card-header">
1063
+ <div>
1064
+ <div class="card-title"><i class="fa-solid fa-box-archive" style="color:#38bdf8;"></i> Biblioteca de Contenidos & Generador JSON</div>
1065
+ <div class="card-sub">Archivos alojados y camuflados en Hugging Face CDN, listos para copiar el JSON exacto para tu app.</div>
1066
+ </div>
1067
+ <div class="filter-pills">
1068
+ <button class="pill-btn active" id="tabAll" onclick="setFilter('all')">Todas (<span id="countAll">0</span>)</button>
1069
+ <button class="pill-btn" id="tabMovies" onclick="setFilter('movie')">🎬 Películas (<span id="countMovies">0</span>)</button>
1070
+ <button class="pill-btn" id="tabSeries" onclick="setFilter('serie')">📺 Series (<span id="countSeries">0</span>)</button>
1071
+ </div>
1072
+ </div>
1073
+
1074
+ <table>
1075
+ <thead>
1076
+ <tr>
1077
+ <th>Póster & Tipo</th>
1078
+ <th>Título en tu App</th>
1079
+ <th>Archivo Camuflado (HF)</th>
1080
+ <th>Detalles / Capítulos</th>
1081
+ <th>Fecha</th>
1082
+ <th style="text-align:right;">Acciones & JSON</th>
1083
+ </tr>
1084
+ </thead>
1085
+ <tbody id="libraryBody">
1086
+ <tr><td colspan="6" style="text-align:center; color:var(--muted); padding:28px;">Cargando biblioteca...</td></tr>
1087
+ </tbody>
1088
+ </table>
1089
+ </div>
1090
+
1091
+ <!-- MODAL PARA VER/COPIAR JSON -->
1092
+ <div class="modal-backdrop" id="jsonModal">
1093
+ <div class="modal-box">
1094
+ <div style="display:flex; justify-content:space-between; align-items:center;">
1095
+ <h3 style="font-size:16px;"><i class="fa-solid fa-code" style="color:#38bdf8;"></i> JSON Generado (Formato Exacto de tu App)</h3>
1096
+ <button class="btn btn-sm" style="background:#334155;" onclick="closeJsonModal()">✖</button>
1097
+ </div>
1098
+ <pre class="modal-pre" id="jsonModalText"></pre>
1099
+ <div style="display:flex; justify-content:flex-end; gap:10px;">
1100
+ <button class="btn btn-green" onclick="copyModalJson()"><i class="fa-solid fa-copy"></i> Copiar JSON al Portapapeles</button>
1101
+ </div>
1102
+ </div>
1103
+ </div>
1104
+
1105
+ <script>
1106
+ let currentFilter = 'all';
1107
+ let stateData = { movies: [], series: [], jobs: [] };
1108
+
1109
+ function toggleTypeFields() {
1110
+ const type = document.getElementById('contentType').value;
1111
+ const seasonBox = document.getElementById('seasonBox');
1112
+ const epBox = document.getElementById('episodeBox');
1113
+ const submitBox = document.getElementById('submitBox');
1114
+ if (type === 'serie') {
1115
+ seasonBox.style.display = 'block';
1116
+ epBox.style.display = 'block';
1117
+ submitBox.style.gridColumn = 'span 4';
1118
+ } else {
1119
+ seasonBox.style.display = 'none';
1120
+ epBox.style.display = 'none';
1121
+ submitBox.style.gridColumn = 'span 2';
1122
+ }
1123
+ }
1124
+
1125
+ async function buscarTMDB() {
1126
+ const q = document.getElementById('contentTitle').value.trim();
1127
+ const type = document.getElementById('contentType').value;
1128
+ if (!q) {
1129
+ alert('Escribí primero el nombre de la película o serie.');
1130
+ return;
1131
+ }
1132
+ const box = document.getElementById('tmdbResultsBox');
1133
+ const grid = document.getElementById('tmdbGrid');
1134
+ box.style.display = 'block';
1135
+ grid.innerHTML = '<div style="padding:12px; color:#94a3b8;">Buscando pósters en TMDB...</div>';
1136
+
1137
+ try {
1138
+ const res = await fetch(`/api/tmdb/search?q=${encodeURIComponent(q)}&type=${type}`);
1139
+ const data = await res.json();
1140
+ if (!data.results || data.results.length === 0) {
1141
+ grid.innerHTML = '<div style="padding:12px; color:#f87171;">No se encontraron portadas con ese nombre. Podés pegar un link de imagen manualmente.</div>';
1142
+ document.getElementById('selectedPosterBar').style.display = 'flex';
1143
+ return;
1144
+ }
1145
+ grid.innerHTML = '';
1146
+ data.results.forEach(item => {
1147
+ const card = document.createElement('div');
1148
+ card.className = 'tmdb-card';
1149
+ card.onclick = () => selectPoster(item.poster, item.title);
1150
+ card.innerHTML = `
1151
+ <img src="${item.poster}" alt="">
1152
+ <div class="tmdb-card-title" title="${item.title} (${item.year})">${item.title} ${item.year ? '('+item.year+')' : ''}</div>
1153
+ `;
1154
+ grid.appendChild(card);
1155
+ });
1156
+ selectPoster(data.results[0].poster, null, false);
1157
+ } catch (e) {
1158
+ grid.innerHTML = '<div style="padding:12px; color:#f87171;">Error consultando TMDB.</div>';
1159
+ }
1160
+ }
1161
+
1162
+ function selectPoster(url, title, closeBox = true) {
1163
+ document.getElementById('selectedPosterBar').style.display = 'flex';
1164
+ document.getElementById('posterPreviewImg').src = url;
1165
+ document.getElementById('posterUrlInput').value = url;
1166
+ if (closeBox) {
1167
+ document.getElementById('tmdbResultsBox').style.display = 'none';
1168
+ }
1169
+ }
1170
+
1171
+ async function iniciarDescarga() {
1172
+ const content_type = document.getElementById('contentType').value;
1173
+ const urls = document.getElementById('downloadUrls').value.trim();
1174
+ const title = document.getElementById('contentTitle').value.trim();
1175
+ const poster_url = document.getElementById('posterUrlInput').value.trim();
1176
+ const rar_password = document.getElementById('rarPassword').value.trim();
1177
+ const season_name = document.getElementById('seasonName').value.trim();
1178
+ const episode_name = document.getElementById('episodeName').value.trim();
1179
+ const dataset_repo = document.getElementById('datasetRepoInput').value.trim();
1180
+
1181
+ if (!urls || !title) {
1182
+ alert('Completá el enlace de descarga y el título del contenido.');
1183
+ return;
1184
+ }
1185
+
1186
+ const res = await fetch('/api/jobs/enqueue', {
1187
+ method: 'POST',
1188
+ headers: {'Content-Type': 'application/json'},
1189
+ body: JSON.stringify({
1190
+ content_type, urls, title, poster_url,
1191
+ rar_password, season_name, episode_name, dataset_repo
1192
+ })
1193
+ });
1194
+ const data = await res.json();
1195
+ if (!data.success) {
1196
+ alert(data.message || 'Error al encolar descarga');
1197
+ return;
1198
+ }
1199
+ document.getElementById('downloadUrls').value = '';
1200
+ if (content_type === 'serie' && data.jobs && data.jobs.length === 1) {
1201
+ const m = episode_name.match(/(\d+)/);
1202
+ if (m) {
1203
+ const nextNum = String(parseInt(m[1], 10) + 1).padStart(2, '0');
1204
+ document.getElementById('episodeName').value = `Capitulo ${nextNum}`;
1205
+ }
1206
+ }
1207
+ refreshState();
1208
+ }
1209
+
1210
+ function setFilter(f) {
1211
+ currentFilter = f;
1212
+ document.getElementById('tabAll').classList.toggle('active', f === 'all');
1213
+ document.getElementById('tabMovies').classList.toggle('active', f === 'movie');
1214
+ document.getElementById('tabSeries').classList.toggle('active', f === 'serie');
1215
+ renderLibrary();
1216
+ }
1217
+
1218
+ function buildMovieJson(m) {
1219
+ const obj = {
1220
+ name: m.name,
1221
+ ico: m.ico,
1222
+ uri: m.uri
1223
+ };
1224
+ return JSON.stringify(obj, null, 2) + ",";
1225
+ }
1226
+
1227
+ function buildSerieJson(s) {
1228
+ const obj = {
1229
+ tipo: "serie",
1230
+ name: s.name,
1231
+ ico: s.ico,
1232
+ temporada: (s.temporada || []).map(ep => ({
1233
+ name: ep.name,
1234
+ ico: s.ico,
1235
+ uri: ep.uri
1236
+ }))
1237
+ };
1238
+ return JSON.stringify(obj, null, 2) + ",";
1239
+ }
1240
+
1241
+ function openJsonModal(jsonStr) {
1242
+ document.getElementById('jsonModalText').textContent = jsonStr;
1243
+ document.getElementById('jsonModal').style.display = 'flex';
1244
+ }
1245
+
1246
+ function closeJsonModal() {
1247
+ document.getElementById('jsonModal').style.display = 'none';
1248
+ }
1249
+
1250
+ function copyModalJson() {
1251
+ const txt = document.getElementById('jsonModalText').textContent;
1252
+ navigator.clipboard.writeText(txt);
1253
+ alert('¡JSON copiado al portapapeles!');
1254
+ }
1255
+
1256
+ function copyDirectJson(type, id) {
1257
+ let jsonStr = '';
1258
+ if (type === 'movie') {
1259
+ const m = stateData.movies.find(x => x.id === id);
1260
+ if (m) jsonStr = buildMovieJson(m);
1261
+ } else {
1262
+ const s = stateData.series.find(x => x.id === id);
1263
+ if (s) jsonStr = buildSerieJson(s);
1264
+ }
1265
+ if (jsonStr) {
1266
+ openJsonModal(jsonStr);
1267
+ navigator.clipboard.writeText(jsonStr);
1268
+ }
1269
+ }
1270
+
1271
+ async function deleteItem(type, id) {
1272
+ if (!confirm('¿Quitar este registro de la lista del panel?')) return;
1273
+ await fetch('/api/item/delete', {
1274
+ method: 'POST',
1275
+ headers: {'Content-Type': 'application/json'},
1276
+ body: JSON.stringify({type, id})
1277
+ });
1278
+ refreshState();
1279
+ }
1280
+
1281
+ function renderLibrary() {
1282
+ const tbody = document.getElementById('libraryBody');
1283
+ const movies = stateData.movies || [];
1284
+ const series = stateData.series || [];
1285
+
1286
+ document.getElementById('countAll').textContent = movies.length + series.length;
1287
+ document.getElementById('countMovies').textContent = movies.length;
1288
+ document.getElementById('countSeries').textContent = series.length;
1289
+
1290
+ let rows = [];
1291
+
1292
+ if (currentFilter === 'all' || currentFilter === 'serie') {
1293
+ series.forEach(s => {
1294
+ const epCount = (s.temporada || []).length;
1295
+ const codes = (s.temporada || []).map(e => e.code || '').filter(Boolean).join(', ');
1296
+ rows.push(`
1297
+ <tr>
1298
+ <td>
1299
+ <div style="display:flex; align-items:center; gap:10px;">
1300
+ <img class="poster-thumb" src="${s.ico}" alt="">
1301
+ <span class="badge-serie">SERIE</span>
1302
+ </div>
1303
+ </td>
1304
+ <td style="font-weight:700;">${s.name}</td>
1305
+ <td><span class="code-pill">${codes || 's_xxxx.mp4'}</span></td>
1306
+ <td><span style="color:#34d399; font-weight:600;">${epCount} capítulo(s) cargados</span></td>
1307
+ <td style="color:var(--muted); font-size:12px;">${s.date || ''}</td>
1308
+ <td style="text-align:right;">
1309
+ <button class="btn btn-green btn-sm" onclick="copyDirectJson('serie', '${s.id}')">
1310
+ <i class="fa-solid fa-code"></i> Ver / Copiar JSON
1311
+ </button>
1312
+ <button class="btn btn-sm" style="background:#ef4444; margin-left:6px;" onclick="deleteItem('serie', '${s.id}')">
1313
+ <i class="fa-solid fa-trash"></i>
1314
+ </button>
1315
+ </td>
1316
+ </tr>
1317
+ `);
1318
+ });
1319
+ }
1320
+
1321
+ if (currentFilter === 'all' || currentFilter === 'movie') {
1322
+ movies.forEach(m => {
1323
+ rows.push(`
1324
+ <tr>
1325
+ <td>
1326
+ <div style="display:flex; align-items:center; gap:10px;">
1327
+ <img class="poster-thumb" src="${m.ico}" alt="">
1328
+ <span class="badge-movie">PELÍCULA</span>
1329
+ </div>
1330
+ </td>
1331
+ <td style="font-weight:700;">${m.name}</td>
1332
+ <td><span class="code-pill">${m.code || ''}</span></td>
1333
+ <td>${m.size_str || ''}</td>
1334
+ <td style="color:var(--muted); font-size:12px;">${m.date || ''}</td>
1335
+ <td style="text-align:right;">
1336
+ <button class="btn btn-green btn-sm" onclick="copyDirectJson('movie', '${m.id}')">
1337
+ <i class="fa-solid fa-code"></i> Ver / Copiar JSON
1338
+ </button>
1339
+ <button class="btn btn-sm" style="background:#ef4444; margin-left:6px;" onclick="deleteItem('movie', '${m.id}')">
1340
+ <i class="fa-solid fa-trash"></i>
1341
+ </button>
1342
+ </td>
1343
+ </tr>
1344
+ `);
1345
+ });
1346
+ }
1347
+
1348
+ if (rows.length === 0) {
1349
+ tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--muted); padding:28px;">Todavía no hay contenidos cargados. ¡Pegá tu primer enlace arriba para empezar!</td></tr>';
1350
+ } else {
1351
+ tbody.innerHTML = rows.join('');
1352
+ }
1353
+ }
1354
+
1355
+ async function refreshState() {
1356
+ try {
1357
+ const res = await fetch('/api/state');
1358
+ const data = await res.json();
1359
+ if (!data.success) return;
1360
+ stateData = data;
1361
+
1362
+ const jobsCard = document.getElementById('jobsCard');
1363
+ const jobsContainer = document.getElementById('jobsContainer');
1364
+ if (data.jobs && data.jobs.length > 0) {
1365
+ jobsCard.style.display = 'block';
1366
+ jobsContainer.innerHTML = data.jobs.map(j => `
1367
+ <div class="job-item">
1368
+ <div class="job-top">
1369
+ <span>${j.display_label}</span>
1370
+ <span style="color:${j.state === 'error' ? '#f87171' : (j.state === 'done' ? '#34d399' : '#38bdf8')}">${j.status}</span>
1371
+ </div>
1372
+ <div class="progress-track">
1373
+ <div class="progress-fill" style="width:${j.progress || 0}%"></div>
1374
+ </div>
1375
+ </div>
1376
+ `).join('');
1377
+ } else {
1378
+ jobsCard.style.display = 'none';
1379
+ }
1380
+
1381
+ renderLibrary();
1382
+ } catch (e) {}
1383
+ }
1384
+
1385
+ setInterval(refreshState, 2000);
1386
+ refreshState();
1387
+ </script>
1388
+ </body>
1389
+ </html>
1390
+ """
1391
+
1392
+
1393
+ @app.route("/")
1394
+ def index():
1395
+ return render_template_string(HTML_TEMPLATE, dataset_repo=CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO))
1396
+
1397
+
1398
+ if __name__ == "__main__":
1399
+ load_catalog_from_hf()
1400
+ port = int(os.environ.get("PORT", 5050))
1401
+ app.run(host="0.0.0.0", port=port, debug=False)