try / app.py
arnaupq2's picture
Upload app.py
a771224 verified
Raw History Blame Contribute Delete
6.75 kB
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! <a href='/debug'>Volver</a>"
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"""
<h1>Debug & Cookie Center</h1>
<p><b>Cookie Actual:</b> {cookie_info}</p>
<form method="POST">
<textarea name="cookies" rows="10" cols="80" placeholder="Pega aqui el contenido de cookies.txt"></textarea><br>
<button type="submit">Actualizar Cookies AHORA</button>
</form>
<h3>Logs Recientes:</h3>
<pre style="background:#f0f0f0;padding:10px;">{log_content}</pre>
"""
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/<file_id>.m3u8')
def play(file_id):
if any(f.startswith(file_id) and not f.endswith('.m3u') for f in os.listdir(DOWNLOAD_FOLDER)):
return redirect(f"/download/{file_id}/video.mp4")
m = load_mappings(); u = m.get(file_id, {}).get('url')
if not u: return "404", 404
info, error, _ = get_yt_info(u)
if error: return f"Error: {error}", 500
s_url = info.get('url')
if not s_url and info.get('formats'):
for f in reversed(info['formats']):
if f.get('url') and 'manifest' not in f['url']: s_url = f['url']; break
if not s_url: s_url = info['formats'][-1].get('url')
if s_url: return redirect(s_url)
return "No link", 404
def load_mappings():
if not os.path.exists(MAPPINGS_FILE): return {}
with open(MAPPINGS_FILE, 'r') as f: return json.load(f)
@app.after_request
def add_cors(r): r.headers['Access-Control-Allow-Origin'] = '*'; return r
@app.route('/download_m3u/<file_id>/<path:n>')
def download_m3u(file_id, n):
p = os.path.join(DOWNLOAD_FOLDER, f"{file_id}.m3u")
if os.path.exists(p): return send_file(p, as_attachment=True)
return "404", 404
@app.route('/download/<file_id>/<path:n>')
def download(file_id, n):
for f in os.listdir(DOWNLOAD_FOLDER):
if f.startswith(file_id) and not f.endswith('.m3u'):
return send_file(os.path.join(DOWNLOAD_FOLDER, f), as_attachment=False, conditional=True, mimetype='video/mp4')
return "404", 404
if __name__ == '__main__': app.run(debug=True, port=5000)