nightly: playback fast-path, windows asyncio fix, v0.1.56

This commit is contained in:
2026-02-19 14:10:09 +01:00
parent 307df97d74
commit 4409f9432c
8 changed files with 382 additions and 44 deletions

View File

@@ -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]
@@ -1195,7 +1210,16 @@ def _show_plugin_search_results(plugin_name: str, query: str) -> None:
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))
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())
@@ -1347,17 +1371,34 @@ def _discover_plugins() -> dict[str, BasisPlugin]:
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]:
@@ -1403,9 +1444,15 @@ 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)
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()]
@@ -1687,6 +1734,8 @@ def _show_episodes(plugin_name: str, title: str, season: str, series_url: str =
episodes = list(plugin.episodes_for(title, season))
if episodes:
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()
)
@@ -1750,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,
@@ -3155,8 +3218,34 @@ 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:
@@ -3233,10 +3322,14 @@ 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:
@@ -3405,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":