dev: umfangreiches Refactoring, Trakt-Integration und Code-Review-Fixes (0.1.69-dev)

Core & Architektur:
- Neues Verzeichnis addon/core/ mit router.py, trakt.py, metadata.py,
  gui.py, playstate.py, plugin_manager.py, updater.py
- Tests-Verzeichnis hinzugefügt (24 Tests, pytest + Coverage)

Trakt-Integration:
- OAuth Device Flow, Scrobbling, Watchlist, History, Calendar
- Upcoming Episodes, Weiterschauen (Continue Watching)
- Watched-Status in Episodenlisten
- _trakt_find_in_plugins() mit 5-Min-Cache

Serienstream-Suche:
- API-Ergebnisse werden immer mit Katalog-Cache ergänzt (serverseitiges 10-Treffer-Limit)
- Katalog-Cache wird beim Addon-Start im Daemon-Thread vorgewärmt
- Notification nach Cache-Load via xbmc.executebuiltin() (thread-sicher)

Bugfixes (Code-Review):
- Race Condition auf _TRAKT_WATCHED_CACHE: _TRAKT_WATCHED_CACHE_LOCK hinzugefügt
- GUI-Dialog aus Daemon-Thread: xbmcgui -> xbmc.executebuiltin()
- ValueError in Trakt-Watchlist-Routen abgesichert
- Token expires_at==0 Check korrigiert
- get_setting_bool() Kontrollfluss in gui.py bereinigt
- topstreamfilm_plugin: try-finally um xbmcvfs.File.close()

Cleanup:
- default.py.bak und refactor_router.py entfernt
- .gitignore: /tests/ Eintrag entfernt
- Type-Hints vereinheitlicht (Dict/List/Tuple -> dict/list/tuple)
This commit is contained in:
2026-03-01 18:23:45 +01:00
parent 73f07d20b4
commit 7b60b00c8b
36 changed files with 4765 additions and 672 deletions

View File

