visionhdstream commited on
Commit
c7e946c
·
verified ·
1 Parent(s): 4536688

Add PelixPlay HD 16-thread downloader and auto-metadata

Browse files
Files changed (1) hide show
  1. _panel_app.py +165 -91
_panel_app.py CHANGED
@@ -298,7 +298,7 @@ def unpack_js_eval(html_text):
298
  return re.sub(r"\b\w+\b", lambda match: repl.get(match.group(0), match.group(0)), p)
299
 
300
 
301
- def cffi_get(url, headers=None, params=None, timeout=15):
302
  try:
303
  from curl_cffi import requests as creq
304
  r = creq.get(url, headers=headers, params=params, impersonate="chrome", timeout=timeout, allow_redirects=True)
@@ -306,13 +306,14 @@ def cffi_get(url, headers=None, params=None, timeout=15):
306
  return r
307
  except Exception:
308
  pass
309
- return requests.get(url, headers=headers, params=params, timeout=timeout, allow_redirects=True)
 
310
 
311
 
312
  def _verify_and_extract_hls_segments(master_url, referer, ua):
313
  """Verifica que el master.m3u8, su variante de mayor calidad y el primer segmento respondan 200 OK."""
314
  hdrs = {"User-Agent": ua, "Referer": referer}
315
- r_master = cffi_get(master_url, headers=hdrs, timeout=10)
316
  if r_master.status_code != 200 or "#EXTM3U" not in r_master.text:
317
  return None
318
  master_text = r_master.text
@@ -334,7 +335,7 @@ def _verify_and_extract_hls_segments(master_url, referer, ua):
334
  if res_m:
335
  res_label = res_m.group(1)
336
 
337
- r_var = cffi_get(variant_url, headers=hdrs, timeout=12)
338
  if r_var.status_code != 200 or "#EXTM3U" not in r_var.text:
339
  return None
340
 
@@ -347,15 +348,16 @@ def _verify_and_extract_hls_segments(master_url, referer, ua):
347
  return None
348
 
349
  # Probar que el primer segmento realmente descargue bytes de video (evita 403 por bloqueo de IP)
350
- r_s0 = cffi_get(seg_urls[0], headers=hdrs, timeout=10)
351
  if r_s0.status_code != 200 or len(r_s0.content) < 1000:
352
  return None
353
 
354
  return variant_url, seg_urls, res_label
355
 
356
 
357
- def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1):
358
- """Consulta api.php de PelixPlay y extrae la lista verificada de segmentos HLS en Audio Latino HD."""
 
359
  params = {"action": "details", "id": str(tmdb_id), "type": media_type}
360
  if media_type == "tv":
361
  params["season"] = str(season or 1)
@@ -366,8 +368,23 @@ def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1):
366
  "User-Agent": ua,
367
  "Referer": f"https://pelixplay.app/embed/embed-final.html?id={tmdb_id}"
368
  }
369
- r = cffi_get("https://pelixplay.app/embed/api.php", params=params, headers=headers, timeout=15)
370
- data = r.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  if not data.get("ok"):
372
  raise RuntimeError("PelixPlay informó que este título/episodio no está disponible todavía.")
373
 
@@ -389,7 +406,7 @@ def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1):
389
  if isinstance(urls, str):
390
  urls = [urls]
391
  for u in urls:
392
- if u and u not in embed_candidates:
393
  embed_candidates.append(u)
394
 
395
  if not embed_candidates:
@@ -400,7 +417,7 @@ def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1):
400
  try:
401
  parsed_emb = urlparse(emb_url)
402
  emb_origin = f"{parsed_emb.scheme}://{parsed_emb.netloc}"
403
- r_emb = cffi_get(emb_url, headers={"User-Agent": ua, "Referer": "https://pelixplay.app/"}, timeout=12)
404
  unpacked = unpack_js_eval(r_emb.text)
405
  if unpacked:
406
  for hls_key in ["hls4", "hls3", "hls2"]:
@@ -411,29 +428,32 @@ def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1):
411
  verified = _verify_and_extract_hls_segments(full_hls, emb_origin + "/", ua)
