Skip to main content

media_tools/providers/
watchmode.rs

1//! Watchmode streaming availability adapter.
2//!
3//! Authentication uses the X-API-Key header so credentials do not appear in
4//! request URLs or HTTP query logs. Provider source IDs are read from API
5//! responses; no country-specific source IDs are hard-coded.
6use std::{
7    collections::HashMap,
8    sync::Arc,
9    time::{Duration, Instant},
10};
11
12use reqwest::{Client, StatusCode};
13use serde::Deserialize;
14use tokio::sync::RwLock;
15
16type CachedOffers = HashMap<String, (Instant, Vec<StreamingOffer>)>;
17
18use crate::{MediaKind, OfferType, StreamingOffer, StreamingService};
19
20const DEFAULT_BASE_URL: &str = "https://api.watchmode.com/v1";
21
22/// A Watchmode source/service discovered from the provider's reference API.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct WatchmodeSource {
25    pub id: u64,
26    pub name: String,
27    pub source_type: Option<String>,
28}
29
30/// Errors returned by the Watchmode adapter.
31#[derive(Debug, thiserror::Error)]
32pub enum WatchmodeError {
33    #[error("Watchmode API key must not be empty")]
34    EmptyApiKey,
35    #[error("Watchmode request failed: {0}")]
36    Request(#[from] reqwest::Error),
37    #[error("Watchmode returned HTTP {status}: {message}")]
38    Api { status: StatusCode, message: String },
39    #[error("Watchmode rate limit reached (retry after {retry_after_seconds:?} seconds)")]
40    RateLimited { retry_after_seconds: Option<u64> },
41    #[error("Watchmode returned an unsupported offer type: {0}")]
42    UnsupportedOfferType(String),
43    #[error("Watchmode returned an invalid response: {0}")]
44    InvalidResponse(String),
45}
46
47#[derive(Clone)]
48pub struct WatchmodeClient {
49    http: Client,
50    api_key: String,
51    base_url: String,
52    cache_ttl: Duration,
53    offers_cache: Arc<RwLock<CachedOffers>>,
54}
55
56impl WatchmodeClient {
57    /// Create a client with a conservative in-memory availability cache.
58    pub fn new(api_key: impl Into<String>) -> Result<Self, WatchmodeError> {
59        Self::with_options(api_key, DEFAULT_BASE_URL, Duration::from_secs(6 * 60 * 60))
60    }
61
62    /// Configure the in-memory availability cache lifetime using the default API endpoint.
63    pub fn with_cache_ttl(
64        api_key: impl Into<String>,
65        cache_ttl: Duration,
66    ) -> Result<Self, WatchmodeError> {
67        Self::with_options(api_key, DEFAULT_BASE_URL, cache_ttl)
68    }
69
70    /// Configure the endpoint and in-memory availability cache lifetime.
71    pub fn with_options(
72        api_key: impl Into<String>,
73        base_url: impl Into<String>,
74        cache_ttl: Duration,
75    ) -> Result<Self, WatchmodeError> {
76        let api_key = api_key.into();
77        if api_key.trim().is_empty() {
78            return Err(WatchmodeError::EmptyApiKey);
79        }
80        Ok(Self {
81            http: Client::new(),
82            api_key,
83            base_url: base_url.into().trim_end_matches('/').to_owned(),
84            cache_ttl,
85            offers_cache: Arc::new(RwLock::new(HashMap::new())),
86        })
87    }
88
89    /// Search Watchmode by a TMDB movie or TV ID and fetch its regional offers.
90    ///
91    /// The TMDB identifier is used to resolve the Watchmode title ID first.
92    /// This avoids assuming that IDs are shared across catalogue providers.
93    pub async fn offers_for_tmdb_id(
94        &self,
95        tmdb_id: u64,
96        kind: MediaKind,
97        region: &str,
98    ) -> Result<Vec<StreamingOffer>, WatchmodeError> {
99        let region = normalize_region(region)?;
100        let cache_key = format!("{}:{}:{}", kind_key(kind), tmdb_id, region);
101        if let Some((created, offers)) = self.offers_cache.read().await.get(&cache_key)
102            && created.elapsed() < self.cache_ttl
103        {
104            return Ok(offers.clone());
105        }
106
107        let search_field = match kind {
108            MediaKind::Movie => "tmdb_movie_id",
109            MediaKind::TvShow => "tmdb_tv_id",
110        };
111        let search: WatchmodeSearchResponse = self
112            .request_json(
113                "/search/",
114                &[
115                    ("search_field", search_field.to_owned()),
116                    ("search_value", tmdb_id.to_string()),
117                ],
118            )
119            .await?;
120        let Some(title) = search.title_results.into_iter().next() else {
121            self.offers_cache
122                .write()
123                .await
124                .insert(cache_key, (Instant::now(), Vec::new()));
125            return Ok(Vec::new());
126        };
127
128        let media_item_id = crate::MediaItemId::from_external_id("tmdb", &tmdb_id.to_string());
129        let offers = self
130            .sources_for_title(title.id, media_item_id, &region)
131            .await?;
132        self.offers_cache
133            .write()
134            .await
135            .insert(cache_key, (Instant::now(), offers.clone()));
136        Ok(offers)
137    }
138
139    /// Fetch offers for a Watchmode title ID in one region.
140    pub async fn sources_for_title(
141        &self,
142        watchmode_id: u64,
143        media_item_id: crate::MediaItemId,
144        region: &str,
145    ) -> Result<Vec<StreamingOffer>, WatchmodeError> {
146        let region = normalize_region(region)?;
147        let path = format!("/title/{watchmode_id}/sources/");
148        let rows: Vec<WatchmodeOfferDto> = self
149            .request_json(&path, &[("regions", region.clone())])
150            .await?;
151        rows.into_iter()
152            .map(|row| {
153                Ok(StreamingOffer {
154                    media_item_id,
155                    service_id: row.source_id.to_string(),
156                    service_name: row.name,
157                    offer_type: parse_offer_type(&row.source_type)?,
158                    region: row.region.unwrap_or_else(|| region.clone()),
159                    url: non_empty(row.web_url),
160                })
161            })
162            .collect()
163    }
164
165    /// List source metadata for a region. IDs and names come from Watchmode.
166    pub async fn list_sources(&self, region: &str) -> Result<Vec<WatchmodeSource>, WatchmodeError> {
167        let region = normalize_region(region)?;
168        let rows: Vec<WatchmodeSourceDto> = self
169            .request_json("/sources/", &[("regions", region)])
170            .await?;
171        Ok(rows
172            .into_iter()
173            .map(|source| WatchmodeSource {
174                id: source.id,
175                name: source.name,
176                source_type: source.source_type,
177            })
178            .collect())
179    }
180
181    async fn request_json<T: for<'de> Deserialize<'de>>(
182        &self,
183        path: &str,
184        extra: &[(&str, String)],
185    ) -> Result<T, WatchmodeError> {
186        let url = format!("{}{}", self.base_url, path);
187        let mut request = self.http.get(url).header("X-API-Key", &self.api_key);
188        for (key, value) in extra {
189            request = request.query(&[(key, value)]);
190        }
191        let started = Instant::now();
192        let response = request.send().await?;
193        let status = response.status();
194        tracing::debug!(
195            provider = "watchmode",
196            status = status.as_u16(),
197            elapsed_ms = started.elapsed().as_millis() as u64,
198            "media provider request completed"
199        );
200        if status == StatusCode::TOO_MANY_REQUESTS {
201            tracing::warn!(provider = "watchmode", "media provider rate limit reached");
202            let retry_after_seconds = response
203                .headers()
204                .get(reqwest::header::RETRY_AFTER)
205                .and_then(|value| value.to_str().ok())
206                .and_then(|value| value.parse().ok());
207            return Err(WatchmodeError::RateLimited {
208                retry_after_seconds,
209            });
210        }
211        if !status.is_success() {
212            tracing::warn!(
213                provider = "watchmode",
214                status = status.as_u16(),
215                "media provider request failed"
216            );
217            let message = response
218                .text()
219                .await
220                .unwrap_or_else(|_| "request failed".into());
221            return Err(WatchmodeError::Api { status, message });
222        }
223        response.json().await.map_err(WatchmodeError::Request)
224    }
225}
226
227/// Keep only offers matching the household's configured subscriptions.
228pub fn filter_subscription_offers(
229    offers: Vec<StreamingOffer>,
230    subscriptions: &[StreamingService],
231) -> Vec<StreamingOffer> {
232    offers
233        .into_iter()
234        .filter(|offer| {
235            offer.offer_type == OfferType::Subscription
236                && subscriptions
237                    .iter()
238                    .any(|service| service_matches(*service, &offer.service_name))
239        })
240        .collect()
241}
242
243fn service_matches(service: StreamingService, provider_name: &str) -> bool {
244    let normalized = normalize_name(provider_name);
245    match service {
246        StreamingService::Netflix => normalized == "netflix",
247        StreamingService::PrimeVideo => {
248            normalized == "prime video" || normalized == "amazon prime video"
249        }
250        StreamingService::DisneyPlus => normalized == "disney+" || normalized == "disney plus",
251        StreamingService::HboMax => normalized == "hbo max" || normalized == "max",
252    }
253}
254
255fn normalize_name(value: &str) -> String {
256    value
257        .trim()
258        .to_lowercase()
259        .split_whitespace()
260        .collect::<Vec<_>>()
261        .join(" ")
262}
263
264fn normalize_region(region: &str) -> Result<String, WatchmodeError> {
265    let region = region.trim().to_ascii_uppercase();
266    if region.len() != 2 || !region.bytes().all(|byte| byte.is_ascii_uppercase()) {
267        return Err(WatchmodeError::InvalidResponse(
268            "region must be a two-letter ISO 3166-1 country code".into(),
269        ));
270    }
271    Ok(region)
272}
273
274fn kind_key(kind: MediaKind) -> &'static str {
275    match kind {
276        MediaKind::Movie => "movie",
277        MediaKind::TvShow => "tv",
278    }
279}
280
281fn parse_offer_type(value: &str) -> Result<OfferType, WatchmodeError> {
282    match value.trim().to_ascii_lowercase().as_str() {
283        "sub" | "subscription" => Ok(OfferType::Subscription),
284        "rent" => Ok(OfferType::Rent),
285        "buy" | "purchase" => Ok(OfferType::Buy),
286        "free" => Ok(OfferType::Free),
287        "ads" | "ad_supported" => Ok(OfferType::AdSupported),
288        "tv" | "tve" | "tv_provider" => Ok(OfferType::TvProvider),
289        other => Err(WatchmodeError::UnsupportedOfferType(other.to_owned())),
290    }
291}
292
293fn non_empty(value: Option<String>) -> Option<String> {
294    value.filter(|value| !value.trim().is_empty())
295}
296
297#[derive(Debug, Deserialize)]
298struct WatchmodeSearchResponse {
299    #[serde(default)]
300    title_results: Vec<WatchmodeSearchTitle>,
301}
302
303#[derive(Debug, Deserialize)]
304struct WatchmodeSearchTitle {
305    id: u64,
306}
307
308#[derive(Debug, Deserialize)]
309struct WatchmodeOfferDto {
310    source_id: u64,
311    name: String,
312    #[serde(rename = "type")]
313    source_type: String,
314    region: Option<String>,
315    web_url: Option<String>,
316}
317
318#[derive(Debug, Deserialize)]
319struct WatchmodeSourceDto {
320    id: u64,
321    name: String,
322    #[serde(rename = "type")]
323    source_type: Option<String>,
324}
325
326#[cfg(test)]
327mod tests {
328    use wiremock::{
329        Mock, MockServer, ResponseTemplate,
330        matchers::{header, method, path, query_param},
331    };
332
333    use super::*;
334
335    #[tokio::test]
336    async fn resolves_tmdb_id_and_maps_regional_subscription_offers() {
337        let server = MockServer::start().await;
338        Mock::given(method("GET"))
339            .and(path("/search/"))
340            .and(header("X-API-Key", "test-key"))
341            .and(query_param("search_field", "tmdb_movie_id"))
342            .and(query_param("search_value", "42"))
343            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
344                "title_results": [{"id": 9001, "name": "Example", "type": "movie"}]
345            })))
346            .mount(&server)
347            .await;
348        Mock::given(method("GET"))
349            .and(path("/title/9001/sources/"))
350            .and(query_param("regions", "ES"))
351            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
352                {"source_id": 203, "name": "Netflix", "type": "sub", "region": "ES", "web_url": "https://netflix.example/title"},
353                {"source_id": 26, "name": "Amazon Prime Video", "type": "sub", "region": "ES", "web_url": "https://prime.example/title"},
354                {"source_id": 203, "name": "Netflix", "type": "rent", "region": "ES", "web_url": "https://netflix.example/rent"}
355            ])))
356            .mount(&server)
357            .await;
358
359        let client =
360            WatchmodeClient::with_options("test-key", server.uri(), Duration::from_secs(60))
361                .unwrap();
362        let offers = client
363            .offers_for_tmdb_id(42, MediaKind::Movie, "es")
364            .await
365            .unwrap();
366        assert_eq!(offers.len(), 3);
367        assert_eq!(offers[0].service_id, "203");
368        assert_eq!(offers[0].offer_type, OfferType::Subscription);
369
370        let configured = filter_subscription_offers(
371            offers,
372            &[StreamingService::Netflix, StreamingService::PrimeVideo],
373        );
374        assert_eq!(configured.len(), 2);
375    }
376
377    #[tokio::test]
378    async fn rejects_invalid_regions_and_handles_rate_limits() {
379        let server = MockServer::start().await;
380        Mock::given(method("GET"))
381            .and(path("/title/1/sources/"))
382            .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "30"))
383            .mount(&server)
384            .await;
385        let client = WatchmodeClient::new("test-key").unwrap();
386        assert!(matches!(
387            client
388                .sources_for_title(1, crate::MediaItemId::new(), "Spain")
389                .await,
390            Err(WatchmodeError::InvalidResponse(_))
391        ));
392
393        let client =
394            WatchmodeClient::with_options("test-key", server.uri(), Duration::from_secs(0))
395                .unwrap();
396        assert!(matches!(
397            client
398                .sources_for_title(1, crate::MediaItemId::new(), "ES")
399                .await,
400            Err(WatchmodeError::RateLimited {
401                retry_after_seconds: Some(30)
402            })
403        ));
404    }
405}