MediaShelf/mediashelf/providers/__init__.py
Jess Hallsworth 6a557bcdd9
Implement MediaShelf v1
The application the design describes: Flask + SQLite, Plex for library data,
Tautulli for watch history, report-only.

Structure follows the design's seams. providers/ splits MediaProvider from
HistoryProvider, because on this network library data and watch data live on
different machines and Jellyfin later will have no Tautulli equivalent.
scoring.py implements the reclaim score twice - as a SQL expression for the
live grid (weights change on every slider drag, so storing it would mean
rewriting thousands of rows per drag) and in Python for CSV export and tests,
with a property test over 500 generated rows asserting the two agree.
rules.py compiles saved views to parameterized SQL through a field/operator
whitelist; nothing user-supplied is ever interpolated.

Three properties are enforced by test rather than asserted in prose:

- Ingest is idempotent. Three consecutive full scans leave every count and
  every byte total unchanged. A scanner that double-counts produces a report
  that looks plausible and is wrong.
- Keep marks survive Plex reassigning every rating key in the library. They
  are keyed on content GUID, scoped per library so the Movies and 4K Movies
  copies of the same film mark independently.
- Every config variable the app reads is declared in docker-compose.yml, so
  a variable set in Portainer can never silently do nothing.

Also found and fixed while verifying against a fake Plex+Tautulli pair:
executescript() commits the pending transaction, so migrations needed their
BEGIN/COMMIT inside the script; replaceChildren() renders null as the literal
text "null"; a hash-only URL change does not reload the document, so deep
links needed a hashchange listener; and SQLite ROUND rounds half away from
zero where Python rounds half to even.

73 tests, no live server required.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GVbG48GAXfCZatcmX123Ra
2026-09-07 14:59:03 +00:00

68 lines
2.2 KiB
Python

"""Provider construction and history-source selection."""
from __future__ import annotations
import logging
from .base import ( # noqa: F401
Account,
AuthError,
Coverage,
HistoryProvider,
Item,
Library,
MediaProvider,
Part,
ProviderError,
ServerInfo,
WatchEvent,
)
from .plex import PlexClient, PlexHistoryProvider, PlexProvider
from .tautulli import TautulliClient, TautulliHistoryProvider
log = logging.getLogger(__name__)
def build_media_provider(cfg) -> PlexProvider:
client = PlexClient(
cfg.plex_base_url, cfg.plex_token,
timeout=cfg.plex_timeout_s,
verify_ssl=cfg.plex_verify_ssl,
page_size=cfg.plex_page_size,
request_delay_ms=cfg.plex_request_delay_ms,
)
return PlexProvider(client)
def build_history_provider(cfg, media: PlexProvider):
"""Pick a history source per HISTORY_SOURCE (§4.11).
'auto' prefers Tautulli and falls back to Plex, reporting the reason rather
than degrading silently — a silently degraded score is one that gets trusted
when it shouldn't be. Returns (provider, degraded_reason_or_None).
"""
mode = (cfg.history_source or "auto").lower()
if mode == "plex":
return PlexHistoryProvider(media.client), None
if mode in ("auto", "tautulli"):
if not cfg.tautulli_configured:
if mode == "tautulli":
raise ProviderError("HISTORY_SOURCE=tautulli but Tautulli is not configured")
return PlexHistoryProvider(media.client), "Tautulli is not configured"
client = TautulliClient(
cfg.tautulli_base_url, cfg.tautulli_api_key,
timeout=cfg.tautulli_timeout_s, page_size=cfg.tautulli_page_size,
)
provider = TautulliHistoryProvider(client)
try:
provider.server_info()
return provider, None
except ProviderError as e:
if mode == "tautulli":
raise
log.warning("Tautulli unreachable, falling back to Plex history: %s", e)
return PlexHistoryProvider(media.client), "Tautulli unreachable: %s" % e
raise ProviderError("unknown HISTORY_SOURCE %r" % cfg.history_source)