Upload files to "kronic/resolver"
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
Kronic resolver wrapper with SpotDL routes.
|
||||
|
||||
This intentionally imports the existing resolver app unchanged, then mounts
|
||||
the SpotDL router on that same FastAPI application.
|
||||
|
||||
Run with:
|
||||
python -m uvicorn kronic.resolver.app_spotdl:app --host 127.0.0.1 --port 3030
|
||||
"""
|
||||
|
||||
from .app import app
|
||||
from .spotdl_router import router as spotdl_router
|
||||
|
||||
|
||||
def _has_spotdl_route() -> bool:
|
||||
for route in getattr(
|
||||
app,
|
||||
"routes",
|
||||
[],
|
||||
):
|
||||
if getattr(
|
||||
route,
|
||||
"path",
|
||||
None,
|
||||
) == "/api/music/spotify/resolve":
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
if not _has_spotdl_route():
|
||||
app.include_router(
|
||||
spotdl_router
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class FormatInfo(BaseModel):
|
||||
id: str
|
||||
name: str | None = None
|
||||
protocol: str | None = None
|
||||
ext: str | None = None
|
||||
container: str | None = None
|
||||
|
||||
width: int | None = None
|
||||
height: int | None = None
|
||||
fps: float | None = None
|
||||
|
||||
vcodec: str | None = None
|
||||
acodec: str | None = None
|
||||
|
||||
bitrate: float | None = None
|
||||
filesize: int | None = None
|
||||
audio_channels: int | None = None
|
||||
language: str | None = None
|
||||
|
||||
video_only: bool = False
|
||||
audio_only: bool = False
|
||||
|
||||
# Kronic backend consumes these immediately with ffmpeg.
|
||||
# Signed URLs are short-lived; do not expose this API publicly.
|
||||
direct_url: str
|
||||
http_headers: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class VideoInfo(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
duration: float | None = None
|
||||
channel: str | None = None
|
||||
channel_id: str | None = None
|
||||
thumbnail: str | None = None
|
||||
formats: list[FormatInfo] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SearchItem(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
duration: float | None = None
|
||||
channel: str | None = None
|
||||
channel_id: str | None = None
|
||||
thumbnail: str | None = None
|
||||
webpage_url: str | None = None
|
||||
|
||||
|
||||
class SearchResponse(BaseModel):
|
||||
items: list[SearchItem] = Field(default_factory=list)
|
||||
@@ -0,0 +1,65 @@
|
||||
# Copyright Insidious authors <https://github.com/xrun1/insidious>
|
||||
# Copyright Kronic resolver modifications
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from asyncio import BoundedSemaphore
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi.datastructures import URL
|
||||
from httpx import USE_CLIENT_DEFAULT, AsyncClient, Request, Response
|
||||
from typing_extensions import override
|
||||
|
||||
PARALLEL_REQUESTS_PER_HOST = 24
|
||||
|
||||
HTTPX_BACKOFF_ERRORS = (
|
||||
httpx.NetworkError,
|
||||
httpx.TimeoutException,
|
||||
httpx.HTTPStatusError,
|
||||
httpx.RemoteProtocolError,
|
||||
)
|
||||
|
||||
_GOOGLE_DOMAINS = {
|
||||
"ytimg.com",
|
||||
"googlevideo.com",
|
||||
"googleusercontent.com",
|
||||
"ggpht.com",
|
||||
}
|
||||
|
||||
_request_semaphores: defaultdict[str, BoundedSemaphore] = defaultdict(
|
||||
lambda: BoundedSemaphore(PARALLEL_REQUESTS_PER_HOST)
|
||||
)
|
||||
|
||||
|
||||
class HttpClient(AsyncClient):
|
||||
@override
|
||||
async def send(
|
||||
self,
|
||||
request: Request,
|
||||
*,
|
||||
stream: bool = False,
|
||||
auth: Any = USE_CLIENT_DEFAULT,
|
||||
follow_redirects: Any = USE_CLIENT_DEFAULT,
|
||||
) -> Response:
|
||||
async with max_parallel_requests(str(request.url)):
|
||||
return await super().send(
|
||||
request,
|
||||
stream=stream,
|
||||
auth=auth,
|
||||
follow_redirects=follow_redirects,
|
||||
)
|
||||
|
||||
|
||||
def max_parallel_requests(url: URL | str) -> BoundedSemaphore:
|
||||
if not (host := URL(str(url)).hostname):
|
||||
raise ValueError(f"{url} has no hostname")
|
||||
|
||||
domain = ".".join(host.split(".")[-2:])
|
||||
|
||||
if domain in _GOOGLE_DOMAINS:
|
||||
domain = "youtube.com"
|
||||
|
||||
return _request_semaphores[domain]
|
||||
@@ -0,0 +1,656 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
try:
|
||||
from spotdl.download.downloader import Downloader as SpotDLDownloader
|
||||
from spotdl.utils.search import (
|
||||
get_simple_songs as spotdl_get_simple_songs,
|
||||
get_search_results as spotdl_get_search_results,
|
||||
)
|
||||
from spotdl.utils.spotify import SpotifyClient as SpotDLSpotifyClient
|
||||
|
||||
SPOTDL_AVAILABLE = True
|
||||
SPOTDL_IMPORT_ERROR = None
|
||||
except Exception as error:
|
||||
SpotDLDownloader = None
|
||||
spotdl_get_simple_songs = None
|
||||
spotdl_get_search_results = None
|
||||
SpotDLSpotifyClient = None
|
||||
SPOTDL_AVAILABLE = False
|
||||
SPOTDL_IMPORT_ERROR = error
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
SPOTDL_MAX_ITEMS = max(
|
||||
1,
|
||||
int(os.getenv("KRONIC_SPOTDL_MAX_ITEMS", "500")),
|
||||
)
|
||||
|
||||
SPOTDL_AUDIO_PROVIDERS = [
|
||||
value.strip()
|
||||
for value in os.getenv(
|
||||
"KRONIC_SPOTDL_AUDIO_PROVIDERS",
|
||||
"youtube-music,youtube",
|
||||
).split(",")
|
||||
if value.strip()
|
||||
]
|
||||
|
||||
SPOTDL_CLIENT_ID = os.getenv(
|
||||
"SPOTIPY_CLIENT_ID",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
SPOTDL_CLIENT_SECRET = os.getenv(
|
||||
"SPOTIPY_CLIENT_SECRET",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
_SPOTDL_LOCK = threading.Lock()
|
||||
_SPOTDL_READY = False
|
||||
_SPOTDL_DOWNLOADER = None
|
||||
_SPOTDL_MATCH_CACHE: dict[str, str] = {}
|
||||
|
||||
|
||||
def _spotify_source_kind(value: str) -> str:
|
||||
match = re.search(
|
||||
r"open\.spotify\.com/(track|album|playlist|artist)/",
|
||||
value or "",
|
||||
re.I,
|
||||
)
|
||||
return match.group(1).lower() if match else "search"
|
||||
|
||||
|
||||
def _youtube_id(value: str) -> str:
|
||||
value = str(value or "")
|
||||
|
||||
patterns = (
|
||||
r"(?:youtu\.be/)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:[?&]v=)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:youtube\.com/embed/)([A-Za-z0-9_-]{6,})",
|
||||
r"(?:music\.youtube\.com/watch\?v=)([A-Za-z0-9_-]{6,})",
|
||||
)
|
||||
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, value)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def _song_value(
|
||||
data: dict[str, Any],
|
||||
*names: str,
|
||||
default=None,
|
||||
):
|
||||
for name in names:
|
||||
value = data.get(name)
|
||||
|
||||
if value not in (None, "", []):
|
||||
return value
|
||||
|
||||
return default
|
||||
|
||||
|
||||
def _ensure_spotdl():
|
||||
global _SPOTDL_READY
|
||||
global _SPOTDL_DOWNLOADER
|
||||
|
||||
if not SPOTDL_AVAILABLE:
|
||||
raise RuntimeError(
|
||||
"spotDL is not installed in the resolver environment: "
|
||||
f"{SPOTDL_IMPORT_ERROR}"
|
||||
)
|
||||
|
||||
with _SPOTDL_LOCK:
|
||||
if (
|
||||
_SPOTDL_READY
|
||||
and _SPOTDL_DOWNLOADER is not None
|
||||
):
|
||||
return _SPOTDL_DOWNLOADER
|
||||
|
||||
init_kwargs = {}
|
||||
|
||||
if SPOTDL_CLIENT_ID:
|
||||
init_kwargs["client_id"] = SPOTDL_CLIENT_ID
|
||||
|
||||
if SPOTDL_CLIENT_SECRET:
|
||||
init_kwargs["client_secret"] = SPOTDL_CLIENT_SECRET
|
||||
|
||||
# spotDL 4.5 defaults to its free Spotify metadata path when official
|
||||
# credentials are not supplied.
|
||||
SpotDLSpotifyClient.init(**init_kwargs)
|
||||
|
||||
_SPOTDL_DOWNLOADER = SpotDLDownloader(
|
||||
settings={
|
||||
"audio_providers": (
|
||||
SPOTDL_AUDIO_PROVIDERS
|
||||
or ["youtube-music", "youtube"]
|
||||
),
|
||||
"lyrics_providers": [],
|
||||
"format": "m4a",
|
||||
"save_file": None,
|
||||
}
|
||||
)
|
||||
|
||||
_SPOTDL_READY = True
|
||||
|
||||
return _SPOTDL_DOWNLOADER
|
||||
|
||||
|
||||
def _song_json(song) -> dict[str, Any]:
|
||||
data = getattr(song, "json", None)
|
||||
|
||||
if callable(data):
|
||||
data = data()
|
||||
|
||||
if isinstance(data, dict):
|
||||
return dict(data)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
|
||||
def _norm_text(value: str) -> str:
|
||||
value = re.sub(r"\([^)]*\)|\[[^\]]*\]", " ", str(value or "").lower())
|
||||
value = re.sub(r"\b(official|audio|video|lyrics?|visualizer|remaster(?:ed)?|hd|4k)\b", " ", value)
|
||||
value = re.sub(r"[^a-z0-9]+", " ", value)
|
||||
return " ".join(value.split())
|
||||
|
||||
|
||||
def _spotify_metadata_item(song) -> dict[str, Any]:
|
||||
data = _song_json(song)
|
||||
artists = _song_value(data, "artists", default=[])
|
||||
if isinstance(artists, str):
|
||||
artists = [artists]
|
||||
artist = str(_song_value(data, "artist", default="") or "")
|
||||
if not artist and artists:
|
||||
artist = str(artists[0])
|
||||
|
||||
return {
|
||||
"spotify_id": str(_song_value(data, "song_id", "track_id", default="") or ""),
|
||||
"spotify_url": str(_song_value(data, "url", default="") or ""),
|
||||
"title": str(_song_value(data, "name", "title", default="") or ""),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(_song_value(data, "album_name", "album", default="") or ""),
|
||||
"duration": _song_value(data, "duration", "duration_seconds"),
|
||||
"cover": str(_song_value(data, "cover_url", "cover", default="") or ""),
|
||||
"year": _song_value(data, "year"),
|
||||
"isrc": str(_song_value(data, "isrc", default="") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _spotify_metadata_score(
|
||||
candidate: dict[str, Any],
|
||||
title: str,
|
||||
artist: str,
|
||||
duration: float | None,
|
||||
) -> float:
|
||||
title_score = SequenceMatcher(
|
||||
None,
|
||||
_norm_text(title),
|
||||
_norm_text(candidate.get("title")),
|
||||
).ratio()
|
||||
|
||||
artist_text = " ".join(
|
||||
[
|
||||
str(candidate.get("artist") or ""),
|
||||
*[str(x) for x in candidate.get("artists") or []],
|
||||
]
|
||||
)
|
||||
if artist:
|
||||
artist_score = SequenceMatcher(
|
||||
None,
|
||||
_norm_text(artist),
|
||||
_norm_text(artist_text),
|
||||
).ratio()
|
||||
else:
|
||||
artist_score = 0.7
|
||||
|
||||
duration_score = 0.7
|
||||
try:
|
||||
requested_duration = float(duration or 0)
|
||||
candidate_duration = float(candidate.get("duration") or 0)
|
||||
if requested_duration > 0 and candidate_duration > 0:
|
||||
delta = abs(requested_duration - candidate_duration)
|
||||
duration_score = max(0.0, 1.0 - min(delta, 30.0) / 30.0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
return round(
|
||||
title_score * 0.58
|
||||
+ artist_score * 0.30
|
||||
+ duration_score * 0.12,
|
||||
4,
|
||||
)
|
||||
|
||||
|
||||
def _spotify_metadata_search_sync(
|
||||
title: str,
|
||||
artist: str = "",
|
||||
duration: float | None = None,
|
||||
limit: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
_ensure_spotdl()
|
||||
|
||||
title = str(title or "").strip()
|
||||
artist = str(artist or "").strip()
|
||||
if not title:
|
||||
raise ValueError("title is required")
|
||||
|
||||
query = " ".join(x for x in (artist, title) if x).strip()
|
||||
songs = list(spotdl_get_search_results(query) or [])[:max(1, min(int(limit or 8), 20))]
|
||||
|
||||
candidates = []
|
||||
for song in songs:
|
||||
item = _spotify_metadata_item(song)
|
||||
if not item.get("title"):
|
||||
continue
|
||||
item["score"] = _spotify_metadata_score(item, title, artist, duration)
|
||||
candidates.append(item)
|
||||
|
||||
candidates.sort(key=lambda item: float(item.get("score") or 0), reverse=True)
|
||||
best = candidates[0] if candidates else None
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"best": best,
|
||||
"candidates": candidates,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_spotify_sync(
|
||||
query: str,
|
||||
limit: int,
|
||||
) -> dict[str, Any]:
|
||||
query = str(query or "").strip()
|
||||
|
||||
if not query:
|
||||
raise ValueError(
|
||||
"Spotify URL or music query is required"
|
||||
)
|
||||
|
||||
downloader = _ensure_spotdl()
|
||||
|
||||
songs = spotdl_get_simple_songs(
|
||||
[query],
|
||||
playlist_retain_track_cover=True,
|
||||
)
|
||||
|
||||
limit = max(
|
||||
1,
|
||||
min(
|
||||
int(limit or SPOTDL_MAX_ITEMS),
|
||||
SPOTDL_MAX_ITEMS,
|
||||
),
|
||||
)
|
||||
|
||||
songs = list(songs or [])[:limit]
|
||||
|
||||
items = []
|
||||
errors = []
|
||||
|
||||
for position, song in enumerate(
|
||||
songs,
|
||||
start=1,
|
||||
):
|
||||
data = _song_json(song)
|
||||
|
||||
spotify_url = str(
|
||||
_song_value(
|
||||
data,
|
||||
"url",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
spotify_id = str(
|
||||
_song_value(
|
||||
data,
|
||||
"song_id",
|
||||
"track_id",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
cache_key = (
|
||||
spotify_id
|
||||
or spotify_url
|
||||
or (
|
||||
f"{data.get('artist', '')}::"
|
||||
f"{data.get('name', '')}"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
youtube_url = _SPOTDL_MATCH_CACHE.get(
|
||||
cache_key
|
||||
)
|
||||
|
||||
if not youtube_url:
|
||||
youtube_url = str(
|
||||
downloader.search(song)
|
||||
or ""
|
||||
)
|
||||
|
||||
if youtube_url:
|
||||
_SPOTDL_MATCH_CACHE[
|
||||
cache_key
|
||||
] = youtube_url
|
||||
|
||||
video_id = _youtube_id(
|
||||
youtube_url
|
||||
)
|
||||
|
||||
if not video_id:
|
||||
raise LookupError(
|
||||
"spotDL match did not contain "
|
||||
"a YouTube video ID: "
|
||||
f"{youtube_url}"
|
||||
)
|
||||
|
||||
artists = _song_value(
|
||||
data,
|
||||
"artists",
|
||||
default=[],
|
||||
)
|
||||
|
||||
if isinstance(
|
||||
artists,
|
||||
str,
|
||||
):
|
||||
artists = [artists]
|
||||
|
||||
artist = str(
|
||||
_song_value(
|
||||
data,
|
||||
"artist",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
if not artist and artists:
|
||||
artist = str(
|
||||
artists[0]
|
||||
)
|
||||
|
||||
items.append(
|
||||
{
|
||||
"spotify_id": spotify_id,
|
||||
"spotify_url": spotify_url,
|
||||
"title": str(
|
||||
_song_value(
|
||||
data,
|
||||
"name",
|
||||
"title",
|
||||
default=video_id,
|
||||
)
|
||||
),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(
|
||||
_song_value(
|
||||
data,
|
||||
"album_name",
|
||||
"album",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"duration": _song_value(
|
||||
data,
|
||||
"duration",
|
||||
"duration_seconds",
|
||||
),
|
||||
"cover": str(
|
||||
_song_value(
|
||||
data,
|
||||
"cover_url",
|
||||
"cover",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"year": _song_value(
|
||||
data,
|
||||
"year",
|
||||
),
|
||||
"isrc": str(
|
||||
_song_value(
|
||||
data,
|
||||
"isrc",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"list_name": str(
|
||||
_song_value(
|
||||
data,
|
||||
"list_name",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"list_position": (
|
||||
_song_value(
|
||||
data,
|
||||
"list_position",
|
||||
default=position,
|
||||
)
|
||||
),
|
||||
"list_length": (
|
||||
_song_value(
|
||||
data,
|
||||
"list_length",
|
||||
)
|
||||
),
|
||||
"youtube_url": youtube_url,
|
||||
"youtube_id": video_id,
|
||||
"source": "spotdl",
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
errors.append(
|
||||
{
|
||||
"position": position,
|
||||
"title": str(
|
||||
_song_value(
|
||||
data,
|
||||
"name",
|
||||
"title",
|
||||
default="Unknown",
|
||||
)
|
||||
),
|
||||
"artist": str(
|
||||
_song_value(
|
||||
data,
|
||||
"artist",
|
||||
default="",
|
||||
)
|
||||
or ""
|
||||
),
|
||||
"error": str(error),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"source_type": _spotify_source_kind(
|
||||
query
|
||||
),
|
||||
"count": len(items),
|
||||
"items": items,
|
||||
"errors": errors,
|
||||
"spotdl": True,
|
||||
}
|
||||
|
||||
|
||||
def _exact_spotify_track_metadata_sync(url: str) -> dict[str, Any]:
|
||||
_ensure_spotdl()
|
||||
url = str(url or "").strip()
|
||||
if not url:
|
||||
raise ValueError("Spotify track URL is required")
|
||||
|
||||
songs = list(
|
||||
spotdl_get_simple_songs(
|
||||
[url],
|
||||
playlist_retain_track_cover=True,
|
||||
)
|
||||
or []
|
||||
)
|
||||
if not songs:
|
||||
raise LookupError("Spotify returned no track metadata")
|
||||
|
||||
song = songs[0]
|
||||
data = _song_json(song)
|
||||
artists = _song_value(data, "artists", default=[])
|
||||
if isinstance(artists, str):
|
||||
artists = [artists]
|
||||
artist = str(_song_value(data, "artist", default="") or "")
|
||||
if not artist and artists:
|
||||
artist = str(artists[0])
|
||||
|
||||
return {
|
||||
"spotify_id": str(_song_value(data, "song_id", "track_id", default="") or ""),
|
||||
"spotify_url": str(_song_value(data, "url", default=url) or url),
|
||||
"title": str(_song_value(data, "name", "title", default="") or ""),
|
||||
"artist": artist,
|
||||
"artists": artists,
|
||||
"album": str(_song_value(data, "album_name", "album", default="") or ""),
|
||||
"duration": _song_value(data, "duration", "duration_seconds"),
|
||||
"cover": str(_song_value(data, "cover_url", "cover", default="") or ""),
|
||||
"year": _song_value(data, "year"),
|
||||
"isrc": str(_song_value(data, "isrc", default="") or ""),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/music/spotify/track-metadata")
|
||||
async def spotify_track_metadata(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
url = str(body.get("url") or "").strip()
|
||||
try:
|
||||
track = await asyncio.to_thread(
|
||||
_exact_spotify_track_metadata_sync,
|
||||
url,
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Spotify exact metadata lookup failed: {error}",
|
||||
) from error
|
||||
|
||||
return JSONResponse({"track": track})
|
||||
|
||||
|
||||
@router.get(
|
||||
"/api/music/spotdl/status"
|
||||
)
|
||||
async def spotdl_status() -> JSONResponse:
|
||||
return JSONResponse(
|
||||
{
|
||||
"available": SPOTDL_AVAILABLE,
|
||||
"error": (
|
||||
str(SPOTDL_IMPORT_ERROR)
|
||||
if SPOTDL_IMPORT_ERROR
|
||||
else None
|
||||
),
|
||||
"audio_providers": (
|
||||
SPOTDL_AUDIO_PROVIDERS
|
||||
),
|
||||
"max_items": SPOTDL_MAX_ITEMS,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/music/spotify/metadata"
|
||||
)
|
||||
async def spotify_metadata(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
title = str(body.get("title") or "").strip()
|
||||
artist = str(body.get("artist") or "").strip()
|
||||
duration = body.get("duration")
|
||||
|
||||
try:
|
||||
data = await asyncio.to_thread(
|
||||
_spotify_metadata_search_sync,
|
||||
title,
|
||||
artist,
|
||||
duration,
|
||||
int(body.get("limit") or 8),
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=400, detail=str(error)) from error
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Spotify metadata lookup failed: {error}",
|
||||
) from error
|
||||
|
||||
return JSONResponse(data)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/api/music/spotify/resolve"
|
||||
)
|
||||
async def spotify_resolve(
|
||||
body: dict[str, Any],
|
||||
) -> JSONResponse:
|
||||
query = str(
|
||||
body.get("url")
|
||||
or body.get("query")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
try:
|
||||
limit = int(
|
||||
body.get("limit")
|
||||
or SPOTDL_MAX_ITEMS
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
limit = SPOTDL_MAX_ITEMS
|
||||
|
||||
try:
|
||||
data = await asyncio.to_thread(
|
||||
_resolve_spotify_sync,
|
||||
query,
|
||||
limit,
|
||||
)
|
||||
|
||||
except ValueError as error:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=str(error),
|
||||
) from error
|
||||
|
||||
except Exception as error:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=(
|
||||
"spotDL resolve failed: "
|
||||
f"{error}"
|
||||
),
|
||||
) from error
|
||||
|
||||
return JSONResponse(
|
||||
data
|
||||
)
|
||||
@@ -0,0 +1,277 @@
|
||||
\
|
||||
# Copyright Insidious authors <https://github.com/xrun1/insidious>
|
||||
# Copyright Kronic resolver modifications
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import yt_dlp
|
||||
from yt_dlp import YoutubeDL
|
||||
|
||||
from .net import PARALLEL_REQUESTS_PER_HOST, max_parallel_requests
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CacheEntry:
|
||||
expires: float
|
||||
value: dict[str, Any]
|
||||
|
||||
|
||||
class YtdlpService:
|
||||
"""
|
||||
Minimal yt-dlp wrapper for Kronic.
|
||||
|
||||
The old Insidious package model/cache/UI stack is deliberately removed.
|
||||
Kronic needs only:
|
||||
- search
|
||||
- video metadata/formats
|
||||
- fresh signed media URLs for a selected format
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._pool = ThreadPoolExecutor(
|
||||
max_workers=PARALLEL_REQUESTS_PER_HOST
|
||||
)
|
||||
self._video_cache: dict[str, CacheEntry] = {}
|
||||
self._search_cache: dict[str, CacheEntry] = {}
|
||||
self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
||||
|
||||
# Keep resolved GoogleVideo URLs fresh enough that Kronic never
|
||||
# depends on the ~6 hour signature lifetime.
|
||||
self.video_cache_seconds = 20 * 60
|
||||
self.search_cache_seconds = 5 * 60
|
||||
|
||||
self._ydl_opts = {
|
||||
"quiet": True,
|
||||
"no_warnings": True,
|
||||
"skip_download": True,
|
||||
"ignore_no_formats_error": True,
|
||||
"noplaylist": True,
|
||||
}
|
||||
|
||||
self._search_opts = {
|
||||
**self._ydl_opts,
|
||||
"extract_flat": True,
|
||||
}
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
# Use yt-dlp's standard browser-like defaults for the HTTP proxy.
|
||||
with YoutubeDL(self._ydl_opts) as ydl:
|
||||
return dict(ydl.params.get("http_headers") or {})
|
||||
|
||||
@staticmethod
|
||||
def _normalize_codec(value: Any) -> str | None:
|
||||
if not value or value == "none":
|
||||
return None
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _normalize_format(cls, fmt: dict[str, Any]) -> dict[str, Any]:
|
||||
vcodec = cls._normalize_codec(fmt.get("vcodec"))
|
||||
acodec = cls._normalize_codec(fmt.get("acodec"))
|
||||
|
||||
return {
|
||||
"id": str(fmt.get("format_id") or ""),
|
||||
"name": fmt.get("format_note"),
|
||||
"protocol": fmt.get("protocol"),
|
||||
"ext": fmt.get("ext"),
|
||||
"container": fmt.get("container"),
|
||||
"width": fmt.get("width"),
|
||||
"height": fmt.get("height"),
|
||||
"fps": fmt.get("fps"),
|
||||
"vcodec": vcodec,
|
||||
"acodec": acodec,
|
||||
"bitrate": fmt.get("tbr"),
|
||||
"filesize": fmt.get("filesize") or fmt.get("filesize_approx"),
|
||||
"audio_channels": fmt.get("audio_channels"),
|
||||
"language": fmt.get("language"),
|
||||
"url": fmt.get("url"),
|
||||
"http_headers": dict(fmt.get("http_headers") or {}),
|
||||
"video_only": bool(vcodec and not acodec),
|
||||
"audio_only": bool(acodec and not vcodec),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _best_thumbnail(data: dict[str, Any]) -> str | None:
|
||||
thumbs = data.get("thumbnails") or []
|
||||
|
||||
if thumbs:
|
||||
thumbs = sorted(
|
||||
(t for t in thumbs if t.get("url")),
|
||||
key=lambda t: (
|
||||
t.get("width") or 0,
|
||||
t.get("height") or 0,
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
if thumbs:
|
||||
return thumbs[0]["url"]
|
||||
|
||||
return data.get("thumbnail")
|
||||
|
||||
def _extract_video_sync(self, video_id: str) -> dict[str, Any]:
|
||||
url = f"https://www.youtube.com/watch?v={video_id}"
|
||||
|
||||
with YoutubeDL(self._ydl_opts) as ydl:
|
||||
data = ydl.extract_info(url, download=False)
|
||||
|
||||
if not data:
|
||||
raise RuntimeError(f"yt-dlp returned no data for {video_id}")
|
||||
|
||||
formats = [
|
||||
self._normalize_format(fmt)
|
||||
for fmt in (data.get("formats") or [])
|
||||
if fmt.get("format_id") and fmt.get("url")
|
||||
]
|
||||
|
||||
return {
|
||||
"id": str(data.get("id") or video_id),
|
||||
"title": data.get("title") or video_id,
|
||||
"duration": data.get("duration"),
|
||||
"channel": data.get("channel") or data.get("uploader"),
|
||||
"channel_id": data.get("channel_id"),
|
||||
"thumbnail": self._best_thumbnail(data),
|
||||
"formats": formats,
|
||||
}
|
||||
|
||||
def _search_sync(self, query: str, limit: int) -> dict[str, Any]:
|
||||
target = f"ytsearch{limit}:{query}"
|
||||
|
||||
with YoutubeDL(self._search_opts) as ydl:
|
||||
data = ydl.extract_info(target, download=False)
|
||||
|
||||
items = []
|
||||
|
||||
for entry in (data or {}).get("entries") or []:
|
||||
if not entry:
|
||||
continue
|
||||
|
||||
video_id = entry.get("id")
|
||||
if not video_id:
|
||||
continue
|
||||
|
||||
items.append({
|
||||
"id": str(video_id),
|
||||
"title": entry.get("title") or str(video_id),
|
||||
"duration": entry.get("duration"),
|
||||
"channel": entry.get("channel") or entry.get("uploader"),
|
||||
"channel_id": entry.get("channel_id"),
|
||||
"thumbnail": self._best_thumbnail(entry),
|
||||
"webpage_url": (
|
||||
entry.get("webpage_url")
|
||||
or f"https://www.youtube.com/watch?v={video_id}"
|
||||
),
|
||||
})
|
||||
|
||||
return {"items": items}
|
||||
|
||||
async def video(
|
||||
self,
|
||||
video_id: str,
|
||||
*,
|
||||
refresh: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
now = time.monotonic()
|
||||
|
||||
if not refresh:
|
||||
cached = self._video_cache.get(video_id)
|
||||
if cached and cached.expires > now:
|
||||
return cached.value
|
||||
|
||||
async with self._locks[f"video:{video_id}"]:
|
||||
now = time.monotonic()
|
||||
|
||||
if not refresh:
|
||||
cached = self._video_cache.get(video_id)
|
||||
if cached and cached.expires > now:
|
||||
return cached.value
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
async with max_parallel_requests("https://youtube.com"):
|
||||
value = await loop.run_in_executor(
|
||||
self._pool,
|
||||
self._extract_video_sync,
|
||||
video_id,
|
||||
)
|
||||
|
||||
self._video_cache[video_id] = CacheEntry(
|
||||
expires=time.monotonic() + self.video_cache_seconds,
|
||||
value=value,
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
async def search(
|
||||
self,
|
||||
query: str,
|
||||
*,
|
||||
limit: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
limit = max(1, min(limit, 50))
|
||||
key = f"{limit}:{query.strip().lower()}"
|
||||
now = time.monotonic()
|
||||
|
||||
cached = self._search_cache.get(key)
|
||||
if cached and cached.expires > now:
|
||||
return cached.value
|
||||
|
||||
async with self._locks[f"search:{key}"]:
|
||||
now = time.monotonic()
|
||||
|
||||
cached = self._search_cache.get(key)
|
||||
if cached and cached.expires > now:
|
||||
return cached.value
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
async with max_parallel_requests("https://youtube.com"):
|
||||
value = await loop.run_in_executor(
|
||||
self._pool,
|
||||
self._search_sync,
|
||||
query,
|
||||
limit,
|
||||
)
|
||||
|
||||
self._search_cache[key] = CacheEntry(
|
||||
expires=time.monotonic() + self.search_cache_seconds,
|
||||
value=value,
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
async def format(
|
||||
self,
|
||||
video_id: str,
|
||||
format_id: str,
|
||||
*,
|
||||
refresh: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
video = await self.video(video_id, refresh=refresh)
|
||||
|
||||
for fmt in video["formats"]:
|
||||
if fmt["id"] == format_id:
|
||||
return fmt
|
||||
|
||||
# The format list can change. Re-resolve once before failing.
|
||||
if not refresh:
|
||||
return await self.format(
|
||||
video_id,
|
||||
format_id,
|
||||
refresh=True,
|
||||
)
|
||||
|
||||
raise KeyError(
|
||||
f"format {format_id!r} not found for video {video_id!r}"
|
||||
)
|
||||
|
||||
|
||||
YTDLP = YtdlpService()
|
||||
Reference in New Issue
Block a user