from flask import Flask, render_template_string, request, redirect, url_for, flash
import os
from controller_core import enqueue_download, start_controller, stop_controller
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "dev-secret")
HTML_FORM = """
Submit YouTube Playlist
Paste a playlist link below. It’ll be queued for download and assigned to the next free slot.
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for m in messages %}
{{ m }}
{% endfor %}
{% endif %}
{% endwith %}
Playlists are kept for roughly 48 hours after they’re downloaded.
"""
@app.route("/", methods=["GET"])
def index():
return render_template_string(HTML_FORM)
@app.route("/submit", methods=["POST"])
def submit():
url = request.form.get("url", "").strip()
submitter = request.form.get("submitter", "").strip() or None
note = request.form.get("note", "").strip() or None
if not url.startswith("http"):
flash("Invalid URL.")
return redirect(url_for("index"))
result = enqueue_download(url, submitter, note)
if result.get("status") == "queue_full":
secs = result.get("oldest_expires_in_seconds", 0)
hours = max(1, secs // 3600)
flash(f"Queue is full. Oldest playlist expires in about {hours} hour(s).")
else:
slot = result.get("slot")
msg = f"Playlist queued in slot {slot}."
if result.get("reused_slot"):
msg += " (Existing slot – only new videos will be added.)"
else:
msg += " It will start downloading shortly."
flash(msg)
return redirect(url_for("index"))
if __name__ == "__main__":
start_controller()
try:
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7531)))
finally:
stop_controller()