diff --git a/README.md b/README.md index 34423993..bdaad09d 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,23 @@ Thank you to everyone who has contributed to the project! +### Minimum IMDb rating + +In configuration, set **Minimum IMDb rating** (0–10, in 0.1 increments), or leave +it blank to disable the filter. The inclusive minimum applies to all movie and +series rows, including trending fallbacks and rewatch picks. Titles without an +IMDb ID or a valid IMDb rating are excluded while filtering is enabled. + +Ratings come from Stremio Cinemeta, rather than TMDB vote averages. Filtering +happens after recommendation selection, so restrictive thresholds can shorten +rows. Enabled filtering also checks cached rows and requires Cinemeta network +requests; an upstream failure does not silently return unfiltered results or +write a partially filtered catalog to cache. With filtering disabled, existing +rating display and recommendation behavior are unchanged. + +The token API accepts `imdb_rating_min: null` (disabled) or a finite number from +0 through 10. Existing configurations default to disabled. + ## Acknowledgements Special thanks to **[The Movie Database (TMDB)](https://www.themoviedb.org/)** for the rich metadata that powers Watchly's recommendations, and to **Trakt** and **Simkl** for their history APIs. diff --git a/app/api/models/tokens.py b/app/api/models/tokens.py index ce541b3b..5c54d557 100644 --- a/app/api/models/tokens.py +++ b/app/api/models/tokens.py @@ -19,6 +19,9 @@ class TokenRequest(BaseModel): popularity: Literal["mainstream", "balanced", "gems", "all"] = Field( default="balanced", description="Popularity for TMDB API" ) + imdb_rating_min: float | None = Field( + default=None, ge=0, le=10, allow_inf_nan=False, description="Minimum IMDb rating; None disables filtering" + ) year_min: int = Field(default=DEFAULT_YEAR_MIN, description="Minimum release year for TMDB API") year_max: int | None = Field(default=None, description="Latest release year; omit for through today") sorting_order: Literal["default", "movies_first", "series_first"] = Field( diff --git a/app/core/settings.py b/app/core/settings.py index 0a214e14..95f9392f 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -113,6 +113,9 @@ class UserSettings(BaseModel): poster_rating: PosterRatingConfig | None = Field(default=None, description="Poster rating provider configuration") excluded_movie_genres: list[str] = Field(default_factory=list) excluded_series_genres: list[str] = Field(default_factory=list) + imdb_rating_min: float | None = Field( + default=None, ge=0, le=10, allow_inf_nan=False, description="Minimum IMDb rating; None disables filtering" + ) year_min: int = Field(default=DEFAULT_YEAR_MIN, description="Minimum release year") year_max: int | None = Field(default=None, description="Latest release year; None means through today") popularity: Literal["mainstream", "balanced", "gems", "all"] = Field( diff --git a/app/services/auth.py b/app/services/auth.py index 0f08a970..dc0a36db 100644 --- a/app/services/auth.py +++ b/app/services/auth.py @@ -21,6 +21,7 @@ from app.services.stremio.service import StremioBundle from app.services.token_store import token_store from app.services.trakt import trakt_service +from app.services.user_cache import user_cache KeyedConfigT = TypeVar("KeyedConfigT", LLMConfig, PosterRatingConfig) @@ -390,6 +391,11 @@ async def create_user_token(self, payload: TokenRequest) -> tuple[TokenResponse, except Exception as e: logger.warning(f"[{redact_token(token)}] Failed to invalidate caches on source change: {e}") + # Rows are cached already filtered, so a changed threshold can't be + # re-applied to them: lowering it would never bring titles back. + if (existing_data.get("settings") or {}).get("imdb_rating_min") != user_settings.imdb_rating_min: + await user_cache.invalidate_all_catalogs(token) + # 5. Build response base_url = settings.HOST_NAME manifest_url = f"{base_url}/{token}/manifest.json" @@ -427,6 +433,7 @@ def unmasked(field: str, value: str | None) -> str | None: poster_rating=self._unmask_nested_key(payload.poster_rating, stored.get("poster_rating")), excluded_movie_genres=payload.excluded_movie_genres, excluded_series_genres=payload.excluded_series_genres, + imdb_rating_min=payload.imdb_rating_min, year_min=payload.year_min, year_max=payload.year_max, popularity=payload.popularity, diff --git a/app/services/dashboard.py b/app/services/dashboard.py index 979445fe..73db8513 100644 --- a/app/services/dashboard.py +++ b/app/services/dashboard.py @@ -50,6 +50,7 @@ async def get_data(self, token: str) -> dict[str, Any] | None: "settings": { "language": user_settings.language, "popularity": user_settings.popularity, + "imdb_rating_min": user_settings.imdb_rating_min, "year_min": user_settings.year_min, "year_max": user_settings.year_max, "sorting_order": user_settings.sorting_order, diff --git a/app/services/recommendation/catalog_service.py b/app/services/recommendation/catalog_service.py index d51e28dd..59b4136b 100644 --- a/app/services/recommendation/catalog_service.py +++ b/app/services/recommendation/catalog_service.py @@ -18,6 +18,7 @@ from app.services.recommendation.all_based import AllBasedService from app.services.recommendation.catalog_utils import clean_meta, shuffle_data_if_needed from app.services.recommendation.creators import CreatorsService +from app.services.recommendation.imdb_ratings import filter_by_imdb_rating from app.services.recommendation.item_based import ItemBasedService from app.services.recommendation.rewatch import RewatchService from app.services.recommendation.theme_based import ThemeBasedService @@ -222,6 +223,9 @@ async def _build_catalog( logger.debug(f"Returning {len(recommendations)} items for {content_type}") + recommendations = await filter_by_imdb_rating( + recommendations, content_type, ctx.user_settings.imdb_rating_min + ) cleaned = [m for m in (clean_meta(m) for m in recommendations) if m is not None] cleaned = shuffle_data_if_needed(ctx.user_settings, catalog_id, cleaned) diff --git a/app/services/recommendation/imdb_ratings.py b/app/services/recommendation/imdb_ratings.py new file mode 100644 index 00000000..f7427849 --- /dev/null +++ b/app/services/recommendation/imdb_ratings.py @@ -0,0 +1,50 @@ +import asyncio +import math +import re +from typing import Any + +import httpx + +from app.core.base_client import BaseClient +from app.core.constants import DEFAULT_CONCURRENCY_LIMIT + + +async def filter_by_imdb_rating( + metas: list[dict[str, Any]], content_type: str, minimum: float | None +) -> list[dict[str, Any]]: + if minimum is None or not metas: + return metas + + client = BaseClient(base_url="https://v3-cinemeta.strem.io") + semaphore = asyncio.Semaphore(DEFAULT_CONCURRENCY_LIMIT) + + async def rated_meta(meta: dict[str, Any]) -> dict[str, Any] | None: + imdb_id = meta.get("imdb_id") or meta.get("id") or "" + if not re.fullmatch(r"tt\d+", imdb_id): + return None + async with semaphore: + try: + response = await client.get(f"/meta/{content_type}/{imdb_id}.json") + except httpx.HTTPStatusError as exc: + if exc.response.status_code == 404: + return None + raise + raw_rating = (response.get("meta") or {}).get("imdbRating") + try: + rating = float(raw_rating) + except (TypeError, ValueError): + return None + if not math.isfinite(rating) or not 0 <= rating <= 10 or rating < minimum: + return None + # The existing imdbRating field contains TMDB votes until replaced here. + return {**meta, "imdbRating": str(rating)} + + try: + # Wait for all requests before closing their shared client, even on failure. + results = await asyncio.gather(*(rated_meta(meta) for meta in metas), return_exceptions=True) + for result in results: + if isinstance(result, BaseException): + raise result + return [meta for meta in results if meta is not None] + finally: + await client.close() diff --git a/app/static/js/modules/auth.js b/app/static/js/modules/auth.js index 60d754b7..9606c440 100644 --- a/app/static/js/modules/auth.js +++ b/app/static/js/modules/auth.js @@ -519,6 +519,8 @@ async function fetchIdentity(payload) { if (s.language && languageSelect) languageSelect.value = s.language; // Popularity & Year Range + const imdbRatingMin = document.getElementById('imdbRatingMin'); + if (imdbRatingMin) imdbRatingMin.value = s.imdb_rating_min ?? ''; const popularitySelect = document.getElementById('popularitySelect'); const yearMinInput = document.getElementById('yearMin'); const yearMaxInput = document.getElementById('yearMax'); diff --git a/app/static/js/modules/dashboard.js b/app/static/js/modules/dashboard.js index 9c1d8167..e9a965f5 100644 --- a/app/static/js/modules/dashboard.js +++ b/app/static/js/modules/dashboard.js @@ -250,6 +250,7 @@ function renderSettings(s) { const fields = [ ['Discovery', POPULARITY_LABELS[s.popularity] || s.popularity], ['Language', s.language], + ['Minimum IMDb rating', s.imdb_rating_min ?? 'Off'], ['Years', `${s.year_min}–${s.year_max ?? 'now'}`], ['Sorting', SORTING_LABELS[s.sorting_order] || s.sorting_order], ]; diff --git a/app/static/js/modules/form.js b/app/static/js/modules/form.js index 2d149543..6523094e 100644 --- a/app/static/js/modules/form.js +++ b/app/static/js/modules/form.js @@ -68,6 +68,7 @@ function getRequestPayload() { const catalogs = appState ? appState.catalogs : []; const authKey = (document.getElementById('authKey')?.value || '').trim() || undefined; const hasSelectedProfile = !!(document.getElementById('stremioProfileId')?.value && authKey); + const imdbRatingMin = document.getElementById('imdbRatingMin')?.value; return { authKey, @@ -84,6 +85,7 @@ function getRequestPayload() { rows: catalog.rows })), language: languageSelect?.value || 'english', + imdb_rating_min: imdbRatingMin ? Number(imdbRatingMin) : null, year_min: parseInt(document.getElementById('yearMin')?.value || String(YEAR_RANGE_DEFAULTS.min), 10), // The slider's right end means "through today", stored as null so it never // turns into a hard cap when the year rolls over. @@ -132,6 +134,7 @@ function buildTokenPayload(formData) { password: formData.password, catalogs: formData.catalogs, language: formData.language, + imdb_rating_min: formData.imdb_rating_min, year_min: formData.year_min, year_max: formData.year_max, popularity: formData.popularity, diff --git a/app/templates/components/section_config.html b/app/templates/components/section_config.html index 1d8f1451..d8ade10d 100644 --- a/app/templates/components/section_config.html +++ b/app/templates/components/section_config.html @@ -135,6 +135,13 @@

