Etappe 3: Metadaten-Lookup + Pre-Scan

- SQLite-Cache für API-Rate-Limits (LRU, 10k Einträge)
- TMDB/MusicBrainz/TheTVDB Clients
- Pre-Scan-Modul für TOC-Lesung ohne Ripping
- Metadaten-Preview UI
- Jellyfin-Formatierung (NFO + Images)
- API Endpoints für Lookup, Confirm, Format
This commit is contained in:
Hitonabi
2026-07-21 17:17:35 +02:00
parent 0cf5413ac0
commit 518155051f
15 changed files with 1530 additions and 3 deletions
+7
View File
@@ -0,0 +1,7 @@
"""API Clients package."""
from .tmdb import TMDBClient
from .musicbrainz import MusicBrainzClient
from .thetvdb import TheTVDBClient
__all__ = ["TMDBClient", "MusicBrainzClient", "TheTVDBClient"]
+80
View File
@@ -0,0 +1,80 @@
"""MusicBrainz API Client mit Caching."""
import requests
from typing import Dict, List, Optional
from .config import settings
from .cache import get, set
MUSICBRAINZ_BASE_URL = "https://musicbrainz.org/ws/2"
class MusicBrainzClient:
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
"User-Agent": "Rippy/1.0 (https://rippy.local)",
"Content-Type": "application/json"
})
def _request(self, endpoint: str, params: Dict = None) -> Optional[Dict]:
"""Mache API-Request mit Caching."""
cache_key = f"musicbrainz:{endpoint}:{params or {}}"
cached = get(cache_key)
if cached:
return cached
try:
response = self.session.get(
f"{MUSICBRAINZ_BASE_URL}/{endpoint}",
params=params,
timeout=10
)
response.raise_for_status()
# XML-Response parsen
if endpoint.endswith(".json"):
data = response.json()
else:
# Fallback: XML als Text
data = {"raw": response.text}
set(cache_key, data)
return data
except Exception as e:
print(f"MusicBrainz API Error: {e}")
return None
def search_artist(self, name: str) -> List[Dict]:
"""Suche Künstler."""
params = {"query": f"artist:{name}", "fmt": "json", "limit": 10}
result = self._request("artist", params)
if result and "artists" in result:
return result["artists"]
return []
def search_release(self, title: str, artist: str = None) -> List[Dict]:
"""Suche Releases."""
query = f"release:{title}"
if artist:
query += f" AND artist:{artist}"
params = {"query": query, "fmt": "json", "limit": 10}
result = self._request("release", params)
if result and "releases" in result:
return result["releases"]
return []
def get_release_info(self, release_id: str) -> Optional[Dict]:
"""Hole Release-Details."""
params = {"fmt": "json", "inc": "artists+media+recordings"}
return self._request(f"release/{release_id}", params)
def get_artist_info(self, artist_id: str) -> Optional[Dict]:
"""Hole Künstler-Details."""
params = {"fmt": "json", "inc": "aliases+ratings"}
return self._request(f"artist/{artist_id}", params)
+109
View File
@@ -0,0 +1,109 @@
"""TheTVDB API Client mit Caching."""
import requests
from typing import Dict, List, Optional
from .config import settings
from .cache import get, set, delete
THETVDB_BASE_URL = "https://api.thetvdb.com"
class TheTVDBClient:
def __init__(self):
self.api_key = settings.thetvdb_api_key
self.base_url = THETVDB_BASE_URL
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
})
self._cached_token = None
def _get_token(self) -> str:
"""Hole API-Token (gecachted)."""
if self._cached_token:
return self._cached_token
try:
response = self.session.post(
f"{self.base_url}/login",
json={"apikey": self.api_key},
timeout=10
)
response.raise_for_status()
data = response.json()
if "token" in data:
self._cached_token = data["token"]
return self._cached_token
except Exception as e:
print(f"TheTVDB Login Error: {e}")
return ""
def _request(self, endpoint: str, params: Dict = None) -> Optional[Dict]:
"""Mache API-Request mit Caching."""
cache_key = f"thetvdb:{endpoint}:{params or {}}"
cached = get(cache_key)
if cached:
return cached
try:
self.session.headers.update({
"Authorization": f"Bearer {self._get_token()}"
})
response = self.session.get(
f"{self.base_url}/{endpoint}",
params=params,
timeout=10
)
response.raise_for_status()
data = response.json()
set(cache_key, data)
return data
except Exception as e:
print(f"TheTVDB API Error: {e}")
return None
def search_series(self, name: str) -> List[Dict]:
"""Suche Serien."""
params = {"name": name}
result = self._request("search/series", params)
if result and "data" in result:
return result["data"]
return []
def get_series_details(self, series_id: int) -> Optional[Dict]:
"""Hole Serien-Details."""
return self._request(f"series/{series_id}")
def get_episode_details(self, series_id: int, episode_id: int) -> Optional[Dict]:
"""Hole Episode-Details."""
return self._request(f"series/{series_id}/episodes/{episode_id}")
def get_series_images(self, series_id: int) -> Dict[str, str]:
"""Hole Serien-Poster/Fanart URLs."""
params = {"type": "poster"}
result = self._request(f"series/{series_id}/images/query", params)
if result and "data" in result:
images = result["data"]
# Finde Poster und Fanart
poster = next((img for img in images if img.get("subKey") == "poster"), None)
fanart = next((img for img in images if img.get("subKey") == "fanart"), None)
return {
"poster": f"{self.base_url}/images/series/{series_id}_{poster['fileName']}" if poster else "",
"fanart": f"{self.base_url}/images/series/{series_id}_{fanart['fileName']}" if fanart else ""
}
return {}
def clear_cache(self) -> None:
"""Leere TheTVDB-Cache."""
delete("thetvdb:*")
+115
View File
@@ -0,0 +1,115 @@
"""TMDB API Client mit Caching."""
import requests
from typing import Dict, List, Optional
from .config import settings
from .cache import get, set, delete
TMDB_BASE_URL = "https://api.themoviedb.org/3"
TMDB_IMAGE_BASE_URL = "https://image.tmdb.org/t/p"
class TMDBClient:
def __init__(self):
self.api_key = settings.tmdb_api_key
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
})
def _request(self, endpoint: str, params: Dict = None) -> Optional[Dict]:
"""Mache API-Request mit Caching."""
cache_key = f"tmdb:{endpoint}:{params or {}}"
cached = get(cache_key)
if cached:
return cached
try:
response = self.session.get(
f"{TMDB_BASE_URL}/{endpoint}",
params=params,
timeout=10
)
response.raise_for_status()
data = response.json()
# Cache nur für erfolgreiche Requests
if response.status_code == 200:
set(cache_key, data)
return data
except Exception as e:
print(f"TMDB API Error: {e}")
return None
def search_movie(self, title: str, year: int = None) -> List[Dict]:
"""Suche Filme."""
params = {"query": title, "language": "de-DE", "include_adult": False}
if year:
params["year"] = year
result = self._request("search/movie", params)
if result and "results" in result:
return result["results"]
return []
def search_tv(self, title: str, year: int = None) -> List[Dict]:
"""Suche Serien."""
params = {"query": title, "language": "de-DE", "include_adult": False}
if year:
params["first_air_date_year"] = year
result = self._request("search/tv", params)
if result and "results" in result:
return result["results"]
return []
def get_movie_details(self, movie_id: int) -> Optional[Dict]:
"""Hole Film-Details."""
params = {"language": "de-DE"}
return self._request(f"movie/{movie_id}", params)
def get_tv_details(self, tv_id: int) -> Optional[Dict]:
"""Hole Serien-Details."""
params = {"language": "de-DE"}
return self._request(f"tv/{tv_id}", params)
def get_movie_images(self, movie_id: int) -> Dict[str, str]:
"""Hole Poster/Fanart URLs."""
params = {"language": "de-DE", "include_image_language": "de,en,null"}
result = self._request(f"movie/{movie_id}/images", params)
if not result or "posters" not in result:
return {}
posters = result["posters"]
fanart = result.get("backdrops", [])
return {
"poster": f"{TMDB_IMAGE_BASE_URL}/w500{posters[0]['file_path']}" if posters else "",
"fanart": f"{TMDB_IMAGE_BASE_URL}/w1920{fanart[0]['file_path']}" if fanart else ""
}
def get_tv_images(self, tv_id: int) -> Dict[str, str]:
"""Hole Serien-Poster/Fanart URLs."""
params = {"language": "de-DE", "include_image_language": "de,en,null"}
result = self._request(f"tv/{tv_id}/images", params)
if not result or "posters" not in result:
return {}
posters = result["posters"]
fanart = result.get("backdrops", [])
return {
"poster": f"{TMDB_IMAGE_BASE_URL}/w500{posters[0]['file_path']}" if posters else "",
"fanart": f"{TMDB_IMAGE_BASE_URL}/w1920{fanart[0]['file_path']}" if fanart else ""
}
def clear_cache(self) -> None:
"""Leere TMDB-Cache."""
delete("tmdb:*")