Spaces:
Paused
Paused
Merge pull request #44 from PNRxA/feat/trakt
Browse files- README.md +3 -2
- api/.env.example +5 -1
- api/src/config.rs +14 -3
- api/src/image/serve.rs +1 -0
- api/src/lib.rs +2 -0
- api/src/main.rs +8 -0
- api/src/services/mod.rs +1 -0
- api/src/services/ratings.rs +94 -5
- api/src/services/retry.rs +7 -0
- api/src/services/trakt.rs +79 -0
- api/tests/common/mod.rs +2 -0
README.md
CHANGED
|
@@ -179,7 +179,7 @@ The `?imageSize=` parameter controls the output dimensions. When omitted, `mediu
|
|
| 179 |
|
| 180 |
## Features
|
| 181 |
|
| 182 |
-
- **Multi-source ratings** — Aggregates from MDBList (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL) and optionally
|
| 183 |
- **Multiple image sources** — Uses TMDB as the primary source for posters, logos, and backdrops, with Fanart.tv as an optional fallback (or preferred source). Supports language selection and textless posters from both sources
|
| 184 |
- **Configurable per API key** — Override image source, language, and textless settings per key, or set global defaults
|
| 185 |
- **ID resolution** — Accepts IMDb, TMDB, or TVDB IDs
|
|
@@ -212,7 +212,7 @@ docker compose up -d
|
|
| 212 |
- Rust toolchain
|
| 213 |
- Node.js 20.19+ (for admin UI)
|
| 214 |
- A [TMDB API key](https://www.themoviedb.org/settings/api)
|
| 215 |
-
- At least one of: [MDBList API key](https://mdblist.com/preferences/) (preferred — covers all 7 rating sources), [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
| 216 |
- Optional: [Fanart.tv API key](https://fanart.tv/get-an-api-key/) (enables Fanart.tv as an alternative or preferred image source)
|
| 217 |
|
| 218 |
|
|
@@ -248,6 +248,7 @@ See [docker-compose.yml](docker-compose.yml) for the full compose configuration.
|
|
| 248 |
| `JWT_SECRET` | *required* | 32-byte hex string (`openssl rand -hex 32`) |
|
| 249 |
| `MDBLIST_API_KEY` | — | MDBList key — preferred, covers all 7 rating sources (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL) |
|
| 250 |
| `OMDB_API_KEY` | — | OMDb key (IMDb, RT Critics, Metacritic only) |
|
|
|
|
| 251 |
| `LISTEN_ADDR` | `0.0.0.0:3000` | Server bind address |
|
| 252 |
| `CACHE_DIR` | `./cache` | Poster and metadata cache directory |
|
| 253 |
| `DB_DIR` | `./db` | SQLite database directory |
|
|
|
|
| 179 |
|
| 180 |
## Features
|
| 181 |
|
| 182 |
+
- **Multi-source ratings** — Aggregates from MDBList (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL), optionally OMDb, and optionally Trakt directly (for episode-level ratings and as a standalone provider)
|
| 183 |
- **Multiple image sources** — Uses TMDB as the primary source for posters, logos, and backdrops, with Fanart.tv as an optional fallback (or preferred source). Supports language selection and textless posters from both sources
|
| 184 |
- **Configurable per API key** — Override image source, language, and textless settings per key, or set global defaults
|
| 185 |
- **ID resolution** — Accepts IMDb, TMDB, or TVDB IDs
|
|
|
|
| 212 |
- Rust toolchain
|
| 213 |
- Node.js 20.19+ (for admin UI)
|
| 214 |
- A [TMDB API key](https://www.themoviedb.org/settings/api)
|
| 215 |
+
- At least one of: [MDBList API key](https://mdblist.com/preferences/) (preferred — covers all 7 rating sources), [OMDb API key](https://www.omdbapi.com/apikey.aspx), [Trakt Client ID](https://trakt.tv/oauth/applications)
|
| 216 |
- Optional: [Fanart.tv API key](https://fanart.tv/get-an-api-key/) (enables Fanart.tv as an alternative or preferred image source)
|
| 217 |
|
| 218 |
|
|
|
|
| 248 |
| `JWT_SECRET` | *required* | 32-byte hex string (`openssl rand -hex 32`) |
|
| 249 |
| `MDBLIST_API_KEY` | — | MDBList key — preferred, covers all 7 rating sources (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL) |
|
| 250 |
| `OMDB_API_KEY` | — | OMDb key (IMDb, RT Critics, Metacritic only) |
|
| 251 |
+
| `TRAKT_CLIENT_ID` | — | [Trakt](https://trakt.tv/oauth/applications) Client ID — provides Trakt community ratings for movies, shows, and episodes |
|
| 252 |
| `LISTEN_ADDR` | `0.0.0.0:3000` | Server bind address |
|
| 253 |
| `CACHE_DIR` | `./cache` | Poster and metadata cache directory |
|
| 254 |
| `DB_DIR` | `./db` | SQLite database directory |
|
api/.env.example
CHANGED
|
@@ -6,7 +6,7 @@ TMDB_API_KEY=your_tmdb_v3_api_key
|
|
| 6 |
# https://fanart.tv/get-an-api-key/
|
| 7 |
FANART_API_KEY=your_fanart_api_key
|
| 8 |
|
| 9 |
-
# At least one of OMDB_API_KEY or
|
| 10 |
# MDBList is the preferred provider — it covers all 7 rating sources
|
| 11 |
# (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL).
|
| 12 |
# OMDb only covers IMDb, RT Critics, and Metacritic.
|
|
@@ -15,6 +15,10 @@ MDBLIST_API_KEY=your_mdblist_api_key
|
|
| 15 |
# OMDb API key (optional) — https://www.omdbapi.com/apikey.aspx
|
| 16 |
# Required for IMDB episode ratings (MDBList does not support episode-level ratings)
|
| 17 |
OMDB_API_KEY=your_omdb_api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Directory to store cached posters and metadata
|
| 20 |
CACHE_DIR=./cache
|
|
|
|
| 6 |
# https://fanart.tv/get-an-api-key/
|
| 7 |
FANART_API_KEY=your_fanart_api_key
|
| 8 |
|
| 9 |
+
# At least one of OMDB_API_KEY, MDBLIST_API_KEY, or TRAKT_CLIENT_ID must be set for ratings.
|
| 10 |
# MDBList is the preferred provider — it covers all 7 rating sources
|
| 11 |
# (IMDb, RT Critics, RT Audience, Metacritic, Trakt, Letterboxd, MAL).
|
| 12 |
# OMDb only covers IMDb, RT Critics, and Metacritic.
|
|
|
|
| 15 |
# OMDb API key (optional) — https://www.omdbapi.com/apikey.aspx
|
| 16 |
# Required for IMDB episode ratings (MDBList does not support episode-level ratings)
|
| 17 |
OMDB_API_KEY=your_omdb_api_key
|
| 18 |
+
# Trakt Client ID (optional) — provides Trakt community ratings for movies, shows,
|
| 19 |
+
# and episodes. Create an app at https://trakt.tv/oauth/applications to get a Client ID.
|
| 20 |
+
# Can be used alongside or instead of MDBList/OMDb as a ratings provider.
|
| 21 |
+
# TRAKT_CLIENT_ID=your_trakt_client_id
|
| 22 |
|
| 23 |
# Directory to store cached posters and metadata
|
| 24 |
CACHE_DIR=./cache
|
api/src/config.rs
CHANGED
|
@@ -16,6 +16,7 @@ pub struct Config {
|
|
| 16 |
pub static_dir: Option<String>,
|
| 17 |
pub cors_origin: Option<String>,
|
| 18 |
pub fanart_api_key: Option<String>,
|
|
|
|
| 19 |
pub enable_cdn_redirects: bool,
|
| 20 |
pub external_cache_only: bool,
|
| 21 |
pub free_key_enabled: Option<bool>,
|
|
@@ -39,6 +40,7 @@ impl std::fmt::Debug for Config {
|
|
| 39 |
.field("static_dir", &self.static_dir)
|
| 40 |
.field("cors_origin", &self.cors_origin)
|
| 41 |
.field("fanart_api_key", &self.fanart_api_key.as_ref().map(|_| "[REDACTED]"))
|
|
|
|
| 42 |
.field("enable_cdn_redirects", &self.enable_cdn_redirects)
|
| 43 |
.field("external_cache_only", &self.external_cache_only)
|
| 44 |
.field("free_key_enabled", &self.free_key_enabled)
|
|
@@ -79,6 +81,7 @@ impl Config {
|
|
| 79 |
static_dir: env::var("STATIC_DIR").ok(),
|
| 80 |
cors_origin: env::var("CORS_ORIGIN").ok(),
|
| 81 |
fanart_api_key: env::var("FANART_API_KEY").ok(),
|
|
|
|
| 82 |
enable_cdn_redirects: env::var("ENABLE_CDN_REDIRECTS")
|
| 83 |
.map(|v| v == "true" || v == "1")
|
| 84 |
.unwrap_or(false),
|
|
@@ -93,8 +96,13 @@ impl Config {
|
|
| 93 |
.unwrap_or(false),
|
| 94 |
};
|
| 95 |
|
| 96 |
-
if config.omdb_api_key.is_none()
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
config
|
|
@@ -127,6 +135,7 @@ mod tests {
|
|
| 127 |
"STATIC_DIR",
|
| 128 |
"CORS_ORIGIN",
|
| 129 |
"FANART_API_KEY",
|
|
|
|
| 130 |
"ENABLE_CDN_REDIRECTS",
|
| 131 |
"EXTERNAL_CACHE_ONLY",
|
| 132 |
"FREE_KEY_ENABLED",
|
|
@@ -216,7 +225,9 @@ mod tests {
|
|
| 216 |
|
| 217 |
#[test]
|
| 218 |
#[serial]
|
| 219 |
-
#[should_panic(
|
|
|
|
|
|
|
| 220 |
fn test_panics_without_ratings_provider() {
|
| 221 |
unsafe { clear_config_env() };
|
| 222 |
unsafe { env::set_var("TMDB_API_KEY", "tmdb_test") };
|
|
|
|
| 16 |
pub static_dir: Option<String>,
|
| 17 |
pub cors_origin: Option<String>,
|
| 18 |
pub fanart_api_key: Option<String>,
|
| 19 |
+
pub trakt_client_id: Option<String>,
|
| 20 |
pub enable_cdn_redirects: bool,
|
| 21 |
pub external_cache_only: bool,
|
| 22 |
pub free_key_enabled: Option<bool>,
|
|
|
|
| 40 |
.field("static_dir", &self.static_dir)
|
| 41 |
.field("cors_origin", &self.cors_origin)
|
| 42 |
.field("fanart_api_key", &self.fanart_api_key.as_ref().map(|_| "[REDACTED]"))
|
| 43 |
+
.field("trakt_client_id", &self.trakt_client_id.as_ref().map(|_| "[REDACTED]"))
|
| 44 |
.field("enable_cdn_redirects", &self.enable_cdn_redirects)
|
| 45 |
.field("external_cache_only", &self.external_cache_only)
|
| 46 |
.field("free_key_enabled", &self.free_key_enabled)
|
|
|
|
| 81 |
static_dir: env::var("STATIC_DIR").ok(),
|
| 82 |
cors_origin: env::var("CORS_ORIGIN").ok(),
|
| 83 |
fanart_api_key: env::var("FANART_API_KEY").ok(),
|
| 84 |
+
trakt_client_id: env::var("TRAKT_CLIENT_ID").ok(),
|
| 85 |
enable_cdn_redirects: env::var("ENABLE_CDN_REDIRECTS")
|
| 86 |
.map(|v| v == "true" || v == "1")
|
| 87 |
.unwrap_or(false),
|
|
|
|
| 96 |
.unwrap_or(false),
|
| 97 |
};
|
| 98 |
|
| 99 |
+
if config.omdb_api_key.is_none()
|
| 100 |
+
&& config.mdblist_api_key.is_none()
|
| 101 |
+
&& config.trakt_client_id.is_none()
|
| 102 |
+
{
|
| 103 |
+
panic!(
|
| 104 |
+
"at least one of OMDB_API_KEY, MDBLIST_API_KEY, or TRAKT_CLIENT_ID must be set"
|
| 105 |
+
);
|
| 106 |
}
|
| 107 |
|
| 108 |
config
|
|
|
|
| 135 |
"STATIC_DIR",
|
| 136 |
"CORS_ORIGIN",
|
| 137 |
"FANART_API_KEY",
|
| 138 |
+
"TRAKT_CLIENT_ID",
|
| 139 |
"ENABLE_CDN_REDIRECTS",
|
| 140 |
"EXTERNAL_CACHE_ONLY",
|
| 141 |
"FREE_KEY_ENABLED",
|
|
|
|
| 225 |
|
| 226 |
#[test]
|
| 227 |
#[serial]
|
| 228 |
+
#[should_panic(
|
| 229 |
+
expected = "at least one of OMDB_API_KEY, MDBLIST_API_KEY, or TRAKT_CLIENT_ID must be set"
|
| 230 |
+
)]
|
| 231 |
fn test_panics_without_ratings_provider() {
|
| 232 |
unsafe { clear_config_env() };
|
| 233 |
unsafe { env::set_var("TMDB_API_KEY", "tmdb_test") };
|
api/src/image/serve.rs
CHANGED
|
@@ -373,6 +373,7 @@ async fn resolve_with_ratings(
|
|
| 373 |
&state.tmdb,
|
| 374 |
state.omdb.as_ref(),
|
| 375 |
state.mdblist.as_ref(),
|
|
|
|
| 376 |
&state.ratings_cache,
|
| 377 |
)
|
| 378 |
.await?
|
|
|
|
| 373 |
&state.tmdb,
|
| 374 |
state.omdb.as_ref(),
|
| 375 |
state.mdblist.as_ref(),
|
| 376 |
+
state.trakt.as_ref(),
|
| 377 |
&state.ratings_cache,
|
| 378 |
)
|
| 379 |
.await?
|
api/src/lib.rs
CHANGED
|
@@ -24,6 +24,7 @@ use services::fanart::{FanartClient, FanartImages};
|
|
| 24 |
use services::mdblist::MdblistClient;
|
| 25 |
use services::omdb::OmdbClient;
|
| 26 |
use services::tmdb::TmdbClient;
|
|
|
|
| 27 |
|
| 28 |
pub use routes::build_app;
|
| 29 |
|
|
@@ -33,6 +34,7 @@ pub struct AppState {
|
|
| 33 |
pub tmdb: TmdbClient,
|
| 34 |
pub omdb: Option<OmdbClient>,
|
| 35 |
pub mdblist: Option<MdblistClient>,
|
|
|
|
| 36 |
|
| 37 |
pub font: FontArc,
|
| 38 |
pub refresh_locks: moka::sync::Cache<String, ()>,
|
|
|
|
| 24 |
use services::mdblist::MdblistClient;
|
| 25 |
use services::omdb::OmdbClient;
|
| 26 |
use services::tmdb::TmdbClient;
|
| 27 |
+
use services::trakt::TraktClient;
|
| 28 |
|
| 29 |
pub use routes::build_app;
|
| 30 |
|
|
|
|
| 34 |
pub tmdb: TmdbClient,
|
| 35 |
pub omdb: Option<OmdbClient>,
|
| 36 |
pub mdblist: Option<MdblistClient>,
|
| 37 |
+
pub trakt: Option<TraktClient>,
|
| 38 |
|
| 39 |
pub font: FontArc,
|
| 40 |
pub refresh_locks: moka::sync::Cache<String, ()>,
|
api/src/main.rs
CHANGED
|
@@ -15,6 +15,7 @@ use openposterdb_api::services::fanart::FanartClient;
|
|
| 15 |
use openposterdb_api::services::mdblist::MdblistClient;
|
| 16 |
use openposterdb_api::services::omdb::OmdbClient;
|
| 17 |
use openposterdb_api::services::tmdb::TmdbClient;
|
|
|
|
| 18 |
use openposterdb_api::{build_app, upgrade, AppState, FONT_BYTES, MIGRATIONS, SCHEMA_SQL};
|
| 19 |
|
| 20 |
#[tokio::main]
|
|
@@ -55,6 +56,11 @@ async fn main() {
|
|
| 55 |
.as_ref()
|
| 56 |
.map(|key| FanartClient::new(key.clone(), http.clone()));
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
// Load JWT secret
|
| 59 |
let jwt_secret = db::load_secret_from_env("JWT_SECRET");
|
| 60 |
let secure_cookies = std::env::var("COOKIE_SECURE")
|
|
@@ -66,6 +72,7 @@ async fn main() {
|
|
| 66 |
mdblist = config.mdblist_api_key.is_some(),
|
| 67 |
omdb = config.omdb_api_key.is_some(),
|
| 68 |
fanart = config.fanart_api_key.is_some(),
|
|
|
|
| 69 |
"rating providers configured"
|
| 70 |
);
|
| 71 |
tracing::info!(
|
|
@@ -292,6 +299,7 @@ async fn main() {
|
|
| 292 |
image_mem_cache,
|
| 293 |
pending_last_used: pending_last_used.clone(),
|
| 294 |
fanart,
|
|
|
|
| 295 |
fanart_cache,
|
| 296 |
fanart_negative,
|
| 297 |
tmdb_images_cache,
|
|
|
|
| 15 |
use openposterdb_api::services::mdblist::MdblistClient;
|
| 16 |
use openposterdb_api::services::omdb::OmdbClient;
|
| 17 |
use openposterdb_api::services::tmdb::TmdbClient;
|
| 18 |
+
use openposterdb_api::services::trakt::TraktClient;
|
| 19 |
use openposterdb_api::{build_app, upgrade, AppState, FONT_BYTES, MIGRATIONS, SCHEMA_SQL};
|
| 20 |
|
| 21 |
#[tokio::main]
|
|
|
|
| 56 |
.as_ref()
|
| 57 |
.map(|key| FanartClient::new(key.clone(), http.clone()));
|
| 58 |
|
| 59 |
+
let trakt = config
|
| 60 |
+
.trakt_client_id
|
| 61 |
+
.as_ref()
|
| 62 |
+
.map(|key| TraktClient::new(key.clone(), http.clone()));
|
| 63 |
+
|
| 64 |
// Load JWT secret
|
| 65 |
let jwt_secret = db::load_secret_from_env("JWT_SECRET");
|
| 66 |
let secure_cookies = std::env::var("COOKIE_SECURE")
|
|
|
|
| 72 |
mdblist = config.mdblist_api_key.is_some(),
|
| 73 |
omdb = config.omdb_api_key.is_some(),
|
| 74 |
fanart = config.fanart_api_key.is_some(),
|
| 75 |
+
trakt = config.trakt_client_id.is_some(),
|
| 76 |
"rating providers configured"
|
| 77 |
);
|
| 78 |
tracing::info!(
|
|
|
|
| 299 |
image_mem_cache,
|
| 300 |
pending_last_used: pending_last_used.clone(),
|
| 301 |
fanart,
|
| 302 |
+
trakt,
|
| 303 |
fanart_cache,
|
| 304 |
fanart_negative,
|
| 305 |
tmdb_images_cache,
|
api/src/services/mod.rs
CHANGED
|
@@ -6,4 +6,5 @@ pub mod omdb;
|
|
| 6 |
pub mod ratings;
|
| 7 |
pub mod retry;
|
| 8 |
pub mod tmdb;
|
|
|
|
| 9 |
pub mod validation;
|
|
|
|
| 6 |
pub mod ratings;
|
| 7 |
pub mod retry;
|
| 8 |
pub mod tmdb;
|
| 9 |
+
pub mod trakt;
|
| 10 |
pub mod validation;
|
api/src/services/ratings.rs
CHANGED
|
@@ -3,6 +3,7 @@ use crate::id::{MediaType, ResolvedId};
|
|
| 3 |
use crate::services::mdblist::MdblistClient;
|
| 4 |
use crate::services::omdb::OmdbClient;
|
| 5 |
use crate::services::tmdb::TmdbClient;
|
|
|
|
| 6 |
use image::Rgba;
|
| 7 |
use serde::Deserialize;
|
| 8 |
|
|
@@ -128,6 +129,7 @@ pub async fn fetch_ratings(
|
|
| 128 |
tmdb: &TmdbClient,
|
| 129 |
omdb: Option<&OmdbClient>,
|
| 130 |
mdblist: Option<&MdblistClient>,
|
|
|
|
| 131 |
cache: &moka::future::Cache<String, RatingsResult>,
|
| 132 |
) -> Result<RatingsResult, AppError> {
|
| 133 |
let key = match resolved.media_type {
|
|
@@ -148,11 +150,12 @@ pub async fn fetch_ratings(
|
|
| 148 |
let tmdb = tmdb.clone();
|
| 149 |
let omdb = omdb.cloned();
|
| 150 |
let mdblist = mdblist.cloned();
|
|
|
|
| 151 |
|
| 152 |
let coalesced = cache
|
| 153 |
.try_get_with(key, async move {
|
| 154 |
let result =
|
| 155 |
-
fetch_ratings_inner(&resolved, &tmdb, omdb.as_ref(), mdblist.as_ref()).await;
|
| 156 |
Ok::<_, std::convert::Infallible>(result)
|
| 157 |
})
|
| 158 |
.await
|
|
@@ -166,6 +169,7 @@ async fn fetch_ratings_inner(
|
|
| 166 |
tmdb: &TmdbClient,
|
| 167 |
omdb: Option<&OmdbClient>,
|
| 168 |
mdblist: Option<&MdblistClient>,
|
|
|
|
| 169 |
) -> RatingsResult {
|
| 170 |
let ratings_start = std::time::Instant::now();
|
| 171 |
|
|
@@ -184,9 +188,18 @@ async fn fetch_ratings_inner(
|
|
| 184 |
let result = fetch_mdblist_ratings(resolved, mdblist).await;
|
| 185 |
(result, start.elapsed())
|
| 186 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
let (
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
let ratings_elapsed = ratings_start.elapsed().as_millis() as u64;
|
| 192 |
if ratings_elapsed > SLOW_RATINGS_MS {
|
|
@@ -197,6 +210,7 @@ async fn fetch_ratings_inner(
|
|
| 197 |
tmdb_ms = tmdb_dur.as_millis() as u64,
|
| 198 |
omdb_ms = omdb_dur.as_millis() as u64,
|
| 199 |
mdblist_ms = mdblist_dur.as_millis() as u64,
|
|
|
|
| 200 |
"slow ratings fetch"
|
| 201 |
);
|
| 202 |
}
|
|
@@ -222,14 +236,14 @@ async fn fetch_ratings_inner(
|
|
| 222 |
};
|
| 223 |
|
| 224 |
// Badge order: IMDb, TMDB, RT, RT Audience, MC, Trakt, Letterboxd, MAL
|
| 225 |
-
// MDBList preferred for overlapping sources; OMDb
|
| 226 |
let ordered: Vec<Option<RatingBadge>> = vec![
|
| 227 |
find_mdb(RatingSource::Imdb).or_else(|| find_omdb(RatingSource::Imdb)),
|
| 228 |
tmdb_badges,
|
| 229 |
find_mdb(RatingSource::Rt).or_else(|| find_omdb(RatingSource::Rt)),
|
| 230 |
find_mdb(RatingSource::RtAudience),
|
| 231 |
find_mdb(RatingSource::Metacritic).or_else(|| find_omdb(RatingSource::Metacritic)),
|
| 232 |
-
find_mdb(RatingSource::Trakt),
|
| 233 |
find_mdb(RatingSource::Letterboxd),
|
| 234 |
find_mdb(RatingSource::Mal),
|
| 235 |
];
|
|
@@ -320,6 +334,81 @@ async fn fetch_omdb_ratings(imdb_id: Option<&str>, omdb: Option<&OmdbClient>) ->
|
|
| 320 |
Some(badges)
|
| 321 |
}
|
| 322 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
/// Build a cache key suffix from actual rendered badges (post-filtering).
|
| 324 |
///
|
| 325 |
/// Unlike `ratings_cache_suffix` which predicts from user settings, this reflects
|
|
|
|
| 3 |
use crate::services::mdblist::MdblistClient;
|
| 4 |
use crate::services::omdb::OmdbClient;
|
| 5 |
use crate::services::tmdb::TmdbClient;
|
| 6 |
+
use crate::services::trakt::TraktClient;
|
| 7 |
use image::Rgba;
|
| 8 |
use serde::Deserialize;
|
| 9 |
|
|
|
|
| 129 |
tmdb: &TmdbClient,
|
| 130 |
omdb: Option<&OmdbClient>,
|
| 131 |
mdblist: Option<&MdblistClient>,
|
| 132 |
+
trakt: Option<&TraktClient>,
|
| 133 |
cache: &moka::future::Cache<String, RatingsResult>,
|
| 134 |
) -> Result<RatingsResult, AppError> {
|
| 135 |
let key = match resolved.media_type {
|
|
|
|
| 150 |
let tmdb = tmdb.clone();
|
| 151 |
let omdb = omdb.cloned();
|
| 152 |
let mdblist = mdblist.cloned();
|
| 153 |
+
let trakt = trakt.cloned();
|
| 154 |
|
| 155 |
let coalesced = cache
|
| 156 |
.try_get_with(key, async move {
|
| 157 |
let result =
|
| 158 |
+
fetch_ratings_inner(&resolved, &tmdb, omdb.as_ref(), mdblist.as_ref(), trakt.as_ref()).await;
|
| 159 |
Ok::<_, std::convert::Infallible>(result)
|
| 160 |
})
|
| 161 |
.await
|
|
|
|
| 169 |
tmdb: &TmdbClient,
|
| 170 |
omdb: Option<&OmdbClient>,
|
| 171 |
mdblist: Option<&MdblistClient>,
|
| 172 |
+
trakt: Option<&TraktClient>,
|
| 173 |
) -> RatingsResult {
|
| 174 |
let ratings_start = std::time::Instant::now();
|
| 175 |
|
|
|
|
| 188 |
let result = fetch_mdblist_ratings(resolved, mdblist).await;
|
| 189 |
(result, start.elapsed())
|
| 190 |
};
|
| 191 |
+
let trakt_fut = async {
|
| 192 |
+
let start = std::time::Instant::now();
|
| 193 |
+
let result = fetch_trakt_rating(resolved, tmdb, trakt).await;
|
| 194 |
+
(result, start.elapsed())
|
| 195 |
+
};
|
| 196 |
|
| 197 |
+
let (
|
| 198 |
+
(tmdb_badges, tmdb_dur),
|
| 199 |
+
(omdb_badges, omdb_dur),
|
| 200 |
+
(mdblist_raw, mdblist_dur),
|
| 201 |
+
(trakt_badge, trakt_dur),
|
| 202 |
+
) = tokio::join!(tmdb_fut, omdb_fut, mdblist_fut, trakt_fut);
|
| 203 |
|
| 204 |
let ratings_elapsed = ratings_start.elapsed().as_millis() as u64;
|
| 205 |
if ratings_elapsed > SLOW_RATINGS_MS {
|
|
|
|
| 210 |
tmdb_ms = tmdb_dur.as_millis() as u64,
|
| 211 |
omdb_ms = omdb_dur.as_millis() as u64,
|
| 212 |
mdblist_ms = mdblist_dur.as_millis() as u64,
|
| 213 |
+
trakt_ms = trakt_dur.as_millis() as u64,
|
| 214 |
"slow ratings fetch"
|
| 215 |
);
|
| 216 |
}
|
|
|
|
| 236 |
};
|
| 237 |
|
| 238 |
// Badge order: IMDb, TMDB, RT, RT Audience, MC, Trakt, Letterboxd, MAL
|
| 239 |
+
// MDBList preferred for overlapping sources; OMDb and direct Trakt fill gaps
|
| 240 |
let ordered: Vec<Option<RatingBadge>> = vec![
|
| 241 |
find_mdb(RatingSource::Imdb).or_else(|| find_omdb(RatingSource::Imdb)),
|
| 242 |
tmdb_badges,
|
| 243 |
find_mdb(RatingSource::Rt).or_else(|| find_omdb(RatingSource::Rt)),
|
| 244 |
find_mdb(RatingSource::RtAudience),
|
| 245 |
find_mdb(RatingSource::Metacritic).or_else(|| find_omdb(RatingSource::Metacritic)),
|
| 246 |
+
find_mdb(RatingSource::Trakt).or(trakt_badge),
|
| 247 |
find_mdb(RatingSource::Letterboxd),
|
| 248 |
find_mdb(RatingSource::Mal),
|
| 249 |
];
|
|
|
|
| 334 |
Some(badges)
|
| 335 |
}
|
| 336 |
|
| 337 |
+
async fn fetch_trakt_rating(
|
| 338 |
+
resolved: &ResolvedId,
|
| 339 |
+
tmdb: &TmdbClient,
|
| 340 |
+
trakt: Option<&TraktClient>,
|
| 341 |
+
) -> Option<RatingBadge> {
|
| 342 |
+
let client = trakt?;
|
| 343 |
+
|
| 344 |
+
let resp = match resolved.media_type {
|
| 345 |
+
MediaType::Movie => {
|
| 346 |
+
let imdb_id = resolved.imdb_id.as_deref()?;
|
| 347 |
+
client.get_movie_rating(imdb_id).await
|
| 348 |
+
}
|
| 349 |
+
MediaType::Tv => {
|
| 350 |
+
let imdb_id = resolved.imdb_id.as_deref()?;
|
| 351 |
+
client.get_show_rating(imdb_id).await
|
| 352 |
+
}
|
| 353 |
+
MediaType::Episode => {
|
| 354 |
+
let ep = resolved.episode.as_ref()?;
|
| 355 |
+
// Trakt's episode ratings endpoint is keyed by the show's IMDb ID.
|
| 356 |
+
// Resolve it lazily here (only when Trakt is configured) so that
|
| 357 |
+
// non-Trakt deployments never pay for the extra TMDB lookup.
|
| 358 |
+
let show_imdb_id = fetch_show_imdb_id(tmdb, ep.show_tmdb_id).await?;
|
| 359 |
+
client
|
| 360 |
+
.get_episode_rating(&show_imdb_id, ep.season_number, ep.episode_number)
|
| 361 |
+
.await
|
| 362 |
+
}
|
| 363 |
+
};
|
| 364 |
+
|
| 365 |
+
let resp = match resp {
|
| 366 |
+
Ok(Some(r)) => r,
|
| 367 |
+
// 404 — the title/episode isn't on Trakt. Expected; no rating to show.
|
| 368 |
+
Ok(None) => return None,
|
| 369 |
+
Err(e) => {
|
| 370 |
+
tracing::warn!(
|
| 371 |
+
tmdb_id = resolved.tmdb_id,
|
| 372 |
+
imdb_id = ?resolved.imdb_id,
|
| 373 |
+
media_type = ?resolved.media_type,
|
| 374 |
+
"trakt rating fetch failed: {e}"
|
| 375 |
+
);
|
| 376 |
+
return None;
|
| 377 |
+
}
|
| 378 |
+
};
|
| 379 |
+
|
| 380 |
+
if resp.rating <= 0.0 || resp.votes == 0 {
|
| 381 |
+
return None;
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
Some(RatingBadge {
|
| 385 |
+
source: RatingSource::Trakt,
|
| 386 |
+
value: format!("{:.0}%", resp.rating * 10.0),
|
| 387 |
+
})
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
/// Look up a show's IMDb ID from its TMDB ID via TMDB's `external_ids` endpoint.
|
| 391 |
+
/// Used only on the episode Trakt path, which keys ratings by show IMDb ID.
|
| 392 |
+
async fn fetch_show_imdb_id(tmdb: &TmdbClient, show_tmdb_id: u64) -> Option<String> {
|
| 393 |
+
#[derive(Deserialize)]
|
| 394 |
+
struct ShowExternalIds {
|
| 395 |
+
imdb_id: Option<String>,
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
let ids: ShowExternalIds = match tmdb
|
| 399 |
+
.get(&format!("/tv/{show_tmdb_id}/external_ids"), &[])
|
| 400 |
+
.await
|
| 401 |
+
{
|
| 402 |
+
Ok(ids) => ids,
|
| 403 |
+
Err(e) => {
|
| 404 |
+
tracing::warn!(show_tmdb_id, "trakt: show external_ids fetch failed: {e}");
|
| 405 |
+
return None;
|
| 406 |
+
}
|
| 407 |
+
};
|
| 408 |
+
|
| 409 |
+
ids.imdb_id
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
/// Build a cache key suffix from actual rendered badges (post-filtering).
|
| 413 |
///
|
| 414 |
/// Unlike `ratings_cache_suffix` which predicts from user settings, this reflects
|
api/src/services/retry.rs
CHANGED
|
@@ -48,6 +48,13 @@ pub const MDBLIST_RETRY: RetryConfig = RetryConfig {
|
|
| 48 |
service_name: "mdblist",
|
| 49 |
};
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
/// Send an HTTP request with retry logic for transient failures.
|
| 52 |
///
|
| 53 |
/// The closure must rebuild and send the request each time (since `RequestBuilder`
|
|
|
|
| 48 |
service_name: "mdblist",
|
| 49 |
};
|
| 50 |
|
| 51 |
+
pub const TRAKT_RETRY: RetryConfig = RetryConfig {
|
| 52 |
+
max_retries: 1,
|
| 53 |
+
base_delay: Duration::from_secs(2),
|
| 54 |
+
max_delay: Duration::from_secs(2),
|
| 55 |
+
service_name: "trakt",
|
| 56 |
+
};
|
| 57 |
+
|
| 58 |
/// Send an HTTP request with retry logic for transient failures.
|
| 59 |
///
|
| 60 |
/// The closure must rebuild and send the request each time (since `RequestBuilder`
|
api/src/services/trakt.rs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::sync::Arc;
|
| 2 |
+
|
| 3 |
+
use crate::error::AppError;
|
| 4 |
+
use crate::services::retry::{self, TRAKT_RETRY};
|
| 5 |
+
use serde::Deserialize;
|
| 6 |
+
use zeroize::Zeroizing;
|
| 7 |
+
|
| 8 |
+
#[derive(Clone)]
|
| 9 |
+
pub struct TraktClient {
|
| 10 |
+
client_id: Arc<Zeroizing<String>>,
|
| 11 |
+
http: reqwest::Client,
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
#[derive(Debug, Deserialize)]
|
| 15 |
+
pub struct TraktRatingsResponse {
|
| 16 |
+
pub rating: f64,
|
| 17 |
+
pub votes: u64,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
impl TraktClient {
|
| 21 |
+
pub fn new(client_id: String, http: reqwest::Client) -> Self {
|
| 22 |
+
Self {
|
| 23 |
+
client_id: Arc::new(Zeroizing::new(client_id)),
|
| 24 |
+
http,
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/// Build a GET request with the required Trakt API headers.
|
| 29 |
+
///
|
| 30 |
+
/// Trakt's API requires `Content-Type: application/json` even on GET
|
| 31 |
+
/// requests (no body). This is a quirk of their API spec.
|
| 32 |
+
fn request(&self, url: &str) -> reqwest::RequestBuilder {
|
| 33 |
+
self.http
|
| 34 |
+
.get(url)
|
| 35 |
+
.header("Content-Type", "application/json")
|
| 36 |
+
.header("trakt-api-version", "2")
|
| 37 |
+
.header("trakt-api-key", self.client_id.as_str())
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/// Fetch a ratings endpoint. Returns `Ok(None)` when Trakt responds 404
|
| 41 |
+
/// (the title/episode simply isn't catalogued), which is an expected,
|
| 42 |
+
/// non-error outcome — only genuine failures surface as `Err`.
|
| 43 |
+
async fn get_rating(&self, url: &str) -> Result<Option<TraktRatingsResponse>, AppError> {
|
| 44 |
+
let resp = retry::send_with_retry(&TRAKT_RETRY, || self.request(url).send()).await?;
|
| 45 |
+
if resp.status() == reqwest::StatusCode::NOT_FOUND {
|
| 46 |
+
return Ok(None);
|
| 47 |
+
}
|
| 48 |
+
let resp = resp.error_for_status()?;
|
| 49 |
+
Ok(Some(resp.json().await?))
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
pub async fn get_movie_rating(
|
| 53 |
+
&self,
|
| 54 |
+
imdb_id: &str,
|
| 55 |
+
) -> Result<Option<TraktRatingsResponse>, AppError> {
|
| 56 |
+
self.get_rating(&format!("https://api.trakt.tv/movies/{imdb_id}/ratings"))
|
| 57 |
+
.await
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
pub async fn get_show_rating(
|
| 61 |
+
&self,
|
| 62 |
+
imdb_id: &str,
|
| 63 |
+
) -> Result<Option<TraktRatingsResponse>, AppError> {
|
| 64 |
+
self.get_rating(&format!("https://api.trakt.tv/shows/{imdb_id}/ratings"))
|
| 65 |
+
.await
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
pub async fn get_episode_rating(
|
| 69 |
+
&self,
|
| 70 |
+
show_id: &str,
|
| 71 |
+
season: u32,
|
| 72 |
+
episode: u32,
|
| 73 |
+
) -> Result<Option<TraktRatingsResponse>, AppError> {
|
| 74 |
+
self.get_rating(&format!(
|
| 75 |
+
"https://api.trakt.tv/shows/{show_id}/seasons/{season}/episodes/{episode}/ratings"
|
| 76 |
+
))
|
| 77 |
+
.await
|
| 78 |
+
}
|
| 79 |
+
}
|
api/tests/common/mod.rs
CHANGED
|
@@ -120,6 +120,7 @@ async fn _setup_test_app(cors_origin: Option<String>, secure_cookies: bool, enab
|
|
| 120 |
static_dir: None,
|
| 121 |
cors_origin,
|
| 122 |
fanart_api_key: if disable_fanart { None } else { Some("test".into()) },
|
|
|
|
| 123 |
enable_cdn_redirects,
|
| 124 |
external_cache_only,
|
| 125 |
free_key_enabled,
|
|
@@ -128,6 +129,7 @@ async fn _setup_test_app(cors_origin: Option<String>, secure_cookies: bool, enab
|
|
| 128 |
tmdb: TmdbClient::new("test".into(), http.clone()),
|
| 129 |
omdb: None,
|
| 130 |
mdblist: None,
|
|
|
|
| 131 |
|
| 132 |
font,
|
| 133 |
refresh_locks,
|
|
|
|
| 120 |
static_dir: None,
|
| 121 |
cors_origin,
|
| 122 |
fanart_api_key: if disable_fanart { None } else { Some("test".into()) },
|
| 123 |
+
trakt_client_id: None,
|
| 124 |
enable_cdn_redirects,
|
| 125 |
external_cache_only,
|
| 126 |
free_key_enabled,
|
|
|
|
| 129 |
tmdb: TmdbClient::new("test".into(), http.clone()),
|
| 130 |
omdb: None,
|
| 131 |
mdblist: None,
|
| 132 |
+
trakt: None,
|
| 133 |
|
| 134 |
font,
|
| 135 |
refresh_locks,
|