Merge nightly into main
This commit is contained in:
508
addon/default.py
508
addon/default.py
@@ -8,6 +8,7 @@ ruft Plugin-Implementierungen auf und startet die Wiedergabe.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
import importlib.util
|
||||
@@ -102,6 +103,13 @@ except ImportError: # pragma: no cover - allow importing outside Kodi (e.g. lin
|
||||
xbmcplugin = _XbmcPluginStub()
|
||||
|
||||
from plugin_interface import BasisPlugin
|
||||
from http_session_pool import close_all_sessions
|
||||
from metadata_utils import (
|
||||
collect_plugin_metadata as _collect_plugin_metadata,
|
||||
merge_metadata as _merge_metadata,
|
||||
metadata_policy as _metadata_policy_impl,
|
||||
needs_tmdb as _needs_tmdb,
|
||||
)
|
||||
from tmdb import TmdbCastMember, fetch_tv_episode_credits, lookup_movie, lookup_tv_season, lookup_tv_season_summary, lookup_tv_show
|
||||
|
||||
PLUGIN_DIR = Path(__file__).with_name("plugins")
|
||||
@@ -116,8 +124,22 @@ _TMDB_LOG_PATH: str | None = None
|
||||
_GENRE_TITLES_CACHE: dict[tuple[str, str], list[str]] = {}
|
||||
_ADDON_INSTANCE = None
|
||||
_PLAYSTATE_CACHE: dict[str, dict[str, object]] | None = None
|
||||
_PLAYSTATE_LOCK = threading.RLock()
|
||||
_TMDB_LOCK = threading.RLock()
|
||||
WATCHED_THRESHOLD = 0.9
|
||||
|
||||
atexit.register(close_all_sessions)
|
||||
|
||||
|
||||
def _tmdb_cache_get(cache: dict, key, default=None):
|
||||
with _TMDB_LOCK:
|
||||
return cache.get(key, default)
|
||||
|
||||
|
||||
def _tmdb_cache_set(cache: dict, key, value) -> None:
|
||||
with _TMDB_LOCK:
|
||||
cache[key] = value
|
||||
|
||||
|
||||
def _tmdb_prefetch_concurrency() -> int:
|
||||
"""Max number of concurrent TMDB lookups when prefetching metadata for lists."""
|
||||
@@ -155,12 +177,19 @@ def _busy_close() -> None:
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _busy_dialog():
|
||||
_busy_open()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_busy_close()
|
||||
def _busy_dialog(message: str = "Bitte warten...", *, heading: str = "Bitte warten"):
|
||||
"""Progress-Dialog statt Spinner, mit kurzem Status-Text."""
|
||||
with _progress_dialog(heading, message) as progress:
|
||||
progress(10, message)
|
||||
|
||||
def _update(step_message: str, percent: int | None = None) -> bool:
|
||||
pct = 50 if percent is None else max(5, min(95, int(percent)))
|
||||
return progress(pct, step_message or message)
|
||||
|
||||
try:
|
||||
yield _update
|
||||
finally:
|
||||
progress(100, "Fertig")
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -202,6 +231,33 @@ def _progress_dialog(heading: str, message: str = ""):
|
||||
pass
|
||||
|
||||
|
||||
def _method_accepts_kwarg(method: object, kwarg_name: str) -> bool:
|
||||
if not callable(method):
|
||||
return False
|
||||
try:
|
||||
signature = inspect.signature(method)
|
||||
except Exception:
|
||||
return False
|
||||
for param in signature.parameters.values():
|
||||
if param.kind == inspect.Parameter.VAR_KEYWORD:
|
||||
return True
|
||||
if param.name == kwarg_name and param.kind in (
|
||||
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
||||
inspect.Parameter.KEYWORD_ONLY,
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _call_plugin_search(plugin: BasisPlugin, query: str, *, progress_callback=None):
|
||||
method = getattr(plugin, "search_titles", None)
|
||||
if not callable(method):
|
||||
raise RuntimeError("Plugin hat keine gueltige search_titles Methode.")
|
||||
if progress_callback is not None and _method_accepts_kwarg(method, "progress_callback"):
|
||||
return method(query, progress_callback=progress_callback)
|
||||
return method(query)
|
||||
|
||||
|
||||
def _get_handle() -> int:
|
||||
return int(sys.argv[1]) if len(sys.argv) > 1 else -1
|
||||
|
||||
@@ -242,52 +298,54 @@ def _playstate_path() -> str:
|
||||
|
||||
def _load_playstate() -> dict[str, dict[str, object]]:
|
||||
global _PLAYSTATE_CACHE
|
||||
if _PLAYSTATE_CACHE is not None:
|
||||
return _PLAYSTATE_CACHE
|
||||
path = _playstate_path()
|
||||
try:
|
||||
if xbmcvfs and xbmcvfs.exists(path):
|
||||
handle = xbmcvfs.File(path)
|
||||
raw = handle.read()
|
||||
handle.close()
|
||||
else:
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
with _PLAYSTATE_LOCK:
|
||||
if _PLAYSTATE_CACHE is not None:
|
||||
return _PLAYSTATE_CACHE
|
||||
path = _playstate_path()
|
||||
try:
|
||||
if xbmcvfs and xbmcvfs.exists(path):
|
||||
handle = xbmcvfs.File(path)
|
||||
raw = handle.read()
|
||||
data = json.loads(raw or "{}")
|
||||
if isinstance(data, dict):
|
||||
normalized: dict[str, dict[str, object]] = {}
|
||||
for key, value in data.items():
|
||||
if isinstance(key, str) and isinstance(value, dict):
|
||||
normalized[key] = dict(value)
|
||||
_PLAYSTATE_CACHE = normalized
|
||||
return normalized
|
||||
except Exception:
|
||||
pass
|
||||
_PLAYSTATE_CACHE = {}
|
||||
return {}
|
||||
handle.close()
|
||||
else:
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
raw = handle.read()
|
||||
data = json.loads(raw or "{}")
|
||||
if isinstance(data, dict):
|
||||
normalized: dict[str, dict[str, object]] = {}
|
||||
for key, value in data.items():
|
||||
if isinstance(key, str) and isinstance(value, dict):
|
||||
normalized[key] = dict(value)
|
||||
_PLAYSTATE_CACHE = normalized
|
||||
return normalized
|
||||
except Exception:
|
||||
pass
|
||||
_PLAYSTATE_CACHE = {}
|
||||
return {}
|
||||
|
||||
|
||||
def _save_playstate(state: dict[str, dict[str, object]]) -> None:
|
||||
global _PLAYSTATE_CACHE
|
||||
_PLAYSTATE_CACHE = state
|
||||
path = _playstate_path()
|
||||
try:
|
||||
payload = json.dumps(state, ensure_ascii=False, sort_keys=True)
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
if xbmcvfs:
|
||||
directory = os.path.dirname(path)
|
||||
if directory and not xbmcvfs.exists(directory):
|
||||
xbmcvfs.mkdirs(directory)
|
||||
handle = xbmcvfs.File(path, "w")
|
||||
handle.write(payload)
|
||||
handle.close()
|
||||
else:
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
with _PLAYSTATE_LOCK:
|
||||
_PLAYSTATE_CACHE = state
|
||||
path = _playstate_path()
|
||||
try:
|
||||
payload = json.dumps(state, ensure_ascii=False, sort_keys=True)
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
if xbmcvfs:
|
||||
directory = os.path.dirname(path)
|
||||
if directory and not xbmcvfs.exists(directory):
|
||||
xbmcvfs.mkdirs(directory)
|
||||
handle = xbmcvfs.File(path, "w")
|
||||
handle.write(payload)
|
||||
except Exception:
|
||||
return
|
||||
handle.close()
|
||||
else:
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write(payload)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def _get_playstate(key: str) -> dict[str, object]:
|
||||
@@ -452,40 +510,18 @@ def _get_setting_int(setting_id: str, *, default: int = 0) -> int:
|
||||
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
|
||||
return _metadata_policy_impl(
|
||||
plugin_name,
|
||||
plugin,
|
||||
allow_tmdb=allow_tmdb,
|
||||
get_setting_int=_get_setting_int,
|
||||
)
|
||||
|
||||
|
||||
def _tmdb_list_enabled() -> bool:
|
||||
@@ -715,11 +751,11 @@ def _tmdb_labels_and_art(title: str) -> tuple[dict[str, str], dict[str, str], li
|
||||
show_cast = _get_setting_bool("tmdb_show_cast", default=False)
|
||||
flags = f"p{int(show_plot)}a{int(show_art)}f{int(show_fanart)}r{int(show_rating)}v{int(show_votes)}c{int(show_cast)}"
|
||||
cache_key = f"{language}|{flags}|{title_key}"
|
||||
cached = _TMDB_CACHE.get(cache_key)
|
||||
cached = _tmdb_cache_get(_TMDB_CACHE, cache_key)
|
||||
if cached is not None:
|
||||
info, art = cached
|
||||
# Cast wird nicht in _TMDB_CACHE gehalten (weil es ListItem.setCast betrifft), daher separat cachen:
|
||||
cast_cached = _TMDB_CAST_CACHE.get(cache_key, [])
|
||||
cast_cached = _tmdb_cache_get(_TMDB_CAST_CACHE, cache_key, [])
|
||||
return info, art, list(cast_cached)
|
||||
|
||||
info_labels: dict[str, str] = {"title": title}
|
||||
@@ -777,7 +813,7 @@ def _tmdb_labels_and_art(title: str) -> tuple[dict[str, str], dict[str, str], li
|
||||
if meta:
|
||||
# Nur TV-IDs cachen (für Staffel-/Episoden-Lookups); Movie-IDs würden dort fehlschlagen.
|
||||
if is_tv:
|
||||
_TMDB_ID_CACHE[title_key] = int(getattr(meta, "tmdb_id", 0) or 0)
|
||||
_tmdb_cache_set(_TMDB_ID_CACHE, title_key, int(getattr(meta, "tmdb_id", 0) or 0))
|
||||
info_labels.setdefault("mediatype", "tvshow")
|
||||
else:
|
||||
info_labels.setdefault("mediatype", "movie")
|
||||
@@ -805,8 +841,8 @@ def _tmdb_labels_and_art(title: str) -> tuple[dict[str, str], dict[str, str], li
|
||||
elif log_requests or log_responses:
|
||||
_tmdb_file_log(f"TMDB MISS title={title!r}")
|
||||
|
||||
_TMDB_CACHE[cache_key] = (info_labels, art)
|
||||
_TMDB_CAST_CACHE[cache_key] = list(cast)
|
||||
_tmdb_cache_set(_TMDB_CACHE, cache_key, (info_labels, art))
|
||||
_tmdb_cache_set(_TMDB_CAST_CACHE, cache_key, list(cast))
|
||||
return info_labels, art, list(cast)
|
||||
|
||||
|
||||
@@ -852,10 +888,10 @@ def _tmdb_episode_labels_and_art(*, title: str, season_label: str, episode_label
|
||||
if not _tmdb_enabled():
|
||||
return {"title": episode_label}, {}
|
||||
title_key = (title or "").strip().casefold()
|
||||
tmdb_id = _TMDB_ID_CACHE.get(title_key)
|
||||
tmdb_id = _tmdb_cache_get(_TMDB_ID_CACHE, title_key)
|
||||
if not tmdb_id:
|
||||
_tmdb_labels_and_art(title)
|
||||
tmdb_id = _TMDB_ID_CACHE.get(title_key)
|
||||
tmdb_id = _tmdb_cache_get(_TMDB_ID_CACHE, title_key)
|
||||
if not tmdb_id:
|
||||
return {"title": episode_label}, {}
|
||||
|
||||
@@ -869,7 +905,7 @@ def _tmdb_episode_labels_and_art(*, title: str, season_label: str, episode_label
|
||||
show_art = _get_setting_bool("tmdb_show_art", default=True)
|
||||
flags = f"p{int(show_plot)}a{int(show_art)}"
|
||||
season_key = (tmdb_id, season_number, language, flags)
|
||||
cached_season = _TMDB_SEASON_CACHE.get(season_key)
|
||||
cached_season = _tmdb_cache_get(_TMDB_SEASON_CACHE, season_key)
|
||||
if cached_season is None:
|
||||
api_key = _get_setting_string("tmdb_api_key").strip()
|
||||
if not api_key:
|
||||
@@ -902,7 +938,7 @@ def _tmdb_episode_labels_and_art(*, title: str, season_label: str, episode_label
|
||||
if show_art and ep.thumb:
|
||||
art = {"thumb": ep.thumb}
|
||||
mapped[ep_no] = (info, art)
|
||||
_TMDB_SEASON_CACHE[season_key] = mapped
|
||||
_tmdb_cache_set(_TMDB_SEASON_CACHE, season_key, mapped)
|
||||
cached_season = mapped
|
||||
|
||||
return cached_season.get(episode_number, ({"title": episode_label}, {}))
|
||||
@@ -916,10 +952,10 @@ def _tmdb_episode_cast(*, title: str, season_label: str, episode_label: str) ->
|
||||
return []
|
||||
|
||||
title_key = (title or "").strip().casefold()
|
||||
tmdb_id = _TMDB_ID_CACHE.get(title_key)
|
||||
tmdb_id = _tmdb_cache_get(_TMDB_ID_CACHE, title_key)
|
||||
if not tmdb_id:
|
||||
_tmdb_labels_and_art(title)
|
||||
tmdb_id = _TMDB_ID_CACHE.get(title_key)
|
||||
tmdb_id = _tmdb_cache_get(_TMDB_ID_CACHE, title_key)
|
||||
if not tmdb_id:
|
||||
return []
|
||||
|
||||
@@ -930,13 +966,13 @@ def _tmdb_episode_cast(*, title: str, season_label: str, episode_label: str) ->
|
||||
|
||||
language = _get_setting_string("tmdb_language").strip() or "de-DE"
|
||||
cache_key = (tmdb_id, season_number, episode_number, language)
|
||||
cached = _TMDB_EPISODE_CAST_CACHE.get(cache_key)
|
||||
cached = _tmdb_cache_get(_TMDB_EPISODE_CAST_CACHE, cache_key)
|
||||
if cached is not None:
|
||||
return list(cached)
|
||||
|
||||
api_key = _get_setting_string("tmdb_api_key").strip()
|
||||
if not api_key:
|
||||
_TMDB_EPISODE_CAST_CACHE[cache_key] = []
|
||||
_tmdb_cache_set(_TMDB_EPISODE_CAST_CACHE, cache_key, [])
|
||||
return []
|
||||
|
||||
log_requests = _get_setting_bool("tmdb_log_requests", default=False)
|
||||
@@ -958,7 +994,7 @@ def _tmdb_episode_cast(*, title: str, season_label: str, episode_label: str) ->
|
||||
f"TMDB ERROR episode_credits_failed tmdb_id={tmdb_id} season={season_number} episode={episode_number} error={exc!r}"
|
||||
)
|
||||
cast = []
|
||||
_TMDB_EPISODE_CAST_CACHE[cache_key] = list(cast)
|
||||
_tmdb_cache_set(_TMDB_EPISODE_CAST_CACHE, cache_key, list(cast))
|
||||
return list(cast)
|
||||
|
||||
|
||||
@@ -1079,52 +1115,6 @@ def _settings_key_for_plugin(name: str) -> str:
|
||||
return f"update_version_{safe}" if safe else "update_version_unknown"
|
||||
|
||||
|
||||
def _collect_plugin_metadata(plugin: BasisPlugin, titles: list[str]) -> dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember] | None]]:
|
||||
getter = getattr(plugin, "metadata_for", None)
|
||||
if not callable(getter):
|
||||
return {}
|
||||
collected: dict[str, tuple[dict[str, str], dict[str, str], list[TmdbCastMember] | None]] = {}
|
||||
for title in titles:
|
||||
try:
|
||||
labels, art, cast = getter(title)
|
||||
except Exception:
|
||||
continue
|
||||
if isinstance(labels, dict) or isinstance(art, dict) or cast:
|
||||
label_map = {str(k): str(v) for k, v in dict(labels or {}).items() if v}
|
||||
art_map = {str(k): str(v) for k, v in dict(art or {}).items() if v}
|
||||
collected[title] = (label_map, art_map, cast if isinstance(cast, list) else None)
|
||||
return collected
|
||||
|
||||
|
||||
def _needs_tmdb(labels: dict[str, str], art: dict[str, str], *, want_plot: bool, want_art: bool) -> bool:
|
||||
if want_plot and not labels.get("plot"):
|
||||
return True
|
||||
if want_art and not (art.get("thumb") or art.get("poster") or art.get("fanart") or art.get("landscape")):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _merge_metadata(
|
||||
title: str,
|
||||
tmdb_labels: dict[str, str] | None,
|
||||
tmdb_art: dict[str, str] | None,
|
||||
tmdb_cast: list[TmdbCastMember] | None,
|
||||
plugin_meta: tuple[dict[str, str], dict[str, str], list[TmdbCastMember] | None] | None,
|
||||
) -> tuple[dict[str, str], dict[str, str], list[TmdbCastMember] | None]:
|
||||
labels = dict(tmdb_labels or {})
|
||||
art = dict(tmdb_art or {})
|
||||
cast = tmdb_cast
|
||||
if plugin_meta is not None:
|
||||
meta_labels, meta_art, meta_cast = plugin_meta
|
||||
labels.update({k: str(v) for k, v in dict(meta_labels or {}).items() if v})
|
||||
art.update({k: str(v) for k, v in dict(meta_art or {}).items() if v})
|
||||
if meta_cast is not None:
|
||||
cast = meta_cast
|
||||
if "title" not in labels:
|
||||
labels["title"] = title
|
||||
return labels, art, cast
|
||||
|
||||
|
||||
def _sync_update_version_settings() -> None:
|
||||
addon = _get_addon()
|
||||
addon_version = "0.0.0"
|
||||
@@ -1236,7 +1226,11 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
|
||||
try:
|
||||
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)
|
||||
plugin_progress = lambda msg="", pct=None: progress( # noqa: E731 - kompakte Callback-Bruecke
|
||||
max(5, min(95, int(pct))) if pct is not None else 20,
|
||||
f"{plugin_name} (1/1) {str(msg or 'Suche...').strip()}",
|
||||
)
|
||||
search_coro = _call_plugin_search(plugin, query, progress_callback=plugin_progress)
|
||||
try:
|
||||
results = _run_async(search_coro)
|
||||
except Exception:
|
||||
@@ -1246,7 +1240,7 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
results = [str(t).strip() for t in (results or []) if t and str(t).strip()]
|
||||
results = _clean_search_titles([str(t).strip() for t in (results or []) if t and str(t).strip()])
|
||||
results.sort(key=lambda value: value.casefold())
|
||||
|
||||
use_source, show_tmdb, prefer_source = _metadata_policy(
|
||||
@@ -1438,6 +1432,33 @@ def _series_url_params(plugin: BasisPlugin, title: str) -> dict[str, str]:
|
||||
return {"series_url": series_url} if series_url else {}
|
||||
|
||||
|
||||
def _clean_search_titles(values: list[str]) -> list[str]:
|
||||
"""Filtert offensichtliche Platzhalter und dedupliziert Treffer."""
|
||||
blocked = {
|
||||
"stream",
|
||||
"streams",
|
||||
"film",
|
||||
"movie",
|
||||
"play",
|
||||
"details",
|
||||
"details/play",
|
||||
}
|
||||
cleaned: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in values:
|
||||
title = (raw or "").strip()
|
||||
if not title:
|
||||
continue
|
||||
key = title.casefold()
|
||||
if key in blocked:
|
||||
continue
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cleaned.append(title)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _show_search() -> None:
|
||||
_log("Suche gestartet.")
|
||||
dialog = xbmcgui.Dialog()
|
||||
@@ -1470,7 +1491,11 @@ def _show_search_results(query: str) -> None:
|
||||
canceled = progress(range_start, f"{plugin_name} ({plugin_index}/{total_plugins}) Suche...")
|
||||
if canceled:
|
||||
break
|
||||
search_coro = plugin.search_titles(query)
|
||||
plugin_progress = lambda msg="", pct=None: progress( # noqa: E731 - kompakte Callback-Bruecke
|
||||
max(range_start, min(range_end, int(pct))) if pct is not None else range_start + 20,
|
||||
f"{plugin_name} ({plugin_index}/{total_plugins}) {str(msg or 'Suche...').strip()}",
|
||||
)
|
||||
search_coro = _call_plugin_search(plugin, query, progress_callback=plugin_progress)
|
||||
try:
|
||||
results = _run_async(search_coro)
|
||||
except Exception as exc:
|
||||
@@ -1481,7 +1506,7 @@ def _show_search_results(query: str) -> None:
|
||||
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()]
|
||||
results = _clean_search_titles([str(t).strip() for t in (results or []) if t and str(t).strip()])
|
||||
_log(f"Treffer ({plugin_name}): {len(results)}", xbmc.LOGDEBUG)
|
||||
use_source, show_tmdb, prefer_source = _metadata_policy(
|
||||
plugin_name, plugin, allow_tmdb=_tmdb_enabled()
|
||||
@@ -1565,6 +1590,73 @@ def _show_search_results(query: str) -> None:
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
|
||||
|
||||
def _movie_seed_for_title(plugin: BasisPlugin, title: str, seasons: list[str]) -> tuple[str, str] | None:
|
||||
"""Ermittelt ein Film-Seed (Season/Episode), um direkt Provider anzeigen zu können."""
|
||||
if not seasons or len(seasons) != 1:
|
||||
return None
|
||||
season = str(seasons[0] or "").strip()
|
||||
if not season:
|
||||
return None
|
||||
try:
|
||||
episodes = [str(value or "").strip() for value in (plugin.episodes_for(title, season) or [])]
|
||||
except Exception:
|
||||
return None
|
||||
episodes = [value for value in episodes if value]
|
||||
if len(episodes) != 1:
|
||||
return None
|
||||
episode = episodes[0]
|
||||
season_key = season.casefold()
|
||||
episode_key = episode.casefold()
|
||||
title_key = (title or "").strip().casefold()
|
||||
generic_seasons = {"film", "movie", "stream"}
|
||||
generic_episodes = {"stream", "film", "play", title_key}
|
||||
if season_key in generic_seasons and episode_key in generic_episodes:
|
||||
return (season, episode)
|
||||
return None
|
||||
|
||||
|
||||
def _show_movie_streams(
|
||||
plugin_name: str,
|
||||
title: str,
|
||||
season: str,
|
||||
episode: str,
|
||||
*,
|
||||
series_url: str = "",
|
||||
) -> None:
|
||||
handle = _get_handle()
|
||||
plugin = _discover_plugins().get(plugin_name)
|
||||
if plugin is None:
|
||||
xbmcgui.Dialog().notification("Streams", "Quelle nicht gefunden.", xbmcgui.NOTIFICATION_INFO, 3000)
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
return
|
||||
|
||||
if series_url:
|
||||
remember_series_url = getattr(plugin, "remember_series_url", None)
|
||||
if callable(remember_series_url):
|
||||
try:
|
||||
remember_series_url(title, series_url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
xbmcplugin.setPluginCategory(handle, f"{title} - Streams")
|
||||
_set_content(handle, "videos")
|
||||
|
||||
base_params = {"plugin": plugin_name, "title": title, "season": season, "episode": episode}
|
||||
if series_url:
|
||||
base_params["series_url"] = series_url
|
||||
|
||||
# Hoster bleiben im Auswahldialog der Wiedergabe (wie bisher).
|
||||
_add_directory_item(
|
||||
handle,
|
||||
title,
|
||||
"play_episode",
|
||||
dict(base_params),
|
||||
is_folder=False,
|
||||
info_labels={"title": title, "mediatype": "movie"},
|
||||
)
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
|
||||
|
||||
def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
handle = _get_handle()
|
||||
_log(f"Staffeln laden: {plugin_name} / {title}")
|
||||
@@ -1581,60 +1673,6 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Einschalten liefert Filme. Für Playback soll nach dem Öffnen des Titels direkt ein
|
||||
# einzelnes abspielbares Item angezeigt werden: <Titel> -> (<Titel> abspielbar).
|
||||
# Wichtig: ohne zusätzliche Netzwerkanfragen (sonst bleibt Kodi ggf. im Busy-Spinner hängen).
|
||||
if (plugin_name or "").casefold() == "einschalten" and _get_setting_bool("einschalten_enable_playback", default=False):
|
||||
xbmcplugin.setPluginCategory(handle, title)
|
||||
_set_content(handle, "movies")
|
||||
playstate = _title_playstate(plugin_name, title)
|
||||
info_labels: dict[str, object] = {"title": title, "mediatype": "movie"}
|
||||
info_labels = _apply_playstate_to_info(info_labels, playstate)
|
||||
display_label = _label_with_playstate(title, playstate)
|
||||
movie_params = {"plugin": plugin_name, "title": title}
|
||||
if series_url:
|
||||
movie_params["series_url"] = series_url
|
||||
_add_directory_item(
|
||||
handle,
|
||||
display_label,
|
||||
"play_movie",
|
||||
movie_params,
|
||||
is_folder=False,
|
||||
info_labels=info_labels,
|
||||
)
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
return
|
||||
|
||||
# Optional: Plugins können schnell (ohne Detail-Request) sagen, ob ein Titel ein Film ist.
|
||||
# Dann zeigen wir direkt ein einzelnes abspielbares Item: <Titel> -> (<Titel>).
|
||||
is_movie = getattr(plugin, "is_movie", None)
|
||||
if callable(is_movie):
|
||||
try:
|
||||
if bool(is_movie(title)):
|
||||
xbmcplugin.setPluginCategory(handle, title)
|
||||
_set_content(handle, "movies")
|
||||
playstate = _title_playstate(plugin_name, title)
|
||||
info_labels: dict[str, object] = {"title": title, "mediatype": "movie"}
|
||||
info_labels = _apply_playstate_to_info(info_labels, playstate)
|
||||
display_label = _label_with_playstate(title, playstate)
|
||||
movie_params = {"plugin": plugin_name, "title": title}
|
||||
if series_url:
|
||||
movie_params["series_url"] = series_url
|
||||
else:
|
||||
movie_params.update(_series_url_params(plugin, title))
|
||||
_add_directory_item(
|
||||
handle,
|
||||
display_label,
|
||||
"play_movie",
|
||||
movie_params,
|
||||
is_folder=False,
|
||||
info_labels=info_labels,
|
||||
)
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
use_source, show_tmdb, _prefer_source = _metadata_policy(
|
||||
plugin_name, plugin, allow_tmdb=_tmdb_enabled()
|
||||
)
|
||||
@@ -1644,7 +1682,7 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
meta_getter = getattr(plugin, "metadata_for", None)
|
||||
if use_source and callable(meta_getter):
|
||||
try:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Metadaten werden geladen..."):
|
||||
meta_labels, meta_art, meta_cast = meta_getter(title)
|
||||
if isinstance(meta_labels, dict):
|
||||
title_info_labels = {str(k): str(v) for k, v in meta_labels.items() if v}
|
||||
@@ -1664,6 +1702,26 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
return
|
||||
|
||||
movie_seed = _movie_seed_for_title(plugin, title, seasons)
|
||||
if movie_seed is not None:
|
||||
# Dieser Action-Pfad wurde als Verzeichnis aufgerufen. Ohne endOfDirectory()
|
||||
# bleibt Kodi im Busy-Zustand, auch wenn wir direkt in die Wiedergabe springen.
|
||||
try:
|
||||
xbmcplugin.endOfDirectory(handle, succeeded=False)
|
||||
except Exception:
|
||||
try:
|
||||
xbmcplugin.endOfDirectory(handle)
|
||||
except Exception:
|
||||
pass
|
||||
_play_episode(
|
||||
plugin_name,
|
||||
title,
|
||||
movie_seed[0],
|
||||
movie_seed[1],
|
||||
series_url=series_url,
|
||||
)
|
||||
return
|
||||
|
||||
count = len(seasons)
|
||||
suffix = "Staffel" if count == 1 else "Staffeln"
|
||||
xbmcplugin.setPluginCategory(handle, f"{title} ({count} {suffix})")
|
||||
@@ -1684,8 +1742,8 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
art: dict[str, str] | None = None
|
||||
season_number = _extract_first_int(season)
|
||||
if api_key and season_number is not None:
|
||||
cache_key = (_TMDB_ID_CACHE.get((title or "").strip().casefold(), 0), season_number, language, flags)
|
||||
cached = _TMDB_SEASON_SUMMARY_CACHE.get(cache_key)
|
||||
cache_key = (_tmdb_cache_get(_TMDB_ID_CACHE, (title or "").strip().casefold(), 0), season_number, language, flags)
|
||||
cached = _tmdb_cache_get(_TMDB_SEASON_SUMMARY_CACHE, cache_key)
|
||||
if cached is None and cache_key[0]:
|
||||
try:
|
||||
meta = lookup_tv_season_summary(
|
||||
@@ -1708,7 +1766,7 @@ def _show_seasons(plugin_name: str, title: str, series_url: str = "") -> None:
|
||||
if show_art and meta.poster:
|
||||
art_map = {"thumb": meta.poster, "poster": meta.poster}
|
||||
cached = (labels, art_map)
|
||||
_TMDB_SEASON_SUMMARY_CACHE[cache_key] = cached
|
||||
_tmdb_cache_set(_TMDB_SEASON_SUMMARY_CACHE, cache_key, cached)
|
||||
if cached is not None:
|
||||
info_labels, art = cached
|
||||
merged_labels = dict(info_labels or {})
|
||||
@@ -1774,7 +1832,7 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
|
||||
meta_getter = getattr(plugin, "metadata_for", None)
|
||||
if callable(meta_getter):
|
||||
try:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Episoden-Metadaten werden geladen..."):
|
||||
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}
|
||||
@@ -1787,7 +1845,7 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
|
||||
|
||||
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():
|
||||
with _busy_dialog("Episoden werden aufbereitet..."):
|
||||
for episode in episodes:
|
||||
if show_tmdb:
|
||||
info_labels, art = _tmdb_episode_labels_and_art(
|
||||
@@ -2018,7 +2076,7 @@ def _show_category_titles_page(plugin_name: str, category: str, page: int = 1) -
|
||||
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():
|
||||
with _busy_dialog("Genre-Liste wird geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2134,7 +2192,7 @@ def _show_genre_titles_page(plugin_name: str, genre: str, page: int = 1) -> 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:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Genre-Seite wird geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2285,7 +2343,7 @@ def _show_alpha_titles_page(plugin_name: str, letter: str, page: int = 1) -> Non
|
||||
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():
|
||||
with _busy_dialog("A-Z Liste wird geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2397,7 +2455,7 @@ def _show_series_catalog(plugin_name: str, page: int = 1) -> 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:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("A-Z Seite wird geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2632,7 +2690,7 @@ def _show_popular(plugin_name: str | None = None, page: int = 1) -> 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:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Beliebte Titel werden geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2780,7 +2838,7 @@ def _show_new_titles(plugin_name: str, page: int = 1) -> 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:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Neue Titel werden geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -2846,7 +2904,7 @@ def _show_latest_episodes(plugin_name: str, page: int = 1) -> None:
|
||||
_set_content(handle, "episodes")
|
||||
|
||||
try:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Neueste Episoden werden geladen..."):
|
||||
entries = list(getter(page) or [])
|
||||
except Exception as exc:
|
||||
_log(f"Neueste Folgen fehlgeschlagen ({plugin_name}): {exc}", xbmc.LOGWARNING)
|
||||
@@ -2951,7 +3009,7 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
|
||||
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():
|
||||
with _busy_dialog("Genre-Gruppe wird geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -3039,7 +3097,7 @@ def _show_genre_series_group(plugin_name: str, genre: str, group_code: str, page
|
||||
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():
|
||||
with _busy_dialog("Genre-Serien werden geladen..."):
|
||||
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 ({}, {}, [])
|
||||
@@ -3237,12 +3295,29 @@ def _track_playback_and_update_state(key: str) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _track_playback_and_update_state_async(key: str) -> None:
|
||||
"""Startet Playstate-Tracking im Hintergrund, damit die UI nicht blockiert."""
|
||||
key = (key or "").strip()
|
||||
if not key:
|
||||
return
|
||||
|
||||
def _worker() -> None:
|
||||
try:
|
||||
_track_playback_and_update_state(key)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
worker = threading.Thread(target=_worker, name="viewit-playstate-tracker", daemon=True)
|
||||
worker.start()
|
||||
|
||||
|
||||
def _play_episode(
|
||||
plugin_name: str,
|
||||
title: str,
|
||||
season: str,
|
||||
episode: str,
|
||||
*,
|
||||
forced_hoster: str = "",
|
||||
episode_url: str = "",
|
||||
series_url: str = "",
|
||||
resolve_handle: int | None = None,
|
||||
@@ -3281,16 +3356,22 @@ def _play_episode(
|
||||
hoster_getter = getattr(plugin, "available_hosters_for", None)
|
||||
if callable(hoster_getter):
|
||||
try:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Hoster werden geladen..."):
|
||||
available_hosters = list(hoster_getter(title, season, episode) or [])
|
||||
except Exception as exc:
|
||||
_log(f"Hoster laden fehlgeschlagen ({plugin_name}): {exc}", xbmc.LOGWARNING)
|
||||
|
||||
selected_hoster: str | None = None
|
||||
forced_hoster = (forced_hoster or "").strip()
|
||||
if available_hosters:
|
||||
if len(available_hosters) == 1:
|
||||
if forced_hoster:
|
||||
for hoster in available_hosters:
|
||||
if hoster.casefold() == forced_hoster.casefold():
|
||||
selected_hoster = hoster
|
||||
break
|
||||
if selected_hoster is None and len(available_hosters) == 1:
|
||||
selected_hoster = available_hosters[0]
|
||||
else:
|
||||
elif selected_hoster is None:
|
||||
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)
|
||||
@@ -3335,7 +3416,7 @@ def _play_episode(
|
||||
cast=cast,
|
||||
resolve_handle=resolve_handle,
|
||||
)
|
||||
_track_playback_and_update_state(
|
||||
_track_playback_and_update_state_async(
|
||||
_playstate_key(plugin_name=plugin_name, title=title, season=season, episode=episode)
|
||||
)
|
||||
|
||||
@@ -3365,7 +3446,7 @@ def _play_episode_url(
|
||||
hoster_getter = getattr(plugin, "available_hosters_for_url", None)
|
||||
if callable(hoster_getter):
|
||||
try:
|
||||
with _busy_dialog():
|
||||
with _busy_dialog("Hoster werden geladen..."):
|
||||
available_hosters = list(hoster_getter(episode_url) or [])
|
||||
except Exception as exc:
|
||||
_log(f"Hoster laden fehlgeschlagen ({plugin_name}): {exc}", xbmc.LOGWARNING)
|
||||
@@ -3423,7 +3504,7 @@ def _play_episode_url(
|
||||
cast=cast,
|
||||
resolve_handle=resolve_handle,
|
||||
)
|
||||
_track_playback_and_update_state(
|
||||
_track_playback_and_update_state_async(
|
||||
_playstate_key(plugin_name=plugin_name, title=title, season=season_label, episode=episode_label)
|
||||
)
|
||||
|
||||
@@ -3523,6 +3604,7 @@ def run() -> None:
|
||||
params.get("title", ""),
|
||||
params.get("season", ""),
|
||||
params.get("episode", ""),
|
||||
forced_hoster=params.get("hoster", ""),
|
||||
episode_url=params.get("url", ""),
|
||||
series_url=params.get("series_url", ""),
|
||||
resolve_handle=_get_handle(),
|
||||
|
||||
Reference in New Issue
Block a user