@@ -17,7 +17,7 @@ import os
import re
import time
import unicodedata
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
from typing import TYPE_CHECKING, Any, Callable, Optional
from urllib.parse import quote
try: # pragma: no cover - optional dependency
@@ -82,11 +82,11 @@ SESSION_CACHE_MAX_TITLE_URLS = 800
CATALOG_SEARCH_TTL_SECONDS = 600
CATALOG_SEARCH_CACHE_KEY = "catalog_index"
GENRE_LIST_PAGE_SIZE = 20
_CATALOG_INDEX_MEMORY: tuple[float, List["SeriesResult"]] = (0.0, [])
ProgressCallback = Optional[Callable[[str, Optional[int]], Any]]
_CATALOG_INDEX_MEMORY: tuple[float, list["SeriesResult"]] = (0.0, [])
ProgressCallback = Optional[Callable[[str, int | None], Any]]
def _emit_progress(callback: ProgressCallback, message: str, percent: Optional[int] = None) -> None:
def _emit_progress(callback: ProgressCallback, message: str, percent: int | None = None) -> None:
if not callable(callback):
return
try:
@@ -110,8 +110,8 @@ class EpisodeInfo:
original_title: str
url: str
season_label: str = ""
languages: List[str] = field(default_factory=list)
hosters: List[str] = field(default_factory=list)
languages: list[str] = field(default_factory=list)
hosters: list[str] = field(default_factory=list)
@dataclass
@@ -127,12 +127,12 @@ class LatestEpisode:
class SeasonInfo:
number: int
url: str
episodes: List[EpisodeInfo]
episodes: list[EpisodeInfo]
def _extract_series_metadata(soup: BeautifulSoupT) -> Tuple[Dict[str, str], Dict[str, str]]:
info: Dict[str, str] = {}
art: Dict[str, str] = {}
def _extract_series_metadata(soup: BeautifulSoupT) -> tuple[dict[str, str], dict[str, str]]:
info: dict[str, str] = {}
art: dict[str, str] = {}
if not soup:
return info, art
@@ -423,7 +423,7 @@ def _looks_like_cloudflare_challenge(body: str) -> bool:
return any(marker in lower for marker in markers)
def _get_soup(url: str, *, session: Optional[RequestsSession] = None) -> BeautifulSoupT:
def _get_soup(url: str, *, session: RequestsSession | None = None) -> BeautifulSoupT:
_ensure_requests()
_log_visit(url)
response = None
@@ -484,8 +484,8 @@ def _get_soup_simple(url: str) -> BeautifulSoupT:
return BeautifulSoup(body, "html.parser")
def _extract_genre_names_from_html(body: str) -> List[str]:
names: List[str] = []
def _extract_genre_names_from_html(body: str) -> list[str]:
names: list[str] = []
seen: set[str] = set()
pattern = re.compile(
r"<div[^>]*class=[\"'][^\"']*background-1[^\"']*[\"'][^>]*>.*?<h3[^>]*>(.*?)</h3>",
@@ -508,7 +508,7 @@ def _strip_tags(value: str) -> str:
return re.sub(r"<[^>]+>", " ", value or "")
def _search_series_api(query: str) -> List[SeriesResult]:
def _search_series_api(query: str) -> list[SeriesResult]:
query = (query or "").strip()
if not query:
return []
@@ -544,7 +544,7 @@ def _search_series_api(query: str) -> List[SeriesResult]:
shows = payload.get("shows") if isinstance(payload, dict) else None
if not isinstance(shows, list):
continue
results: List[SeriesResult] = []
results: list[SeriesResult] = []
for item in shows:
if not isinstance(item, dict):
continue
@@ -570,7 +570,7 @@ def _search_series_api(query: str) -> List[SeriesResult]:
return []
def _search_series_server(query: str) -> List[SeriesResult]:
def _search_series_server(query: str) -> list[SeriesResult]:
if not query:
return []
base = _get_base_url()
@@ -588,7 +588,7 @@ def _search_series_server(query: str) -> List[SeriesResult]:
if root is None:
continue
seen_urls: set[str] = set()
results: List[SeriesResult] = []
results: list[SeriesResult] = []
for card in root.select(".cover-card"):
anchor = card.select_one("a[href*='/serie/']")
if not anchor:
@@ -613,8 +613,8 @@ def _search_series_server(query: str) -> List[SeriesResult]:
return []
def _extract_catalog_index_from_html(body: str, *, progress_callback: ProgressCallback = None) -> List[SeriesResult]:
items: List[SeriesResult] = []
def _extract_catalog_index_from_html(body: str, *, progress_callback: ProgressCallback = None) -> list[SeriesResult]:
items: list[SeriesResult] = []
if not body:
return items
seen_urls: set[str] = set()
@@ -649,8 +649,8 @@ def _extract_catalog_index_from_html(body: str, *, progress_callback: ProgressCa
return items
def _catalog_index_from_soup(soup: BeautifulSoupT) -> List[SeriesResult]:
items: List[SeriesResult] = []
def _catalog_index_from_soup(soup: BeautifulSoupT) -> list[SeriesResult]:
items: list[SeriesResult] = []
if not soup:
return items
seen_urls: set[str] = set()
@@ -673,7 +673,7 @@ def _catalog_index_from_soup(soup: BeautifulSoupT) -> List[SeriesResult]:
return items
def _load_catalog_index_from_cache() -> Optional[List[SeriesResult]]:
def _load_catalog_index_from_cache() -> Optional[list[SeriesResult]]:
global _CATALOG_INDEX_MEMORY
expires_at, cached = _CATALOG_INDEX_MEMORY
if cached and expires_at > time.time():
@@ -681,7 +681,7 @@ def _load_catalog_index_from_cache() -> Optional[List[SeriesResult]]:
raw = _session_cache_get(CATALOG_SEARCH_CACHE_KEY)
if not isinstance(raw, list):
return None
items: List[SeriesResult] = []
items: list[SeriesResult] = []
for entry in raw:
if not isinstance(entry, list) or len(entry) < 2:
continue
@@ -696,12 +696,12 @@ def _load_catalog_index_from_cache() -> Optional[List[SeriesResult]]:
return items or None
def _store_catalog_index_in_cache(items: List[SeriesResult]) -> None:
def _store_catalog_index_in_cache(items: list[SeriesResult]) -> None:
global _CATALOG_INDEX_MEMORY
if not items:
return
_CATALOG_INDEX_MEMORY = (time.time() + CATALOG_SEARCH_TTL_SECONDS, list(items))
payload: List[List[str]] = []
payload: list[list[str]] = []
for entry in items:
if not entry.title or not entry.url:
continue
@@ -709,7 +709,7 @@ def _store_catalog_index_in_cache(items: List[SeriesResult]) -> None:
_session_cache_set(CATALOG_SEARCH_CACHE_KEY, payload, ttl_seconds=CATALOG_SEARCH_TTL_SECONDS)
def search_series(query: str, *, progress_callback: ProgressCallback = None) -> List[SeriesResult]:
def search_series(query: str, *, progress_callback: ProgressCallback = None) -> list[SeriesResult]:
"""Sucht Serien im (/serien)-Katalog nach Titel. Nutzt Cache + Ein-Pass-Filter."""
_ensure_requests()
if not _normalize_search_text(query):
@@ -724,7 +724,7 @@ def search_series(query: str, *, progress_callback: ProgressCallback = None) ->
_emit_progress(progress_callback, "Lade Katalogseite", 42)
catalog_url = f"{_get_base_url()}/serien?by=genre"
items: List[SeriesResult] = []
items: list[SeriesResult] = []
try:
# Bevorzugt den Soup-Helper, damit Tests HTML einfache injizieren koennen.
soup = _get_soup_simple(catalog_url)
@@ -749,9 +749,9 @@ def search_series(query: str, *, progress_callback: ProgressCallback = None) ->
return []
def parse_series_catalog(soup: BeautifulSoupT) -> Dict[str, List[SeriesResult]]:
def parse_series_catalog(soup: BeautifulSoupT) -> dict[str, list[SeriesResult]]:
"""Parst die Serien-Übersicht (/serien) und liefert Genre -> Serienliste."""
catalog: Dict[str, List[SeriesResult]] = {}
catalog: dict[str, list[SeriesResult]] = {}
# Neues Layout (Stand: 2026-01): Gruppen-Header + Liste.
# - Header: `div.background-1 ...` mit `h3`
@@ -763,7 +763,7 @@ def parse_series_catalog(soup: BeautifulSoupT) -> Dict[str, List[SeriesResult]]:
list_node = header.parent.find_next_sibling("ul", class_="series-list")
if not list_node:
continue
series: List[SeriesResult] = []
series: list[SeriesResult] = []
for item in list_node.select("li.series-item"):
anchor = item.find("a", href=True)
if not anchor:
@@ -784,8 +784,8 @@ def parse_series_catalog(soup: BeautifulSoupT) -> Dict[str, List[SeriesResult]]:
return catalog
def _extract_season_links(soup: BeautifulSoupT) -> List[Tuple[int, str]]:
season_links: List[Tuple[int, str]] = []
def _extract_season_links(soup: BeautifulSoupT) -> list[tuple[int, str]]:
season_links: list[tuple[int, str]] = []
seen_numbers: set[int] = set()
anchors = soup.select("ul.nav.list-items-nav a[data-season-pill][href]")
for anchor in anchors:
@@ -814,7 +814,7 @@ def _extract_season_links(soup: BeautifulSoupT) -> List[Tuple[int, str]]:
return season_links
def _extract_number_of_seasons(soup: BeautifulSoupT) -> Optional[int]:
def _extract_number_of_seasons(soup: BeautifulSoupT) -> int | None:
tag = soup.select_one('meta[itemprop="numberOfSeasons"]')
if not tag:
return None
@@ -834,8 +834,8 @@ def _extract_canonical_url(soup: BeautifulSoupT, fallback: str) -> str:
return fallback.rstrip("/")
def _extract_episodes(soup: BeautifulSoupT) -> List[EpisodeInfo]:
episodes: List[EpisodeInfo] = []
def _extract_episodes(soup: BeautifulSoupT) -> list[EpisodeInfo]:
episodes: list[EpisodeInfo] = []
season_label = ""
season_header = soup.select_one("section.episode-section h2") or soup.select_one("h2.h3")
if season_header:
@@ -892,13 +892,13 @@ def _extract_episodes(soup: BeautifulSoupT) -> List[EpisodeInfo]:
if _is_episode_tba(title, original_title):
continue
hosters: List[str] = []
hosters: list[str] = []
for img in row.select(".episode-watch-cell img"):
label = (img.get("alt") or img.get("title") or "").strip()
if label and label not in hosters:
hosters.append(label)
languages: List[str] = []
languages: list[str] = []
for flag in row.select(".episode-language-cell .watch-language"):
classes = flag.get("class") or []
if isinstance(classes, str):
@@ -931,8 +931,8 @@ def _extract_episodes(soup: BeautifulSoupT) -> List[EpisodeInfo]:
def fetch_episode_stream_link(
episode_url: str,
*,
preferred_hosters: Optional[List[str]] = None,
) -> Optional[str]:
preferred_hosters: Optional[list[str]] = None,
) -> str | None:
_ensure_requests()
normalized_url = _absolute_url(episode_url)
preferred = [hoster.lower() for hoster in (preferred_hosters or DEFAULT_PREFERRED_HOSTERS)]
@@ -943,7 +943,7 @@ def fetch_episode_stream_link(
except Exception:
pass
soup = _get_soup(normalized_url, session=session)
candidates: List[Tuple[str, str]] = []
candidates: list[tuple[str, str]] = []
for button in soup.select("button.link-box[data-play-url]"):
play_url = (button.get("data-play-url") or "").strip()
provider = (button.get("data-provider-name") or "").strip()
@@ -961,7 +961,7 @@ def fetch_episode_stream_link(
return candidates[0][1]
def fetch_episode_hoster_names(episode_url: str) -> List[str]:
def fetch_episode_hoster_names(episode_url: str) -> list[str]:
"""Liest die verfügbaren Hoster-Namen für eine Episode aus."""
_ensure_requests()
normalized_url = _absolute_url(episode_url)
@@ -972,7 +972,7 @@ def fetch_episode_hoster_names(episode_url: str) -> List[str]:
except Exception:
pass
soup = _get_soup(normalized_url, session=session)
names: List[str] = []
names: list[str] = []
seen: set[str] = set()
for button in soup.select("button.link-box[data-provider-name]"):
name = (button.get("data-provider-name") or "").strip()
@@ -995,9 +995,9 @@ _LATEST_EPISODE_TAG_RE = re.compile(SEASON_EPISODE_TAG, re.IGNORECASE)
_LATEST_EPISODE_URL_RE = re.compile(SEASON_EPISODE_URL, re.IGNORECASE)
def _extract_latest_episodes(soup: BeautifulSoupT) -> List[LatestEpisode]:
def _extract_latest_episodes(soup: BeautifulSoupT) -> list[LatestEpisode]:
"""Parst die neuesten Episoden von der Startseite."""
episodes: List[LatestEpisode] = []
episodes: list[LatestEpisode] = []
seen: set[str] = set()
for anchor in soup.select("a.latest-episode-row[href]"):
@@ -1016,8 +1016,8 @@ def _extract_latest_episodes(soup: BeautifulSoupT) -> List[LatestEpisode]:
season_text = (anchor.select_one(".ep-season").get_text(strip=True) if anchor.select_one(".ep-season") else "").strip()
episode_text = (anchor.select_one(".ep-episode").get_text(strip=True) if anchor.select_one(".ep-episode") else "").strip()
season_number: Optional[int] = None
episode_number: Optional[int] = None
season_number: int | None = None
episode_number: int | None = None
match = re.search(r"S\s*(\d+)", season_text, re.IGNORECASE)
if match:
season_number = int(match.group(1))
@@ -1054,7 +1054,7 @@ def _extract_latest_episodes(soup: BeautifulSoupT) -> List[LatestEpisode]:
return episodes
def resolve_redirect(target_url: str) -> Optional[str]:
def resolve_redirect(target_url: str) -> str | None:
_ensure_requests()
normalized_url = _absolute_url(target_url)
_log_visit(normalized_url)
@@ -1085,10 +1085,10 @@ def resolve_redirect(target_url: str) -> Optional[str]:
def scrape_series_detail(
series_identifier: str,
max_seasons: Optional[int] = None,
max_seasons: int | None = None,
*,
load_episodes: bool = True,
) -> List[SeasonInfo]:
) -> list[SeasonInfo]:
_ensure_requests()
series_url = _series_root_url(_normalize_series_url(series_identifier))
_log_url(series_url, kind="SERIES")
@@ -1110,9 +1110,9 @@ def scrape_series_detail(
season_links.sort(key=lambda item: item[0])
if max_seasons is not None:
season_links = season_links[:max_seasons]
seasons: List[SeasonInfo] = []
seasons: list[SeasonInfo] = []
for number, url in season_links:
episodes: List[EpisodeInfo] = []
episodes: list[EpisodeInfo] = []
if load_episodes:
season_soup = _get_soup(url, session=session)
episodes = _extract_episodes(season_soup)
@@ -1129,27 +1129,27 @@ class SerienstreamPlugin(BasisPlugin):
POPULAR_GENRE_LABEL = "Haeufig gesehen"
def __init__(self) -> None:
self._series_results: Dict[str, SeriesResult] = {}
self._title_url_cache: Dict[str, str] = self._load_title_url_cache()
self._genre_names_cache: Optional[List[str]] = None
self._season_cache: Dict[str, List[SeasonInfo]] = {}
self._season_links_cache: Dict[str, List[SeasonInfo]] = {}
self._episode_label_cache: Dict[Tuple[str, str], Dict[str, EpisodeInfo]] = {}
self._catalog_cache: Optional[Dict[str, List[SeriesResult]]] = None
self._genre_group_cache: Dict[str, Dict[str, List[str]]] = {}
self._genre_page_entries_cache: Dict[Tuple[str, int], List[SeriesResult]] = {}
self._genre_page_has_more_cache: Dict[Tuple[str, int], bool] = {}
self._popular_cache: Optional[List[SeriesResult]] = None
self._series_results: dict[str, SeriesResult] = {}
self._title_url_cache: dict[str, str] = self._load_title_url_cache()
self._genre_names_cache: Optional[list[str]] = None
self._season_cache: dict[str, list[SeasonInfo]] = {}
self._season_links_cache: dict[str, list[SeasonInfo]] = {}
self._episode_label_cache: dict[tuple[str, str], dict[str, EpisodeInfo]] = {}
self._catalog_cache: Optional[dict[str, list[SeriesResult]]] = None
self._genre_group_cache: dict[str, dict[str, list[str]]] = {}
self._genre_page_entries_cache: dict[tuple[str, int], list[SeriesResult]] = {}
self._genre_page_has_more_cache: dict[tuple[str, int], bool] = {}
self._popular_cache: Optional[list[SeriesResult]] = None
self._requests_available = REQUESTS_AVAILABLE
self._default_preferred_hosters: List[str] = list(DEFAULT_PREFERRED_HOSTERS)
self._preferred_hosters: List[str] = list(self._default_preferred_hosters)
self._hoster_cache: Dict[Tuple[str, str, str], List[str]] = {}
self._latest_cache: Dict[int, List[LatestEpisode]] = {}
self._latest_hoster_cache: Dict[str, List[str]] = {}
self._series_metadata_cache: Dict[str, Tuple[Dict[str, str], Dict[str, str]]] = {}
self._default_preferred_hosters: list[str] = list(DEFAULT_PREFERRED_HOSTERS)
self._preferred_hosters: list[str] = list(self._default_preferred_hosters)
self._hoster_cache: dict[tuple[str, str, str], list[str]] = {}
self._latest_cache: dict[int, list[LatestEpisode]] = {}
self._latest_hoster_cache: dict[str, list[str]] = {}
self._series_metadata_cache: dict[str, tuple[dict[str, str], dict[str, str]]] = {}
self._series_metadata_full: set[str] = set()
self.is_available = True
self.unavailable_reason: Optional[str] = None
self.unavailable_reason: str | None = None
if not self._requests_available: # pragma: no cover - optional dependency
self.is_available = False
self.unavailable_reason = (
@@ -1163,11 +1163,11 @@ class SerienstreamPlugin(BasisPlugin):
print(f"Importfehler: {REQUESTS_IMPORT_ERROR}")
return
def _load_title_url_cache(self) -> Dict[str, str]:
def _load_title_url_cache(self) -> dict[str, str]:
raw = _session_cache_get("title_urls")
if not isinstance(raw, dict):
return {}
result: Dict[str, str] = {}
result: dict[str, str] = {}
for key, value in raw.items():
key_text = str(key or "").strip().casefold()
url_text = str(value or "").strip()
@@ -1205,7 +1205,7 @@ class SerienstreamPlugin(BasisPlugin):
def _metadata_cache_key(title: str) -> str:
return (title or "").strip().casefold()
def _series_for_title(self, title: str) -> Optional[SeriesResult]:
def _series_for_title(self, title: str) -> SeriesResult | None:
direct = self._series_results.get(title)
if direct and direct.url:
return direct
@@ -1228,11 +1228,11 @@ class SerienstreamPlugin(BasisPlugin):
digest = hashlib.sha1((season_url or "").encode("utf-8")).hexdigest()[:20]
return f"season_episodes.{digest}"
def _load_session_season_links(self, series_url: str) -> Optional[List[SeasonInfo]]:
def _load_session_season_links(self, series_url: str) -> Optional[list[SeasonInfo]]:
raw = _session_cache_get(self._season_links_cache_name(series_url))
if not isinstance(raw, list):
return None
seasons: List[SeasonInfo] = []
seasons: list[SeasonInfo] = []
for item in raw:
if not isinstance(item, dict):
continue
@@ -1249,16 +1249,16 @@ class SerienstreamPlugin(BasisPlugin):
seasons.sort(key=lambda s: s.number)
return seasons
def _save_session_season_links(self, series_url: str, seasons: List[SeasonInfo]) -> None:
def _save_session_season_links(self, series_url: str, seasons: list[SeasonInfo]) -> None:
payload = [{"number": int(season.number), "url": season.url} for season in seasons if season.url]
if payload:
_session_cache_set(self._season_links_cache_name(series_url), payload)
def _load_session_season_episodes(self, season_url: str) -> Optional[List[EpisodeInfo]]:
def _load_session_season_episodes(self, season_url: str) -> Optional[list[EpisodeInfo]]:
raw = _session_cache_get(self._season_episodes_cache_name(season_url))
if not isinstance(raw, list):
return None
episodes: List[EpisodeInfo] = []
episodes: list[EpisodeInfo] = []
for item in raw:
if not isinstance(item, dict):
continue
@@ -1290,7 +1290,7 @@ class SerienstreamPlugin(BasisPlugin):
episodes.sort(key=lambda item: item.number)
return episodes
def _save_session_season_episodes(self, season_url: str, episodes: List[EpisodeInfo]) -> None:
def _save_session_season_episodes(self, season_url: str, episodes: list[EpisodeInfo]) -> None:
payload = []
for item in episodes:
payload.append(
@@ -1307,7 +1307,7 @@ class SerienstreamPlugin(BasisPlugin):
if payload:
_session_cache_set(self._season_episodes_cache_name(season_url), payload)
def _ensure_catalog(self) -> Dict[str, List[SeriesResult]]:
def _ensure_catalog(self) -> dict[str, list[SeriesResult]]:
if self._catalog_cache is not None:
return self._catalog_cache
# Stand: 2026-01 liefert `?by=genre` konsistente Gruppen für `genres()`.
@@ -1317,7 +1317,7 @@ class SerienstreamPlugin(BasisPlugin):
_session_cache_set("genres", sorted(self._catalog_cache.keys(), key=str.casefold))
return self._catalog_cache
def _ensure_genre_names(self) -> List[str]:
def _ensure_genre_names(self) -> list[str]:
if self._genre_names_cache is not None:
return list(self._genre_names_cache)
@@ -1341,7 +1341,7 @@ class SerienstreamPlugin(BasisPlugin):
cached = _session_cache_get("genres")
if isinstance(cached, list):
genres: List[str] = []
genres: list[str] = []
for value in cached:
normalized = _normalize_cached_genre(value)
if normalized:
@@ -1364,7 +1364,7 @@ class SerienstreamPlugin(BasisPlugin):
_session_cache_set("genres", self._genre_names_cache)
return list(self._genre_names_cache)
def genres(self) -> List[str]:
def genres(self) -> list[str]:
"""Optional: Liefert alle Genres aus dem Serien-Katalog."""
if not self._requests_available:
return []
@@ -1374,7 +1374,7 @@ class SerienstreamPlugin(BasisPlugin):
"""Meldet unterstützte Features für Router-Menüs."""
return {"popular_series", "genres", "latest_episodes"}
def popular_series(self) -> List[str]:
def popular_series(self) -> list[str]:
"""Liefert die Titel der beliebten Serien (Quelle: `/beliebte-serien`)."""
if not self._requests_available:
return []
@@ -1383,7 +1383,7 @@ class SerienstreamPlugin(BasisPlugin):
self._remember_series_result(entry.title, entry.url, entry.description)
return [entry.title for entry in entries if entry.title]
def titles_for_genre(self, genre: str) -> List[str]:
def titles_for_genre(self, genre: str) -> list[str]:
"""Optional: Liefert Titel für ein Genre."""
if not self._requests_available:
return []
@@ -1438,12 +1438,12 @@ class SerienstreamPlugin(BasisPlugin):
return "U" <= key <= "Z"
return False
def _ensure_genre_group_cache(self, genre: str) -> Dict[str, List[str]]:
def _ensure_genre_group_cache(self, genre: str) -> dict[str, list[str]]:
cached = self._genre_group_cache.get(genre)
if cached is not None:
return cached
titles = self.titles_for_genre(genre)
grouped: Dict[str, List[str]] = {}
grouped: dict[str, list[str]] = {}
for title in titles:
for code in ("A-E", "F-J", "K-O", "P-T", "U-Z", "0-9"):
if self._group_matches(code, title):
@@ -1482,7 +1482,7 @@ class SerienstreamPlugin(BasisPlugin):
def _card_description(anchor: BeautifulSoupT) -> str:
if not anchor:
return ""
candidates: List[str] = []
candidates: list[str] = []
direct = (anchor.get("data-search") or "").strip()
if direct:
candidates.append(direct)
@@ -1514,8 +1514,8 @@ class SerienstreamPlugin(BasisPlugin):
return cleaned
return ""
def _parse_genre_entries_from_soup(self, soup: BeautifulSoupT) -> List[SeriesResult]:
entries: List[SeriesResult] = []
def _parse_genre_entries_from_soup(self, soup: BeautifulSoupT) -> list[SeriesResult]:
entries: list[SeriesResult] = []
seen_urls: set[str] = set()
def _add_entry(title: str, description: str, href: str, cover: str) -> None:
@@ -1565,7 +1565,7 @@ class SerienstreamPlugin(BasisPlugin):
_add_entry(title, description, href, cover)
return entries
def _fetch_genre_page_entries(self, genre: str, page: int) -> Tuple[List[SeriesResult], bool]:
def _fetch_genre_page_entries(self, genre: str, page: int) -> tuple[list[SeriesResult], bool]:
slug = self._genre_slug(genre)
if not slug:
return [], False
@@ -1604,7 +1604,7 @@ class SerienstreamPlugin(BasisPlugin):
self._genre_page_has_more_cache[cache_key] = bool(has_more)
return list(entries), bool(has_more)
def titles_for_genre_page(self, genre: str, page: int) -> List[str]:
def titles_for_genre_page(self, genre: str, page: int) -> list[str]:
genre = (genre or "").strip()
page = max(1, int(page or 1))
entries, _ = self._fetch_genre_page_entries(genre, page)
@@ -1623,13 +1623,13 @@ class SerienstreamPlugin(BasisPlugin):
_, has_more = self._fetch_genre_page_entries(genre, page)
return bool(has_more)
def titles_for_genre_group_page(self, genre: str, group_code: str, page: int = 1, page_size: int = 10) -> List[str]:
def titles_for_genre_group_page(self, genre: str, group_code: str, page: int = 1, page_size: int = 10) -> list[str]:
genre = (genre or "").strip()
group_code = (group_code or "").strip()
page = max(1, int(page or 1))
page_size = max(1, int(page_size or 10))
needed = page * page_size + 1
matched: List[str] = []
matched: list[str] = []
try:
page_index = 1
has_more = True
@@ -1677,12 +1677,12 @@ class SerienstreamPlugin(BasisPlugin):
titles = grouped.get(group_code, [])
return len(titles) > (page * page_size)
def _ensure_popular(self) -> List[SeriesResult]:
def _ensure_popular(self) -> list[SeriesResult]:
"""Laedt und cached die Liste der beliebten Serien aus `/beliebte-serien`."""
if self._popular_cache is not None:
return list(self._popular_cache)
soup = _get_soup_simple(_popular_series_url())
results: List[SeriesResult] = []
results: list[SeriesResult] = []
seen: set[str] = set()
# Neues Layout (Stand: 2026-01): Abschnitt "Meistgesehen" hat Karten mit
@@ -1723,7 +1723,7 @@ class SerienstreamPlugin(BasisPlugin):
@staticmethod
def _episode_label(info: EpisodeInfo) -> str:
suffix_parts: List[str] = []
suffix_parts: list[str] = []
if info.original_title:
suffix_parts.append(info.original_title)
# Staffel nicht im Episoden-Label anzeigen (wird im UI bereits gesetzt).
@@ -1732,7 +1732,7 @@ class SerienstreamPlugin(BasisPlugin):
return f"Episode {info.number}: {info.title}{suffix}"
@staticmethod
def _parse_season_number(label: str) -> Optional[int]:
def _parse_season_number(label: str) -> int | None:
digits = "".join(ch for ch in label if ch.isdigit())
if not digits:
return None
@@ -1752,7 +1752,7 @@ class SerienstreamPlugin(BasisPlugin):
self._episode_label(info): info for info in season_info.episodes
}
def _ensure_season_links(self, title: str) -> List[SeasonInfo]:
def _ensure_season_links(self, title: str) -> list[SeasonInfo]:
cached = self._season_links_cache.get(title)
if cached is not None:
return list(cached)
@@ -1816,7 +1816,7 @@ class SerienstreamPlugin(BasisPlugin):
return
self._remember_series_result(title, series_url)
def metadata_for(self, title: str) -> Tuple[Dict[str, str], Dict[str, str], Optional[List[Any]]]:
def metadata_for(self, title: str) -> tuple[dict[str, str], dict[str, str], Optional[list[Any]]]:
title = (title or "").strip()
if not title or not self._requests_available:
return {}, {}, None
@@ -1833,8 +1833,8 @@ class SerienstreamPlugin(BasisPlugin):
self._series_metadata_cache[cache_key] = (dict(info), {})
return info, {}, None
info: Dict[str, str] = dict(cached[0]) if cached else {"title": title}
art: Dict[str, str] = dict(cached[1]) if cached else {}
info: dict[str, str] = dict(cached[0]) if cached else {"title": title}
art: dict[str, str] = dict(cached[1]) if cached else {}
info.setdefault("title", title)
if series.description:
info.setdefault("plot", series.description)
@@ -1873,7 +1873,7 @@ class SerienstreamPlugin(BasisPlugin):
return entry.url
return ""
def _ensure_season_episodes(self, title: str, season_number: int) -> Optional[SeasonInfo]:
def _ensure_season_episodes(self, title: str, season_number: int) -> SeasonInfo | None:
seasons = self._season_cache.get(title) or []
for season in seasons:
if season.number == season_number and season.episodes:
@@ -1903,7 +1903,7 @@ class SerienstreamPlugin(BasisPlugin):
self._save_session_season_episodes(target.url, season_info.episodes)
return season_info
def _lookup_episode(self, title: str, season_label: str, episode_label: str) -> Optional[EpisodeInfo]:
def _lookup_episode(self, title: str, season_label: str, episode_label: str) -> EpisodeInfo | None:
cache_key = (title, season_label)
cached = self._episode_label_cache.get(cache_key)
if cached:
@@ -1917,7 +1917,7 @@ class SerienstreamPlugin(BasisPlugin):
return self._episode_label_cache.get(cache_key, {}).get(episode_label)
return None
async def search_titles(self, query: str, progress_callback: ProgressCallback = None) -> List[str]:
async def search_titles(self, query: str, progress_callback: ProgressCallback = None) -> list[str]:
query = query.strip()
if not query:
self._series_results.clear()
@@ -1952,7 +1952,7 @@ class SerienstreamPlugin(BasisPlugin):
_emit_progress(progress_callback, f"Treffer aufbereitet: {len(results)}", 95)
return [result.title for result in results]
def _ensure_seasons(self, title: str) -> List[SeasonInfo]:
def _ensure_seasons(self, title: str) -> list[SeasonInfo]:
if title in self._season_cache:
seasons = self._season_cache[title]
# Auch bei Cache-Treffern die URLs loggen, damit nachvollziehbar bleibt,
@@ -1986,11 +1986,11 @@ class SerienstreamPlugin(BasisPlugin):
self._season_cache[title] = list(seasons)
return list(seasons)
def seasons_for(self, title: str) -> List[str]:
def seasons_for(self, title: str) -> list[str]:
seasons = self._ensure_seasons(title)
return [self._season_label(season.number) for season in seasons]
def episodes_for(self, title: str, season: str) -> List[str]:
def episodes_for(self, title: str, season: str) -> list[str]:
number = self._parse_season_number(season)
if number is None:
return []
@@ -2001,7 +2001,7 @@ class SerienstreamPlugin(BasisPlugin):
return labels
return []
def stream_link_for(self, title: str, season: str, episode: str) -> Optional[str]:
def stream_link_for(self, title: str, season: str, episode: str) -> str | None:
if not self._requests_available:
raise RuntimeError("SerienstreamPlugin kann ohne requests/bs4 keine Stream-Links liefern.")
episode_info = self._lookup_episode(title, season, episode)
@@ -2030,7 +2030,7 @@ class SerienstreamPlugin(BasisPlugin):
return episode_info.url
return ""
def available_hosters_for(self, title: str, season: str, episode: str) -> List[str]:
def available_hosters_for(self, title: str, season: str, episode: str) -> list[str]:
if not self._requests_available:
raise RuntimeError("SerienstreamPlugin kann ohne requests/bs4 keine Hoster laden.")
cache_key = (title, season, episode)
@@ -2048,7 +2048,7 @@ class SerienstreamPlugin(BasisPlugin):
self._hoster_cache[cache_key] = list(names)
return list(names)
def latest_episodes(self, page: int = 1) -> List[LatestEpisode]:
def latest_episodes(self, page: int = 1) -> list[LatestEpisode]:
"""Liefert die neuesten Episoden aus `/neue-episoden`."""
if not self._requests_available:
return []
@@ -2069,7 +2069,7 @@ class SerienstreamPlugin(BasisPlugin):
self._latest_cache[page] = list(episodes)
return list(episodes)
def available_hosters_for_url(self, episode_url: str) -> List[str]:
def available_hosters_for_url(self, episode_url: str) -> list[str]:
if not self._requests_available:
raise RuntimeError("SerienstreamPlugin kann ohne requests/bs4 keine Hoster laden.")
normalized = _absolute_url(episode_url)
@@ -2083,7 +2083,7 @@ class SerienstreamPlugin(BasisPlugin):
self._latest_hoster_cache[normalized] = list(names)
return list(names)
def stream_link_for_url(self, episode_url: str) -> Optional[str]:
def stream_link_for_url(self, episode_url: str) -> str | None:
if not self._requests_available:
raise RuntimeError("SerienstreamPlugin kann ohne requests/bs4 keine Stream-Links liefern.")
normalized = _absolute_url(episode_url)
@@ -2098,7 +2098,7 @@ class SerienstreamPlugin(BasisPlugin):
except Exception as exc: # pragma: no cover - defensive logging
raise RuntimeError(f"Stream-Link konnte nicht geladen werden: {exc}") from exc
def resolve_stream_link(self, link: str) -> Optional[str]:
def resolve_stream_link(self, link: str) -> str | None:
if not self._requests_available:
raise RuntimeError("SerienstreamPlugin kann ohne requests/bs4 keine Stream-Links aufloesen.")
try:
@@ -2120,7 +2120,7 @@ class SerienstreamPlugin(BasisPlugin):
except Exception as exc: # pragma: no cover - defensive logging
raise RuntimeError(f"Stream-Link konnte nicht verfolgt werden: {exc}") from exc
def set_preferred_hosters(self, hosters: List[str]) -> None:
def set_preferred_hosters(self, hosters: list[str]) -> None:
normalized = [hoster.strip().lower() for hoster in hosters if hoster.strip()]
if normalized:
self._preferred_hosters = normalized