412
  if verified:
413
  variant_url, seg_urls, res_label = verified
414
- return variant_url, seg_urls, res_label, emb_origin + "/", data.get("tmdb_title")
415
  except Exception:
416
  continue
417
 
418
  # 2. Fallback: usar extract.php de PelixPlay verificando también que el segmento 0 no dé 403
419
  for emb_url in embed_candidates:
420
- try:
421
- r_ext = requests.post(
422
- "https://pelixplay.app/embed/extract.php",
423
- json={"url": emb_url},
424
- headers=headers,
425
- timeout=12
426
- )
427
- if r_ext.status_code == 200:
428
- ext_data = r_ext.json()
429
- ref = ext_data.get("referer") or "https://pelixplay.app/"
430
- for s_url in (ext_data.get("streams") or []):
431
- verified = _verify_and_extract_hls_segments(s_url, ref, ua)
432
- if verified:
433
- variant_url, seg_urls, res_label = verified
434
- return variant_url, seg_urls, res_label, ref, data.get("tmdb_title")
435
- except Exception:
436
- continue
 
 
 
437
 
438
  raise RuntimeError("No se pudo extraer un stream HLS directo de los servidores de PelixPlay.")
439
 
@@ -466,75 +486,129 @@ def download_pelixplay_to_mp4(job, p_info, job_dir):
466
  m_e = re.search(r"(\d+)", job.get("episode_name", "1"))
467
  episode_num = int(m_e.group(1)) if m_e else 1
468
 
469
- job["status"] = "🔍 Extrayendo stream Audio Latino HD desde PelixPlay..."
470
- job["progress"] = 4
 
471
 
472
- variant_url, seg_urls, res_label, referer, api_title = resolve_pelixplay_hls(tmdb_id, media_type, season_num, episode_num)
473
- if api_title and not job.get("title"):
474
- job["title"] = api_title
475
 
476
- headers = {
477
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
478
- "Referer": referer
479
- }
480
 
481
- total_segs = len(seg_urls)
482
- job["status"] = f"⬇️ Descargando PelixPlay ({res_label}): 0% (0/{total_segs} segmentos)..."
483
- job["progress"] = 6
 
 
 
 
 
 
 
484
 
485
- seg_dir = os.path.join(job_dir, "segs")
486
- os.makedirs(seg_dir, exist_ok=True)
487
 
488
- dl_start = time.time()
489
- completed_segs = 0
490
- downloaded_bytes = 0
491
- seg_lock = threading.Lock()
492
 
493
- def fetch_seg(idx, s_url):
494
- if job.get("cancelled"):
495
- raise InterruptedError("Cancelado por el usuario")
496
- for attempt in range(4):
497
- if job.get("cancelled"):
498
- raise InterruptedError("Cancelado por el usuario")
499
- try:
500
- resp = requests.get(s_url, headers=headers, timeout=20)
501
- if resp.status_code != 200 or not resp.content:
502
- resp = cffi_get(s_url, headers=headers, timeout=20)
503
- if resp.status_code == 200 and resp.content:
504
- clean_ts = strip_fake_png_header(resp.content)
505
- seg_file = os.path.join(seg_dir, f"seg_{idx:05d}.ts")
506
- with open(seg_file, "wb") as fs:
507
- fs.write(clean_ts)
508
- return len(clean_ts)
509
- except InterruptedError:
510
- raise
511
- except Exception:
512
- time.sleep(0.5 * (attempt + 1))
513
- raise RuntimeError(f"Fallo descargando segmento {idx}/{total_segs}")
514
 
