Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,23 @@ Thank you to everyone who has contributed to the project!
<img src="https://contrib.rocks/image?repo=TimilsinaBimal/watchly" />
</a>

### Minimum IMDb rating

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section landed under Contributors. It fits better with the other configuration docs. Please also add a CHANGELOG.md entry.


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.
3 changes: 3 additions & 0 deletions app/api/models/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
3 changes: 3 additions & 0 deletions app/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 7 additions & 0 deletions app/services/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions app/services/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions app/services/recommendation/catalog_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -222,6 +223,9 @@ async def _build_catalog(

logger.debug(f"Returning {len(recommendations)} items for {content_type}")

recommendations = await filter_by_imdb_rating(

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runs after _get_recommendations has already truncated to the row limit, so rows shrink instead of backfilling.

Filtering belongs in the shared pipeline before truncation, alongside genre exclusion and the watched filter. That means more rating lookups per build, so it needs a small shared rating cache. Ratings are not user-specific, so one Redis entry per title serves everyone.

recommendations, content_type, ctx.user_settings.imdb_rating_min
)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few lines down, if cleaned: skips the cache write for an empty row. With a strict threshold that filters a row down to nothing, every request for that row becomes a full cold build plus the Cinemeta calls.

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)

Expand Down
50 changes: 50 additions & 0 deletions app/services/recommendation/imdb_ratings.py
Original file line number Diff line number Diff line change
@@ -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")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app/services/cinemeta_service.py already has a process-wide cinemeta_service with this base URL. A BaseClient per call means a new connection pool and TLS handshake per row.

That service currently uses raw httpx and swallows errors, so it needs a method that raises (ideally by moving it onto BaseClient) — happy for that to be part of this PR.

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):

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clean_meta already drops ids that don't start with tt, so this can't fail for anything that would be served. Same for the finite and 0–10 checks on line 37: Cinemeta doesn't return those values.

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
Comment on lines +28 to +30

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the time this catches the 404, BaseClient has already logged "Non-retryable request failure" at ERROR, so every unrated title produces an error line on every request.

Please count the dropped titles and log one line per row instead. That also leaves a trace when a row comes back short, which is otherwise invisible.

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)}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes imdbRating the real IMDb value only when the filter is on, so the same title shows a different rating to different users. Worth either doing it for everyone or leaving the displayed value alone.


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
Comment on lines +43 to +47

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exists only to keep the per-call client open until every request settles. With a shared client it becomes a plain asyncio.gather.

return [meta for meta in results if meta is not None]
finally:
await client.close()
2 changes: 2 additions & 0 deletions app/static/js/modules/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
1 change: 1 addition & 0 deletions app/static/js/modules/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
];
Expand Down
3 changes: 3 additions & 0 deletions app/static/js/modules/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions app/templates/components/section_config.html
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,13 @@ <h3 class="card-title">Discovery</h3>
</div>
</div>

<div>
<label for="imdbRatingMin" class="field-label">Minimum IMDb rating</label>
<input id="imdbRatingMin" type="number" min="0" max="10" step="0.1"
class="input" placeholder="No minimum">
<p class="field-hint">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.</p>
</div>

<div>
<label for="popularitySelect" class="field-label">Discovery style</label>
<div class="relative">
Expand Down
24 changes: 24 additions & 0 deletions tests/test_account_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions tests/test_configure_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
151 changes: 151 additions & 0 deletions tests/test_imdb_rating_filter.py
Original file line number Diff line number Diff line change
@@ -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)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both catalog tests replace filter_by_imdb_rating, so nothing exercises the real request path. A test for the cache-hit path during a Cinemeta failure would have caught the 500.

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])