Upload files to "routes"
This commit is contained in:
111
routes/music.py
Normal file
111
routes/music.py
Normal file
@@ -0,0 +1,111 @@
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, jsonify, send_file, abort
|
||||
|
||||
bp = Blueprint("music", __name__)
|
||||
|
||||
MUSIC_DIR = Path(__file__).parent.parent / "music"
|
||||
|
||||
_CONVERT_EXTS = {".mp3", ".ogg", ".flac", ".m4a", ".aac", ".opus", ".wma"}
|
||||
|
||||
def _ensure_dir():
|
||||
MUSIC_DIR.mkdir(exist_ok=True)
|
||||
|
||||
def _needs_convert(src: Path, dst: Path) -> bool:
|
||||
return not dst.exists() or dst.stat().st_mtime < src.stat().st_mtime
|
||||
|
||||
def _convert_to_wav(src: Path) -> Path:
|
||||
dst = src.with_suffix(".wav")
|
||||
if not _needs_convert(src, dst):
|
||||
return dst
|
||||
|
||||
print(f"[Music] Converting: {src.name} → {dst.name}")
|
||||
result = subprocess.run(
|
||||
[
|
||||
"ffmpeg", "-y",
|
||||
"-i", str(src),
|
||||
"-ar", "44100",
|
||||
"-ac", "2",
|
||||
"-acodec", "pcm_s16le",
|
||||
str(dst),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f"[Music] ffmpeg error for {src.name}:\n{result.stderr[-500:]}")
|
||||
raise RuntimeError(f"ffmpeg failed on {src.name}")
|
||||
|
||||
print(f"[Music] Done: {dst.name} ({dst.stat().st_size // 1024} KB)")
|
||||
return dst
|
||||
|
||||
def _build_playlist() -> list[dict]:
|
||||
_ensure_dir()
|
||||
tracks = []
|
||||
seen_stems = set()
|
||||
|
||||
for f in sorted(MUSIC_DIR.iterdir()):
|
||||
if f.is_dir() or f.name.startswith("."):
|
||||
continue
|
||||
|
||||
ext = f.suffix.lower()
|
||||
|
||||
if ext in _CONVERT_EXTS:
|
||||
try:
|
||||
wav = _convert_to_wav(f)
|
||||
stem = wav.stem
|
||||
if stem not in seen_stems:
|
||||
seen_stems.add(stem)
|
||||
tracks.append({
|
||||
"Id": str(uuid.uuid5(uuid.NAMESPACE_URL, wav.name)),
|
||||
"friendlyName": wav.stem,
|
||||
"fileName": wav.name,
|
||||
"fileType": 20,
|
||||
})
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
elif ext == ".wav":
|
||||
stem = f.stem
|
||||
if stem not in seen_stems:
|
||||
seen_stems.add(stem)
|
||||
tracks.append({
|
||||
"Id": str(uuid.uuid5(uuid.NAMESPACE_URL, f.name)),
|
||||
"friendlyName": f.stem,
|
||||
"fileName": f.name,
|
||||
"fileType": 20,
|
||||
})
|
||||
|
||||
return tracks
|
||||
|
||||
@bp.route("/api/music/v1/playlist", methods=["GET", "POST"])
|
||||
def get_playlist():
|
||||
tracks = _build_playlist()
|
||||
print(f"[Music] Playlist → {len(tracks)} track(s)")
|
||||
return jsonify(tracks)
|
||||
|
||||
@bp.route("/api/music/v1/file/<path:filename>", methods=["GET"])
|
||||
def serve_track(filename):
|
||||
_ensure_dir()
|
||||
|
||||
try:
|
||||
target = (MUSIC_DIR / filename).resolve()
|
||||
except Exception:
|
||||
abort(400)
|
||||
|
||||
music_root = MUSIC_DIR.resolve()
|
||||
if not str(target).startswith(str(music_root) + os.sep):
|
||||
abort(403)
|
||||
|
||||
if not target.exists() or not target.is_file():
|
||||
abort(404)
|
||||
|
||||
return send_file(
|
||||
str(target),
|
||||
mimetype="audio/wav",
|
||||
conditional=True,
|
||||
)
|
||||
Reference in New Issue
Block a user