Discovery

+
+ + +

Leave blank to disable. Applies to all movie and series rows, including rewatch picks. Unrated titles are excluded when enabled. Strict filters may shorten rows.

+
+
diff --git a/tests/test_account_identity.py b/tests/test_account_identity.py index 69667b3e..c0a2d640 100644 --- a/tests/test_account_identity.py +++ b/tests/test_account_identity.py @@ -193,6 +193,30 @@ def test_signups_disabled_still_updates_existing_account(monkeypatch): assert response.token == "tok_existing" +@pytest.mark.parametrize( + ("old", "new", "cleared"), + [(None, 7.5, True), (8, 7, True), (7.5, None, True), (7.5, 7.5, False), (None, None, False)], +) +def test_changed_imdb_minimum_clears_cached_catalogs(monkeypatch, old, new, cleared): + fake = setup_fakes(monkeypatch) + seed_account(fake, "tok_existing", "2024-01-01T00:00:00+00:00", identities={"trakt": "trakt-bob"}) + key = "watchly:token:tok_existing" + blob = json.loads(fake.data[key]) + blob["settings"].update(watch_history_source="trakt", imdb_rating_min=old) + fake.data[key] = json.dumps(blob) + invalidated = [] + + async def record(token): + invalidated.append(token) + + monkeypatch.setattr("app.services.auth.user_cache.invalidate_all_catalogs", record) + payload = TokenRequest(trakt_access_token="t-abc", watch_history_source="trakt", imdb_rating_min=new) + + asyncio.run(AuthService().create_user_token(payload)) + + assert invalidated == (["tok_existing"] if cleared else []) + + def test_legacy_stremio_account_keeps_its_token(monkeypatch): fake = setup_fakes(monkeypatch, stremio_identity=("user123", "user@example.com", "authkey-1")) # Pre-identity-index account: token IS the Stremio user id, no index entry. diff --git a/tests/test_configure_page.py b/tests/test_configure_page.py index bd29b07a..1f6b81ad 100644 --- a/tests/test_configure_page.py +++ b/tests/test_configure_page.py @@ -25,6 +25,7 @@ async def fake_count_users(): assert 'window.YEAR_RANGE_DEFAULTS = {"min": 1970, "max": ' in html assert "window.MAX_ITEM_ROWS = 3;" in html assert '"rows": 1' in html + assert 'id="imdbRatingMin" type="number" min="0" max="10" step="0.1"' in html assert 'id="yearMin" min="1970"' in html assert 'id="yearMax" min="1970"' in html diff --git a/tests/test_imdb_rating_filter.py b/tests/test_imdb_rating_filter.py new file mode 100644 index 00000000..44d4ca66 --- /dev/null +++ b/tests/test_imdb_rating_filter.py @@ -0,0 +1,151 @@ +import asyncio +import time +from types import SimpleNamespace + +import httpx +import pytest +from pydantic import ValidationError + +from app.api.models.tokens import TokenRequest +from app.core.settings import UserSettings +from app.services.auth import AuthService +from app.services.recommendation import catalog_service as cs +from app.services.recommendation import imdb_ratings + + +@pytest.mark.parametrize("value", [-0.1, 10.1, float("nan"), float("inf")]) +def test_invalid_minimum_is_rejected(value): + for model in (TokenRequest, UserSettings): + with pytest.raises(ValidationError): + model(catalogs=[], imdb_rating_min=value) + + +@pytest.mark.parametrize("value", [None, 0, 7.5, 10]) +def test_minimum_survives_settings_round_trip(value): + payload = TokenRequest(imdb_rating_min=value) + settings = AuthService()._build_user_settings(payload) + assert UserSettings.model_validate(settings.model_dump()).imdb_rating_min == value + + +def test_disabled_filter_makes_no_requests(monkeypatch): + def unexpected_client(**kwargs): + pytest.fail("Disabled filter must not create a client") + + monkeypatch.setattr(imdb_ratings, "BaseClient", unexpected_client) + metas = [{"id": "tt1", "imdbRating": "8.9"}] + assert asyncio.run(imdb_ratings.filter_by_imdb_rating(metas, "movie", None)) is metas + + +@pytest.mark.parametrize("content_type", ["movie", "series"]) +def test_filter_uses_imdb_inclusive_boundary_and_preserves_order(monkeypatch, content_type): + ratings = {"tt1": "7.4", "tt2": "7.5", "tt3": "9.1", "tt4": None, "tt5": "N/A", "tt6": "nan", "tt7": "11"} + calls = [] + closed = [] + + class Client: + def __init__(self, **kwargs): + pass + + async def get(self, path): + calls.append(path) + return {"meta": {"imdbRating": ratings[path.split("/")[-1].split(".")[0]]}} + + async def close(self): + closed.append(True) + + monkeypatch.setattr(imdb_ratings, "BaseClient", Client) + metas = [{"id": key, "imdbRating": "10"} for key in ratings] + [{"id": "tmdb:99"}] + result = asyncio.run(imdb_ratings.filter_by_imdb_rating(metas, content_type, 7.5)) + assert [m["id"] for m in result] == ["tt2", "tt3"] + assert result[0]["imdbRating"] == "7.5" + assert metas[1]["imdbRating"] == "10" + assert all(path.startswith(f"/meta/{content_type}/") for path in calls) + assert closed == [True] + + +@pytest.mark.parametrize("status", [404, 503]) +def test_missing_metadata_excluded_but_outages_raise_and_close(monkeypatch, status): + closed = [] + + class Client: + def __init__(self, **kwargs): + pass + + async def get(self, path): + response = httpx.Response(status, request=httpx.Request("GET", "https://example.com")) + response.raise_for_status() + + async def close(self): + closed.append(True) + + monkeypatch.setattr(imdb_ratings, "BaseClient", Client) + + def run(): + return asyncio.run(imdb_ratings.filter_by_imdb_rating([{"id": "tt1"}], "movie", 7)) + + if status == 404: + assert run() == [] + else: + with pytest.raises(httpx.HTTPStatusError): + run() + assert closed == [True] + + +def test_cached_catalog_is_served_without_rating_requests(monkeypatch): + cached_body = {"metas": [{"id": "tt1"}, {"id": "tt2"}]} + + async def alias(token): + return token + + async def credentials(token): + return {"settings": UserSettings(catalogs=[], imdb_rating_min=7.5).model_dump()} + + async def cached(*args): + return cached_body, int(time.time()) + + async def filter_metas(*args): + pytest.fail("Cached rows are already filtered; a hit must not call Cinemeta") + + monkeypatch.setattr(cs.settings, "AUTO_UPDATE_CATALOGS", False) + monkeypatch.setattr(cs.token_store, "resolve_alias", alias) + monkeypatch.setattr(cs.token_store, "get_user_data", credentials) + monkeypatch.setattr(cs.user_cache, "get_catalog", cached) + monkeypatch.setattr(cs, "filter_by_imdb_rating", filter_metas) + data, _ = asyncio.run(cs.CatalogService().get_catalog("token", "series", "watchly.rewatch")) + assert data["metas"] == [{"id": "tt1"}, {"id": "tt2"}] + + +@pytest.mark.parametrize("outage", [False, True]) +def test_cold_catalog_filters_before_cache_write(monkeypatch, outage): + service = cs.CatalogService() + settings = UserSettings(catalogs=[], imdb_rating_min=7.5) + ctx = SimpleNamespace(token="token", user_settings=settings, library=None) + writes = [] + + async def resolve(*args): + return "watchly.rec" + + async def profile(*args): + return SimpleNamespace(source="stremio"), set(), set() + + async def recommendations(**kwargs): + return [{"id": "tt1", "type": "movie", "name": "Low"}, {"id": "tt2", "type": "movie", "name": "High"}] + + async def filter_metas(metas, content_type, minimum): + assert minimum == 7.5 + if outage: + raise httpx.ConnectError("Cinemeta unavailable") + return metas[1:] + + async def write(*args): + writes.append(args[3]) + + monkeypatch.setattr(service, "_resolve_slot", resolve) + monkeypatch.setattr(service, "_initialize_services", lambda _: {"profile": None}) + monkeypatch.setattr(service, "_get_recommendations", recommendations) + monkeypatch.setattr(cs.user_cache, "get_profile_and_watched_sets", profile) + monkeypatch.setattr(cs.user_cache, "set_catalog", write) + monkeypatch.setattr(cs, "filter_by_imdb_rating", filter_metas) + data, _ = asyncio.run(service._build_catalog(ctx, "movie", "watchly.rec", {})) + assert [m["id"] for m in data["metas"]] == ([] if outage else ["tt2"]) + assert writes == ([] if outage else [data])