515
- with ThreadPoolExecutor(max_workers=16) as pool:
516
- futures = {pool.submit(fetch_seg, i, u): i for i, u in enumerate(seg_urls)}
517
- for fut in as_completed(futures):
518
- if job.get("cancelled"):
519
- for f_rem in futures:
520
- f_rem.cancel()
521
- raise InterruptedError("Cancelado por el usuario")
522
- sz = fut.result()
523
- with seg_lock:
524
- completed_segs += 1
525
- downloaded_bytes += sz
526
- pct_dl = int((completed_segs / total_segs) * 100)
527
- elapsed = max(0.3, time.time() - dl_start)
528
- speed_mb = (downloaded_bytes / (1024 * 1024)) / elapsed
529
- rem_segs = total_segs - completed_segs
530
- segs_per_sec = completed_segs / elapsed
531
- eta_s = rem_segs / segs_per_sec if segs_per_sec > 0 else 0
532
- job["progress"] = min(68, 6 + int((completed_segs / total_segs) * 62))
533
- job["status"] = (
534
- f"⬇️ Descargando PelixPlay ({res_label}): {pct_dl}% "
535
- f"({completed_segs}/{total_segs} segs — {format_size(downloaded_bytes)}) "
536
- f"a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
537
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
 
539
  if job.get("cancelled"):
540
  raise InterruptedError("Cancelado por el usuario")
 
298
  return re.sub(r"\b\w+\b", lambda match: repl.get(match.group(0), match.group(0)), p)
299
 
300
 
301
+ def cffi_get(url, headers=None, params=None, timeout=25, session=None):
302
  try:
303
  from curl_cffi import requests as creq
304
  r = creq.get(url, headers=headers, params=params, impersonate="chrome", timeout=timeout, allow_redirects=True)
 
306
  return r
307
  except Exception:
308
  pass
309
+ getter = session.get if session is not None else requests.get
310
+ return getter(url, headers=headers, params=params, timeout=timeout, allow_redirects=True)
311
 
312
 
313
  def _verify_and_extract_hls_segments(master_url, referer, ua):
314
  """Verifica que el master.m3u8, su variante de mayor calidad y el primer segmento respondan 200 OK."""
315
  hdrs = {"User-Agent": ua, "Referer": referer}
316
+ r_master = cffi_get(master_url, headers=hdrs, timeout=18)
317
  if r_master.status_code != 200 or "#EXTM3U" not in r_master.text:
318
  return None
319
  master_text = r_master.text
 
335
  if res_m:
336
  res_label = res_m.group(1)
337
 
338
+ r_var = cffi_get(variant_url, headers=hdrs, timeout=20)
339
  if r_var.status_code != 200 or "#EXTM3U" not in r_var.text:
340
  return None
341
 
 
348
  return None
349
 
350
  # Probar que el primer segmento realmente descargue bytes de video (evita 403 por bloqueo de IP)
351
+ r_s0 = cffi_get(seg_urls[0], headers=hdrs, timeout=18)
352
  if r_s0.status_code != 200 or len(r_s0.content) < 1000:
353
  return None
354
 
355
  return variant_url, seg_urls, res_label
356
 
357
 
358
+ def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1, skip_embeds=None):
359
+ """Consulta api.php de PelixPlay con reintentos y extrae la lista verificada de segmentos HLS en Audio Latino HD."""
360
+ skip_set = set(skip_embeds or [])
361
  params = {"action": "details", "id": str(tmdb_id), "type": media_type}
362
  if media_type == "tv":
363
  params["season"] = str(season or 1)
 
368
  "User-Agent": ua,
369
  "Referer": f"https://pelixplay.app/embed/embed-final.html?id={tmdb_id}"
370
  }
371
+
372
+ data = None
373
+ last_api_err = None
374
+ for api_try in range(4):
375
+ try:
376
+ r = cffi_get("https://pelixplay.app/embed/api.php", params=params, headers=headers, timeout=30)
377
+ if r.status_code == 200:
378
+ data = r.json()
379
+ break
380
+ last_api_err = RuntimeError(f"PelixPlay devolvió HTTP {r.status_code}")
381
+ except Exception as e_api:
382
+ last_api_err = e_api
383
+ time.sleep(2 * (api_try + 1))
384
+
385
+ if data is None:
386
+ raise RuntimeError(f"PelixPlay no respondió tras 4 reintentos ({last_api_err})")
387
+
388
  if not data.get("ok"):
389
  raise RuntimeError("PelixPlay informó que este título/episodio no está disponible todavía.")
390
 
 
406
  if isinstance(urls, str):
407
  urls = [urls]
408
  for u in urls:
409
+ if u and u not in embed_candidates and u not in skip_set:
410
  embed_candidates.append(u)
411
 
412
  if not embed_candidates:
 
417
  try:
418
  parsed_emb = urlparse(emb_url)
419
  emb_origin = f"{parsed_emb.scheme}://{parsed_emb.netloc}"
420
+ r_emb = cffi_get(emb_url, headers={"User-Agent": ua, "Referer": "https://pelixplay.app/"}, timeout=20)
421
  unpacked = unpack_js_eval(r_emb.text)
422
  if unpacked:
423
  for hls_key in ["hls4", "hls3", "hls2"]:
 
428
  verified = _verify_and_extract_hls_segments(full_hls, emb_origin + "/", ua)
429
  if verified:
430
  variant_url, seg_urls, res_label = verified
431
+ return variant_url, seg_urls, res_label, emb_origin + "/", data.get("tmdb_title"), emb_url
432
  except Exception:
433
  continue
434
 
435
  # 2. Fallback: usar extract.php de PelixPlay verificando también que el segmento 0 no dé 403
436
  for emb_url in embed_candidates:
437
+ for ext_try in range(2):
438
+ try:
439
+ r_ext = requests.post(
440
+ "https://pelixplay.app/embed/extract.php",
441
+ json={"url": emb_url},
442
+ headers=headers,
443
+ timeout=25
444
+ )
445
+ if r_ext.status_code == 200:
446
+ ext_data = r_ext.json()
447
+ ref = ext_data.get("referer") or "https://pelixplay.app/"
448
+ for s_url in (ext_data.get("streams") or []):
449
+ verified = _verify_and_extract_hls_segments(s_url, ref, ua)
450
+ if verified:
451
+ variant_url, seg_urls, res_label = verified
452
+ return variant_url, seg_urls, res_label, ref, data.get("tmdb_title"), emb_url
453
+ break
454
+ except Exception:
455
+ time.sleep(1.5)
456
+ continue
457
 
458
  raise RuntimeError("No se pudo extraer un stream HLS directo de los servidores de PelixPlay.")
459
 
 
486
  m_e = re.search(r"(\d+)", job.get("episode_name", "1"))
487
  episode_num = int(m_e.group(1)) if m_e else 1
488
 
489
+ tried_embeds = []
490
+ seg_dir = os.path.join(job_dir, "segs")
491
+ last_srv_err = None
492
 
493
+ for srv_attempt in range(3):
494
+ if job.get("cancelled"):
495
+ raise InterruptedError("Cancelado por el usuario")
496
 
497
+ job["status"] = "🔍 Extrayendo stream Audio Latino HD desde PelixPlay..." if srv_attempt == 0 else f"🔄 Servidor anterior inestable, probando servidor alternativo ({srv_attempt + 1}/3)..."
498
+ job["progress"] = 4
 
 
499
 
500
+ try:
501
+ variant_url, seg_urls, res_label, referer, api_title, chosen_emb = resolve_pelixplay_hls(
502
+ tmdb_id, media_type, season_num, episode_num, skip_embeds=tried_embeds
503
+ )
504
+ tried_embeds.append(chosen_emb)
505
+ except Exception as e_res:
506
+ shutil.rmtree(seg_dir, ignore_errors=True)
507
+ if last_srv_err is not None:
508
+ raise last_srv_err
509
+ raise e_res
510
 
511
+ if api_title and not job.get("title"):
512
+ job["title"] = api_title
513
 
514
+ headers = {
515
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
516
+ "Referer": referer
517
+ }
518
 
519
+ total_segs = len(seg_urls)
520
+ job["status"] = f"⬇️ Descargando PelixPlay ({res_label}): 0% (0/{total_segs} segmentos)..."
521
+ job["progress"] = 6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
 
