diff --git a/.gitignore b/.gitignore
index 6920558..d210053 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,6 @@
__pycache__/
*.pyc
.coverage
+
+# Plugin runtime caches
+/addon/plugins/*_cache.json
diff --git a/README.md b/README.md
index 79e8abd..7acafb8 100644
--- a/README.md
+++ b/README.md
@@ -2,40 +2,37 @@
-ViewIT ist ein Kodi‑Addon zum Durchsuchen und Abspielen von Inhalten der unterstützten Anbieter.
+ViewIT ist ein Kodi Addon.
+Es durchsucht Provider und startet Streams.
## Projektstruktur
-- `addon/` Kodi‑Addon Quellcode
-- `scripts/` Build‑Scripts (arbeiten mit `addon/` + `dist/`)
-- `dist/` Build‑Ausgaben (ZIPs)
-- `docs/`, `tests/`
+- `addon/` Kodi Addon Quellcode
+- `scripts/` Build Scripts
+- `dist/` Build Ausgaben
+- `docs/` Doku
+- `tests/` Tests
-## Build & Release
-- Addon‑Ordner bauen: `./scripts/build_install_addon.sh` → `dist//`
-- Kodi‑ZIP bauen: `./scripts/build_kodi_zip.sh` → `dist/-.zip`
-- Addon‑Version in `addon/addon.xml`
+## Build und Release
+- Addon Ordner bauen: `./scripts/build_install_addon.sh`
+- Kodi ZIP bauen: `./scripts/build_kodi_zip.sh`
+- Version pflegen: `addon/addon.xml`
+- Reproduzierbares ZIP: `SOURCE_DATE_EPOCH` optional setzen
-## Lokales Kodi-Repository
-- Repository bauen (inkl. ZIPs + `addons.xml` + `addons.xml.md5`): `./scripts/build_local_kodi_repo.sh`
-- Lokal bereitstellen: `./scripts/serve_local_kodi_repo.sh`
-- Standard-URL: `http://127.0.0.1:8080/repo/addons.xml`
-- Optional eigene URL beim Build setzen: `REPO_BASE_URL=http://:/repo ./scripts/build_local_kodi_repo.sh`
+## Lokales Kodi Repository
+- Repository bauen: `./scripts/build_local_kodi_repo.sh`
+- Repository starten: `./scripts/serve_local_kodi_repo.sh`
+- Standard URL: `http://127.0.0.1:8080/repo/addons.xml`
+- Eigene URL beim Build: `REPO_BASE_URL=http://:/repo ./scripts/build_local_kodi_repo.sh`
-## Gitea Release-Asset Upload
-- ZIP bauen: `./scripts/build_kodi_zip.sh`
-- Token setzen: `export GITEA_TOKEN=`
-- Asset an Tag hochladen (erstellt Release bei Bedarf): `./scripts/publish_gitea_release.sh`
-- Optional: `--tag v0.1.50 --asset dist/plugin.video.viewit-0.1.50.zip`
-
-## Entwicklung (kurz)
-- Hauptlogik: `addon/default.py`
+## Entwicklung
+- Router: `addon/default.py`
- Plugins: `addon/plugins/*_plugin.py`
-- Einstellungen: `addon/resources/settings.xml`
+- Settings: `addon/resources/settings.xml`
-## Tests mit Abdeckung
-- Dev-Abhängigkeiten installieren: `./.venv/bin/pip install -r requirements-dev.txt`
-- Tests + Coverage starten: `./.venv/bin/pytest`
-- Optional (XML-Report): `./.venv/bin/pytest --cov-report=xml`
+## Tests
+- Dev Pakete installieren: `./.venv/bin/pip install -r requirements-dev.txt`
+- Tests starten: `./.venv/bin/pytest`
+- XML Report: `./.venv/bin/pytest --cov-report=xml`
## Dokumentation
Siehe `docs/`.
diff --git a/addon/__pycache__/http_session_pool.cpython-312.pyc b/addon/__pycache__/http_session_pool.cpython-312.pyc
deleted file mode 100644
index 83e6a44..0000000
Binary files a/addon/__pycache__/http_session_pool.cpython-312.pyc and /dev/null differ
diff --git a/addon/__pycache__/plugin_helpers.cpython-312.pyc b/addon/__pycache__/plugin_helpers.cpython-312.pyc
deleted file mode 100644
index 449c2dd..0000000
Binary files a/addon/__pycache__/plugin_helpers.cpython-312.pyc and /dev/null differ
diff --git a/addon/__pycache__/regex_patterns.cpython-312.pyc b/addon/__pycache__/regex_patterns.cpython-312.pyc
deleted file mode 100644
index 4d7fc68..0000000
Binary files a/addon/__pycache__/regex_patterns.cpython-312.pyc and /dev/null differ
diff --git a/addon/__pycache__/resolveurl_backend.cpython-312.pyc b/addon/__pycache__/resolveurl_backend.cpython-312.pyc
deleted file mode 100644
index 1f14f61..0000000
Binary files a/addon/__pycache__/resolveurl_backend.cpython-312.pyc and /dev/null differ
diff --git a/addon/__pycache__/tmdb.cpython-312.pyc b/addon/__pycache__/tmdb.cpython-312.pyc
deleted file mode 100644
index 6e208ab..0000000
Binary files a/addon/__pycache__/tmdb.cpython-312.pyc and /dev/null differ
diff --git a/addon/addon.xml b/addon/addon.xml
index e29259a..23ff847 100644
--- a/addon/addon.xml
+++ b/addon/addon.xml
@@ -1,5 +1,5 @@
-
+
@@ -10,8 +10,8 @@
video
- ViewIt Kodi Plugin
- Streaming-Addon für Streamingseiten: Suche, Staffeln/Episoden und Wiedergabe.
+ Suche und Wiedergabe fuer mehrere Quellen
+ Findet Titel in unterstuetzten Quellen und startet Filme oder Episoden direkt in Kodi.
icon.png
diff --git a/addon/default.py b/addon/default.py
index ee63d76..f5e8ff5 100644
--- a/addon/default.py
+++ b/addon/default.py
@@ -16,11 +16,26 @@ import json
import os
import re
import sys
+import threading
import xml.etree.ElementTree as ET
from pathlib import Path
from types import ModuleType
from urllib.parse import parse_qs, urlencode
+
+def _ensure_windows_selector_policy() -> None:
+ """Erzwingt unter Windows einen Selector-Loop (thread-kompatibel in Kodi)."""
+ if not sys.platform.startswith("win"):
+ return
+ try:
+ current = asyncio.get_event_loop_policy()
+ if current.__class__.__name__ == "WindowsSelectorEventLoopPolicy":
+ return
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
+ except Exception:
+ # Fallback: Wenn die Policy nicht verfügbar ist, arbeitet der Code mit Default-Policy weiter.
+ return
+
try: # pragma: no cover - Kodi runtime
import xbmc # type: ignore[import-not-found]
import xbmcaddon # type: ignore[import-not-found]
@@ -402,6 +417,81 @@ def _get_setting_bool(setting_id: str, *, default: bool = False) -> bool:
return default
+def _get_setting_int(setting_id: str, *, default: int = 0) -> int:
+ if xbmcaddon is None:
+ return default
+ addon = _get_addon()
+ if addon is None:
+ return default
+ getter = getattr(addon, "getSettingInt", None)
+ if callable(getter):
+ raw_getter = getattr(addon, "getSetting", None)
+ if callable(raw_getter):
+ try:
+ raw = str(raw_getter(setting_id) or "").strip()
+ except TypeError:
+ raw = ""
+ if raw == "":
+ return default
+ try:
+ return int(getter(setting_id))
+ except TypeError:
+ return default
+ getter = getattr(addon, "getSetting", None)
+ if callable(getter):
+ try:
+ raw = str(getter(setting_id) or "").strip()
+ except TypeError:
+ return default
+ if raw == "":
+ return default
+ try:
+ return int(raw)
+ except ValueError:
+ return default
+ return default
+
+
+METADATA_MODE_AUTO = 0
+METADATA_MODE_SOURCE = 1
+METADATA_MODE_TMDB = 2
+METADATA_MODE_MIX = 3
+
+
+def _metadata_setting_id(plugin_name: str) -> str:
+ safe = re.sub(r"[^a-z0-9]+", "_", (plugin_name or "").strip().casefold()).strip("_")
+ return f"{safe}_metadata_source" if safe else "metadata_source"
+
+
+def _plugin_supports_metadata(plugin: BasisPlugin) -> bool:
+ try:
+ return plugin.__class__.metadata_for is not BasisPlugin.metadata_for
+ except Exception:
+ return False
+
+
+def _metadata_policy(
+ plugin_name: str,
+ plugin: BasisPlugin,
+ *,
+ allow_tmdb: bool,
+) -> tuple[bool, bool, bool]:
+ mode = _get_setting_int(_metadata_setting_id(plugin_name), default=METADATA_MODE_AUTO)
+ supports_source = _plugin_supports_metadata(plugin)
+ if mode == METADATA_MODE_SOURCE:
+ return supports_source, False, True
+ if mode == METADATA_MODE_TMDB:
+ return False, allow_tmdb, False
+ if mode == METADATA_MODE_MIX:
+ return supports_source, allow_tmdb, True
+ prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
+ return supports_source, allow_tmdb, prefer_source
+
+
+def _tmdb_list_enabled() -> bool:
+ return _tmdb_enabled() and _get_setting_bool("tmdb_genre_metadata", default=False)
+
+
def _set_setting_string(setting_id: str, value: str) -> None:
if xbmcaddon is None:
return
@@ -1038,7 +1128,7 @@ def _sync_update_version_settings() -> None:
def _show_root_menu() -> None:
handle = _get_handle()
_log("Root-Menue wird angezeigt.")
- _add_directory_item(handle, "Globale Suche", "search")
+ _add_directory_item(handle, "Suche in allen Quellen", "search")
plugins = _discover_plugins()
for plugin_name in sorted(plugins.keys(), key=lambda value: value.casefold()):
@@ -1053,7 +1143,7 @@ def _show_plugin_menu(plugin_name: str) -> None:
plugin_name = (plugin_name or "").strip()
plugin = _discover_plugins().get(plugin_name)
if not plugin:
- xbmcgui.Dialog().notification("Plugin", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Quelle", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1077,7 +1167,7 @@ def _show_plugin_menu(plugin_name: str) -> None:
_add_directory_item(handle, "Serien", "series_catalog", {"plugin": plugin_name, "page": "1"}, is_folder=True)
if _plugin_has_capability(plugin, "popular_series"):
- _add_directory_item(handle, "Meist gesehen", "popular", {"plugin": plugin_name, "page": "1"}, is_folder=True)
+ _add_directory_item(handle, "Beliebte Serien", "popular", {"plugin": plugin_name, "page": "1"}, is_folder=True)
xbmcplugin.endOfDirectory(handle)
@@ -1086,7 +1176,7 @@ def _show_plugin_search(plugin_name: str) -> None:
plugin_name = (plugin_name or "").strip()
plugin = _discover_plugins().get(plugin_name)
if not plugin:
- xbmcgui.Dialog().notification("Suche", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Suche", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
_show_root_menu()
return
@@ -1107,7 +1197,7 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
query = (query or "").strip()
plugin = _discover_plugins().get(plugin_name)
if not plugin:
- xbmcgui.Dialog().notification("Suche", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Suche", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1118,20 +1208,30 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
list_items: list[dict[str, object]] = []
canceled = False
try:
- with _progress_dialog("Suche läuft", f"{plugin_name} (1/1) starte…") as progress:
- canceled = progress(5, f"{plugin_name} (1/1) Suche…")
- results = _run_async(plugin.search_titles(query))
+ with _progress_dialog("Suche laeuft", f"{plugin_name} (1/1) startet...") as progress:
+ canceled = progress(5, f"{plugin_name} (1/1) Suche...")
+ search_coro = plugin.search_titles(query)
+ try:
+ results = _run_async(search_coro)
+ except Exception:
+ if inspect.iscoroutine(search_coro):
+ try:
+ search_coro.close()
+ except Exception:
+ pass
+ raise
results = [str(t).strip() for t in (results or []) if t and str(t).strip()]
results.sort(key=lambda value: value.casefold())
- plugin_meta = _collect_plugin_metadata(plugin, results)
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, results) if use_source else {}
tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
- show_tmdb = _tmdb_enabled()
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
- prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
- tmdb_titles = list(results)
- if show_tmdb and prefer_source:
+ tmdb_titles = list(results) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
tmdb_titles = []
for title in results:
meta = plugin_meta.get(title)
@@ -1140,7 +1240,7 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
tmdb_titles.append(title)
if show_tmdb and tmdb_titles and not canceled:
- canceled = progress(35, f"{plugin_name} (1/1) Metadaten…")
+ canceled = progress(35, f"{plugin_name} (1/1) Metadaten...")
tmdb_prefetched = _tmdb_labels_and_art_bulk(list(tmdb_titles))
total_results = max(1, len(results))
@@ -1230,11 +1330,16 @@ def _discover_plugins() -> dict[str, BasisPlugin]:
except Exception as exc:
xbmc.log(f"Plugin-Datei {file_path.name} konnte nicht geladen werden: {exc}", xbmc.LOGWARNING)
continue
- plugin_classes = [
- obj
- for obj in module.__dict__.values()
- if inspect.isclass(obj) and issubclass(obj, BasisPlugin) and obj is not BasisPlugin
- ]
+ preferred = getattr(module, "Plugin", None)
+ if inspect.isclass(preferred) and issubclass(preferred, BasisPlugin) and preferred is not BasisPlugin:
+ plugin_classes = [preferred]
+ else:
+ plugin_classes = [
+ obj
+ for obj in module.__dict__.values()
+ if inspect.isclass(obj) and issubclass(obj, BasisPlugin) and obj is not BasisPlugin
+ ]
+ plugin_classes.sort(key=lambda cls: cls.__name__.casefold())
for cls in plugin_classes:
try:
instance = cls()
@@ -1245,24 +1350,55 @@ def _discover_plugins() -> dict[str, BasisPlugin]:
reason = getattr(instance, "unavailable_reason", "Nicht verfuegbar.")
xbmc.log(f"Plugin {cls.__name__} deaktiviert: {reason}", xbmc.LOGWARNING)
continue
- plugins[instance.name] = instance
+ plugin_name = str(getattr(instance, "name", "") or "").strip()
+ if not plugin_name:
+ xbmc.log(
+ f"Plugin {cls.__name__} wurde ohne Name registriert und wird uebersprungen.",
+ xbmc.LOGWARNING,
+ )
+ continue
+ if plugin_name in plugins:
+ xbmc.log(
+ f"Plugin-Name doppelt ({plugin_name}), {cls.__name__} wird uebersprungen.",
+ xbmc.LOGWARNING,
+ )
+ continue
+ plugins[plugin_name] = instance
+ plugins = dict(sorted(plugins.items(), key=lambda item: item[0].casefold()))
_PLUGIN_CACHE = plugins
return plugins
def _run_async(coro):
"""Fuehrt eine Coroutine aus, auch wenn Kodi bereits einen Event-Loop hat."""
+ _ensure_windows_selector_policy()
+
+ def _run_with_asyncio_run():
+ return asyncio.run(coro)
+
try:
- loop = asyncio.get_event_loop()
+ running_loop = asyncio.get_running_loop()
except RuntimeError:
- loop = None
- if loop and loop.is_running():
- temp_loop = asyncio.new_event_loop()
- try:
- return temp_loop.run_until_complete(coro)
- finally:
- temp_loop.close()
- return asyncio.run(coro)
+ running_loop = None
+
+ if running_loop and running_loop.is_running():
+ result_box: dict[str, object] = {}
+ error_box: dict[str, BaseException] = {}
+
+ def _worker() -> None:
+ try:
+ result_box["value"] = _run_with_asyncio_run()
+ except BaseException as exc: # pragma: no cover - defensive
+ error_box["error"] = exc
+
+ worker = threading.Thread(target=_worker, name="viewit-async-runner")
+ worker.start()
+ worker.join()
+ if "error" in error_box:
+ raise error_box["error"]
+ return result_box.get("value")
+
+ return _run_with_asyncio_run()
def _series_url_params(plugin: BasisPlugin, title: str) -> dict[str, str]:
@@ -1279,7 +1415,7 @@ def _series_url_params(plugin: BasisPlugin, title: str) -> dict[str, str]:
def _show_search() -> None:
_log("Suche gestartet.")
dialog = xbmcgui.Dialog()
- query = dialog.input("Serientitel eingeben", type=xbmcgui.INPUT_ALPHANUM).strip()
+ query = dialog.input("Titel eingeben", type=xbmcgui.INPUT_ALPHANUM).strip()
if not query:
_log("Suche abgebrochen (leere Eingabe).", xbmc.LOGDEBUG)
_show_root_menu()
@@ -1294,35 +1430,42 @@ def _show_search_results(query: str) -> None:
_set_content(handle, "tvshows")
plugins = _discover_plugins()
if not plugins:
- xbmcgui.Dialog().notification("Suche", "Keine Plugins gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Suche", "Keine Quellen gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
list_items: list[dict[str, object]] = []
canceled = False
plugin_entries = list(plugins.items())
total_plugins = max(1, len(plugin_entries))
- with _progress_dialog("Suche läuft", "Suche gestartet…") as progress:
+ with _progress_dialog("Suche laeuft", "Suche startet...") as progress:
for plugin_index, (plugin_name, plugin) in enumerate(plugin_entries, start=1):
range_start = int(((plugin_index - 1) / float(total_plugins)) * 100)
range_end = int((plugin_index / float(total_plugins)) * 100)
- canceled = progress(range_start, f"{plugin_name} ({plugin_index}/{total_plugins}) Suche…")
+ canceled = progress(range_start, f"{plugin_name} ({plugin_index}/{total_plugins}) Suche...")
if canceled:
break
+ search_coro = plugin.search_titles(query)
try:
- results = _run_async(plugin.search_titles(query))
+ results = _run_async(search_coro)
except Exception as exc:
+ if inspect.iscoroutine(search_coro):
+ try:
+ search_coro.close()
+ except Exception:
+ pass
_log(f"Suche fehlgeschlagen ({plugin_name}): {exc}", xbmc.LOGWARNING)
continue
results = [str(t).strip() for t in (results or []) if t and str(t).strip()]
_log(f"Treffer ({plugin_name}): {len(results)}", xbmc.LOGDEBUG)
- plugin_meta = _collect_plugin_metadata(plugin, results)
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, results) if use_source else {}
tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
- show_tmdb = _tmdb_enabled()
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
- prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
- tmdb_titles = list(results)
- if show_tmdb and prefer_source:
+ tmdb_titles = list(results) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
tmdb_titles = []
for title in results:
meta = plugin_meta.get(title)
@@ -1333,7 +1476,7 @@ def _show_search_results(query: str) -> None:
if show_tmdb and tmdb_titles:
canceled = progress(
range_start + int((range_end - range_start) * 0.35),
- f"{plugin_name} ({plugin_index}/{total_plugins}) Metadaten…",
+ f"{plugin_name} ({plugin_index}/{total_plugins}) Metadaten...",
)
if canceled:
break
@@ -1376,7 +1519,7 @@ def _show_search_results(query: str) -> None:
if canceled:
break
if not canceled:
- progress(100, "Suche abgeschlossen")
+ progress(100, "Suche fertig")
if canceled and not list_items:
xbmcgui.Dialog().notification("Suche", "Suche abgebrochen.", xbmcgui.NOTIFICATION_INFO, 2500)
xbmcplugin.endOfDirectory(handle)
@@ -1401,7 +1544,7 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
_log(f"Staffeln laden: {plugin_name} / {title}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Staffeln", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Staffeln", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
if series_url:
@@ -1466,11 +1609,14 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
except Exception:
pass
+ use_source, show_tmdb, _prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_enabled()
+ )
title_info_labels: dict[str, str] | None = None
title_art: dict[str, str] | None = None
title_cast: list[TmdbCastMember] | None = None
meta_getter = getattr(plugin, "metadata_for", None)
- if callable(meta_getter):
+ if use_source and callable(meta_getter):
try:
with _busy_dialog():
meta_labels, meta_art, meta_cast = meta_getter(title)
@@ -1488,7 +1634,7 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
seasons = plugin.seasons_for(title)
except Exception as exc:
_log(f"Staffeln laden fehlgeschlagen ({plugin_name}): {exc}", xbmc.LOGWARNING)
- xbmcgui.Dialog().notification("Staffeln", "Konnte Staffeln nicht laden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Staffeln", "Staffeln konnten nicht geladen werden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1497,8 +1643,9 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
xbmcplugin.setPluginCategory(handle, f"{title} ({count} {suffix})")
_set_content(handle, "seasons")
# Staffel-Metadaten (Plot/Poster) optional via TMDB.
- _tmdb_labels_and_art(title)
- api_key = _get_setting_string("tmdb_api_key").strip()
+ if show_tmdb:
+ _tmdb_labels_and_art(title)
+ api_key = _get_setting_string("tmdb_api_key").strip() if show_tmdb else ""
language = _get_setting_string("tmdb_language").strip() or "de-DE"
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
@@ -1568,7 +1715,7 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
_log(f"Episoden laden: {plugin_name} / {title} / {season}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Episoden", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Episoden", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
if series_url:
@@ -1587,13 +1734,42 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
episodes = list(plugin.episodes_for(title, season))
if episodes:
- show_info, show_art, show_cast = _tmdb_labels_and_art(title)
+ episode_url_getter = getattr(plugin, "episode_url_for", None)
+ supports_direct_episode_url = callable(getattr(plugin, "stream_link_for_url", None))
+ use_source, show_tmdb, _prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_enabled()
+ )
+ show_info: dict[str, str] = {}
+ show_art: dict[str, str] = {}
+ show_cast: list[TmdbCastMember] | None = None
+ if show_tmdb:
+ show_info, show_art, show_cast = _tmdb_labels_and_art(title)
+ elif use_source:
+ meta_getter = getattr(plugin, "metadata_for", None)
+ if callable(meta_getter):
+ try:
+ with _busy_dialog():
+ meta_labels, meta_art, meta_cast = meta_getter(title)
+ if isinstance(meta_labels, dict):
+ show_info = {str(k): str(v) for k, v in meta_labels.items() if v}
+ if isinstance(meta_art, dict):
+ show_art = {str(k): str(v) for k, v in meta_art.items() if v}
+ if isinstance(meta_cast, list):
+ show_cast = meta_cast # noqa: PGH003
+ except Exception:
+ pass
+
show_fanart = (show_art or {}).get("fanart") if isinstance(show_art, dict) else ""
show_poster = (show_art or {}).get("poster") if isinstance(show_art, dict) else ""
with _busy_dialog():
for episode in episodes:
- info_labels, art = _tmdb_episode_labels_and_art(title=title, season_label=season, episode_label=episode)
- episode_cast = _tmdb_episode_cast(title=title, season_label=season, episode_label=episode)
+ if show_tmdb:
+ info_labels, art = _tmdb_episode_labels_and_art(
+ title=title, season_label=season, episode_label=episode
+ )
+ episode_cast = _tmdb_episode_cast(title=title, season_label=season, episode_label=episode)
+ else:
+ info_labels, art, episode_cast = {}, {}, []
merged_info = dict(show_info or {})
merged_info.update(dict(info_labels or {}))
merged_art: dict[str, str] = {}
@@ -1623,11 +1799,25 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
merged_info = _apply_playstate_to_info(merged_info, _get_playstate(key))
display_label = episode
+ play_params = {
+ "plugin": plugin_name,
+ "title": title,
+ "season": season,
+ "episode": episode,
+ "series_url": series_url,
+ }
+ if supports_direct_episode_url and callable(episode_url_getter):
+ try:
+ episode_url = str(episode_url_getter(title, season, episode) or "").strip()
+ except Exception:
+ episode_url = ""
+ if episode_url:
+ play_params["url"] = episode_url
_add_directory_item(
handle,
display_label,
"play_episode",
- {"plugin": plugin_name, "title": title, "season": season, "episode": episode},
+ play_params,
is_folder=False,
info_labels=merged_info,
art=merged_art,
@@ -1649,7 +1839,7 @@ def _show_genre_sources() -> None:
sources.append((plugin_name, plugin))
if not sources:
- xbmcgui.Dialog().notification("Genres", "Keine Genre-Quellen gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Genres", "Keine Quellen mit Genres gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1669,7 +1859,7 @@ def _show_genres(plugin_name: str) -> None:
_log(f"Genres laden: {plugin_name}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Genres", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Genres", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
try:
@@ -1706,7 +1896,7 @@ def _show_categories(plugin_name: str) -> None:
_log(f"Kategorien laden: {plugin_name}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Kategorien", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Kategorien", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
getter = getattr(plugin, "categories", None)
@@ -1739,14 +1929,14 @@ def _show_category_titles_page(plugin_name: str, category: str, page: int = 1) -
handle = _get_handle()
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Kategorien", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Kategorien", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
page = max(1, int(page or 1))
paging_getter = getattr(plugin, "titles_for_genre_page", None)
if not callable(paging_getter):
- xbmcgui.Dialog().notification("Kategorien", "Paging nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Kategorien", "Seitenwechsel nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1784,16 +1974,16 @@ def _show_category_titles_page(plugin_name: str, category: str, page: int = 1) -
titles = [str(t).strip() for t in titles if t and str(t).strip()]
titles.sort(key=lambda value: value.casefold())
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if titles:
- plugin_meta = _collect_plugin_metadata(plugin, titles)
- show_tmdb = _tmdb_enabled()
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, titles) if use_source else {}
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
- prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
- tmdb_titles = list(titles)
- if show_tmdb and prefer_source:
+ tmdb_titles = list(titles) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
tmdb_titles = []
for title in titles:
meta = plugin_meta.get(title)
@@ -1804,51 +1994,31 @@ def _show_category_titles_page(plugin_name: str, category: str, page: int = 1) -
if show_tmdb and tmdb_titles:
with _busy_dialog():
tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
- if show_tmdb:
- for title in titles:
- tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, []))
- meta = plugin_meta.get(title)
- info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
- info_labels.setdefault("mediatype", "tvshow")
- if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
- info_labels.setdefault("tvshowtitle", title)
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- display_label,
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
- for title in titles:
- playstate = _title_playstate(plugin_name, title)
- meta = plugin_meta.get(title)
- info_labels, art, cast = _merge_metadata(title, {}, {}, None, meta)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=_apply_playstate_to_info(info_labels, playstate),
- art=art,
- cast=cast,
- )
+ for title in titles:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels.setdefault("mediatype", "tvshow")
+ if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
+ info_labels.setdefault("tvshowtitle", title)
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ direct_play = bool(
+ plugin_name.casefold() == "einschalten"
+ and _get_setting_bool("einschalten_enable_playback", default=False)
+ )
+ _add_directory_item(
+ handle,
+ display_label,
+ "play_movie" if direct_play else "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=not direct_play,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
show_next = False
if total_pages is not None:
@@ -1875,14 +2045,14 @@ def _show_genre_titles_page(plugin_name: str, genre: str, page: int = 1) -> None
handle = _get_handle()
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Genres", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Genres", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
page = max(1, int(page or 1))
paging_getter = getattr(plugin, "titles_for_genre_page", None)
if not callable(paging_getter):
- xbmcgui.Dialog().notification("Genres", "Paging nicht verfügbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Genres", "Seitenwechsel nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -1920,16 +2090,16 @@ def _show_genre_titles_page(plugin_name: str, genre: str, page: int = 1) -> None
titles = [str(t).strip() for t in titles if t and str(t).strip()]
titles.sort(key=lambda value: value.casefold())
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if titles:
- plugin_meta = _collect_plugin_metadata(plugin, titles)
- show_tmdb = show_tmdb and _tmdb_enabled()
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, titles) if use_source else {}
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
- prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
- tmdb_titles = list(titles)
- if show_tmdb and prefer_source:
+ tmdb_titles = list(titles) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
tmdb_titles = []
for title in titles:
meta = plugin_meta.get(title)
@@ -1993,12 +2163,12 @@ def _show_alpha_index(plugin_name: str) -> None:
_log(f"A-Z laden: {plugin_name}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("A-Z", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("A-Z", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
getter = getattr(plugin, "alpha_index", None)
if not callable(getter):
- xbmcgui.Dialog().notification("A-Z", "A-Z nicht verfügbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("A-Z", "A-Z nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
try:
@@ -2026,14 +2196,14 @@ def _show_alpha_titles_page(plugin_name: str, letter: str, page: int = 1) -> Non
handle = _get_handle()
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("A-Z", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("A-Z", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
page = max(1, int(page or 1))
paging_getter = getattr(plugin, "titles_for_alpha_page", None)
if not callable(paging_getter):
- xbmcgui.Dialog().notification("A-Z", "Paging nicht verfügbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("A-Z", "Seitenwechsel nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -2071,50 +2241,52 @@ def _show_alpha_titles_page(plugin_name: str, letter: str, page: int = 1) -> Non
titles = [str(t).strip() for t in titles if t and str(t).strip()]
titles.sort(key=lambda value: value.casefold())
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if titles:
- if show_tmdb:
- with _busy_dialog():
- tmdb_prefetched = _tmdb_labels_and_art_bulk(titles)
- for title in titles:
- info_labels, art, cast = tmdb_prefetched.get(title, _tmdb_labels_and_art(title))
- info_labels = dict(info_labels or {})
- info_labels.setdefault("mediatype", "tvshow")
- if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
- info_labels.setdefault("tvshowtitle", title)
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- display_label,
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, titles) if use_source else {}
+ show_plot = _get_setting_bool("tmdb_show_plot", default=True)
+ show_art = _get_setting_bool("tmdb_show_art", default=True)
+ tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
+ tmdb_titles = list(titles) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
+ tmdb_titles = []
for title in titles:
- playstate = _title_playstate(plugin_name, title)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=_apply_playstate_to_info({"title": title}, playstate),
- )
+ meta = plugin_meta.get(title)
+ meta_labels = meta[0] if meta else {}
+ meta_art = meta[1] if meta else {}
+ if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
+ tmdb_titles.append(title)
+ if show_tmdb and tmdb_titles:
+ with _busy_dialog():
+ tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
+ for title in titles:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels = dict(info_labels or {})
+ info_labels.setdefault("mediatype", "tvshow")
+ if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
+ info_labels.setdefault("tvshowtitle", title)
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ direct_play = bool(
+ plugin_name.casefold() == "einschalten"
+ and _get_setting_bool("einschalten_enable_playback", default=False)
+ )
+ _add_directory_item(
+ handle,
+ display_label,
+ "play_movie" if direct_play else "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=not direct_play,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
show_next = False
if total_pages is not None:
@@ -2136,14 +2308,14 @@ def _show_series_catalog(plugin_name: str, page: int = 1) -> None:
plugin_name = (plugin_name or "").strip()
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Serien", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Serien", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
page = max(1, int(page or 1))
paging_getter = getattr(plugin, "series_catalog_page", None)
if not callable(paging_getter):
- xbmcgui.Dialog().notification("Serien", "Serien nicht verfügbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Serien", "Serienkatalog nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -2181,42 +2353,48 @@ def _show_series_catalog(plugin_name: str, page: int = 1) -> None:
titles = [str(t).strip() for t in titles if t and str(t).strip()]
titles.sort(key=lambda value: value.casefold())
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if titles:
- if show_tmdb:
- with _busy_dialog():
- tmdb_prefetched = _tmdb_labels_and_art_bulk(titles)
- for title in titles:
- info_labels, art, cast = tmdb_prefetched.get(title, _tmdb_labels_and_art(title))
- info_labels = dict(info_labels or {})
- info_labels.setdefault("mediatype", "tvshow")
- if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
- info_labels.setdefault("tvshowtitle", title)
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- _add_directory_item(
- handle,
- display_label,
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, titles) if use_source else {}
+ show_plot = _get_setting_bool("tmdb_show_plot", default=True)
+ show_art = _get_setting_bool("tmdb_show_art", default=True)
+ tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
+ tmdb_titles = list(titles) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
+ tmdb_titles = []
for title in titles:
- playstate = _title_playstate(plugin_name, title)
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=_apply_playstate_to_info({"title": title}, playstate),
- )
+ meta = plugin_meta.get(title)
+ meta_labels = meta[0] if meta else {}
+ meta_art = meta[1] if meta else {}
+ if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
+ tmdb_titles.append(title)
+ if show_tmdb and tmdb_titles:
+ with _busy_dialog():
+ tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
+ for title in titles:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels = dict(info_labels or {})
+ info_labels.setdefault("mediatype", "tvshow")
+ if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
+ info_labels.setdefault("tvshowtitle", title)
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ _add_directory_item(
+ handle,
+ display_label,
+ "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=True,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
show_next = False
if total_pages is not None:
@@ -2370,7 +2548,7 @@ def _show_popular(plugin_name: str | None = None, page: int = 1) -> None:
if plugin_name:
plugin = _discover_plugins().get(plugin_name)
if plugin is None or not _plugin_has_capability(plugin, "popular_series"):
- xbmcgui.Dialog().notification("Beliebte Serien", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Beliebte Serien", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
try:
@@ -2410,16 +2588,16 @@ def _show_popular(plugin_name: str | None = None, page: int = 1) -> None:
end = start + page_size
page_items = titles[start:end]
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if page_items:
- plugin_meta = _collect_plugin_metadata(plugin, page_items)
- show_tmdb = show_tmdb and _tmdb_enabled()
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, page_items) if use_source else {}
show_plot = _get_setting_bool("tmdb_show_plot", default=True)
show_art = _get_setting_bool("tmdb_show_art", default=True)
- prefer_source = bool(getattr(plugin, "prefer_source_metadata", False))
tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
- tmdb_titles = list(page_items)
- if show_tmdb and prefer_source:
+ tmdb_titles = list(page_items) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
tmdb_titles = []
for title in page_items:
meta = plugin_meta.get(title)
@@ -2431,7 +2609,7 @@ def _show_popular(plugin_name: str | None = None, page: int = 1) -> None:
with _busy_dialog():
tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
for title in page_items:
- tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, []))
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
meta = plugin_meta.get(title)
info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
info_labels.setdefault("mediatype", "tvshow")
@@ -2489,13 +2667,13 @@ def _show_new_titles(plugin_name: str, page: int = 1) -> None:
plugin_name = (plugin_name or "").strip()
plugin = _discover_plugins().get(plugin_name)
if plugin is None or not _plugin_has_capability(plugin, "new_titles"):
- xbmcgui.Dialog().notification("Neue Titel", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Neue Titel", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
getter = getattr(plugin, "new_titles", None)
if not callable(getter):
- xbmcgui.Dialog().notification("Neue Titel", "Nicht verfügbar.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Neue Titel", "Diese Liste ist nicht verfuegbar.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -2537,7 +2715,7 @@ def _show_new_titles(plugin_name: str, page: int = 1) -> None:
if total == 0:
xbmcgui.Dialog().notification(
"Neue Titel",
- "Keine Titel gefunden (Basis-URL/Index prüfen).",
+ "Keine Titel gefunden. Bitte Basis-URL oder Index pruefen.",
xbmcgui.NOTIFICATION_INFO,
4000,
)
@@ -2558,48 +2736,50 @@ def _show_new_titles(plugin_name: str, page: int = 1) -> None:
start = (page - 1) * page_size
end = start + page_size
page_items = titles[start:end]
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
if page_items:
- if show_tmdb:
- with _busy_dialog():
- tmdb_prefetched = _tmdb_labels_and_art_bulk(page_items)
- for title in page_items:
- info_labels, art, cast = tmdb_prefetched.get(title, _tmdb_labels_and_art(title))
- info_labels = dict(info_labels or {})
- info_labels.setdefault("mediatype", "movie")
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- display_label,
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
+ plugin_meta = _collect_plugin_metadata(plugin, page_items) if use_source else {}
+ show_plot = _get_setting_bool("tmdb_show_plot", default=True)
+ show_art = _get_setting_bool("tmdb_show_art", default=True)
+ tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
+ tmdb_titles = list(page_items) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
+ tmdb_titles = []
for title in page_items:
- playstate = _title_playstate(plugin_name, title)
- direct_play = bool(
- plugin_name.casefold() == "einschalten"
- and _get_setting_bool("einschalten_enable_playback", default=False)
- )
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "play_movie" if direct_play else "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=not direct_play,
- info_labels=_apply_playstate_to_info({"title": title}, playstate),
- )
+ meta = plugin_meta.get(title)
+ meta_labels = meta[0] if meta else {}
+ meta_art = meta[1] if meta else {}
+ if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
+ tmdb_titles.append(title)
+ if show_tmdb and tmdb_titles:
+ with _busy_dialog():
+ tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
+ for title in page_items:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels = dict(info_labels or {})
+ info_labels.setdefault("mediatype", "movie")
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ direct_play = bool(
+ plugin_name.casefold() == "einschalten"
+ and _get_setting_bool("einschalten_enable_playback", default=False)
+ )
+ _add_directory_item(
+ handle,
+ display_label,
+ "play_movie" if direct_play else "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=not direct_play,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
show_next = False
if callable(paging_getter) and callable(has_more_getter):
@@ -2626,13 +2806,13 @@ def _show_latest_episodes(plugin_name: str, page: int = 1) -> None:
plugin_name = (plugin_name or "").strip()
plugin = _discover_plugins().get(plugin_name)
if not plugin:
- xbmcgui.Dialog().notification("Neueste Folgen", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Neueste Folgen", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
getter = getattr(plugin, "latest_episodes", None)
if not callable(getter):
- xbmcgui.Dialog().notification("Neueste Folgen", "Nicht unterstützt.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Neueste Folgen", "Diese Quelle bietet das nicht an.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -2703,7 +2883,7 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
page = max(1, int(page or 1))
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Genres", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Genres", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
xbmcplugin.endOfDirectory(handle)
return
@@ -2719,7 +2899,9 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
return
xbmcplugin.setPluginCategory(handle, f"{genre} [{group_code}] ({page})")
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
if page > 1:
_add_directory_item(
handle,
@@ -2729,40 +2911,44 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
is_folder=True,
)
if page_items:
- if show_tmdb:
- with _busy_dialog():
- tmdb_prefetched = _tmdb_labels_and_art_bulk(page_items)
- for title in page_items:
- info_labels, art, cast = tmdb_prefetched.get(title, _tmdb_labels_and_art(title))
- info_labels = dict(info_labels or {})
- info_labels.setdefault("mediatype", "tvshow")
- if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
- info_labels.setdefault("tvshowtitle", title)
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- _add_directory_item(
- handle,
- display_label,
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
+ plugin_meta = _collect_plugin_metadata(plugin, page_items) if use_source else {}
+ show_plot = _get_setting_bool("tmdb_show_plot", default=True)
+ show_art = _get_setting_bool("tmdb_show_art", default=True)
+ tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
+ tmdb_titles = list(page_items) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
+ tmdb_titles = []
for title in page_items:
- playstate = _title_playstate(plugin_name, title)
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=_apply_playstate_to_info({"title": title}, playstate),
- )
+ meta = plugin_meta.get(title)
+ meta_labels = meta[0] if meta else {}
+ meta_art = meta[1] if meta else {}
+ if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
+ tmdb_titles.append(title)
+ if show_tmdb and tmdb_titles:
+ with _busy_dialog():
+ tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
+ for title in page_items:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels = dict(info_labels or {})
+ info_labels.setdefault("mediatype", "tvshow")
+ if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
+ info_labels.setdefault("tvshowtitle", title)
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ _add_directory_item(
+ handle,
+ display_label,
+ "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=True,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
show_next = False
if callable(grouped_has_more):
try:
@@ -2808,43 +2994,49 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
start = (page - 1) * page_size
end = start + page_size
page_items = filtered[start:end]
- show_tmdb = _get_setting_bool("tmdb_genre_metadata", default=False)
+ use_source, show_tmdb, prefer_source = _metadata_policy(
+ plugin_name, plugin, allow_tmdb=_tmdb_list_enabled()
+ )
if page_items:
- if show_tmdb:
- with _busy_dialog():
- tmdb_prefetched = _tmdb_labels_and_art_bulk(page_items)
- for title in page_items:
- info_labels, art, cast = tmdb_prefetched.get(title, _tmdb_labels_and_art(title))
- info_labels = dict(info_labels or {})
- info_labels.setdefault("mediatype", "tvshow")
- if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
- info_labels.setdefault("tvshowtitle", title)
- playstate = _title_playstate(plugin_name, title)
- info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
- display_label = _label_with_duration(title, info_labels)
- display_label = _label_with_playstate(display_label, playstate)
- _add_directory_item(
- handle,
- display_label,
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=info_labels,
- art=art,
- cast=cast,
- )
- else:
+ plugin_meta = _collect_plugin_metadata(plugin, page_items) if use_source else {}
+ show_plot = _get_setting_bool("tmdb_show_plot", default=True)
+ show_art = _get_setting_bool("tmdb_show_art", default=True)
+ tmdb_prefetched: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember]]] = {}
+ tmdb_titles = list(page_items) if show_tmdb else []
+ if show_tmdb and prefer_source and use_source:
+ tmdb_titles = []
for title in page_items:
- playstate = _title_playstate(plugin_name, title)
- _add_directory_item(
- handle,
- _label_with_playstate(title, playstate),
- "seasons",
- {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
- is_folder=True,
- info_labels=_apply_playstate_to_info({"title": title}, playstate),
- )
+ meta = plugin_meta.get(title)
+ meta_labels = meta[0] if meta else {}
+ meta_art = meta[1] if meta else {}
+ if _needs_tmdb(meta_labels, meta_art, want_plot=show_plot, want_art=show_art):
+ tmdb_titles.append(title)
+ if show_tmdb and tmdb_titles:
+ with _busy_dialog():
+ tmdb_prefetched = _tmdb_labels_and_art_bulk(tmdb_titles)
+ for title in page_items:
+ tmdb_info, tmdb_art, tmdb_cast = tmdb_prefetched.get(title, ({}, {}, [])) if show_tmdb else ({}, {}, [])
+ meta = plugin_meta.get(title)
+ info_labels, art, cast = _merge_metadata(title, tmdb_info, tmdb_art, tmdb_cast, meta)
+ info_labels = dict(info_labels or {})
+ info_labels.setdefault("mediatype", "tvshow")
+ if (info_labels.get("mediatype") or "").strip().casefold() == "tvshow":
+ info_labels.setdefault("tvshowtitle", title)
+ playstate = _title_playstate(plugin_name, title)
+ info_labels = _apply_playstate_to_info(dict(info_labels), playstate)
+ display_label = _label_with_duration(title, info_labels)
+ display_label = _label_with_playstate(display_label, playstate)
+ _add_directory_item(
+ handle,
+ display_label,
+ "seasons",
+ {"plugin": plugin_name, "title": title, **_series_url_params(plugin, title)},
+ is_folder=True,
+ info_labels=info_labels,
+ art=art,
+ cast=cast,
+ )
if total_pages > 1 and page < total_pages:
_add_directory_item(
@@ -2879,11 +3071,11 @@ def _run_update_check() -> None:
builtin("UpdateAddonRepos")
builtin("UpdateLocalAddons")
builtin("ActivateWindow(addonbrowser,addons://updates/)")
- xbmcgui.Dialog().notification("ViewIT Update", "Update-Pruefung gestartet.", xbmcgui.NOTIFICATION_INFO, 4000)
+ xbmcgui.Dialog().notification("Updates", "Update-Check gestartet.", xbmcgui.NOTIFICATION_INFO, 4000)
except Exception as exc:
_log(f"Update-Pruefung fehlgeschlagen: {exc}", xbmc.LOGWARNING)
try:
- xbmcgui.Dialog().notification("ViewIT Update", "Update-Pruefung fehlgeschlagen.", xbmcgui.NOTIFICATION_ERROR, 4000)
+ xbmcgui.Dialog().notification("Updates", "Update-Check fehlgeschlagen.", xbmcgui.NOTIFICATION_ERROR, 4000)
except Exception:
pass
@@ -3026,12 +3218,38 @@ def _play_episode(
season: str,
episode: str,
*,
+ episode_url: str = "",
+ series_url: str = "",
resolve_handle: int | None = None,
) -> None:
+ episode_url = (episode_url or "").strip()
+ if episode_url:
+ _play_episode_url(
+ plugin_name,
+ title=title,
+ season_number=_extract_first_int(season) or 0,
+ episode_number=_extract_first_int(episode) or 0,
+ episode_url=episode_url,
+ season_label_override=season,
+ episode_label_override=episode,
+ resolve_handle=resolve_handle,
+ )
+ return
+
+ series_url = (series_url or "").strip()
+ if series_url:
+ plugin_for_url = _discover_plugins().get(plugin_name)
+ remember_series_url = getattr(plugin_for_url, "remember_series_url", None) if plugin_for_url is not None else None
+ if callable(remember_series_url):
+ try:
+ remember_series_url(title, series_url)
+ except Exception:
+ pass
+
_log(f"Play anfordern: {plugin_name} / {title} / {season} / {episode}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Play", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Wiedergabe", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
return
available_hosters: list[str] = []
@@ -3048,7 +3266,7 @@ def _play_episode(
if len(available_hosters) == 1:
selected_hoster = available_hosters[0]
else:
- selected_index = xbmcgui.Dialog().select("Hoster wählen", available_hosters)
+ selected_index = xbmcgui.Dialog().select("Hoster waehlen", available_hosters)
if selected_index is None or selected_index < 0:
_log("Play abgebrochen (kein Hoster gewählt).", xbmc.LOGDEBUG)
return
@@ -3066,8 +3284,8 @@ def _play_episode(
try:
link = plugin.stream_link_for(title, season, episode)
if not link:
- _log("Kein Stream-Link gefunden.", xbmc.LOGWARNING)
- xbmcgui.Dialog().notification("Play", "Kein Stream-Link gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ _log("Kein Stream gefunden.", xbmc.LOGWARNING)
+ xbmcgui.Dialog().notification("Wiedergabe", "Kein Stream gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
return
_log(f"Stream-Link: {link}", xbmc.LOGDEBUG)
final_link = plugin.resolve_stream_link(link) or link
@@ -3104,14 +3322,18 @@ def _play_episode_url(
season_number: int,
episode_number: int,
episode_url: str,
+ season_label_override: str = "",
+ episode_label_override: str = "",
resolve_handle: int | None = None,
) -> None:
- season_label = f"Staffel {season_number}" if season_number > 0 else ""
- episode_label = f"Episode {episode_number}" if episode_number > 0 else ""
+ season_label = (season_label_override or "").strip() or (f"Staffel {season_number}" if season_number > 0 else "")
+ episode_label = (episode_label_override or "").strip() or (
+ f"Episode {episode_number}" if episode_number > 0 else ""
+ )
_log(f"Play (URL) anfordern: {plugin_name} / {title} / {season_label} / {episode_label} / {episode_url}")
plugin = _discover_plugins().get(plugin_name)
if plugin is None:
- xbmcgui.Dialog().notification("Play", "Plugin nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Wiedergabe", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
return
available_hosters: list[str] = []
@@ -3128,7 +3350,7 @@ def _play_episode_url(
if len(available_hosters) == 1:
selected_hoster = available_hosters[0]
else:
- selected_index = xbmcgui.Dialog().select("Hoster wählen", available_hosters)
+ selected_index = xbmcgui.Dialog().select("Hoster waehlen", available_hosters)
if selected_index is None or selected_index < 0:
_log("Play abgebrochen (kein Hoster gewählt).", xbmc.LOGDEBUG)
return
@@ -3145,12 +3367,12 @@ def _play_episode_url(
try:
link_getter = getattr(plugin, "stream_link_for_url", None)
if not callable(link_getter):
- xbmcgui.Dialog().notification("Play", "Nicht unterstützt.", xbmcgui.NOTIFICATION_INFO, 3000)
+ xbmcgui.Dialog().notification("Wiedergabe", "Diese Funktion wird von der Quelle nicht unterstuetzt.", xbmcgui.NOTIFICATION_INFO, 3000)
return
link = link_getter(episode_url)
if not link:
- _log("Kein Stream-Link gefunden.", xbmc.LOGWARNING)
- xbmcgui.Dialog().notification("Play", "Kein Stream-Link gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
+ _log("Kein Stream gefunden.", xbmc.LOGWARNING)
+ xbmcgui.Dialog().notification("Wiedergabe", "Kein Stream gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
return
_log(f"Stream-Link: {link}", xbmc.LOGDEBUG)
final_link = plugin.resolve_stream_link(link) or link
@@ -3276,6 +3498,8 @@ def run() -> None:
params.get("title", ""),
params.get("season", ""),
params.get("episode", ""),
+ episode_url=params.get("url", ""),
+ series_url=params.get("series_url", ""),
resolve_handle=_get_handle(),
)
elif action == "play_movie":
diff --git a/addon/plugin_interface.py b/addon/plugin_interface.py
index f8c266d..273a00b 100644
--- a/addon/plugin_interface.py
+++ b/addon/plugin_interface.py
@@ -4,7 +4,7 @@
from __future__ import annotations
from abc import ABC, abstractmethod
-from typing import List, Optional, Set
+from typing import Any, Dict, List, Optional, Set, Tuple
class BasisPlugin(ABC):
@@ -12,6 +12,7 @@ class BasisPlugin(ABC):
name: str
version: str = "0.0.0"
+ prefer_source_metadata: bool = False
@abstractmethod
async def search_titles(self, query: str) -> List[str]:
@@ -29,6 +30,10 @@ class BasisPlugin(ABC):
"""Optional: Liefert den Stream-Link fuer eine konkrete Folge."""
return None
+ def metadata_for(self, title: str) -> Tuple[Dict[str, str], Dict[str, str], Optional[List[Any]]]:
+ """Optional: Liefert Info-Labels, Art und Cast fuer einen Titel."""
+ return {}, {}, None
+
def resolve_stream_link(self, link: str) -> Optional[str]:
"""Optional: Folgt einem Stream-Link und liefert die finale URL."""
return None
diff --git a/addon/plugins/__pycache__/__init__.cpython-312.pyc b/addon/plugins/__pycache__/__init__.cpython-312.pyc
deleted file mode 100644
index 26e3918..0000000
Binary files a/addon/plugins/__pycache__/__init__.cpython-312.pyc and /dev/null differ
diff --git a/addon/plugins/__pycache__/_template_plugin.cpython-312.pyc b/addon/plugins/__pycache__/_template_plugin.cpython-312.pyc
deleted file mode 100644
index 4d0c98b..0000000
Binary files a/addon/plugins/__pycache__/_template_plugin.cpython-312.pyc and /dev/null differ
diff --git a/addon/plugins/__pycache__/einschalten_plugin.cpython-312.pyc b/addon/plugins/__pycache__/einschalten_plugin.cpython-312.pyc
deleted file mode 100644
index b5da04f..0000000
Binary files a/addon/plugins/__pycache__/einschalten_plugin.cpython-312.pyc and /dev/null differ
diff --git a/addon/plugins/_template_plugin.py b/addon/plugins/_template_plugin.py
index a5244e2..ae286a7 100644
--- a/addon/plugins/_template_plugin.py
+++ b/addon/plugins/_template_plugin.py
@@ -9,7 +9,7 @@ Zum Verwenden:
from __future__ import annotations
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, List, Optional, TypeAlias
+from typing import TYPE_CHECKING, Any, List, Optional
try: # pragma: no cover - optional dependency
import requests
@@ -34,8 +34,8 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
ADDON_ID = "plugin.video.viewit"
diff --git a/addon/plugins/aniworld_plugin.py b/addon/plugins/aniworld_plugin.py
index 7271a7a..bb8cb7e 100644
--- a/addon/plugins/aniworld_plugin.py
+++ b/addon/plugins/aniworld_plugin.py
@@ -13,7 +13,7 @@ import hashlib
import json
import re
import time
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, TypeAlias
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
try: # pragma: no cover - optional dependency
import requests
@@ -43,8 +43,8 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
SETTING_BASE_URL = "aniworld_base_url"
@@ -1213,6 +1213,18 @@ class AniworldPlugin(BasisPlugin):
_log_url(link, kind="FOUND")
return link
+ def episode_url_for(self, title: str, season: str, episode: str) -> str:
+ cache_key = (title, season)
+ cached = self._episode_label_cache.get(cache_key)
+ if cached:
+ info = cached.get(episode)
+ if info and info.url:
+ return info.url
+ episode_info = self._lookup_episode(title, season, episode)
+ if episode_info and episode_info.url:
+ return episode_info.url
+ return ""
+
def available_hosters_for(self, title: str, season: str, episode: str) -> List[str]:
if not self._requests_available:
raise RuntimeError("AniworldPlugin kann ohne requests/bs4 keine Hoster laden.")
diff --git a/addon/plugins/dokustreams_plugin.py b/addon/plugins/dokustreams_plugin.py
index 047a652..14a39c2 100644
--- a/addon/plugins/dokustreams_plugin.py
+++ b/addon/plugins/dokustreams_plugin.py
@@ -5,7 +5,7 @@ from __future__ import annotations
from dataclasses import dataclass
import re
from urllib.parse import quote
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeAlias
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
try: # pragma: no cover - optional dependency
import requests
@@ -27,8 +27,8 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
ADDON_ID = "plugin.video.viewit"
diff --git a/addon/plugins/einschalten_plugin.py b/addon/plugins/einschalten_plugin.py
index 62f35b5..4ec2fbf 100644
--- a/addon/plugins/einschalten_plugin.py
+++ b/addon/plugins/einschalten_plugin.py
@@ -43,7 +43,7 @@ SETTING_DUMP_HTML = "dump_html_einschalten"
SETTING_SHOW_URL_INFO = "show_url_info_einschalten"
SETTING_LOG_ERRORS = "log_errors_einschalten"
-DEFAULT_BASE_URL = ""
+DEFAULT_BASE_URL = "https://einschalten.in"
DEFAULT_INDEX_PATH = "/"
DEFAULT_NEW_TITLES_PATH = "/movies/new"
DEFAULT_SEARCH_PATH = "/search"
@@ -1079,3 +1079,7 @@ class EinschaltenPlugin(BasisPlugin):
return []
# Backwards compatible: first page only. UI uses paging via `new_titles_page`.
return self.new_titles_page(1)
+
+
+# Alias für die automatische Plugin-Erkennung.
+Plugin = EinschaltenPlugin
diff --git a/addon/plugins/filmpalast_plugin.py b/addon/plugins/filmpalast_plugin.py
index 82c6509..5615a41 100644
--- a/addon/plugins/filmpalast_plugin.py
+++ b/addon/plugins/filmpalast_plugin.py
@@ -11,7 +11,7 @@ from dataclasses import dataclass
import re
from urllib.parse import quote, urlencode
from urllib.parse import urljoin
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, TypeAlias
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
try: # pragma: no cover - optional dependency
import requests
@@ -33,8 +33,8 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
ADDON_ID = "plugin.video.viewit"
@@ -820,11 +820,23 @@ class FilmpalastPlugin(BasisPlugin):
def available_hosters_for(self, title: str, season: str, episode: str) -> List[str]:
detail_url = self._detail_url_for_selection(title, season, episode)
- hosters = self._hosters_for_detail_url(detail_url)
- return list(hosters.keys())
+ return self.available_hosters_for_url(detail_url)
def stream_link_for(self, title: str, season: str, episode: str) -> Optional[str]:
detail_url = self._detail_url_for_selection(title, season, episode)
+ return self.stream_link_for_url(detail_url)
+
+ def episode_url_for(self, title: str, season: str, episode: str) -> str:
+ detail_url = self._detail_url_for_selection(title, season, episode)
+ return (detail_url or "").strip()
+
+ def available_hosters_for_url(self, episode_url: str) -> List[str]:
+ detail_url = (episode_url or "").strip()
+ hosters = self._hosters_for_detail_url(detail_url)
+ return list(hosters.keys())
+
+ def stream_link_for_url(self, episode_url: str) -> Optional[str]:
+ detail_url = (episode_url or "").strip()
if not detail_url:
return None
hosters = self._hosters_for_detail_url(detail_url)
@@ -922,3 +934,7 @@ class FilmpalastPlugin(BasisPlugin):
_log_url_event(redirected, kind="FINAL")
return redirected
return None
+
+
+# Alias für die automatische Plugin-Erkennung.
+Plugin = FilmpalastPlugin
diff --git a/addon/plugins/serienstream_plugin.py b/addon/plugins/serienstream_plugin.py
index d2f67f3..e516120 100644
--- a/addon/plugins/serienstream_plugin.py
+++ b/addon/plugins/serienstream_plugin.py
@@ -17,7 +17,8 @@ import os
import re
import time
import unicodedata
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, TypeAlias
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+from urllib.parse import quote
try: # pragma: no cover - optional dependency
import requests
@@ -49,14 +50,15 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
SETTING_BASE_URL = "serienstream_base_url"
DEFAULT_BASE_URL = "https://s.to"
DEFAULT_PREFERRED_HOSTERS = ["voe"]
DEFAULT_TIMEOUT = 20
+SEARCH_TIMEOUT = 8
ADDON_ID = "plugin.video.viewit"
GLOBAL_SETTING_LOG_URLS = "debug_log_urls"
GLOBAL_SETTING_DUMP_HTML = "debug_dump_html"
@@ -75,6 +77,9 @@ HEADERS = {
SESSION_CACHE_TTL_SECONDS = 300
SESSION_CACHE_PREFIX = "viewit.serienstream"
SESSION_CACHE_MAX_TITLE_URLS = 800
+CATALOG_SEARCH_TTL_SECONDS = 600
+CATALOG_SEARCH_CACHE_KEY = "catalog_index"
+_CATALOG_INDEX_MEMORY: tuple[float, List["SeriesResult"]] = (0.0, [])
@dataclass
@@ -111,6 +116,57 @@ class SeasonInfo:
episodes: List[EpisodeInfo]
+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
+
+ title_tag = soup.select_one("h1")
+ title = (title_tag.get_text(" ", strip=True) if title_tag else "").strip()
+ if title:
+ info["title"] = title
+
+ description = ""
+ desc_tag = soup.select_one(".series-description .description-text")
+ if desc_tag:
+ description = (desc_tag.get_text(" ", strip=True) or "").strip()
+ if not description:
+ meta_desc = soup.select_one("meta[property='og:description'], meta[name='description']")
+ if meta_desc:
+ description = (meta_desc.get("content") or "").strip()
+ if description:
+ info["plot"] = description
+
+ poster = ""
+ poster_tag = soup.select_one(
+ ".show-cover-mobile img[data-src], .show-cover-mobile img[src], .col-3 img[data-src], .col-3 img[src]"
+ )
+ if poster_tag:
+ poster = (poster_tag.get("data-src") or poster_tag.get("src") or "").strip()
+ if not poster:
+ for candidate in soup.select("img[data-src], img[src]"):
+ url = (candidate.get("data-src") or candidate.get("src") or "").strip()
+ if "/media/images/channel/" in url:
+ poster = url
+ break
+ if poster:
+ poster = _absolute_url(poster)
+ art["poster"] = poster
+ art["thumb"] = poster
+
+ fanart = ""
+ fanart_tag = soup.select_one("meta[property='og:image']")
+ if fanart_tag:
+ fanart = (fanart_tag.get("content") or "").strip()
+ if fanart:
+ fanart = _absolute_url(fanart)
+ art["fanart"] = fanart
+ art["landscape"] = fanart
+
+ return info, art
+
+
def _get_base_url() -> str:
base = get_setting_string(ADDON_ID, SETTING_BASE_URL, default=DEFAULT_BASE_URL).strip()
if not base:
@@ -400,20 +456,222 @@ def _extract_genre_names_from_html(body: str) -> List[str]:
return names
+def _strip_tags(value: str) -> str:
+ return re.sub(r"<[^>]+>", " ", value or "")
+
+
+def _search_series_api(query: str) -> List[SeriesResult]:
+ query = (query or "").strip()
+ if not query:
+ return []
+ _ensure_requests()
+ sess = get_requests_session("serienstream", headers=HEADERS)
+ terms = [query]
+ if " " in query:
+ # Fallback: einzelne Tokens liefern in der API oft bessere Treffer.
+ terms.extend([token for token in query.split() if token])
+ seen_urls: set[str] = set()
+ for term in terms:
+ try:
+ response = sess.get(
+ f"{_get_base_url()}/api/search/suggest",
+ params={"term": term},
+ headers=HEADERS,
+ timeout=SEARCH_TIMEOUT,
+ )
+ response.raise_for_status()
+ except Exception:
+ continue
+ try:
+ payload = response.json()
+ except Exception:
+ continue
+ shows = payload.get("shows") if isinstance(payload, dict) else None
+ if not isinstance(shows, list):
+ continue
+ results: List[SeriesResult] = []
+ for item in shows:
+ if not isinstance(item, dict):
+ continue
+ title = (item.get("name") or "").strip()
+ href = (item.get("url") or "").strip()
+ if not title or not href:
+ continue
+ url_abs = _absolute_url(href)
+ if not url_abs or url_abs in seen_urls:
+ continue
+ if "/staffel-" in url_abs or "/episode-" in url_abs:
+ continue
+ seen_urls.add(url_abs)
+ results.append(SeriesResult(title=title, description="", url=url_abs))
+ if not results:
+ continue
+ filtered = [entry for entry in results if _matches_query(query, title=entry.title)]
+ if filtered:
+ return filtered
+ # Falls nur Token-Suche möglich war, zumindest die Ergebnisse liefern.
+ if term != query:
+ return results
+ return []
+
+
+def _search_series_server(query: str) -> List[SeriesResult]:
+ if not query:
+ return []
+ api_results = _search_series_api(query)
+ if api_results:
+ return api_results
+ base = _get_base_url()
+ search_url = f"{base}/search?q={quote(query)}"
+ alt_url = f"{base}/suche?q={quote(query)}"
+ for url in (search_url, alt_url):
+ try:
+ body = _get_html_simple(url)
+ except Exception:
+ continue
+ if not body:
+ continue
+ soup = BeautifulSoup(body, "html.parser")
+ root = soup.select_one(".search-results-list")
+ if root is None:
+ continue
+ seen_urls: set[str] = set()
+ results: List[SeriesResult] = []
+ for card in root.select(".cover-card"):
+ anchor = card.select_one("a[href*='/serie/']")
+ if not anchor:
+ continue
+ href = (anchor.get("href") or "").strip()
+ url_abs = _absolute_url(href)
+ if not url_abs or url_abs in seen_urls:
+ continue
+ if "/staffel-" in url_abs or "/episode-" in url_abs:
+ continue
+ title_tag = card.select_one(".show-title") or card.select_one("h3") or card.select_one("h4")
+ title = (title_tag.get_text(" ", strip=True) if title_tag else anchor.get_text(" ", strip=True)).strip()
+ if not title:
+ continue
+ seen_urls.add(url_abs)
+ results.append(SeriesResult(title=title, description="", url=url_abs))
+ if results:
+ return results
+ return []
+
+
+def _extract_catalog_index_from_html(body: str) -> List[SeriesResult]:
+ items: List[SeriesResult] = []
+ if not body:
+ return items
+ seen_urls: set[str] = set()
+ item_re = re.compile(
+ r"]*class=[\"'][^\"']*series-item[^\"']*[\"'][^>]*>(.*?)",
+ re.IGNORECASE | re.DOTALL,
+ )
+ anchor_re = re.compile(r"]+href=[\"']([^\"']+)[\"'][^>]*>(.*?)", re.IGNORECASE | re.DOTALL)
+ data_search_re = re.compile(r"data-search=[\"']([^\"']*)[\"']", re.IGNORECASE)
+ for match in item_re.finditer(body):
+ block = match.group(0)
+ inner = match.group(1) or ""
+ anchor_match = anchor_re.search(inner)
+ if not anchor_match:
+ continue
+ href = (anchor_match.group(1) or "").strip()
+ url = _absolute_url(href)
+ if not url or "/serie/" not in url or "/staffel-" in url or "/episode-" in url:
+ continue
+ if url in seen_urls:
+ continue
+ seen_urls.add(url)
+ title_raw = anchor_match.group(2) or ""
+ title = unescape(re.sub(r"\s+", " ", _strip_tags(title_raw))).strip()
+ if not title:
+ continue
+ search_match = data_search_re.search(block)
+ description = (search_match.group(1) or "").strip() if search_match else ""
+ items.append(SeriesResult(title=title, description=description, url=url))
+ return items
+
+
+def _catalog_index_from_soup(soup: BeautifulSoupT) -> List[SeriesResult]:
+ items: List[SeriesResult] = []
+ if not soup:
+ return items
+ seen_urls: set[str] = set()
+ for item in soup.select("li.series-item"):
+ anchor = item.find("a", href=True)
+ if not anchor:
+ continue
+ href = (anchor.get("href") or "").strip()
+ url = _absolute_url(href)
+ if not url or "/serie/" not in url or "/staffel-" in url or "/episode-" in url:
+ continue
+ if url in seen_urls:
+ continue
+ seen_urls.add(url)
+ title = (anchor.get_text(" ", strip=True) or "").strip()
+ if not title:
+ continue
+ description = (item.get("data-search") or "").strip()
+ items.append(SeriesResult(title=title, description=description, url=url))
+ return items
+
+
+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():
+ return list(cached)
+ raw = _session_cache_get(CATALOG_SEARCH_CACHE_KEY)
+ if not isinstance(raw, list):
+ return None
+ items: List[SeriesResult] = []
+ for entry in raw:
+ if not isinstance(entry, list) or len(entry) < 2:
+ continue
+ title = str(entry[0] or "").strip()
+ url = str(entry[1] or "").strip()
+ description = str(entry[2] or "") if len(entry) > 2 else ""
+ if title and url:
+ items.append(SeriesResult(title=title, description=description, url=url))
+ if items:
+ _CATALOG_INDEX_MEMORY = (time.time() + CATALOG_SEARCH_TTL_SECONDS, list(items))
+ return items or 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]] = []
+ for entry in items:
+ if not entry.title or not entry.url:
+ continue
+ payload.append([entry.title, entry.url, entry.description])
+ _session_cache_set(CATALOG_SEARCH_CACHE_KEY, payload, ttl_seconds=CATALOG_SEARCH_TTL_SECONDS)
+
+
def search_series(query: str) -> List[SeriesResult]:
- """Sucht Serien im (/serien)-Katalog (Genre-liste) nach Titel/Alt-Titel."""
+ """Sucht Serien im (/serien)-Katalog nach Titel. Nutzt Cache + Ein-Pass-Filter."""
_ensure_requests()
if not _normalize_search_text(query):
return []
- # Direkter Abruf wie in fetch_serien.py.
+ server_results = _search_series_server(query)
+ if server_results:
+ return [entry for entry in server_results if entry.title and _matches_query(query, title=entry.title)]
+ cached = _load_catalog_index_from_cache()
+ if cached is not None:
+ return [entry for entry in cached if entry.title and _matches_query(query, title=entry.title)]
+
catalog_url = f"{_get_base_url()}/serien?by=genre"
- soup = _get_soup_simple(catalog_url)
- results: List[SeriesResult] = []
- for series in parse_series_catalog(soup).values():
- for entry in series:
- if entry.title and _matches_query(query, title=entry.title):
- results.append(entry)
- return results
+ body = _get_html_simple(catalog_url)
+ items = _extract_catalog_index_from_html(body)
+ if not items:
+ soup = BeautifulSoup(body, "html.parser")
+ items = _catalog_index_from_soup(soup)
+ if items:
+ _store_catalog_index_in_cache(items)
+ return [entry for entry in items if entry.title and _matches_query(query, title=entry.title)]
def parse_series_catalog(soup: BeautifulSoupT) -> Dict[str, List[SeriesResult]]:
@@ -805,6 +1063,7 @@ class SerienstreamPlugin(BasisPlugin):
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.is_available = True
self.unavailable_reason: Optional[str] = None
if not self._requests_available: # pragma: no cover - optional dependency
@@ -851,12 +1110,30 @@ class SerienstreamPlugin(BasisPlugin):
cache_key = title.casefold()
if self._title_url_cache.get(cache_key) != url:
self._title_url_cache[cache_key] = url
- self._save_title_url_cache()
+ self._save_title_url_cache()
+ if url:
return
current = self._series_results.get(title)
if current is None:
self._series_results[title] = SeriesResult(title=title, description=description, url="")
+ @staticmethod
+ def _metadata_cache_key(title: str) -> str:
+ return (title or "").strip().casefold()
+
+ def _series_for_title(self, title: str) -> Optional[SeriesResult]:
+ direct = self._series_results.get(title)
+ if direct and direct.url:
+ return direct
+ lookup_key = (title or "").strip().casefold()
+ for item in self._series_results.values():
+ if item.title.casefold().strip() == lookup_key and item.url:
+ return item
+ cached_url = self._title_url_cache.get(lookup_key, "")
+ if cached_url:
+ return SeriesResult(title=title, description="", url=cached_url)
+ return None
+
@staticmethod
def _season_links_cache_name(series_url: str) -> str:
digest = hashlib.sha1((series_url or "").encode("utf-8")).hexdigest()[:20]
@@ -1274,7 +1551,28 @@ class SerienstreamPlugin(BasisPlugin):
self._season_links_cache[title] = list(session_links)
return list(session_links)
try:
- seasons = scrape_series_detail(series.url, load_episodes=False)
+ series_soup = _get_soup(series.url, session=get_requests_session("serienstream", headers=HEADERS))
+ info_labels, art = _extract_series_metadata(series_soup)
+ if series.description and "plot" not in info_labels:
+ info_labels["plot"] = series.description
+ cache_key = self._metadata_cache_key(title)
+ if info_labels or art:
+ self._series_metadata_cache[cache_key] = (info_labels, art)
+
+ base_series_url = _series_root_url(_extract_canonical_url(series_soup, series.url))
+ season_links = _extract_season_links(series_soup)
+ season_count = _extract_number_of_seasons(series_soup)
+ if season_count and (not season_links or len(season_links) < season_count):
+ existing = {number for number, _ in season_links}
+ for number in range(1, season_count + 1):
+ if number in existing:
+ continue
+ season_url = f"{base_series_url}/staffel-{number}"
+ _log_parsed_url(season_url)
+ season_links.append((number, season_url))
+ season_links.sort(key=lambda item: item[0])
+ seasons = [SeasonInfo(number=number, url=url, episodes=[]) for number, url in season_links]
+ seasons.sort(key=lambda s: s.number)
except Exception as exc: # pragma: no cover - defensive logging
raise RuntimeError(f"Serienstream-Staffeln konnten nicht geladen werden: {exc}") from exc
self._season_links_cache[title] = list(seasons)
@@ -1288,6 +1586,41 @@ 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]]]:
+ title = (title or "").strip()
+ if not title or not self._requests_available:
+ return {}, {}, None
+
+ cache_key = self._metadata_cache_key(title)
+ cached = self._series_metadata_cache.get(cache_key)
+ if cached is not None:
+ info, art = cached
+ return dict(info), dict(art), None
+
+ series = self._series_for_title(title)
+ if series is None or not series.url:
+ info = {"title": title}
+ self._series_metadata_cache[cache_key] = (dict(info), {})
+ return info, {}, None
+
+ info: Dict[str, str] = {"title": title}
+ art: Dict[str, str] = {}
+ if series.description:
+ info["plot"] = series.description
+
+ try:
+ soup = _get_soup(series.url, session=get_requests_session("serienstream", headers=HEADERS))
+ parsed_info, parsed_art = _extract_series_metadata(soup)
+ if parsed_info:
+ info.update(parsed_info)
+ if parsed_art:
+ art.update(parsed_art)
+ except Exception:
+ pass
+
+ self._series_metadata_cache[cache_key] = (dict(info), dict(art))
+ return info, art, None
+
def series_url_for_title(self, title: str) -> str:
title = (title or "").strip()
if not title:
@@ -1443,6 +1776,18 @@ 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 episode_url_for(self, title: str, season: str, episode: str) -> str:
+ cache_key = (title, season)
+ cached = self._episode_label_cache.get(cache_key)
+ if cached:
+ info = cached.get(episode)
+ if info and info.url:
+ return info.url
+ episode_info = self._lookup_episode(title, season, episode)
+ if episode_info and episode_info.url:
+ return episode_info.url
+ return ""
+
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.")
diff --git a/addon/plugins/topstreamfilm_plugin.py b/addon/plugins/topstreamfilm_plugin.py
index 97c9e4b..8915dab 100644
--- a/addon/plugins/topstreamfilm_plugin.py
+++ b/addon/plugins/topstreamfilm_plugin.py
@@ -19,7 +19,7 @@ import hashlib
import os
import re
import json
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeAlias
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
from urllib.parse import urlencode, urljoin
try: # pragma: no cover - optional dependency
@@ -51,13 +51,13 @@ if TYPE_CHECKING: # pragma: no cover
from requests import Session as RequestsSession
from bs4 import BeautifulSoup as BeautifulSoupT # type: ignore[import-not-found]
else: # pragma: no cover
- RequestsSession: TypeAlias = Any
- BeautifulSoupT: TypeAlias = Any
+ RequestsSession = Any
+ BeautifulSoupT = Any
ADDON_ID = "plugin.video.viewit"
SETTING_BASE_URL = "topstream_base_url"
-DEFAULT_BASE_URL = "https://www.meineseite"
+DEFAULT_BASE_URL = "https://topstreamfilm.live"
GLOBAL_SETTING_LOG_URLS = "debug_log_urls"
GLOBAL_SETTING_DUMP_HTML = "debug_dump_html"
GLOBAL_SETTING_SHOW_URL_INFO = "debug_show_url_info"
diff --git a/addon/resources/settings.xml b/addon/resources/settings.xml
index d9f7c76..d75ec60 100644
--- a/addon/resources/settings.xml
+++ b/addon/resources/settings.xml
@@ -1,79 +1,85 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
-
+
+
-
+
+
-
+
+
-
+
+
-
+
+
-
-
-
-
+
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
diff --git a/docs/DEFAULT_ROUTER.md b/docs/DEFAULT_ROUTER.md
index 61a2aed..4503d58 100644
--- a/docs/DEFAULT_ROUTER.md
+++ b/docs/DEFAULT_ROUTER.md
@@ -1,54 +1,49 @@
-# ViewIT – Hauptlogik (`addon/default.py`)
+# ViewIT Hauptlogik (`addon/default.py`)
-Dieses Dokument beschreibt den Einstiegspunkt des Addons und die zentrale Steuerlogik.
+Diese Datei ist der Router des Addons.
+Sie verbindet Kodi UI, Plugin Calls und Playback.
-## Aufgabe der Datei
-`addon/default.py` ist der Router des Addons. Er:
-- lädt die Plugin‑Module dynamisch,
-- stellt die Kodi‑Navigation bereit,
-- übersetzt UI‑Aktionen in Plugin‑Aufrufe,
-- startet die Wiedergabe und verwaltet Playstate/Resume.
+## Kernaufgabe
+- Plugins laden
+- Menues bauen
+- Aktionen auf Plugin Methoden mappen
+- Playback starten
+- Playstate speichern
-## Ablauf (high level)
-1. **Plugin‑Discovery**: Lädt alle `addon/plugins/*.py` (ohne `_`‑Prefix) und instanziiert Klassen, die von `BasisPlugin` erben.
-2. **Navigation**: Baut Kodi‑Listen (Serien/Staffeln/Episoden) auf Basis der Plugin‑Antworten.
-3. **Playback**: Holt Stream‑Links aus dem Plugin und startet die Wiedergabe.
-4. **Playstate**: Speichert Resume‑Daten lokal (`playstate.json`) und setzt `playcount`/Resume‑Infos.
+## Ablauf
+1. Plugin Discovery fuer `addon/plugins/*.py` ohne `_` Prefix.
+2. Navigation fuer Titel, Staffeln und Episoden.
+3. Playback: Link holen, optional aufloesen, abspielen.
+4. Playstate: watched und resume in `playstate.json` schreiben.
-## Routing & Aktionen
-Die Datei arbeitet mit URL‑Parametern (Kodi‑Plugin‑Standard). Typische Aktionen:
-- `search` → Suche über ein Plugin
-- `seasons` → Staffeln für einen Titel
-- `episodes` → Episoden für eine Staffel
-- `play` → Stream‑Link auflösen und abspielen
+## Routing
+Der Router liest Query Parameter aus `sys.argv[2]`.
+Typische Aktionen:
+- `search`
+- `seasons`
+- `episodes`
+- `play_episode`
+- `play_movie`
+- `play_episode_url`
-Die genaue Aktion wird aus den Query‑Parametern gelesen und an das entsprechende Plugin delegiert.
+## Playstate
+- Speicherort: Addon Profilordner, Datei `playstate.json`
+- Key: Plugin + Titel + Staffel + Episode
+- Werte: watched, playcount, resume_position, resume_total
-## Playstate (Resume/Watched)
-- **Speicherort**: `playstate.json` im Addon‑Profilordner.
-- **Key**: Kombination aus Plugin‑Name, Titel, Staffel, Episode.
-- **Verwendung**:
- - `playcount` wird gesetzt, wenn „gesehen“ markiert ist.
- - `resume_position`/`resume_total` werden gesetzt, wenn vorhanden.
+## Wichtige Helper
+- Plugin Loader und Discovery
+- UI Builder fuer ListItems
+- Playstate Load/Save/Merge
+- TMDB Merge mit Source Fallback
-## Wichtige Hilfsfunktionen
-- **Plugin‑Loader**: findet & instanziiert Plugins.
-- **UI‑Helper**: setzt Content‑Type, baut Verzeichnisseinträge.
-- **Playstate‑Helper**: `_load_playstate`, `_save_playstate`, `_apply_playstate_to_info`.
+## Fehlerverhalten
+- Importfehler pro Plugin werden isoliert behandelt.
+- Fehler in einem Plugin sollen das Addon nicht stoppen.
+- User bekommt kurze Fehlermeldungen in Kodi.
-## Fehlerbehandlung
-- Plugin‑Importfehler werden isoliert behandelt, damit das Addon nicht komplett ausfällt.
-- Netzwerk‑Fehler werden in Plugins abgefangen, `default.py` sollte nur saubere Fehlermeldungen weitergeben.
-
-## Debugging
-- Globale Debug‑Settings werden über `addon/resources/settings.xml` gesteuert.
-- Plugins loggen URLs/HTML optional (siehe jeweilige Plugin‑Doku).
-
-## Änderungen & Erweiterungen
-Für neue Aktionen:
-1. Neue Aktion im Router registrieren.
-2. UI‑Einträge passend anlegen.
-3. Entsprechende Plugin‑Methode definieren oder erweitern.
-
-## Hinweis zur Erstellung
-Teile dieser Dokumentation wurden KI‑gestützt erstellt und bei Bedarf manuell angepasst.
+## Erweiterung
+Fuer neue Aktion im Router:
+1. Action im `run()` Handler registrieren.
+2. ListItem mit passenden Parametern bauen.
+3. Zielmethode im Plugin bereitstellen.
diff --git a/docs/PLUGIN_DEVELOPMENT.md b/docs/PLUGIN_DEVELOPMENT.md
index 84e8c96..b167134 100644
--- a/docs/PLUGIN_DEVELOPMENT.md
+++ b/docs/PLUGIN_DEVELOPMENT.md
@@ -1,109 +1,85 @@
-# ViewIT – Entwicklerdoku Plugins (`addon/plugins/*_plugin.py`)
+# ViewIT Plugin Entwicklung (`addon/plugins/*_plugin.py`)
-Diese Doku beschreibt, wie Plugins im ViewIT‑Addon aufgebaut sind und wie neue Provider‑Integrationen entwickelt werden.
+Diese Datei zeigt, wie Plugins im Projekt aufgebaut sind und wie sie mit dem Router zusammenarbeiten.
## Grundlagen
-- Jedes Plugin ist eine einzelne Datei unter `addon/plugins/`.
-- Dateinamen **ohne** `_`‑Prefix werden automatisch geladen.
-- Jede Datei enthält eine Klasse, die von `BasisPlugin` erbt.
+- Ein Plugin ist eine Python Datei in `addon/plugins/`.
+- Dateien mit `_` Prefix werden nicht geladen.
+- Plugin Klasse erbt von `BasisPlugin`.
+- Optional: `Plugin = ` als klarer Einstiegspunkt.
-## Pflicht‑Methoden (BasisPlugin)
-Jedes Plugin muss diese Methoden implementieren:
+## Pflichtmethoden
+Jedes Plugin implementiert:
- `async search_titles(query: str) -> list[str]`
- `seasons_for(title: str) -> list[str]`
- `episodes_for(title: str, season: str) -> list[str]`
-## Vertrag Plugin ↔ Hauptlogik (`default.py`)
-Die Hauptlogik ruft Plugin-Methoden auf und verarbeitet ausschließlich deren Rückgaben.
+## Wichtige optionale Methoden
+- `stream_link_for(...)`
+- `resolve_stream_link(...)`
+- `metadata_for(...)`
+- `available_hosters_for(...)`
+- `series_url_for_title(...)`
+- `remember_series_url(...)`
+- `episode_url_for(...)`
+- `available_hosters_for_url(...)`
+- `stream_link_for_url(...)`
-Wesentliche Rückgaben an die Hauptlogik:
-- `search_titles(...)` → Liste von Titel-Strings für die Trefferliste
-- `seasons_for(...)` → Liste von Staffel-Labels
-- `episodes_for(...)` → Liste von Episoden-Labels
-- `stream_link_for(...)` → Hoster-/Player-Link (nicht zwingend finale Media-URL)
-- `resolve_stream_link(...)` → finale/spielbare URL nach Redirect/Resolver
-- Optional `available_hosters_for(...)` → auswählbare Hoster-Namen im Dialog
-- Optional `series_url_for_title(...)` → stabile Detail-URL pro Titel für Folgeaufrufe
-- Optional `remember_series_url(...)` → Übernahme einer bereits bekannten Detail-URL
+## Film Provider Standard
+Wenn keine echten Staffeln existieren:
+- `seasons_for(title)` gibt `['Film']`
+- `episodes_for(title, 'Film')` gibt `['Stream']`
-Standard für Film-Provider (ohne echte Staffeln):
-- `seasons_for(title)` gibt `["Film"]` zurück
-- `episodes_for(title, "Film")` gibt `["Stream"]` zurück
+## Capabilities
+Ein Plugin kann Features melden ueber `capabilities()`.
+Bekannte Werte:
+- `popular_series`
+- `genres`
+- `latest_episodes`
+- `new_titles`
+- `alpha`
+- `series_catalog`
-## Optionale Features (Capabilities)
-Über `capabilities()` kann das Plugin zusätzliche Funktionen anbieten:
-- `popular_series` → `popular_series()`
-- `genres` → `genres()` + `titles_for_genre(genre)`
-- `latest_episodes` → `latest_episodes(page=1)`
+## Suche
+Aktuelle Regeln fuer Suchtreffer:
+- Match auf Titel
+- Wortbasiert
+- Keine Teilwort Treffer im selben Wort
+- Beschreibungen nicht fuer Match nutzen
-## Empfohlene Struktur
-- Konstanten für URLs/Endpoints (BASE_URL, Pfade, Templates)
-- `requests` + `bs4` optional (fehlt beides, Plugin sollte sauber deaktivieren)
-- Helper‑Funktionen für Parsing und Normalisierung
-- Caches für Such‑, Staffel‑ und Episoden‑Daten
+## Settings
+Pro Plugin meist `*_base_url`.
+Beispiele:
+- `serienstream_base_url`
+- `aniworld_base_url`
+- `einschalten_base_url`
+- `topstream_base_url`
+- `filmpalast_base_url`
+- `doku_streams_base_url`
-## Suche (aktuelle Policy)
-- **Nur Titel‑Matches**
-- **Wortbasierter Match** nach Normalisierung (Lowercase + Nicht‑Alnum → Leerzeichen)
-- Keine Teilwort-Treffer innerhalb eines Wortes (Beispiel: `hund` matcht nicht `thunder`)
-- Keine Beschreibung/Plot/Meta für Matches
+## Playback Flow
+1. Episode oder Film auswaehlen.
+2. Optional Hosterliste anzeigen.
+3. `stream_link_for` oder `stream_link_for_url` aufrufen.
+4. `resolve_stream_link` aufrufen.
+5. Finale URL an Kodi geben.
-## Namensgebung
-- Plugin‑Klassenname: `XxxPlugin`
-- Anzeigename (Property `name`): **mit Großbuchstaben beginnen** (z. B. `Serienstream`, `Einschalten`)
-
-## Settings pro Plugin
-Standard: `*_base_url` (Domain / BASE_URL)
-- Beispiele:
- - `serienstream_base_url`
- - `aniworld_base_url`
- - `einschalten_base_url`
- - `topstream_base_url`
- - `filmpalast_base_url`
-
-## Playback
-- `stream_link_for(...)` implementieren (liefert bevorzugten Hoster-Link).
-- `available_hosters_for(...)` bereitstellen, wenn die Seite mehrere Hoster anbietet.
-- `resolve_stream_link(...)` nach einheitlichem Flow umsetzen:
- 1. Redirects auflösen (falls vorhanden)
- 2. ResolveURL (`resolveurl_backend.resolve`) versuchen
- 3. Bei Fehlschlag auf den besten verfügbaren Link zurückfallen
-- Optional `set_preferred_hosters(...)` unterstützen, damit die Hoster-Auswahl aus der Hauptlogik direkt greift.
-
-## Standard‑Flow (empfohlen)
-1. **Suche**: nur Titel liefern und Titel→Detail-URL mappen.
-2. **Navigation**: `series_url_for_title`/`remember_series_url` unterstützen, damit URLs zwischen Aufrufen stabil bleiben.
-3. **Auswahl Hoster**: Hoster-Namen aus der Detailseite extrahieren und anbieten.
-4. **Playback**: Hoster-Link liefern, danach konsistent über `resolve_stream_link` finalisieren.
-5. **Fallbacks**: bei Layout-Unterschieden defensiv parsen und Logging aktivierbar halten.
-
-## Debugging
-Global gesteuert über Settings:
-- `debug_log_urls`
-- `debug_dump_html`
-- `debug_show_url_info`
-
-Plugins sollten die Helper aus `addon/plugin_helpers.py` nutzen:
+## Logging
+Nutze Helper aus `addon/plugin_helpers.py`:
- `log_url(...)`
- `dump_response_html(...)`
- `notify_url(...)`
-## Template
-`addon/plugins/_template_plugin.py` dient als Startpunkt für neue Provider.
+## Build und Checks
+- ZIP: `./scripts/build_kodi_zip.sh`
+- Addon Ordner: `./scripts/build_install_addon.sh`
+- Manifest: `python3 scripts/generate_plugin_manifest.py`
+- Snapshot Checks: `python3 qa/run_plugin_snapshots.py`
-## Build & Test
-- ZIP bauen: `./scripts/build_kodi_zip.sh`
-- Addon‑Ordner: `./scripts/build_install_addon.sh`
-
-## Beispiel‑Checkliste
-- [ ] `name` korrekt gesetzt
-- [ ] `*_base_url` in Settings vorhanden
-- [ ] Suche matcht nur Titel und wortbasiert
-- [ ] `stream_link_for` + `resolve_stream_link` folgen dem Standard-Flow
-- [ ] Optional: `available_hosters_for` + `set_preferred_hosters` vorhanden
-- [ ] Optional: `series_url_for_title` + `remember_series_url` vorhanden
-- [ ] Fehlerbehandlung und Timeouts vorhanden
-- [ ] Optional: Caches für Performance
-
-## Hinweis zur Erstellung
-Teile dieser Dokumentation wurden KI‑gestützt erstellt und bei Bedarf manuell angepasst.
+## Kurze Checkliste
+- `name` gesetzt und korrekt
+- `*_base_url` in Settings vorhanden
+- Suche liefert nur passende Titel
+- Playback Methoden vorhanden
+- Fehler und Timeouts behandelt
+- Cache nur da, wo er Zeit spart
diff --git a/docs/PLUGIN_MANIFEST.json b/docs/PLUGIN_MANIFEST.json
new file mode 100644
index 0000000..07f73d4
--- /dev/null
+++ b/docs/PLUGIN_MANIFEST.json
@@ -0,0 +1,104 @@
+{
+ "schema_version": 1,
+ "plugins": [
+ {
+ "file": "addon/plugins/aniworld_plugin.py",
+ "module": "aniworld_plugin",
+ "name": "Aniworld",
+ "class": "AniworldPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "genres",
+ "latest_episodes",
+ "popular_series"
+ ],
+ "prefer_source_metadata": false,
+ "base_url_setting": "aniworld_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ },
+ {
+ "file": "addon/plugins/dokustreams_plugin.py",
+ "module": "dokustreams_plugin",
+ "name": "Doku-Streams",
+ "class": "DokuStreamsPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "genres",
+ "popular_series"
+ ],
+ "prefer_source_metadata": true,
+ "base_url_setting": "doku_streams_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ },
+ {
+ "file": "addon/plugins/einschalten_plugin.py",
+ "module": "einschalten_plugin",
+ "name": "Einschalten",
+ "class": "EinschaltenPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "genres",
+ "new_titles"
+ ],
+ "prefer_source_metadata": false,
+ "base_url_setting": "einschalten_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ },
+ {
+ "file": "addon/plugins/filmpalast_plugin.py",
+ "module": "filmpalast_plugin",
+ "name": "Filmpalast",
+ "class": "FilmpalastPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "alpha",
+ "genres",
+ "series_catalog"
+ ],
+ "prefer_source_metadata": false,
+ "base_url_setting": "filmpalast_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ },
+ {
+ "file": "addon/plugins/serienstream_plugin.py",
+ "module": "serienstream_plugin",
+ "name": "Serienstream",
+ "class": "SerienstreamPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "genres",
+ "latest_episodes",
+ "popular_series"
+ ],
+ "prefer_source_metadata": false,
+ "base_url_setting": "serienstream_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ },
+ {
+ "file": "addon/plugins/topstreamfilm_plugin.py",
+ "module": "topstreamfilm_plugin",
+ "name": "Topstreamfilm",
+ "class": "TopstreamfilmPlugin",
+ "version": "1.0.0",
+ "capabilities": [
+ "genres",
+ "popular_series"
+ ],
+ "prefer_source_metadata": false,
+ "base_url_setting": "topstream_base_url",
+ "available": true,
+ "unavailable_reason": null,
+ "error": null
+ }
+ ]
+}
diff --git a/docs/PLUGIN_SYSTEM.md b/docs/PLUGIN_SYSTEM.md
index d4ac5b7..37394ac 100644
--- a/docs/PLUGIN_SYSTEM.md
+++ b/docs/PLUGIN_SYSTEM.md
@@ -1,96 +1,71 @@
-## ViewIt Plugin-System
+# ViewIT Plugin System
-Dieses Dokument beschreibt, wie das Plugin-System von **ViewIt** funktioniert und wie die Community neue Integrationen hinzufügen kann.
+Dieses Dokument beschreibt Laden, Vertrag und Betrieb der Plugins.
-### Überblick
+## Ueberblick
+Der Router laedt Provider Integrationen aus `addon/plugins/*.py`.
+Aktive Plugins werden instanziiert und im UI genutzt.
-ViewIt lädt Provider-Integrationen dynamisch aus `addon/plugins/*.py`. Jede Datei enthält eine Klasse, die von `BasisPlugin` erbt. Beim Start werden alle Plugins instanziiert und nur aktiv genutzt, wenn sie verfügbar sind.
+Relevante Dateien:
+- `addon/default.py`
+- `addon/plugin_interface.py`
+- `docs/DEFAULT_ROUTER.md`
+- `docs/PLUGIN_DEVELOPMENT.md`
-Weitere Details:
-- `docs/DEFAULT_ROUTER.md` (Hauptlogik in `addon/default.py`)
-- `docs/PLUGIN_DEVELOPMENT.md` (Entwicklerdoku für Plugins)
+## Aktuelle Plugins
+- `serienstream_plugin.py`
+- `topstreamfilm_plugin.py`
+- `einschalten_plugin.py`
+- `aniworld_plugin.py`
+- `filmpalast_plugin.py`
+- `dokustreams_plugin.py`
+- `_template_plugin.py` (Vorlage)
-### Aktuelle Plugins
+## Discovery Ablauf
+In `addon/default.py`:
+1. Finde `*.py` in `addon/plugins/`
+2. Ueberspringe Dateien mit `_` Prefix
+3. Importiere Modul
+4. Nutze `Plugin = `, falls vorhanden
+5. Sonst instanziiere `BasisPlugin` Subklassen deterministisch
+6. Ueberspringe Plugins mit `is_available = False`
-- `serienstream_plugin.py` – Serienstream (s.to)
-- `topstreamfilm_plugin.py` – Topstreamfilm
-- `einschalten_plugin.py` – Einschalten
-- `aniworld_plugin.py` – Aniworld
-- `filmpalast_plugin.py` – Filmpalast
-- `_template_plugin.py` – Vorlage für neue Plugins
+## Basis Interface
+`BasisPlugin` definiert den Kern:
+- `search_titles`
+- `seasons_for`
+- `episodes_for`
-### Plugin-Discovery (Ladeprozess)
+Weitere Methoden sind optional und werden nur genutzt, wenn vorhanden.
-Der Loader in `addon/default.py`:
+## Capabilities
+Plugins koennen Features aktiv melden.
+Typische Werte:
+- `popular_series`
+- `genres`
+- `latest_episodes`
+- `new_titles`
+- `alpha`
+- `series_catalog`
-1. Sucht alle `*.py` in `addon/plugins/`
-2. Überspringt Dateien, die mit `_` beginnen
-3. Lädt Module dynamisch
-4. Instanziert Klassen, die von `BasisPlugin` erben
-5. Ignoriert Plugins mit `is_available = False`
+Das UI zeigt nur Menues fuer aktiv gemeldete Features.
-Damit bleiben fehlerhafte Plugins isoliert und blockieren nicht das gesamte Add-on.
+## Metadaten Quelle
+`prefer_source_metadata = True` bedeutet:
+- Quelle zuerst
+- TMDB nur Fallback
-### BasisPlugin – verpflichtende Methoden
+## Stabilitaet
+- Keine Netz Calls im Import Block.
+- Fehler im Plugin muessen lokal behandelt werden.
+- Ein defektes Plugin darf andere Plugins nicht blockieren.
-Definiert in `addon/plugin_interface.py`:
+## Build
+Kodi ZIP bauen:
-- `async search_titles(query: str) -> list[str]`
-- `seasons_for(title: str) -> list[str]`
-- `episodes_for(title: str, season: str) -> list[str]`
-
-### Optionale Features (Capabilities)
-
-Plugins können zusätzliche Features anbieten:
-
-- `capabilities() -> set[str]`
- - `popular_series`: liefert beliebte Serien
- - `genres`: Genre-Liste verfügbar
- - `latest_episodes`: neue Episoden verfügbar
-- `popular_series() -> list[str]`
-- `genres() -> list[str]`
-- `titles_for_genre(genre: str) -> list[str]`
-- `latest_episodes(page: int = 1) -> list[LatestEpisode]` (wenn angeboten)
-
-ViewIt zeigt im UI nur die Features an, die ein Plugin tatsächlich liefert.
-
-### Plugin-Struktur (empfohlen)
-
-Eine Integration sollte typischerweise bieten:
-
-- Konstante `BASE_URL`
-- `search_titles()` mit Provider-Suche
-- `seasons_for()` und `episodes_for()` mit HTML-Parsing
-- `stream_link_for()` optional für direkte Playback-Links
-- Optional: `available_hosters_for()` oder Provider-spezifische Helfer
-
-Als Startpunkt dient `addon/plugins/_template_plugin.py`.
-
-### Community-Erweiterungen (Workflow)
-
-1. Fork/Branch erstellen
-2. Neue Datei unter `addon/plugins/` hinzufügen (z. B. `meinprovider_plugin.py`)
-3. Klasse erstellen, die `BasisPlugin` implementiert
-4. In Kodi testen (ZIP bauen, installieren)
-5. PR öffnen
-
-### Qualitätsrichtlinien
-
-- Keine Netzwerkzugriffe im Import-Top-Level
-- Netzwerkzugriffe nur in Methoden (z. B. `search_titles`)
-- Fehler sauber abfangen und verständliche Fehlermeldungen liefern
-- Kein globaler Zustand, der across instances überrascht
-- Provider-spezifische Parser in Helper-Funktionen kapseln
-
-### Debugging & Logs
-
-Hilfreiche Logs werden nach `userdata/addon_data/plugin.video.viewit/logs/` geschrieben.
-Provider sollten URL-Logging optional halten (Settings).
-
-### ZIP-Build
-
-```
+```bash
./scripts/build_kodi_zip.sh
```
-Das ZIP liegt anschließend unter `dist/plugin.video.viewit-.zip`.
+Ergebnis:
+`dist/plugin.video.viewit-.zip`
diff --git a/qa/plugin_snapshots.json b/qa/plugin_snapshots.json
new file mode 100644
index 0000000..71d5c4d
--- /dev/null
+++ b/qa/plugin_snapshots.json
@@ -0,0 +1,73 @@
+{
+ "snapshots": {
+ "Serienstream::search_titles::trek": [
+ "Star Trek: Lower Decks",
+ "Star Trek: Prodigy",
+ "Star Trek: The Animated Series",
+ "Inside Star Trek",
+ "Raumschiff Enterprise - Star Trek: The Original Series",
+ "Star Trek: Deep Space Nine",
+ "Star Trek: Discovery",
+ "Star Trek: Enterprise",
+ "Star Trek: Picard",
+ "Star Trek: Raumschiff Voyager",
+ "Star Trek: Short Treks",
+ "Star Trek: Starfleet Academy",
+ "Star Trek: Strange New Worlds",
+ "Star Trek: The Next Generation"
+ ],
+ "Aniworld::search_titles::naruto": [
+ "Naruto",
+ "Naruto Shippuden",
+ "Boruto: Naruto Next Generations",
+ "Naruto Spin-Off: Rock Lee & His Ninja Pals"
+ ],
+ "Topstreamfilm::search_titles::matrix": [
+ "Darkdrive – Verschollen in der Matrix",
+ "Matrix Reloaded",
+ "Armitage III: Poly Matrix",
+ "Matrix Resurrections",
+ "Matrix",
+ "Matrix Revolutions",
+ "Matrix Fighters"
+ ],
+ "Einschalten::new_titles_page::1": [
+ "Miracle: Das Eishockeywunder von 1980",
+ "No Escape - Grizzly Night",
+ "Kidnapped: Der Fall Elizabeth Smart",
+ "The Internship",
+ "The Rip",
+ "Die Toten vom Bodensee – Schicksalsrad",
+ "People We Meet on Vacation",
+ "Anaconda",
+ "Even If This Love Disappears Tonight",
+ "Die Stunde der Mutigen",
+ "10DANCE",
+ "SpongeBob Schwammkopf: Piraten Ahoi!",
+ "Ella McCay",
+ "Merv",
+ "Elmo and Mark Rober's Merry Giftmas",
+ "Als mein Vater Weihnachten rettete 2",
+ "Die Fraggles: Der erste Schnee",
+ "Gregs Tagebuch 3: Jetzt reicht's!",
+ "Not Without Hope",
+ "Five Nights at Freddy's 2"
+ ],
+ "Filmpalast::search_titles::trek": [
+ "Star Trek",
+ "Star Trek - Der Film",
+ "Star Trek 2 - Der Zorn des Khan",
+ "Star Trek 9 Der Aufstand",
+ "Star Trek: Nemesis",
+ "Star Trek: Section 31",
+ "Star Trek: Starfleet Academy",
+ "Star Trek: Strange New Worlds"
+ ],
+ "Doku-Streams::search_titles::japan": [
+ "Deutsche im Knast - Japan und die Disziplin",
+ "Die Meerfrauen von Japan",
+ "Japan - Land der Moderne und Tradition",
+ "Japan im Zweiten Weltkrieg - Der Fall des Kaiserreichs"
+ ]
+ }
+}
diff --git a/qa/run_plugin_snapshots.py b/qa/run_plugin_snapshots.py
new file mode 100755
index 0000000..2fdd89d
--- /dev/null
+++ b/qa/run_plugin_snapshots.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Run live snapshot checks for plugins.
+
+Use --update to refresh stored snapshots.
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import importlib.util
+import inspect
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+PLUGIN_DIR = ROOT_DIR / "addon" / "plugins"
+SNAPSHOT_PATH = ROOT_DIR / "qa" / "plugin_snapshots.json"
+
+sys.path.insert(0, str(ROOT_DIR / "addon"))
+
+try:
+ from plugin_interface import BasisPlugin # type: ignore
+except Exception as exc: # pragma: no cover
+ raise SystemExit(f"Failed to import BasisPlugin: {exc}")
+
+CONFIG = [
+ {"plugin": "Serienstream", "method": "search_titles", "args": ["trek"], "max_items": 20},
+ {"plugin": "Aniworld", "method": "search_titles", "args": ["naruto"], "max_items": 20},
+ {"plugin": "Topstreamfilm", "method": "search_titles", "args": ["matrix"], "max_items": 20},
+ {"plugin": "Einschalten", "method": "new_titles_page", "args": [1], "max_items": 20},
+ {"plugin": "Filmpalast", "method": "search_titles", "args": ["trek"], "max_items": 20},
+ {"plugin": "Doku-Streams", "method": "search_titles", "args": ["japan"], "max_items": 20},
+]
+
+
+def _import_module(path: Path):
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"Missing spec for {path}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _discover_plugins() -> dict[str, BasisPlugin]:
+ plugins: dict[str, BasisPlugin] = {}
+ for file_path in sorted(PLUGIN_DIR.glob("*.py")):
+ if file_path.name.startswith("_"):
+ continue
+ module = _import_module(file_path)
+ preferred = getattr(module, "Plugin", None)
+ if inspect.isclass(preferred) and issubclass(preferred, BasisPlugin) and preferred is not BasisPlugin:
+ classes = [preferred]
+ else:
+ classes = [
+ obj
+ for obj in module.__dict__.values()
+ if inspect.isclass(obj) and issubclass(obj, BasisPlugin) and obj is not BasisPlugin
+ ]
+ classes.sort(key=lambda cls: cls.__name__.casefold())
+ for cls in classes:
+ instance = cls()
+ name = str(getattr(instance, "name", "") or "").strip()
+ if name and name not in plugins:
+ plugins[name] = instance
+ return plugins
+
+
+def _normalize_titles(value: Any, max_items: int) -> list[str]:
+ if not value:
+ return []
+ titles = [str(item).strip() for item in list(value) if item and str(item).strip()]
+ seen = set()
+ normalized: list[str] = []
+ for title in titles:
+ key = title.casefold()
+ if key in seen:
+ continue
+ seen.add(key)
+ normalized.append(title)
+ if len(normalized) >= max_items:
+ break
+ return normalized
+
+
+def _snapshot_key(entry: dict[str, Any]) -> str:
+ args = entry.get("args", [])
+ return f"{entry['plugin']}::{entry['method']}::{','.join(str(a) for a in args)}"
+
+
+def _call_method(plugin: BasisPlugin, method_name: str, args: list[Any]):
+ method = getattr(plugin, method_name, None)
+ if not callable(method):
+ raise RuntimeError(f"Method missing: {method_name}")
+ result = method(*args)
+ if asyncio.iscoroutine(result):
+ return asyncio.run(result)
+ return result
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--update", action="store_true")
+ args = parser.parse_args()
+
+ snapshots: dict[str, Any] = {}
+ if SNAPSHOT_PATH.exists():
+ snapshots = json.loads(SNAPSHOT_PATH.read_text(encoding="utf-8"))
+ data = snapshots.get("snapshots", {}) if isinstance(snapshots, dict) else {}
+ if args.update:
+ data = {}
+
+ plugins = _discover_plugins()
+ errors = []
+
+ for entry in CONFIG:
+ plugin_name = entry["plugin"]
+ plugin = plugins.get(plugin_name)
+ if plugin is None:
+ errors.append(f"Plugin missing: {plugin_name}")
+ continue
+ key = _snapshot_key(entry)
+ try:
+ result = _call_method(plugin, entry["method"], entry.get("args", []))
+ normalized = _normalize_titles(result, entry.get("max_items", 20))
+ except Exception as exc:
+ errors.append(f"Snapshot error: {key} ({exc})")
+ if args.update:
+ data[key] = {"error": str(exc)}
+ continue
+ if args.update:
+ data[key] = normalized
+ else:
+ expected = data.get(key)
+ if expected != normalized:
+ errors.append(f"Snapshot mismatch: {key}\nExpected: {expected}\nActual: {normalized}")
+
+ if args.update:
+ SNAPSHOT_PATH.parent.mkdir(parents=True, exist_ok=True)
+ SNAPSHOT_PATH.write_text(json.dumps({"snapshots": data}, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+ if errors:
+ for err in errors:
+ print(err)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/__pycache__/test_einschalten_api.cpython-312.pyc b/scripts/__pycache__/test_einschalten_api.cpython-312.pyc
deleted file mode 100644
index 46a3480..0000000
Binary files a/scripts/__pycache__/test_einschalten_api.cpython-312.pyc and /dev/null differ
diff --git a/scripts/__pycache__/test_tmdb.cpython-312.pyc b/scripts/__pycache__/test_tmdb.cpython-312.pyc
deleted file mode 100644
index 37da5a3..0000000
Binary files a/scripts/__pycache__/test_tmdb.cpython-312.pyc and /dev/null differ
diff --git a/scripts/build_kodi_zip.sh b/scripts/build_kodi_zip.sh
index 4ae5971..96277de 100755
--- a/scripts/build_kodi_zip.sh
+++ b/scripts/build_kodi_zip.sh
@@ -37,6 +37,6 @@ ZIP_PATH="${INSTALL_DIR}/${ZIP_NAME}"
ADDON_DIR="$("${ROOT_DIR}/scripts/build_install_addon.sh" >/dev/null; echo "${INSTALL_DIR}/${ADDON_ID}")"
rm -f "${ZIP_PATH}"
-(cd "${INSTALL_DIR}" && zip -r "${ZIP_NAME}" "$(basename "${ADDON_DIR}")" >/dev/null)
+python3 "${ROOT_DIR}/scripts/zip_deterministic.py" "${ZIP_PATH}" "${ADDON_DIR}" >/dev/null
echo "${ZIP_PATH}"
diff --git a/scripts/build_local_kodi_repo.sh b/scripts/build_local_kodi_repo.sh
index ddedb92..861970d 100755
--- a/scripts/build_local_kodi_repo.sh
+++ b/scripts/build_local_kodi_repo.sh
@@ -21,8 +21,20 @@ fi
mkdir -p "${REPO_DIR}"
+read -r ADDON_ID ADDON_VERSION < <(python3 - "${PLUGIN_ADDON_XML}" <<'PY'
+import sys
+import xml.etree.ElementTree as ET
+
+root = ET.parse(sys.argv[1]).getroot()
+print(root.attrib.get("id", "plugin.video.viewit"), root.attrib.get("version", "0.0.0"))
+PY
+)
+
PLUGIN_ZIP="$("${ROOT_DIR}/scripts/build_kodi_zip.sh")"
-cp -f "${PLUGIN_ZIP}" "${REPO_DIR}/"
+PLUGIN_ZIP_NAME="$(basename "${PLUGIN_ZIP}")"
+PLUGIN_ADDON_DIR_IN_REPO="${REPO_DIR}/${ADDON_ID}"
+mkdir -p "${PLUGIN_ADDON_DIR_IN_REPO}"
+cp -f "${PLUGIN_ZIP}" "${PLUGIN_ADDON_DIR_IN_REPO}/${PLUGIN_ZIP_NAME}"
read -r REPO_ADDON_ID REPO_ADDON_VERSION < <(python3 - "${REPO_ADDON_XML}" <<'PY'
import sys
@@ -73,7 +85,10 @@ PY
REPO_ZIP_NAME="${REPO_ADDON_ID}-${REPO_ADDON_VERSION}.zip"
REPO_ZIP_PATH="${REPO_DIR}/${REPO_ZIP_NAME}"
rm -f "${REPO_ZIP_PATH}"
-(cd "${TMP_DIR}" && zip -r "${REPO_ZIP_PATH}" "${REPO_ADDON_ID}" >/dev/null)
+python3 "${ROOT_DIR}/scripts/zip_deterministic.py" "${REPO_ZIP_PATH}" "${TMP_REPO_ADDON_DIR}" >/dev/null
+REPO_ADDON_DIR_IN_REPO="${REPO_DIR}/${REPO_ADDON_ID}"
+mkdir -p "${REPO_ADDON_DIR_IN_REPO}"
+cp -f "${REPO_ZIP_PATH}" "${REPO_ADDON_DIR_IN_REPO}/${REPO_ZIP_NAME}"
python3 - "${PLUGIN_ADDON_XML}" "${TMP_REPO_ADDON_DIR}/addon.xml" "${REPO_DIR}/addons.xml" <<'PY'
import sys
@@ -107,4 +122,5 @@ echo "Repo built:"
echo " ${REPO_DIR}/addons.xml"
echo " ${REPO_DIR}/addons.xml.md5"
echo " ${REPO_ZIP_PATH}"
-echo " ${REPO_DIR}/$(basename "${PLUGIN_ZIP}")"
+echo " ${PLUGIN_ADDON_DIR_IN_REPO}/${PLUGIN_ZIP_NAME}"
+echo " ${REPO_ADDON_DIR_IN_REPO}/${REPO_ZIP_NAME}"
diff --git a/scripts/generate_plugin_manifest.py b/scripts/generate_plugin_manifest.py
new file mode 100755
index 0000000..fe8d3b9
--- /dev/null
+++ b/scripts/generate_plugin_manifest.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Generate a JSON manifest for addon plugins."""
+from __future__ import annotations
+
+import importlib.util
+import inspect
+import json
+import sys
+from pathlib import Path
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+PLUGIN_DIR = ROOT_DIR / "addon" / "plugins"
+OUTPUT_PATH = ROOT_DIR / "docs" / "PLUGIN_MANIFEST.json"
+
+sys.path.insert(0, str(ROOT_DIR / "addon"))
+
+try:
+ from plugin_interface import BasisPlugin # type: ignore
+except Exception as exc: # pragma: no cover
+ raise SystemExit(f"Failed to import BasisPlugin: {exc}")
+
+
+def _import_module(path: Path):
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"Missing spec for {path}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _collect_plugins():
+ plugins = []
+ for file_path in sorted(PLUGIN_DIR.glob("*.py")):
+ if file_path.name.startswith("_"):
+ continue
+ entry = {
+ "file": str(file_path.relative_to(ROOT_DIR)),
+ "module": file_path.stem,
+ "name": None,
+ "class": None,
+ "version": None,
+ "capabilities": [],
+ "prefer_source_metadata": False,
+ "base_url_setting": None,
+ "available": None,
+ "unavailable_reason": None,
+ "error": None,
+ }
+ try:
+ module = _import_module(file_path)
+ preferred = getattr(module, "Plugin", None)
+ if inspect.isclass(preferred) and issubclass(preferred, BasisPlugin) and preferred is not BasisPlugin:
+ classes = [preferred]
+ else:
+ classes = [
+ obj
+ for obj in module.__dict__.values()
+ if inspect.isclass(obj) and issubclass(obj, BasisPlugin) and obj is not BasisPlugin
+ ]
+ classes.sort(key=lambda cls: cls.__name__.casefold())
+
+ if not classes:
+ entry["error"] = "No plugin classes found"
+ plugins.append(entry)
+ continue
+
+ cls = classes[0]
+ instance = cls()
+ entry["class"] = cls.__name__
+ entry["name"] = str(getattr(instance, "name", "") or "") or None
+ entry["version"] = str(getattr(instance, "version", "0.0.0") or "0.0.0")
+ entry["prefer_source_metadata"] = bool(getattr(instance, "prefer_source_metadata", False))
+ entry["available"] = bool(getattr(instance, "is_available", True))
+ entry["unavailable_reason"] = getattr(instance, "unavailable_reason", None)
+ try:
+ caps = instance.capabilities() # type: ignore[call-arg]
+ entry["capabilities"] = sorted([str(c) for c in caps]) if caps else []
+ except Exception:
+ entry["capabilities"] = []
+
+ entry["base_url_setting"] = getattr(module, "SETTING_BASE_URL", None)
+ except Exception as exc: # pragma: no cover
+ entry["error"] = str(exc)
+ plugins.append(entry)
+
+ plugins.sort(key=lambda item: (item.get("name") or item["module"]).casefold())
+ return plugins
+
+
+def main() -> int:
+ if not PLUGIN_DIR.exists():
+ raise SystemExit("Plugin directory missing")
+ manifest = {
+ "schema_version": 1,
+ "plugins": _collect_plugins(),
+ }
+ OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
+ OUTPUT_PATH.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(str(OUTPUT_PATH))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/zip_deterministic.py b/scripts/zip_deterministic.py
new file mode 100755
index 0000000..f3cea34
--- /dev/null
+++ b/scripts/zip_deterministic.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""Create deterministic zip archives.
+
+Usage:
+ zip_deterministic.py
+
+The archive will include the root directory itself and all files under it.
+"""
+from __future__ import annotations
+
+import os
+import sys
+import time
+import zipfile
+from pathlib import Path
+
+
+def _timestamp() -> tuple[int, int, int, int, int, int]:
+ epoch = os.environ.get("SOURCE_DATE_EPOCH")
+ if epoch:
+ try:
+ value = int(epoch)
+ return time.gmtime(value)[:6]
+ except Exception:
+ pass
+ return (2000, 1, 1, 0, 0, 0)
+
+
+def _iter_files(root: Path):
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = sorted([d for d in dirnames if d != "__pycache__"])
+ for filename in sorted(filenames):
+ if filename.endswith(".pyc"):
+ continue
+ yield Path(dirpath) / filename
+
+
+def _add_file(zf: zipfile.ZipFile, file_path: Path, arcname: str) -> None:
+ info = zipfile.ZipInfo(arcname, date_time=_timestamp())
+ info.compress_type = zipfile.ZIP_DEFLATED
+ info.external_attr = (0o644 & 0xFFFF) << 16
+ with file_path.open("rb") as handle:
+ data = handle.read()
+ zf.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED)
+
+
+def main() -> int:
+ if len(sys.argv) != 3:
+ print("Usage: zip_deterministic.py ")
+ return 2
+
+ zip_path = Path(sys.argv[1]).resolve()
+ root = Path(sys.argv[2]).resolve()
+ if not root.exists() or not root.is_dir():
+ print(f"Missing root dir: {root}")
+ return 2
+
+ base = root.parent
+ zip_path.parent.mkdir(parents=True, exist_ok=True)
+ if zip_path.exists():
+ zip_path.unlink()
+
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ for file_path in sorted(_iter_files(root)):
+ arcname = str(file_path.relative_to(base)).replace(os.sep, "/")
+ _add_file(zf, file_path, arcname)
+
+ print(str(zip_path))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())