import os import uuid import json import yt_dlp import copy import time from flask import Flask, render_template, request, send_file, jsonify, redirect app = Flask(__name__, template_folder='.') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DOWNLOAD_FOLDER = os.path.join(BASE_DIR, 'downloads') if not os.path.exists(DOWNLOAD_FOLDER): os.makedirs(DOWNLOAD_FOLDER) MAPPINGS_FILE = os.path.join(BASE_DIR, 'mappings.json') COOKIES_FILE = os.path.join(BASE_DIR, 'cookies.txt') DEBUG_LOG_FILE = os.path.join(BASE_DIR, 'debug.log') def log_debug(msg): timestamp = time.strftime("%Y-%m-%d %H:%M:%S") with open(DEBUG_LOG_FILE, 'a', encoding='utf-8') as f: f.write(f"[{timestamp}] {msg}\n") print(msg) # Write initial cookies DEFAULT_COOKIES = os.getenv('YT_COOKIES') if DEFAULT_COOKIES and not os.path.exists(COOKIES_FILE): with open(COOKIES_FILE, 'w', encoding='utf-8') as f: f.write(DEFAULT_COOKIES.strip()) log_debug(f"LOADED: Cookies from HF Secret") @app.route('/debug', methods=['GET', 'POST']) def debug_page(): if request.method == 'POST': new_cookies = request.form.get('cookies') if new_cookies: with open(COOKIES_FILE, 'w', encoding='utf-8') as f: f.write(new_cookies.strip()) log_debug("UPDATED: Cookies saved via Debug Page") return "Cookies actualizadas correctamente! Volver" log_content = "" if os.path.exists(DEBUG_LOG_FILE): with open(DEBUG_LOG_FILE, 'r') as f: log_content = "".join(f.readlines()[-60:]) cookie_info = "NO" if os.path.exists(COOKIES_FILE): cookie_info = f"SI ({os.path.getsize(COOKIES_FILE)} bytes)" return f"""
Cookie Actual: {cookie_info}
{log_content}
"""
def get_yt_info(url):
clients = [
('tv', True), ('tvhtml5', True), ('android', True),
('tv', False), ('tvhtml5', False), ('ios', True),
('mweb', True), ('web_creator', True)
]
base_ydl_opts = {
'format': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]/bestvideo+bestaudio/best',
'quiet': True, 'no_warnings': True, 'nocheckcertificate': True,
'extractor_args': {'youtube': {'include_dash_manifest': False, 'include_hls_manifest': True}}
}
last_err = "Init"
for c_name, use_c in clients:
opts = copy.deepcopy(base_ydl_opts)
opts['extractor_args']['youtube']['player_client'] = [c_name]
if use_c and os.path.exists(COOKIES_FILE): opts['cookiefile'] = COOKIES_FILE
log_debug(f"TRY: {c_name} (Cookies={use_c})")
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
log_debug(f"OK: {c_name}")
return info, None, opts
except Exception as e:
last_err = str(e)
log_debug(f"FAIL: {c_name} -> {last_err[:80]}...")
return None, f"Todo falló. Ultimo Error: {last_err}", None
@app.route('/')
def index(): return render_template('index.html')
@app.route('/convert', methods=['POST'])
def convert():
data = request.json
url = data.get('url')
if not url: return jsonify({'error': 'No URL'}), 400
file_id = str(uuid.uuid4())
info, error, successful_opts = get_yt_info(url)
if error: return jsonify({'error': error}), 500
try:
is_live = info.get('is_live', False) or info.get('live_status') == 'is_live'
title = info.get('title', 'video')
mappings = load_mappings()
mappings[file_id] = {'url': url, 'title': title}
with open(MAPPINGS_FILE, 'w') as f: json.dump(mappings, f)
# Download logic (MP4 only if not live)
has_dl = False
if not is_live:
try:
dl_opts = copy.deepcopy(successful_opts)
dl_opts.update({'outtmpl': os.path.join(DOWNLOAD_FOLDER, f"{file_id}.%(ext)s"), 'merge_output_format': 'mp4'})
with yt_dlp.YoutubeDL(dl_opts) as ydl_dl: ydl_dl.download([url])
has_dl = any(f.startswith(file_id) and not f.endswith('.m3u') for f in os.listdir(DOWNLOAD_FOLDER))
except Exception as e: log_debug(f"DL_FAIL: {str(e)}")
# M3U
play_url = f"{request.host_url.rstrip('/')}/play/youtube/{file_id}.m3u8"
with open(os.path.join(DOWNLOAD_FOLDER, f"{file_id}.m3u"), 'w', encoding='utf-8') as f:
f.write(f"#EXTM3U\n#EXTINF:-1 tvg-name=\"{title}\", {title}\n{play_url}\n")
return jsonify({'success':True, 'file_id':file_id, 'title':title, 'is_live':is_live, 'has_download':has_dl,
'download_url': f'/download/{file_id}/video.mp4' if has_dl else None,
'm3u_url': f'/download_m3u/{file_id}/video.m3u'})
except Exception as e: return jsonify({'error': str(e)}), 500
@app.route('/play/youtube/