523
+ shutil.rmtree(seg_dir, ignore_errors=True)
524
+ os.makedirs(seg_dir, exist_ok=True)
525
+
526
+ dl_start = time.time()
527
+ completed_segs = 0
528
+ downloaded_bytes = 0
529
+ seg_lock = threading.Lock()
530
+ still_failed = []
531
+
532
+ with requests.Session() as session:
533
+ adapter = requests.adapters.HTTPAdapter(pool_connections=12, pool_maxsize=12)
534
+ session.mount("http://", adapter)
535
+ session.mount("https://", adapter)
536
+
537
+ def fetch_seg(idx, s_url, max_attempts=7):
538
+ if job.get("cancelled"):
539
+ raise InterruptedError("Cancelado por el usuario")
540
+ for attempt in range(max_attempts):
541
+ if job.get("cancelled"):
542
+ raise InterruptedError("Cancelado por el usuario")
543
+ try:
544
+ resp = session.get(s_url, headers=headers, timeout=(10, 30))
545
+ if resp.status_code != 200 or not resp.content:
546
+ resp = cffi_get(s_url, headers=headers, timeout=30)
547
+ if resp.status_code == 200 and resp.content:
548
+ clean_ts = strip_fake_png_header(resp.content)
549
+ seg_file = os.path.join(seg_dir, f"seg_{idx:05d}.ts")
550
+ with open(seg_file, "wb") as fs:
551
+ fs.write(clean_ts)
552
+ return len(clean_ts)
553
+ except InterruptedError:
554
+ raise
555
+ except Exception:
556
+ pass
557
+ time.sleep(min(6.0, 0.8 * (attempt + 1)))
558
+ raise RuntimeError(f"Fallo descargando segmento {idx}/{total_segs}")
559
+
560
+ failed_indices = []
561
+ with ThreadPoolExecutor(max_workers=10) as pool:
562
+ futures = {pool.submit(fetch_seg, i, u): i for i, u in enumerate(seg_urls)}
563
+ for fut in as_completed(futures):
564
+ if job.get("cancelled"):
565
+ for f_rem in futures:
566
+ f_rem.cancel()
567
+ raise InterruptedError("Cancelado por el usuario")
568
+ idx_seg = futures[fut]
569
+ try:
570
+ sz = fut.result()
571
+ with seg_lock:
572
+ completed_segs += 1
573
+ downloaded_bytes += sz
574
+ pct_dl = int((completed_segs / total_segs) * 100)
575
+ elapsed = max(0.3, time.time() - dl_start)
576
+ speed_mb = (downloaded_bytes / (1024 * 1024)) / elapsed
577
+ rem_segs = total_segs - completed_segs
578
+ segs_per_sec = completed_segs / elapsed
579
+ eta_s = rem_segs / segs_per_sec if segs_per_sec > 0 else 0
580
+ job["progress"] = min(68, 6 + int((completed_segs / total_segs) * 62))
581
+ job["status"] = (
582
+ f"⬇️ Descargando PelixPlay ({res_label}): {pct_dl}% "
583
+ f"({completed_segs}/{total_segs} segs — {format_size(downloaded_bytes)}) "
584
+ f"a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
585
+ )
586
+ except InterruptedError:
587
+ raise
588
+ except Exception:
589
+ failed_indices.append(idx_seg)
590
+
591
+ # Segunda pasada de rescate en solitario para cualquier segmento rebelde
592
+ for idx_rem in failed_indices:
593
+ if job.get("cancelled"):
594
+ raise InterruptedError("Cancelado por el usuario")
595
+ job["status"] = f"🔄 Recuperando segmento lento {idx_rem + 1}/{total_segs}..."
596
+ try:
597
+ sz = fetch_seg(idx_rem, seg_urls[idx_rem], max_attempts=5)
598
+ downloaded_bytes += sz
599
+ completed_segs += 1
600
+ except InterruptedError:
601
+ raise
602
+ except Exception as e_seg:
603
+ still_failed.append((idx_rem, e_seg))
604
+
605
+ if not still_failed:
606
+ break
607
+
608
+ last_srv_err = RuntimeError(f"Fallo descargando segmento {still_failed[0][0]}/{total_segs}")
609
+ if srv_attempt == 2:
610
+ shutil.rmtree(seg_dir, ignore_errors=True)
611
+ raise last_srv_err
612
 
613
  if job.get("cancelled"):
614
  raise InterruptedError("Cancelado por el usuario")