Upload files to "/"
This commit is contained in:
+1146
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,477 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
load_dotenv(BASE_DIR / "config.env")
|
||||
|
||||
YTDLP_METADATA_ENRICH = os.getenv(
|
||||
"YOUTUBE_METADATA_ENRICH",
|
||||
"true",
|
||||
).lower() not in {"0", "false", "no", "off"}
|
||||
|
||||
YTDLP_WRITE_INFO_JSON = os.getenv(
|
||||
"YOUTUBE_WRITE_INFO_JSON",
|
||||
"true",
|
||||
).lower() not in {"0", "false", "no", "off"}
|
||||
|
||||
ARTWORK_TIMEOUT = max(
|
||||
3,
|
||||
int(os.getenv("METADATA_ARTWORK_TIMEOUT", "20")),
|
||||
)
|
||||
|
||||
_IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
|
||||
|
||||
|
||||
def _safe_sidecar(path: Path, media_path: str | Path) -> Path | None:
|
||||
"""Only serve sidecars that resolve beneath the directory containing the media."""
|
||||
root = Path(media_path).resolve().parent
|
||||
try:
|
||||
resolved = path.resolve(strict=True)
|
||||
resolved.relative_to(root)
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
return None
|
||||
return resolved if resolved.is_file() else None
|
||||
|
||||
|
||||
def _text(node, *names):
|
||||
for name in names:
|
||||
child = node.find(name)
|
||||
if child is not None and child.text:
|
||||
value = child.text.strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _int_text(node, *names):
|
||||
value = _text(node, *names)
|
||||
if not value:
|
||||
return None
|
||||
match = re.search(r"-?\d+", value)
|
||||
return int(match.group(0)) if match else None
|
||||
|
||||
|
||||
def _all_text(node, name):
|
||||
values = []
|
||||
for child in node.findall(name):
|
||||
if child.text and child.text.strip():
|
||||
values.append(child.text.strip())
|
||||
return values
|
||||
|
||||
|
||||
def nfo_candidates(media_path: str | Path):
|
||||
path = Path(media_path)
|
||||
# Prefer matching episode NFO over generic movie/show metadata.
|
||||
return [
|
||||
path.with_suffix(".nfo"),
|
||||
path.parent / "movie.nfo",
|
||||
path.parent / "episode.nfo",
|
||||
path.parent / "musicvideo.nfo",
|
||||
path.parent / "tvshow.nfo",
|
||||
]
|
||||
|
||||
|
||||
def artwork_candidates(media_path: str | Path):
|
||||
path = Path(media_path)
|
||||
names = [f"{path.stem}-poster", f"{path.stem}-thumb", f"{path.stem}-primary", path.stem,
|
||||
"poster", "folder", "cover", "primary", "thumb", "landscape", "backdrop"]
|
||||
return [path.parent / f"{name}{ext}" for name in names for ext in _IMAGE_EXTS]
|
||||
|
||||
|
||||
def _trickplay_candidates(media_path: str | Path):
|
||||
"""Jellyfin trickplay is fallback imagery, not a movie poster."""
|
||||
path = Path(media_path)
|
||||
folder = path.parent / f"{path.stem}.trickplay"
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
candidates = []
|
||||
# Prefer first contact sheet at the largest available supported resolution.
|
||||
for subdir in folder.iterdir():
|
||||
if subdir.is_dir():
|
||||
for name in ("0.jpg", "0.jpeg", "0.png", "1.jpg", "1.jpeg"):
|
||||
candidate = subdir / name
|
||||
if candidate.is_file():
|
||||
candidates.append(candidate)
|
||||
break
|
||||
def sort_key(p):
|
||||
try: width = int(p.parent.name.split("-", 1)[0])
|
||||
except ValueError: width = 0
|
||||
return (-width, p.parent.name)
|
||||
return sorted(candidates, key=sort_key)
|
||||
|
||||
|
||||
def find_nfo(media_path: str | Path):
|
||||
for candidate in nfo_candidates(media_path):
|
||||
safe = _safe_sidecar(candidate, media_path)
|
||||
if safe is not None:
|
||||
return safe
|
||||
return None
|
||||
|
||||
|
||||
def find_artwork(media_path: str | Path):
|
||||
for candidate in artwork_candidates(media_path):
|
||||
safe = _safe_sidecar(candidate, media_path)
|
||||
if safe is not None:
|
||||
return safe
|
||||
# Trickplay contact sheets are grids of frames, not cover artwork.
|
||||
# A single-frame generated thumbnail is the fallback when no sidecar poster exists.
|
||||
return None
|
||||
|
||||
|
||||
def sidecar_signature(media_path: str | Path):
|
||||
newest = 0
|
||||
for candidate in nfo_candidates(media_path) + artwork_candidates(media_path):
|
||||
try:
|
||||
safe = _safe_sidecar(candidate, media_path)
|
||||
if safe is not None:
|
||||
newest = max(newest, int(safe.stat().st_mtime_ns))
|
||||
except OSError:
|
||||
pass
|
||||
return newest
|
||||
|
||||
|
||||
def read_nfo(media_path: str | Path) -> dict[str, Any]:
|
||||
nfo = find_nfo(media_path)
|
||||
art = find_artwork(media_path)
|
||||
if nfo is None:
|
||||
return {
|
||||
"nfo_path": "",
|
||||
"artwork_path": str(art) if art else "",
|
||||
"sidecar_mtime_ns": sidecar_signature(media_path),
|
||||
}
|
||||
|
||||
try:
|
||||
root = ET.parse(nfo).getroot()
|
||||
except Exception as error:
|
||||
return {
|
||||
"nfo_path": str(nfo),
|
||||
"artwork_path": str(art) if art else "",
|
||||
"sidecar_mtime_ns": sidecar_signature(media_path),
|
||||
"nfo_error": str(error),
|
||||
}
|
||||
|
||||
uniqueids = {}
|
||||
for child in root.findall("uniqueid"):
|
||||
value = (child.text or "").strip()
|
||||
if value:
|
||||
uniqueids[str(child.attrib.get("type") or "default")] = value
|
||||
|
||||
artists = _all_text(root, "artist")
|
||||
genres = _all_text(root, "genre")
|
||||
tags = _all_text(root, "tag")
|
||||
|
||||
result = {
|
||||
"root": root.tag,
|
||||
"title": _text(root, "title", "name"),
|
||||
"sort_title": _text(root, "sorttitle"),
|
||||
"original_title": _text(root, "originaltitle"),
|
||||
"series_title": _text(root, "showtitle", "series"),
|
||||
"episode_title": _text(root, "episodetitle"),
|
||||
"year": _int_text(root, "year"),
|
||||
"season": _int_text(root, "season"),
|
||||
"episode": _int_text(root, "episode"),
|
||||
"plot": _text(root, "plot", "outline", "description"),
|
||||
"album": _text(root, "album"),
|
||||
"artist": _text(root, "albumartist") or (artists[0] if artists else ""),
|
||||
"artists": artists,
|
||||
"channel": _text(root, "studio", "channel", "uploader"),
|
||||
"premiered": _text(root, "premiered", "aired", "date"),
|
||||
"runtime": _text(root, "runtime"),
|
||||
"genres": genres,
|
||||
"tags": tags,
|
||||
"uniqueids": uniqueids,
|
||||
"nfo_path": str(nfo),
|
||||
"artwork_path": str(art) if art else "",
|
||||
"sidecar_mtime_ns": sidecar_signature(media_path),
|
||||
}
|
||||
|
||||
# An NFO may reference a local artwork file explicitly.
|
||||
thumb = _text(root, "thumb")
|
||||
if thumb and not result["artwork_path"]:
|
||||
thumb_path = Path(thumb)
|
||||
if not thumb_path.is_absolute():
|
||||
thumb_path = nfo.parent / thumb_path
|
||||
safe_thumb = _safe_sidecar(thumb_path, media_path)
|
||||
if safe_thumb is not None and not any(part.endswith(".trickplay") for part in safe_thumb.parts):
|
||||
if safe_thumb.suffix.lower() in _IMAGE_EXTS:
|
||||
result["artwork_path"] = str(safe_thumb)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def apply_nfo_to_item(item: dict[str, Any], media_path: str | Path):
|
||||
sidecar = read_nfo(media_path)
|
||||
item = dict(item)
|
||||
|
||||
if sidecar.get("title"):
|
||||
item["title"] = sidecar["title"]
|
||||
if sidecar.get("series_title"):
|
||||
item["series_title"] = sidecar["series_title"]
|
||||
if sidecar.get("episode_title"):
|
||||
item["episode_title"] = sidecar["episode_title"]
|
||||
if sidecar.get("year") is not None:
|
||||
item["year"] = sidecar["year"]
|
||||
if sidecar.get("season") is not None:
|
||||
item["season"] = sidecar["season"]
|
||||
if sidecar.get("episode") is not None:
|
||||
item["episode"] = sidecar["episode"]
|
||||
|
||||
item["description"] = sidecar.get("plot") or item.get("description") or ""
|
||||
item["nfo_path"] = sidecar.get("nfo_path") or ""
|
||||
item["artwork_path"] = sidecar.get("artwork_path") or ""
|
||||
item["sidecar_mtime_ns"] = int(sidecar.get("sidecar_mtime_ns") or 0)
|
||||
item["metadata_json"] = json.dumps(
|
||||
sidecar,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def _safe_xml_text(value):
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value)
|
||||
|
||||
|
||||
def _add_text(root, tag, value):
|
||||
if value in (None, "", []):
|
||||
return
|
||||
child = ET.SubElement(root, tag)
|
||||
child.text = _safe_xml_text(value)
|
||||
|
||||
|
||||
def _write_xml(path: Path, root):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tree = ET.ElementTree(root)
|
||||
try:
|
||||
ET.indent(tree, space=" ")
|
||||
except AttributeError:
|
||||
pass
|
||||
temp = path.with_suffix(path.suffix + ".tmp")
|
||||
tree.write(temp, encoding="utf-8", xml_declaration=True)
|
||||
os.replace(temp, path)
|
||||
return path
|
||||
|
||||
|
||||
def download_artwork(url: str, destination: str | Path):
|
||||
url = str(url or "").strip()
|
||||
destination = Path(destination)
|
||||
if not url:
|
||||
return None
|
||||
|
||||
if destination.is_file() and destination.stat().st_size > 0:
|
||||
return destination
|
||||
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = destination.with_suffix(destination.suffix + ".tmp")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 KronicMedia/1.0",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=ARTWORK_TIMEOUT) as response:
|
||||
with open(temp, "wb") as handle:
|
||||
shutil.copyfileobj(response, handle)
|
||||
if temp.stat().st_size <= 0:
|
||||
temp.unlink(missing_ok=True)
|
||||
return None
|
||||
os.replace(temp, destination)
|
||||
return destination
|
||||
except Exception:
|
||||
try:
|
||||
temp.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def enrich_youtube_info(video_id: str, existing: dict | None = None):
|
||||
info = dict(existing or {})
|
||||
if not YTDLP_METADATA_ENRICH:
|
||||
return info
|
||||
|
||||
# If the resolver already returned the important fields, avoid an extra
|
||||
# network extraction.
|
||||
if (
|
||||
info.get("title")
|
||||
and (info.get("thumbnail") or info.get("thumbnails"))
|
||||
and info.get("description") is not None
|
||||
):
|
||||
return info
|
||||
|
||||
try:
|
||||
import yt_dlp
|
||||
except Exception:
|
||||
return info
|
||||
|
||||
url = f"https://www.youtube.com/watch?v={video_id}"
|
||||
options = {
|
||||
"quiet": True,
|
||||
"no_warnings": True,
|
||||
"skip_download": True,
|
||||
"noplaylist": True,
|
||||
"extract_flat": False,
|
||||
}
|
||||
|
||||
try:
|
||||
with yt_dlp.YoutubeDL(options) as ydl:
|
||||
fetched = ydl.extract_info(url, download=False) or {}
|
||||
except Exception:
|
||||
return info
|
||||
|
||||
for key, value in fetched.items():
|
||||
if info.get(key) in (None, "", [], {}):
|
||||
info[key] = value
|
||||
return info
|
||||
|
||||
|
||||
def youtube_metadata(video_id: str, info: dict | None = None):
|
||||
info = enrich_youtube_info(video_id, info)
|
||||
thumbnails = info.get("thumbnails") or []
|
||||
thumbnail = info.get("thumbnail") or ""
|
||||
if not thumbnail and thumbnails:
|
||||
for item in reversed(thumbnails):
|
||||
if isinstance(item, dict) and item.get("url"):
|
||||
thumbnail = item["url"]
|
||||
break
|
||||
|
||||
return {
|
||||
"video_id": video_id,
|
||||
"title": info.get("title") or video_id,
|
||||
"description": info.get("description") or "",
|
||||
"channel": info.get("channel") or info.get("uploader") or "",
|
||||
"channel_id": info.get("channel_id") or info.get("uploader_id") or "",
|
||||
"webpage_url": info.get("webpage_url") or f"https://www.youtube.com/watch?v={video_id}",
|
||||
"thumbnail": thumbnail,
|
||||
"duration": info.get("duration"),
|
||||
"upload_date": info.get("upload_date") or "",
|
||||
"timestamp": info.get("timestamp"),
|
||||
"live_status": info.get("live_status") or "",
|
||||
"is_live": bool(info.get("is_live")),
|
||||
"categories": info.get("categories") or [],
|
||||
"tags": info.get("tags") or [],
|
||||
"raw": info,
|
||||
}
|
||||
|
||||
|
||||
def write_video_sidecar(
|
||||
media_path: str | Path,
|
||||
video_id: str,
|
||||
info: dict | None = None,
|
||||
):
|
||||
media_path = Path(media_path).resolve()
|
||||
meta = youtube_metadata(video_id, info)
|
||||
|
||||
nfo_path = media_path.with_suffix(".nfo")
|
||||
art_path = media_path.with_suffix(".jpg")
|
||||
|
||||
root = ET.Element("movie")
|
||||
_add_text(root, "title", meta["title"])
|
||||
_add_text(root, "plot", meta["description"])
|
||||
_add_text(root, "studio", meta["channel"])
|
||||
_add_text(root, "premiered", meta["upload_date"])
|
||||
_add_text(root, "runtime", meta["duration"])
|
||||
_add_text(root, "source", "youtube")
|
||||
_add_text(root, "webpage", meta["webpage_url"])
|
||||
|
||||
uid = ET.SubElement(root, "uniqueid", {"type": "youtube", "default": "true"})
|
||||
uid.text = str(video_id)
|
||||
|
||||
if meta["thumbnail"]:
|
||||
_add_text(root, "thumb", art_path.name)
|
||||
|
||||
for category in meta["categories"]:
|
||||
_add_text(root, "genre", category)
|
||||
for tag in meta["tags"]:
|
||||
_add_text(root, "tag", tag)
|
||||
|
||||
_write_xml(nfo_path, root)
|
||||
if meta["thumbnail"]:
|
||||
download_artwork(meta["thumbnail"], art_path)
|
||||
|
||||
if YTDLP_WRITE_INFO_JSON:
|
||||
info_path = media_path.with_suffix(".info.json")
|
||||
clean = dict(meta["raw"])
|
||||
# Keep sidecars serializable even when extractor internals contain
|
||||
# special objects.
|
||||
try:
|
||||
info_path.write_text(
|
||||
json.dumps(clean, ensure_ascii=False, indent=2, default=str),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"nfo_path": str(nfo_path),
|
||||
"artwork_path": str(art_path) if art_path.is_file() else "",
|
||||
"metadata": meta,
|
||||
}
|
||||
|
||||
|
||||
def write_audio_sidecar(
|
||||
media_path: str | Path,
|
||||
*,
|
||||
title: str,
|
||||
artist: str = "",
|
||||
artists=None,
|
||||
album: str = "",
|
||||
year=None,
|
||||
duration=None,
|
||||
cover_url: str = "",
|
||||
spotify_id: str = "",
|
||||
spotify_url: str = "",
|
||||
youtube_id: str = "",
|
||||
description: str = "",
|
||||
isrc: str = "",
|
||||
list_name: str = "",
|
||||
):
|
||||
media_path = Path(media_path).resolve()
|
||||
nfo_path = media_path.with_suffix(".nfo")
|
||||
art_path = media_path.with_suffix(".jpg")
|
||||
|
||||
root = ET.Element("audio")
|
||||
_add_text(root, "title", title)
|
||||
for value in (artists or ([artist] if artist else [])):
|
||||
_add_text(root, "artist", value)
|
||||
_add_text(root, "album", album)
|
||||
_add_text(root, "year", year)
|
||||
_add_text(root, "runtime", duration)
|
||||
_add_text(root, "plot", description)
|
||||
_add_text(root, "isrc", isrc)
|
||||
_add_text(root, "playlist", list_name)
|
||||
_add_text(root, "source", "kronic-music")
|
||||
|
||||
if spotify_id:
|
||||
uid = ET.SubElement(root, "uniqueid", {"type": "spotify", "default": "true"})
|
||||
uid.text = spotify_id
|
||||
if youtube_id:
|
||||
uid = ET.SubElement(root, "uniqueid", {"type": "youtube"})
|
||||
uid.text = youtube_id
|
||||
if spotify_url:
|
||||
_add_text(root, "spotifyurl", spotify_url)
|
||||
|
||||
if cover_url:
|
||||
_add_text(root, "thumb", art_path.name)
|
||||
|
||||
_write_xml(nfo_path, root)
|
||||
if cover_url:
|
||||
download_artwork(cover_url, art_path)
|
||||
|
||||
return {
|
||||
"nfo_path": str(nfo_path),
|
||||
"artwork_path": str(art_path) if art_path.is_file() else "",
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Persistent scheduled recording queue shared by Twitch and YouTube.
|
||||
|
||||
The worker uses the media application's SQLite database and runs even when
|
||||
no browser is open. UTC timestamps avoid client/server timezone ambiguity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
DB_PATH = Path(os.getenv('DB_PATH', str(Path(__file__).resolve().parent / 'media_library.db'))).expanduser().resolve()
|
||||
_LOCK = threading.Lock()
|
||||
_THREAD = None
|
||||
_STOP = threading.Event()
|
||||
|
||||
|
||||
def _db():
|
||||
connection = sqlite3.connect(DB_PATH, timeout=30)
|
||||
connection.row_factory = sqlite3.Row
|
||||
return connection
|
||||
|
||||
|
||||
def initialize():
|
||||
with _db() as db:
|
||||
db.execute('''CREATE TABLE IF NOT EXISTS scheduled_recordings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
media_key TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
start_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'scheduled',
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL
|
||||
)''')
|
||||
db.execute('CREATE INDEX IF NOT EXISTS idx_scheduled_recordings_due ON scheduled_recordings(status,start_at)')
|
||||
db.commit()
|
||||
|
||||
|
||||
def schedule(user_id, provider, media_key, start_at, title=''):
|
||||
if provider not in {'twitch', 'youtube'}:
|
||||
raise ValueError('Unsupported recording type')
|
||||
key = str(media_key or '').strip()
|
||||
if not key:
|
||||
raise ValueError('Channel ID or video ID is required')
|
||||
try:
|
||||
start = datetime.fromisoformat(str(start_at).replace('Z', '+00:00'))
|
||||
if start.tzinfo is None:
|
||||
raise ValueError('Recording time must include a timezone')
|
||||
timestamp = int(start.timestamp())
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError('Enter a valid date and time with timezone') from exc
|
||||
now = int(time.time())
|
||||
if timestamp < now + 15 or timestamp > now + 366 * 86400:
|
||||
raise ValueError('Scheduled time must be at least 15 seconds away and within one year')
|
||||
if provider == 'twitch':
|
||||
from twitch_jobs import get_channel
|
||||
if get_channel(int(user_id), int(key)) is None:
|
||||
raise ValueError('Twitch channel is unavailable to this account')
|
||||
else:
|
||||
import re
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{11}', key):
|
||||
raise ValueError('YouTube recording requires a valid video ID')
|
||||
with _db() as db:
|
||||
cursor = db.execute('''INSERT INTO scheduled_recordings
|
||||
(user_id,provider,media_key,title,start_at,created_at) VALUES (?,?,?,?,?,?)''',
|
||||
(int(user_id), provider, key, str(title or '')[:300], timestamp, now))
|
||||
db.commit()
|
||||
return {'id':cursor.lastrowid, 'status':'scheduled', 'start_at':timestamp}
|
||||
|
||||
|
||||
def list_jobs(user_id):
|
||||
with _db() as db:
|
||||
return [dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings
|
||||
WHERE user_id=? ORDER BY start_at DESC LIMIT 80''', (int(user_id),))]
|
||||
|
||||
|
||||
def cancel(user_id, job_id):
|
||||
with _db() as db:
|
||||
cursor = db.execute("UPDATE scheduled_recordings SET status='cancelled' WHERE id=? AND user_id=? AND status='scheduled'",(int(job_id),int(user_id)))
|
||||
db.commit()
|
||||
if not cursor.rowcount:
|
||||
raise ValueError('No pending scheduled recording found')
|
||||
return {'cancelled':True}
|
||||
|
||||
|
||||
def _execute(job):
|
||||
if job['provider'] == 'twitch':
|
||||
from twitch_jobs import enqueue_recording
|
||||
enqueue_recording(job['user_id'], int(job['media_key']))
|
||||
else:
|
||||
from cache_jobs import enqueue_cache_job
|
||||
enqueue_cache_job(user_id=job['user_id'], video_id=job['media_key'], mode='video', title=job['title'])
|
||||
|
||||
|
||||
def _tick():
|
||||
now = int(time.time())
|
||||
with _LOCK:
|
||||
with _db() as db:
|
||||
due=[dict(row) for row in db.execute('''SELECT * FROM scheduled_recordings
|
||||
WHERE status='scheduled' AND start_at<=? ORDER BY start_at LIMIT 15''',(now,))]
|
||||
for job in due:
|
||||
db.execute("UPDATE scheduled_recordings SET status='dispatching' WHERE id=? AND status='scheduled'", (job['id'],))
|
||||
db.commit()
|
||||
for job in due:
|
||||
try:
|
||||
_execute(job)
|
||||
status, message='started','Recording job dispatched'
|
||||
except Exception as exc:
|
||||
status, message='failed',str(exc)[:400]
|
||||
with _db() as db:
|
||||
db.execute('UPDATE scheduled_recordings SET status=?,message=? WHERE id=?', (status,message,job['id']))
|
||||
db.commit()
|
||||
|
||||
|
||||
def start():
|
||||
global _THREAD
|
||||
initialize()
|
||||
with _db() as db:
|
||||
# A service restart during dispatch leaves the state visible and retryable.
|
||||
db.execute("UPDATE scheduled_recordings SET status='scheduled' WHERE status='dispatching'")
|
||||
db.commit()
|
||||
if _THREAD and _THREAD.is_alive():
|
||||
return
|
||||
def worker():
|
||||
while not _STOP.is_set():
|
||||
try: _tick()
|
||||
except Exception as exc: print('[SCHEDULE] Worker error:',exc,flush=True)
|
||||
_STOP.wait(10)
|
||||
_THREAD=threading.Thread(target=worker, daemon=True,name='kronic-recording-schedule')
|
||||
_THREAD.start()
|
||||
@@ -0,0 +1,489 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
load_dotenv(BASE_DIR / "config.env")
|
||||
|
||||
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg")
|
||||
FFPROBE_BIN = os.getenv("FFPROBE_BIN", "/usr/bin/ffprobe")
|
||||
|
||||
TWITCH_RECORD_DIR = Path(
|
||||
os.getenv("TWITCH_RECORD_DIR", "/blade-media/twitch-cache")
|
||||
).expanduser().resolve()
|
||||
|
||||
TWITCH_STREAM_TIMEOUT = max(
|
||||
5,
|
||||
int(os.getenv("TWITCH_STREAM_TIMEOUT", "30")),
|
||||
)
|
||||
|
||||
TWITCH_SUPPORTED_CODECS = [
|
||||
item.strip().lower()
|
||||
for item in os.getenv("TWITCH_SUPPORTED_CODECS", "h264").split(",")
|
||||
if item.strip()
|
||||
]
|
||||
|
||||
logger = logging.getLogger("kronic.twitch")
|
||||
|
||||
|
||||
class TwitchOffline(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class TwitchResolutionError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class TwitchResolved:
|
||||
url: str
|
||||
channel: str
|
||||
quality: str
|
||||
stream: Any
|
||||
available_qualities: list[str]
|
||||
stream_id: str = ""
|
||||
title: str = ""
|
||||
author: str = ""
|
||||
category: str = ""
|
||||
|
||||
def as_dict(self):
|
||||
return {
|
||||
"url": self.url,
|
||||
"channel": self.channel,
|
||||
"quality": self.quality,
|
||||
"available_qualities": list(self.available_qualities),
|
||||
"stream_id": self.stream_id,
|
||||
"title": self.title,
|
||||
"author": self.author,
|
||||
"category": self.category,
|
||||
"live": True,
|
||||
}
|
||||
|
||||
|
||||
def normalize_twitch_url(value: str) -> tuple[str, str]:
|
||||
value = str(value or "").strip()
|
||||
if not value:
|
||||
raise ValueError("Twitch channel or URL is required.")
|
||||
|
||||
if re.fullmatch(r"[A-Za-z0-9_]{2,40}", value):
|
||||
channel = value
|
||||
return f"https://www.twitch.tv/{channel}", channel
|
||||
|
||||
if not re.match(r"^https?://", value, re.I):
|
||||
value = "https://" + value.lstrip("/")
|
||||
|
||||
match = re.search(
|
||||
r"(?:www\.)?twitch\.tv/([A-Za-z0-9_]{2,40})",
|
||||
value,
|
||||
re.I,
|
||||
)
|
||||
if not match:
|
||||
raise ValueError("Enter a Twitch channel name or twitch.tv channel URL.")
|
||||
|
||||
channel = match.group(1)
|
||||
return f"https://www.twitch.tv/{channel}", channel
|
||||
|
||||
|
||||
def _new_session():
|
||||
try:
|
||||
from streamlink import Streamlink
|
||||
except ImportError as error:
|
||||
raise RuntimeError(
|
||||
"Streamlink is not installed in the Kronic virtualenv. "
|
||||
"Run: pip install -r requirements-twitch.txt"
|
||||
) from error
|
||||
|
||||
session = Streamlink()
|
||||
session.set_option("stream-timeout", TWITCH_STREAM_TIMEOUT)
|
||||
# Streamlink normally sits ~3 HLS segments behind live. Five segments
|
||||
# adds ~67% headroom at the cost of additional live latency.
|
||||
session.set_option("hls-live-edge", max(3, int(os.getenv("TWITCH_HLS_LIVE_EDGE", "5"))))
|
||||
return session
|
||||
|
||||
|
||||
def _plugin_options():
|
||||
options = {}
|
||||
# Streamlink's Twitch plugin defaults to H.264. Explicitly keep Kronic's
|
||||
# supported codec list conservative because browser playback is H.264/AAC.
|
||||
if TWITCH_SUPPORTED_CODECS:
|
||||
options["supported-codecs"] = ",".join(TWITCH_SUPPORTED_CODECS)
|
||||
return options
|
||||
|
||||
|
||||
def resolve_twitch(
|
||||
value: str,
|
||||
quality: str = "best",
|
||||
) -> TwitchResolved:
|
||||
url, channel = normalize_twitch_url(value)
|
||||
session = _new_session()
|
||||
|
||||
try:
|
||||
plugin_name, plugin_class, resolved_url = session.resolve_url(url)
|
||||
plugin = plugin_class(
|
||||
session,
|
||||
resolved_url,
|
||||
options=_plugin_options(),
|
||||
)
|
||||
streams = plugin.streams()
|
||||
except Exception as error:
|
||||
text = str(error)
|
||||
if "No playable streams found" in text or "offline" in text.lower():
|
||||
raise TwitchOffline(f"{channel} is offline.") from error
|
||||
raise TwitchResolutionError(
|
||||
f"Streamlink could not resolve {channel}: {error}"
|
||||
) from error
|
||||
|
||||
if not streams:
|
||||
raise TwitchOffline(f"{channel} is offline.")
|
||||
|
||||
available = [
|
||||
key for key in streams.keys()
|
||||
if key not in {"best", "worst"}
|
||||
]
|
||||
|
||||
requested = str(quality or "best").strip()
|
||||
selected_name = requested if requested in streams else "best"
|
||||
selected = streams.get(selected_name)
|
||||
if selected is None:
|
||||
# Streamlink normally exposes best/worst aliases, but be defensive.
|
||||
selected_name, selected = next(iter(streams.items()))
|
||||
|
||||
return TwitchResolved(
|
||||
url=url,
|
||||
channel=channel,
|
||||
quality=selected_name,
|
||||
stream=selected,
|
||||
available_qualities=available,
|
||||
stream_id=str(getattr(plugin, "id", "") or ""),
|
||||
title=str(getattr(plugin, "title", "") or ""),
|
||||
author=str(getattr(plugin, "author", "") or channel),
|
||||
category=str(getattr(plugin, "category", "") or ""),
|
||||
)
|
||||
|
||||
|
||||
def probe_twitch(value: str, quality: str = "best") -> dict:
|
||||
try:
|
||||
resolved = resolve_twitch(value, quality=quality)
|
||||
except TwitchOffline:
|
||||
url, channel = normalize_twitch_url(value)
|
||||
return {
|
||||
"url": url,
|
||||
"channel": channel,
|
||||
"live": False,
|
||||
"available_qualities": [],
|
||||
"quality": quality or "best",
|
||||
"stream_id": "",
|
||||
"title": "",
|
||||
"author": channel,
|
||||
"category": "",
|
||||
}
|
||||
return resolved.as_dict()
|
||||
|
||||
|
||||
class TwitchFFmpegPipeline:
|
||||
"""Streamlink -> Python pipe -> FFmpeg.
|
||||
|
||||
Streamlink owns Twitch/HLS specifics. FFmpeg owns browser-compatible
|
||||
remuxing/transcoding. This works for HLSStream and MuxedHLSStream because
|
||||
both expose Stream.open().
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resolved: TwitchResolved,
|
||||
*,
|
||||
output_path: Path | None = None,
|
||||
browser_output: bool = False,
|
||||
):
|
||||
self.resolved = resolved
|
||||
self.output_path = Path(output_path).resolve() if output_path else None
|
||||
self.browser_output = bool(browser_output)
|
||||
|
||||
self.source = None
|
||||
self.process = None
|
||||
self.pump_thread = None
|
||||
self.stop_event = threading.Event()
|
||||
self.stderr_chunks: list[bytes] = []
|
||||
self.stderr_thread = None
|
||||
|
||||
def _ffmpeg_command(self):
|
||||
command = [
|
||||
FFMPEG_BIN,
|
||||
"-nostdin",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"warning",
|
||||
"-fflags",
|
||||
"+genpts",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-map",
|
||||
"0:v:0?",
|
||||
"-map",
|
||||
"0:a:0?",
|
||||
"-c:v",
|
||||
"copy",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"192k",
|
||||
"-ac",
|
||||
"2",
|
||||
]
|
||||
|
||||
if self.browser_output:
|
||||
command.extend([
|
||||
"-movflags",
|
||||
"frag_keyframe+empty_moov+default_base_moof",
|
||||
"-f",
|
||||
"mp4",
|
||||
"pipe:1",
|
||||
])
|
||||
else:
|
||||
command.extend([
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-f",
|
||||
"mp4",
|
||||
"-y",
|
||||
str(self.output_path),
|
||||
])
|
||||
|
||||
return command
|
||||
|
||||
def start(self):
|
||||
self.source = self.resolved.stream.open()
|
||||
|
||||
self.process = subprocess.Popen(
|
||||
self._ffmpeg_command(),
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE if self.browser_output else subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
)
|
||||
|
||||
def pump():
|
||||
try:
|
||||
while not self.stop_event.is_set():
|
||||
chunk = self.source.read(256 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
if not self.process or not self.process.stdin:
|
||||
break
|
||||
try:
|
||||
self.process.stdin.write(chunk)
|
||||
self.process.stdin.flush()
|
||||
except (BrokenPipeError, OSError):
|
||||
break
|
||||
except Exception as error:
|
||||
logger.debug("Twitch source pump ended: %s", error)
|
||||
finally:
|
||||
try:
|
||||
if self.process and self.process.stdin:
|
||||
self.process.stdin.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def collect_stderr():
|
||||
try:
|
||||
if not self.process or not self.process.stderr:
|
||||
return
|
||||
while True:
|
||||
chunk = self.process.stderr.read(8192)
|
||||
if not chunk:
|
||||
break
|
||||
self.stderr_chunks.append(chunk)
|
||||
total = sum(len(part) for part in self.stderr_chunks)
|
||||
if total > 128 * 1024:
|
||||
del self.stderr_chunks[:-8]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.pump_thread = threading.Thread(
|
||||
target=pump,
|
||||
daemon=True,
|
||||
name=f"twitch-pump-{self.resolved.channel}",
|
||||
)
|
||||
self.stderr_thread = threading.Thread(
|
||||
target=collect_stderr,
|
||||
daemon=True,
|
||||
name=f"twitch-ffmpeg-stderr-{self.resolved.channel}",
|
||||
)
|
||||
self.pump_thread.start()
|
||||
self.stderr_thread.start()
|
||||
return self
|
||||
|
||||
def stop(self, graceful=True):
|
||||
self.stop_event.set()
|
||||
|
||||
try:
|
||||
if self.source is not None:
|
||||
self.source.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if self.process is not None and self.process.poll() is None:
|
||||
if graceful:
|
||||
try:
|
||||
self.process.send_signal(signal.SIGINT)
|
||||
except Exception:
|
||||
self.process.terminate()
|
||||
else:
|
||||
self.process.terminate()
|
||||
|
||||
try:
|
||||
self.process.wait(timeout=8 if graceful else 3)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill()
|
||||
try:
|
||||
self.process.wait(timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if self.pump_thread:
|
||||
self.pump_thread.join(timeout=2)
|
||||
if self.stderr_thread:
|
||||
self.stderr_thread.join(timeout=1)
|
||||
|
||||
def wait(self):
|
||||
if not self.process:
|
||||
return -1
|
||||
return self.process.wait()
|
||||
|
||||
def stderr_text(self):
|
||||
return b"".join(self.stderr_chunks).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def start_browser_pipeline(value: str, quality: str = "best"):
|
||||
resolved = resolve_twitch(value, quality=quality)
|
||||
pipeline = TwitchFFmpegPipeline(
|
||||
resolved,
|
||||
browser_output=True,
|
||||
).start()
|
||||
return resolved, pipeline
|
||||
|
||||
|
||||
def safe_recording_stem(resolved: TwitchResolved):
|
||||
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
|
||||
title = resolved.title or resolved.channel
|
||||
safe_title = re.sub(r"[^A-Za-z0-9._ -]+", "", title).strip()
|
||||
safe_title = re.sub(r"\s+", " ", safe_title)[:100] or resolved.channel
|
||||
return f"{resolved.channel} - {timestamp} - {safe_title}"
|
||||
|
||||
|
||||
def write_twitch_nfo(path: Path, resolved: TwitchResolved):
|
||||
root = ET.Element("movie")
|
||||
|
||||
def add(tag, value):
|
||||
if value in (None, ""):
|
||||
return
|
||||
child = ET.SubElement(root, tag)
|
||||
child.text = str(value)
|
||||
|
||||
add("title", resolved.title or f"{resolved.channel} Twitch Stream")
|
||||
add("plot", f"Recorded live from Twitch channel {resolved.author or resolved.channel}.")
|
||||
add("studio", resolved.author or resolved.channel)
|
||||
add("genre", resolved.category)
|
||||
add("source", "twitch")
|
||||
add("webpage", resolved.url)
|
||||
add("recorded", time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
if resolved.stream_id:
|
||||
uid = ET.SubElement(
|
||||
root,
|
||||
"uniqueid",
|
||||
{"type": "twitch", "default": "true"},
|
||||
)
|
||||
uid.text = resolved.stream_id
|
||||
|
||||
tree = ET.ElementTree(root)
|
||||
try:
|
||||
ET.indent(tree, space=" ")
|
||||
except AttributeError:
|
||||
pass
|
||||
tree.write(
|
||||
path.with_suffix(".nfo"),
|
||||
encoding="utf-8",
|
||||
xml_declaration=True,
|
||||
)
|
||||
|
||||
|
||||
def record_twitch(
|
||||
value: str,
|
||||
quality: str = "best",
|
||||
*,
|
||||
stop_check=None,
|
||||
progress_callback=None,
|
||||
):
|
||||
TWITCH_RECORD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
resolved = resolve_twitch(value, quality=quality)
|
||||
|
||||
final_path = TWITCH_RECORD_DIR / f"{safe_recording_stem(resolved)}.mp4"
|
||||
part_path = final_path.with_suffix(".part.mp4")
|
||||
|
||||
pipeline = TwitchFFmpegPipeline(
|
||||
resolved,
|
||||
output_path=part_path,
|
||||
browser_output=False,
|
||||
).start()
|
||||
|
||||
started = time.monotonic()
|
||||
try:
|
||||
while pipeline.process and pipeline.process.poll() is None:
|
||||
if stop_check and stop_check():
|
||||
pipeline.stop(graceful=True)
|
||||
break
|
||||
|
||||
elapsed = max(0, int(time.monotonic() - started))
|
||||
hours, rem = divmod(elapsed, 3600)
|
||||
minutes, seconds = divmod(rem, 60)
|
||||
if progress_callback:
|
||||
progress_callback(
|
||||
f"recording live · {hours:02d}:{minutes:02d}:{seconds:02d}"
|
||||
)
|
||||
time.sleep(1)
|
||||
|
||||
returncode = pipeline.process.returncode if pipeline.process else -1
|
||||
finally:
|
||||
if pipeline.process and pipeline.process.poll() is None:
|
||||
pipeline.stop(graceful=True)
|
||||
else:
|
||||
pipeline.stop_event.set()
|
||||
try:
|
||||
if pipeline.source is not None:
|
||||
pipeline.source.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if part_path.is_file() and part_path.stat().st_size > 0:
|
||||
os.replace(part_path, final_path)
|
||||
try:
|
||||
write_twitch_nfo(final_path, resolved)
|
||||
except Exception as error:
|
||||
logger.warning("Could not write Twitch NFO: %s", error)
|
||||
|
||||
return {
|
||||
**resolved.as_dict(),
|
||||
"output_path": str(final_path),
|
||||
"size_bytes": final_path.stat().st_size,
|
||||
"returncode": returncode,
|
||||
}
|
||||
|
||||
error = pipeline.stderr_text()[-4000:]
|
||||
raise RuntimeError(
|
||||
f"Twitch recording produced no playable file. "
|
||||
f"FFmpeg return code {returncode}. {error}"
|
||||
)
|
||||
Reference in New Issue
Block a user