Upload files to "/"

This commit is contained in:
2026-11-25 20:20:27 -06:00
parent 9c1e0134d9
commit ce7b8f704e
5 changed files with 2561 additions and 0 deletions
+284
View File
@@ -0,0 +1,284 @@
from __future__ import annotations
import hashlib
import json
import os
import subprocess
import time
from pathlib import Path
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")
THUMBNAIL_DIR = Path(
os.getenv("THUMBNAIL_DIR", str(BASE_DIR / "thumbnails"))
).expanduser().resolve()
THUMBNAIL_DIR.mkdir(parents=True, exist_ok=True)
# A failed source is retried automatically when its size or mtime changes.
_FAILURE_SUFFIX = ".failed.json"
# These errors mean the input itself could not be opened/parsed. Retrying at a
# different timestamp cannot possibly help and just creates duplicate log spam.
_FATAL_INPUT_ERRORS = (
"ebml header parsing failed",
"invalid as first byte of an ebml number",
"invalid data found when processing input",
"error opening input",
"error opening input file",
"error opening input files",
"moov atom not found",
"invalid atom size",
)
def _key_text(key_path) -> str:
return str(key_path)
def _thumbnail_hash(key_path) -> str:
return hashlib.sha1(
_key_text(key_path).encode("utf-8", "surrogatepass")
).hexdigest()
def get_thumbnail_path(key_path) -> Path:
return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}.jpg"
def _failure_path(key_path) -> Path:
return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}{_FAILURE_SUFFIX}"
def _source_fingerprint(path: Path) -> dict:
try:
stat = path.stat()
return {
"path": str(path),
"size": int(stat.st_size),
"mtime_ns": int(stat.st_mtime_ns),
}
except OSError:
return {
"path": str(path),
"size": -1,
"mtime_ns": -1,
}
def _load_failure(key_path):
marker = _failure_path(key_path)
try:
return json.loads(marker.read_text(encoding="utf-8"))
except Exception:
return None
def _failure_still_valid(source_path: Path, key_path) -> bool:
failure = _load_failure(key_path)
if not failure:
return False
current = _source_fingerprint(source_path)
previous = failure.get("fingerprint") or {}
return (
current.get("path") == previous.get("path")
and current.get("size") == previous.get("size")
and current.get("mtime_ns") == previous.get("mtime_ns")
)
def _write_failure(source_path: Path, key_path, error_text: str):
marker = _failure_path(key_path)
payload = {
"fingerprint": _source_fingerprint(source_path),
"failed_at": int(time.time()),
"error": str(error_text or "")[-4000:],
}
temp = marker.with_suffix(marker.suffix + ".tmp")
try:
temp.write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
os.replace(temp, marker)
except OSError:
try:
temp.unlink(missing_ok=True)
except OSError:
pass
def _clear_failure(key_path):
try:
_failure_path(key_path).unlink(missing_ok=True)
except OSError:
pass
def _looks_like_obviously_invalid_matroska(path: Path):
"""
MKV/WebM files begin with the EBML magic 1A 45 DF A3.
We only use this quick check for .mkv/.webm because it is deterministic
and avoids spawning FFmpeg for a file that starts with zeros or other
obviously invalid data.
It is intentionally conservative: all other media types continue to
FFmpeg normally.
"""
if path.suffix.lower() not in {".mkv", ".webm"}:
return False, ""
try:
with path.open("rb") as handle:
header = handle.read(4)
except OSError as error:
return True, f"could not read source file: {error}"
if len(header) < 4:
return True, "file is too small to contain an EBML header"
if header != b"\x1a\x45\xdf\xa3":
return True, (
"invalid MKV/WebM EBML header "
f"(first bytes: {header.hex(' ')})"
)
return False, ""
def _fatal_input_error(stderr_text: str) -> bool:
text = str(stderr_text or "").lower()
return any(pattern in text for pattern in _FATAL_INPUT_ERRORS)
def _capture(source_path: Path, output_path: Path, seek_seconds: int):
command = [
FFMPEG_BIN,
"-hide_banner",
"-loglevel",
"error",
"-ss",
str(int(seek_seconds)),
"-i",
str(source_path),
"-frames:v",
"1",
"-vf",
"scale=480:-2",
"-q:v",
"3",
"-y",
str(output_path),
]
result = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
errors="replace",
)
if result.returncode == 0 and output_path.is_file():
try:
if output_path.stat().st_size > 0:
return True, ""
except OSError:
pass
try:
output_path.unlink(missing_ok=True)
except OSError:
pass
return False, (result.stderr or "").strip()
def generate_thumbnail(
source_path,
*,
key_path=None,
):
"""
Generate and return the JPEG thumbnail path, or None.
Compatibility:
generate_thumbnail(path)
generate_thumbnail(path, key_path=original_library_path)
Failed media is remembered persistently until the source file changes.
"""
source = Path(source_path).expanduser()
key = key_path if key_path is not None else source_path
output = get_thumbnail_path(key)
if output.is_file():
return output
# If this exact source version already failed, do not run FFmpeg again.
if _failure_still_valid(source, key):
return None
if not source.is_file():
message = "source file does not exist"
_write_failure(source, key, message)
print(
f"[THUMBNAIL] Skipping {source}: {message}",
flush=True,
)
return None
# Cheap deterministic guard for the exact failure shown in the logs:
# 00 00 ... instead of the MKV EBML header.
invalid, reason = _looks_like_obviously_invalid_matroska(source)
if invalid:
_write_failure(source, key, reason)
print(
f"[THUMBNAIL] Skipping invalid media {source}: {reason}",
flush=True,
)
return None
# Normal first attempt.
ok, error = _capture(source, output, 5)
if ok:
_clear_failure(key)
return output
# If FFmpeg could not even parse/open the input, seeking to 60 seconds
# cannot fix it. Persist the failure immediately.
if _fatal_input_error(error):
_write_failure(source, key, error)
summary = error.splitlines()[-1] if error else "invalid media input"
print(
f"[THUMBNAIL] Invalid media {source}: {summary}",
flush=True,
)
return None
# Some valid files have black/empty/opening frames at 5 seconds, so retain
# the original 60-second fallback for ordinary decode/capture failures.
ok60, error60 = _capture(source, output, 60)
if ok60:
_clear_failure(key)
return output
final_error = error60 or error or "thumbnail capture failed"
_write_failure(source, key, final_error)
# One concise log entry instead of subprocess traceback + a second wall of
# FFmpeg diagnostics every scan.
summary = final_error.splitlines()[-1] if final_error else "unknown error"
print(
f"[THUMBNAIL] Failed {source}: {summary}",
flush=True,
)
return None
+50
View File
@@ -0,0 +1,50 @@
from dataclasses import dataclass
import re
@dataclass
class TranscodePlan:
input_path: str
video_codec: str
audio_codec: str
target_container: str = "mp4"
# Example rules:
# - If not H.264 or not AAC → transcode
# - If resolution > 1080p → downscale
def plan_transcodes(media_items):
plans = []
for item in media_items:
needs_transcode = False
if item.video_codec != "AVC": # pymediainfo may report H.264 as AVC
needs_transcode = True
if item.audio_codec != "AAC":
needs_transcode = True
if item.width and item.width > 1920:
needs_transcode = True
if needs_transcode:
print(f"Planning transcode for: {item.path}")
plans.append(
TranscodePlan(
input_path=str(item.path),
video_codec="h264",
audio_codec="aac"
)
)
return plans
def sanitize_filename(name: str) -> str:
"""
Make filename filesystem-safe and add _dup before extension.
"""
name = name.replace(":", "-").replace("@", "-").replace("–", "-")
name = re.sub(r"\s+", " ", name).strip()
if "." in name:
base, ext = name.rsplit(".", 1)
return f"{base}_dup.{ext}"
else:
return f"{name}_dup"
+527
View File
@@ -0,0 +1,527 @@
from __future__ import annotations
import os
import sqlite3
import threading
import time
from pathlib import Path
from dotenv import load_dotenv
from twitch_stream import (
TwitchOffline,
probe_twitch,
record_twitch,
normalize_twitch_url,
)
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
DB_PATH = Path(
os.getenv("DB_PATH", str(BASE_DIR / "media_library.db"))
).expanduser().resolve()
TWITCH_WATCH_INTERVAL = max(
10,
int(os.getenv("TWITCH_WATCH_INTERVAL", "30")),
)
_THREAD = None
_STOP = threading.Event()
_RECORD_THREADS = {}
_RECORD_LOCK = threading.Lock()
def _db():
db = sqlite3.connect(DB_PATH, timeout=30)
db.row_factory = sqlite3.Row
return db
def init_twitch_db():
with _db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS twitch_channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
url TEXT NOT NULL,
channel_name TEXT NOT NULL,
quality TEXT NOT NULL DEFAULT 'best',
auto_record INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
live INTEGER NOT NULL DEFAULT 0,
stream_id TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
author TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT '',
available_qualities TEXT NOT NULL DEFAULT '',
last_checked_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, channel_name)
);
CREATE TABLE IF NOT EXISTS twitch_recordings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
message TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
stream_id TEXT NOT NULL DEFAULT '',
output_path TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
cancel_requested INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
started_at INTEGER,
finished_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_twitch_recordings_status
ON twitch_recordings(status, created_at);
""")
db.execute(
"""UPDATE twitch_recordings
SET status='failed',
message='interrupted by service restart',
error='Recording was interrupted by Media Server restart.',
finished_at=?
WHERE status='recording'""",
(int(time.time()),),
)
db.commit()
def add_channel(user_id: int, value: str, quality: str = "best"):
url, channel = normalize_twitch_url(value)
now = int(time.time())
with _db() as db:
row = db.execute(
"SELECT id FROM twitch_channels WHERE user_id=? AND channel_name=?",
(int(user_id), channel.lower()),
).fetchone()
if row:
channel_id = int(row["id"])
db.execute(
"""UPDATE twitch_channels SET
url=?,
quality=?,
enabled=1,
updated_at=?
WHERE id=?""",
(url, quality or "best", now, channel_id),
)
else:
cur = db.execute(
"""INSERT INTO twitch_channels(
user_id,url,channel_name,quality,created_at,updated_at
) VALUES(?,?,?,?,?,?)""",
(
int(user_id),
url,
channel.lower(),
quality or "best",
now,
now,
),
)
channel_id = int(cur.lastrowid)
db.commit()
refresh_channel(user_id, channel_id)
return get_channel(user_id, channel_id)
def get_channel(user_id: int, channel_id: int):
with _db() as db:
row = db.execute(
"SELECT * FROM twitch_channels WHERE id=? AND user_id=?",
(int(channel_id), int(user_id)),
).fetchone()
return dict(row) if row else None
def list_channels(user_id: int):
with _db() as db:
rows = db.execute(
"""SELECT * FROM twitch_channels
WHERE user_id=?
ORDER BY channel_name""",
(int(user_id),),
).fetchall()
return [dict(row) for row in rows]
def delete_channel(user_id: int, channel_id: int):
channel = get_channel(user_id, channel_id)
if not channel:
return False
active = active_recording_for_channel(channel_id)
if active:
raise ValueError("Stop the active recording before removing this channel.")
with _db() as db:
db.execute(
"DELETE FROM twitch_channels WHERE id=? AND user_id=?",
(int(channel_id), int(user_id)),
)
db.commit()
return True
def set_auto_record(user_id: int, channel_id: int, enabled: bool):
with _db() as db:
cur = db.execute(
"""UPDATE twitch_channels
SET auto_record=?,updated_at=?
WHERE id=? AND user_id=?""",
(
1 if enabled else 0,
int(time.time()),
int(channel_id),
int(user_id),
),
)
db.commit()
if cur.rowcount != 1:
raise ValueError("Twitch channel not found.")
return get_channel(user_id, channel_id)
def set_quality(user_id: int, channel_id: int, quality: str):
quality = str(quality or "best").strip() or "best"
with _db() as db:
cur = db.execute(
"""UPDATE twitch_channels
SET quality=?,updated_at=?
WHERE id=? AND user_id=?""",
(
quality,
int(time.time()),
int(channel_id),
int(user_id),
),
)
db.commit()
if cur.rowcount != 1:
raise ValueError("Twitch channel not found.")
return get_channel(user_id, channel_id)
def refresh_channel(user_id: int, channel_id: int):
channel = get_channel(user_id, channel_id)
if not channel:
raise ValueError("Twitch channel not found.")
status = probe_twitch(
channel["url"],
quality=channel.get("quality") or "best",
)
now = int(time.time())
qualities = ",".join(status.get("available_qualities") or [])
with _db() as db:
db.execute(
"""UPDATE twitch_channels SET
live=?,
stream_id=?,
title=?,
author=?,
category=?,
available_qualities=?,
last_checked_at=?,
updated_at=?
WHERE id=?""",
(
1 if status.get("live") else 0,
str(status.get("stream_id") or ""),
str(status.get("title") or ""),
str(status.get("author") or ""),
str(status.get("category") or ""),
qualities,
now,
now,
int(channel_id),
),
)
db.commit()
return get_channel(user_id, channel_id)
def list_recordings(user_id: int, limit=50):
with _db() as db:
rows = db.execute(
"""SELECT r.*,c.channel_name,c.url,c.quality
FROM twitch_recordings r
JOIN twitch_channels c ON c.id=r.channel_id
WHERE r.user_id=?
ORDER BY r.id DESC
LIMIT ?""",
(int(user_id), max(1, min(int(limit), 200))),
).fetchall()
return [dict(row) for row in rows]
def active_recording_for_channel(channel_id: int):
with _db() as db:
row = db.execute(
"""SELECT * FROM twitch_recordings
WHERE channel_id=? AND status IN ('queued','recording')
ORDER BY id DESC LIMIT 1""",
(int(channel_id),),
).fetchone()
return dict(row) if row else None
def enqueue_recording(user_id: int, channel_id: int):
channel = get_channel(user_id, channel_id)
if not channel:
raise ValueError("Twitch channel not found.")
existing = active_recording_for_channel(channel_id)
if existing:
return existing
now = int(time.time())
with _db() as db:
cur = db.execute(
"""INSERT INTO twitch_recordings(
channel_id,user_id,status,message,created_at
) VALUES(?,?,'queued','checking Twitch stream…',?)""",
(int(channel_id), int(user_id), now),
)
job_id = int(cur.lastrowid)
db.commit()
_start_record_thread(job_id)
return get_recording(user_id, job_id)
def get_recording(user_id: int, job_id: int):
with _db() as db:
row = db.execute(
"SELECT * FROM twitch_recordings WHERE id=? AND user_id=?",
(int(job_id), int(user_id)),
).fetchone()
return dict(row) if row else None
def stop_recording(user_id: int, job_id: int):
with _db() as db:
row = db.execute(
"SELECT * FROM twitch_recordings WHERE id=? AND user_id=?",
(int(job_id), int(user_id)),
).fetchone()
if not row:
raise ValueError("Twitch recording job not found.")
if row["status"] in {"complete", "failed", "cancelled"}:
return dict(row)
db.execute(
"""UPDATE twitch_recordings
SET cancel_requested=1,
message='stopping recording…'
WHERE id=?""",
(int(job_id),),
)
db.commit()
return get_recording(user_id, job_id)
def clear_finished_recordings(user_id: int):
with _db() as db:
cur = db.execute(
"""DELETE FROM twitch_recordings
WHERE user_id=?
AND status IN ('complete','failed','cancelled')""",
(int(user_id),),
)
db.commit()
return int(cur.rowcount or 0)
def _cancel_requested(job_id: int):
with _db() as db:
row = db.execute(
"SELECT cancel_requested FROM twitch_recordings WHERE id=?",
(int(job_id),),
).fetchone()
return bool(row and row["cancel_requested"])
def _update_recording(job_id: int, **values):
if not values:
return
sets = []
args = []
for key, value in values.items():
sets.append(f"{key}=?")
args.append(value)
args.append(int(job_id))
with _db() as db:
db.execute(
f"UPDATE twitch_recordings SET {', '.join(sets)} WHERE id=?",
args,
)
db.commit()
def _record_worker(job_id: int):
try:
with _db() as db:
job = db.execute(
"SELECT * FROM twitch_recordings WHERE id=?",
(int(job_id),),
).fetchone()
if not job:
return
channel = db.execute(
"SELECT * FROM twitch_channels WHERE id=?",
(int(job["channel_id"]),),
).fetchone()
if not channel:
raise RuntimeError("Twitch channel was removed.")
try:
status = refresh_channel(
int(job["user_id"]),
int(job["channel_id"]),
)
except Exception as error:
raise RuntimeError(f"Could not refresh Twitch channel: {error}") from error
if not status.get("live"):
_update_recording(
job_id,
status="failed",
message="channel is offline",
error=f"{status.get('channel_name') or 'Channel'} is not live.",
finished_at=int(time.time()),
)
return
_update_recording(
job_id,
status="recording",
message="recording live · 00:00:00",
title=status.get("title") or "",
stream_id=status.get("stream_id") or "",
started_at=int(time.time()),
)
def progress(message):
_update_recording(job_id, message=message)
result = record_twitch(
status["url"],
quality=status.get("quality") or "best",
stop_check=lambda: _cancel_requested(job_id),
progress_callback=progress,
)
cancelled = _cancel_requested(job_id)
_update_recording(
job_id,
status="cancelled" if cancelled else "complete",
message="recording saved" if cancelled else "complete",
output_path=result.get("output_path") or "",
finished_at=int(time.time()),
)
except Exception as error:
_update_recording(
job_id,
status="failed",
message="failed",
error=str(error)[:4000],
finished_at=int(time.time()),
)
print(
"[TWITCH] recording failed",
{"job_id": job_id, "error": str(error)},
flush=True,
)
finally:
with _RECORD_LOCK:
_RECORD_THREADS.pop(int(job_id), None)
def _start_record_thread(job_id: int):
with _RECORD_LOCK:
existing = _RECORD_THREADS.get(int(job_id))
if existing and existing.is_alive():
return
thread = threading.Thread(
target=_record_worker,
args=(int(job_id),),
daemon=True,
name=f"twitch-record-{job_id}",
)
_RECORD_THREADS[int(job_id)] = thread
thread.start()
def _watch_loop():
while not _STOP.is_set():
try:
with _db() as db:
rows = db.execute(
"""SELECT * FROM twitch_channels
WHERE enabled=1 AND auto_record=1
ORDER BY id"""
).fetchall()
for row in rows:
if _STOP.is_set():
break
channel = dict(row)
try:
refreshed = refresh_channel(
int(channel["user_id"]),
int(channel["id"]),
)
if refreshed.get("live"):
active = active_recording_for_channel(
int(channel["id"])
)
if not active:
enqueue_recording(
int(channel["user_id"]),
int(channel["id"]),
)
except Exception as error:
print(
"[TWITCH] watcher check failed",
{
"channel": channel.get("channel_name"),
"error": str(error),
},
flush=True,
)
if _STOP.wait(0.5):
break
except Exception as error:
print("[TWITCH] watcher error:", error, flush=True)
_STOP.wait(TWITCH_WATCH_INTERVAL)
def start_twitch_watcher():
global _THREAD
if _THREAD and _THREAD.is_alive():
return
_STOP.clear()
_THREAD = threading.Thread(
target=_watch_loop,
daemon=True,
name="twitch-live-watcher",
)
_THREAD.start()
+109
View File
@@ -0,0 +1,109 @@
import json
import os
import re
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
YOUTUBE_METADATA_TIMEOUT = float(os.getenv("YOUTUBE_METADATA_TIMEOUT", "12"))
YOUTUBE_OEMBED_URL = "https://www.youtube.com/oembed"
YOUTUBE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
INVALID_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
WHITESPACE_RE = re.compile(r"\s+")
def extract_youtube_id(value):
"""Extract an 11-character YouTube video ID from a path or filename."""
if value is None:
return None
stem = Path(str(value)).stem.strip()
if YOUTUBE_ID_RE.fullmatch(stem):
return stem
bracketed = re.findall(r"\[([A-Za-z0-9_-]{11})\]", stem)
if bracketed:
return bracketed[-1]
# Common downloader filenames end in a space/dot/dash/underscore plus ID.
if len(stem) >= 11:
candidate = stem[-11:]
prefix = stem[:-11]
if YOUTUBE_ID_RE.fullmatch(candidate):
if not prefix or prefix[-1] in " ._-()[]":
return candidate
# Last resort: scan delimited tokens without assuming words are IDs.
tokens = re.split(r"[\s.()\[\]]+", stem)
for token in reversed(tokens):
if YOUTUBE_ID_RE.fullmatch(token):
return token
return None
def fetch_youtube_metadata(video_id, timeout=None):
"""Fetch title/channel metadata using YouTube's public oEmbed endpoint."""
if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")):
raise ValueError("Invalid YouTube video ID")
query = urlencode({
"url": f"https://www.youtube.com/watch?v={video_id}",
"format": "json",
})
request = Request(
f"{YOUTUBE_OEMBED_URL}?{query}",
headers={
"User-Agent": "MediaServer-YouTubeMetadata/1.0",
"Accept": "application/json",
},
)
try:
with urlopen(request, timeout=timeout or YOUTUBE_METADATA_TIMEOUT) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
if exc.code == 404:
raise LookupError(f"YouTube metadata not found for {video_id}") from exc
raise RuntimeError(f"YouTube HTTP error {exc.code} for {video_id}") from exc
except URLError as exc:
raise RuntimeError(f"YouTube request failed for {video_id}: {exc.reason}") from exc
title = str(payload.get("title") or "").strip()
if not title:
raise LookupError(f"YouTube returned no title for {video_id}")
return {
"video_id": video_id,
"title": title,
"channel_name": str(payload.get("author_name") or "").strip() or None,
"channel_url": str(payload.get("author_url") or "").strip() or None,
}
def safe_filename_title(title, max_length=180):
"""Return a filesystem-safe title while keeping normal punctuation readable."""
value = INVALID_FILENAME_CHARS.sub("", str(title or ""))
value = WHITESPACE_RE.sub(" ", value).strip(" .")
if not value:
value = "YouTube Video"
if len(value) > max_length:
value = value[:max_length].rstrip(" .")
return value
def build_youtube_filename(title, video_id, suffix):
"""Build: Nice Video Title [VIDEO_ID].ext"""
if not YOUTUBE_ID_RE.fullmatch(str(video_id or "")):
raise ValueError("Invalid YouTube video ID")
suffix = str(suffix or "")
if suffix and not suffix.startswith("."):
suffix = "." + suffix
return f"{safe_filename_title(title)} [{video_id}]{suffix}"
+1591
View File
File diff suppressed because it is too large Load Diff