1use std::{
3 collections::{HashMap, HashSet},
4 time::Instant,
5};
6
7use chrono::Datelike;
8
9use crate::{
10 ContentRestrictions, FamilyMediaPreferences, MediaConfig, MediaItem, MediaItemId, MediaKind,
11 MediaProfile, MediaProfileId, MediaRating, MediaStore, MediaStoreError, MediaWatchEvent,
12 ProfilePreferences, RecommendationContext, RecommendationCriteria, RecommendationWeights,
13 StreamingOffer, TmdbClient, TmdbError, WatchedPolicy, WatchmodeClient, WatchmodeError,
14};
15
16#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
18pub struct MediaRecommendation {
19 pub item: MediaItem,
20 pub score: i32,
22 pub reasons: Vec<String>,
23 pub offers: Vec<StreamingOffer>,
24 pub watched_by: Vec<MediaProfileId>,
25 pub history_unknown_for: Vec<MediaProfileId>,
27}
28
29#[derive(Debug, thiserror::Error)]
30pub enum RecommendationError {
31 #[error("invalid media configuration: {0}")]
32 Configuration(String),
33 #[error("recommendation context must include at least one participant")]
34 NoParticipants,
35 #[error("profile {0} is not an active member of the requested family")]
36 InvalidParticipant(MediaProfileId),
37 #[error("catalogue request failed: {0}")]
38 Catalogue(#[from] TmdbError),
39 #[error("availability request failed: {0}")]
40 Availability(#[from] WatchmodeError),
41 #[error("media storage failed: {0}")]
42 Storage(#[from] MediaStoreError),
43}
44
45#[derive(Clone)]
47pub struct RecommendationService {
48 media: MediaStore,
49 tmdb: TmdbClient,
50 watchmode: Option<WatchmodeClient>,
51 config: MediaConfig,
52 candidate_limit_per_kind: usize,
53}
54
55impl RecommendationService {
56 pub fn new(
57 media: MediaStore,
58 tmdb: TmdbClient,
59 watchmode: Option<WatchmodeClient>,
60 config: MediaConfig,
61 ) -> Result<Self, RecommendationError> {
62 config
63 .validate()
64 .map_err(|error| RecommendationError::Configuration(error.to_string()))?;
65 Ok(Self {
66 media,
67 tmdb,
68 watchmode,
69 config,
70 candidate_limit_per_kind: 20,
71 })
72 }
73
74 pub async fn recommend(
80 &self,
81 context: &RecommendationContext,
82 ) -> Result<Vec<MediaRecommendation>, RecommendationError> {
83 let started = Instant::now();
84 tracing::debug!(
85 participant_count = context.participants.len(),
86 "starting media recommendation"
87 );
88 if context.participants.is_empty() {
89 return Err(RecommendationError::NoParticipants);
90 }
91 let mut seen = HashSet::new();
92 if context.participants.iter().any(|id| !seen.insert(*id)) {
93 return Err(RecommendationError::NoParticipants);
94 }
95
96 let family_preferences = self
97 .media
98 .get_family_preferences(context.family_id)
99 .await?
100 .unwrap_or_else(|| FamilyMediaPreferences::new(context.family_id));
101 let mut participants = Vec::with_capacity(context.participants.len());
102 for profile_id in &context.participants {
103 let profile = self
104 .media
105 .get_profile(context.family_id, *profile_id)
106 .await?
107 .filter(|profile| profile.active)
108 .ok_or(RecommendationError::InvalidParticipant(*profile_id))?;
109 participants.push(self.load_participant(profile).await?);
110 }
111
112 let candidates = self.discover_candidates(&context.criteria).await?;
113 let discovered_count = candidates.len();
114 let watched_policy = context.watched_policy.unwrap_or(self.config.watched_policy);
115
116 let mut recommendations = Vec::new();
117 let mut excluded_by_criteria = 0;
118 let mut excluded_by_restrictions = 0;
119 let mut excluded_as_watched = 0;
120 let mut excluded_by_availability = 0;
121 for candidate in candidates {
122 let item = self.enrich(candidate).await?;
123 if !matches_criteria(&item, &context.criteria) {
124 excluded_by_criteria += 1;
125 continue;
126 }
127 if !participants
128 .iter()
129 .all(|participant| passes_restrictions(&item, &participant.restrictions))
130 {
131 excluded_by_restrictions += 1;
132 continue;
133 }
134
135 let (watched_by, history_unknown_for) = watched_evidence(item.id, &participants);
136 if should_exclude_watched(watched_policy, participants.len(), watched_by.len()) {
137 excluded_as_watched += 1;
138 continue;
139 }
140
141 let offers = self.availability(&item).await?;
142 if self.config.require_subscription && offers.is_empty() {
143 excluded_by_availability += 1;
144 continue;
145 }
146
147 let (score, mut reasons) = score_item(
148 &item,
149 &family_preferences,
150 &participants,
151 &self.config.recommendation_weights,
152 );
153 for offer in &offers {
154 reasons.push(format!("Available on {}", offer.service_name));
155 }
156 if !history_unknown_for.is_empty() {
157 reasons.push(format!(
158 "Viewing history is incomplete for {} selected participant(s)",
159 history_unknown_for.len()
160 ));
161 }
162 recommendations.push(MediaRecommendation {
163 item,
164 score: score.round() as i32,
165 reasons,
166 offers,
167 watched_by,
168 history_unknown_for,
169 });
170 }
171
172 let eligible_count = recommendations.len();
173 let recommendations = apply_diversity(
174 recommendations,
175 self.config.recommendation_limit,
176 self.config.recommendation_weights.diversity_penalty,
177 );
178 let uncertain_profile_count = recommendations
179 .iter()
180 .map(|recommendation| recommendation.history_unknown_for.len())
181 .sum::<usize>();
182 tracing::info!(
183 discovered = discovered_count,
184 eligible = eligible_count,
185 returned = recommendations.len(),
186 excluded_by_criteria,
187 excluded_by_restrictions,
188 excluded_as_watched,
189 excluded_by_availability,
190 history_uncertain_profiles = uncertain_profile_count,
191 elapsed_ms = started.elapsed().as_millis() as u64,
192 "media recommendation completed"
193 );
194 Ok(recommendations)
195 }
196
197 async fn load_participant(
198 &self,
199 profile: MediaProfile,
200 ) -> Result<ParticipantData, RecommendationError> {
201 let preferences = self
202 .media
203 .get_profile_preferences(profile.id)
204 .await?
205 .unwrap_or_else(|| ProfilePreferences::new(profile.id));
206 let restrictions = self
207 .media
208 .get_content_restrictions(profile.id)
209 .await?
210 .unwrap_or_else(|| ContentRestrictions::new(profile.id));
211 let history = self.media.list_watch_history(profile.id).await?;
212 let watched_items = history
213 .into_iter()
214 .map(|event: MediaWatchEvent| event.media_item_id)
215 .collect();
216 let history_complete = self
217 .media
218 .get_provider_sync_state(profile.id, "trakt")
219 .await?
220 .is_some_and(|state| state.status == "complete");
221 let ratings = self.media.list_ratings(profile.id).await?;
222 let genre_affinity = self.genre_affinity(&ratings).await?;
223 Ok(ParticipantData {
224 profile,
225 preferences,
226 restrictions,
227 watched_items,
228 history_complete,
229 genre_affinity,
230 })
231 }
232
233 async fn genre_affinity(
234 &self,
235 ratings: &[MediaRating],
236 ) -> Result<HashMap<String, f32>, RecommendationError> {
237 let mut totals: HashMap<String, (f32, usize)> = HashMap::new();
238 let mut seen_items = HashSet::new();
244 for rating in ratings
248 .iter()
249 .filter(|rating| seen_items.insert(rating.media_item_id))
250 .take(100)
251 {
252 let Some(mut item) = self.media.get_media_item(rating.media_item_id).await? else {
253 continue;
254 };
255 if item.genres.is_empty() {
256 if let Some(tmdb_id) = item
257 .external_ids
258 .iter()
259 .find(|id| id.provider == "tmdb")
260 .and_then(|id| id.value.parse::<u64>().ok())
261 {
262 let enriched = match item.kind {
263 MediaKind::Movie => self.tmdb.movie_details(tmdb_id).await,
264 MediaKind::TvShow => self.tmdb.tv_details(tmdb_id).await,
265 };
266 if let Ok(enriched) = enriched {
267 self.media.save_media_item(&enriched).await?;
268 item = enriched;
269 }
270 }
271 }
272 for genre in item.genres {
273 let entry = totals.entry(normalize(&genre)).or_default();
274 entry.0 += rating.value;
275 entry.1 += 1;
276 }
277 }
278 Ok(totals
279 .into_iter()
280 .filter_map(|(genre, (total, count))| {
281 (count > 0).then_some((genre, total / count as f32))
282 })
283 .collect())
284 }
285
286 async fn discover_candidates(
287 &self,
288 criteria: &RecommendationCriteria,
289 ) -> Result<Vec<MediaItem>, RecommendationError> {
290 let mut seen = HashSet::new();
291 let mut items = Vec::new();
292 let query = criteria
293 .query
294 .as_deref()
295 .filter(|query| !query.trim().is_empty());
296 for kind in requested_kinds(criteria) {
297 let page = match (kind, query) {
298 (MediaKind::Movie, Some(query)) => self.tmdb.search_movies(query, 1).await?,
299 (MediaKind::TvShow, Some(query)) => self.tmdb.search_tv(query, 1).await?,
300 (MediaKind::Movie, None) => self.tmdb.popular_movies(1).await?,
301 (MediaKind::TvShow, None) => self.tmdb.popular_tv(1).await?,
302 };
303 for item in page.items.into_iter().take(self.candidate_limit_per_kind) {
304 if seen.insert(item.id) {
305 items.push(item);
306 }
307 }
308 }
309 Ok(items)
310 }
311
312 async fn enrich(&self, candidate: MediaItem) -> Result<MediaItem, RecommendationError> {
313 let tmdb_id = candidate
314 .external_ids
315 .iter()
316 .find(|id| id.provider == "tmdb")
317 .and_then(|id| id.value.parse::<u64>().ok());
318 let Some(tmdb_id) = tmdb_id else {
319 return Ok(candidate);
320 };
321 Ok(match candidate.kind {
322 MediaKind::Movie => self.tmdb.movie_details(tmdb_id).await?,
323 MediaKind::TvShow => self.tmdb.tv_details(tmdb_id).await?,
324 })
325 }
326
327 async fn availability(
328 &self,
329 item: &MediaItem,
330 ) -> Result<Vec<StreamingOffer>, RecommendationError> {
331 let Some(tmdb_id) = item
332 .external_ids
333 .iter()
334 .find(|id| id.provider == "tmdb")
335 .and_then(|id| id.value.parse::<u64>().ok())
336 else {
337 return Ok(Vec::new());
338 };
339
340 let watchmode_offers = if let Some(watchmode) = &self.watchmode {
341 match watchmode
342 .offers_for_tmdb_id(tmdb_id, item.kind, &self.config.country)
343 .await
344 {
345 Ok(offers) => offers,
346 Err(_) => {
347 tracing::warn!(
348 provider = "watchmode",
349 "availability lookup failed; falling back to TMDB watch providers"
350 );
351 Vec::new()
352 }
353 }
354 } else {
355 Vec::new()
356 };
357 let usable_watchmode = if self.config.require_subscription {
358 crate::filter_subscription_offers(watchmode_offers, &self.config.subscriptions)
359 } else {
360 watchmode_offers
361 };
362 if !usable_watchmode.is_empty() {
363 return Ok(usable_watchmode);
364 }
365
366 let tmdb_offers = self
367 .tmdb
368 .watch_providers(tmdb_id, item.kind, &self.config.country)
369 .await?;
370 if self.config.require_subscription {
371 Ok(crate::filter_subscription_offers(
372 tmdb_offers,
373 &self.config.subscriptions,
374 ))
375 } else {
376 Ok(tmdb_offers)
377 }
378 }
379}
380
381#[derive(Clone)]
382struct ParticipantData {
383 profile: MediaProfile,
384 preferences: ProfilePreferences,
385 restrictions: ContentRestrictions,
386 watched_items: HashSet<MediaItemId>,
387 history_complete: bool,
388 genre_affinity: HashMap<String, f32>,
389}
390
391fn requested_kinds(criteria: &RecommendationCriteria) -> Vec<MediaKind> {
392 if criteria.kinds.is_empty() {
393 vec![MediaKind::Movie, MediaKind::TvShow]
394 } else {
395 let mut kinds = Vec::new();
396 for kind in &criteria.kinds {
397 if !kinds.contains(kind) {
398 kinds.push(*kind);
399 }
400 }
401 kinds
402 }
403}
404
405fn matches_criteria(item: &MediaItem, criteria: &RecommendationCriteria) -> bool {
406 if !criteria.kinds.is_empty() && !criteria.kinds.contains(&item.kind) {
407 return false;
408 }
409 if !criteria.genres.is_empty()
410 && !criteria.genres.iter().any(|genre| {
411 item.genres
412 .iter()
413 .any(|item_genre| normalize(item_genre) == normalize(genre))
414 })
415 {
416 return false;
417 }
418 if !criteria.languages.is_empty()
419 && !item.original_language.as_ref().is_some_and(|language| {
420 criteria
421 .languages
422 .iter()
423 .any(|candidate| normalize(candidate) == normalize(language))
424 })
425 {
426 return false;
427 }
428 if !criteria.themes.is_empty()
429 && !criteria
430 .themes
431 .iter()
432 .any(|theme| theme_matches(item, theme))
433 {
434 return false;
435 }
436 if let Some(maximum_runtime) = criteria.maximum_runtime_minutes
437 && !item
438 .runtime_minutes
439 .is_some_and(|runtime| runtime <= maximum_runtime)
440 {
441 return false;
442 }
443 true
444}
445
446fn passes_restrictions(item: &MediaItem, restrictions: &ContentRestrictions) -> bool {
447 if restrictions.disallowed_genres.iter().any(|genre| {
448 item.genres
449 .iter()
450 .any(|item_genre| normalize(item_genre) == normalize(genre))
451 }) {
452 return false;
453 }
454 if restrictions
455 .disallowed_themes
456 .iter()
457 .any(|theme| theme_matches(item, theme))
458 {
459 return false;
460 }
461 let Some(maximum) = restrictions.maximum_certification.as_deref() else {
462 return true;
463 };
464 let Some(certification) = item.certification.as_deref() else {
465 return restrictions.allow_unrated;
466 };
467 match (
468 certification_rank(certification),
469 certification_rank(maximum),
470 ) {
471 (Some(actual), Some(maximum)) => actual <= maximum,
472 _ => restrictions.allow_unrated,
473 }
474}
475
476fn certification_rank(value: &str) -> Option<u8> {
477 match normalize(value).as_str() {
478 "tp" | "0" | "g" => Some(0),
479 "7" | "pg" => Some(1),
480 "12" | "pg-13" => Some(2),
481 "16" | "r" => Some(3),
482 "18" | "nc-17" => Some(4),
483 _ => None,
484 }
485}
486
487fn theme_matches(item: &MediaItem, theme: &str) -> bool {
488 let theme = normalize(theme);
489 if theme.is_empty() {
490 return false;
491 }
492 let title = normalize(&item.title);
493 let overview = normalize(item.overview.as_deref().unwrap_or_default());
494 title.contains(&theme) || overview.contains(&theme)
495}
496
497fn preference_themes(
498 family: &FamilyMediaPreferences,
499 participants: &[ParticipantData],
500) -> Vec<String> {
501 let mut themes = family
502 .liked_themes
503 .iter()
504 .chain(&family.disliked_themes)
505 .chain(
506 participants
507 .iter()
508 .flat_map(|participant| participant.preferences.liked_themes.iter()),
509 )
510 .chain(
511 participants
512 .iter()
513 .flat_map(|participant| participant.preferences.disliked_themes.iter()),
514 )
515 .map(|theme| normalize(theme))
516 .collect::<Vec<_>>();
517 themes.sort();
518 themes.dedup();
519 themes
520}
521
522fn watched_evidence(
523 item_id: MediaItemId,
524 participants: &[ParticipantData],
525) -> (Vec<MediaProfileId>, Vec<MediaProfileId>) {
526 let watched_by = participants
527 .iter()
528 .filter(|participant| participant.watched_items.contains(&item_id))
529 .map(|participant| participant.profile.id)
530 .collect();
531 let unknown = participants
532 .iter()
533 .filter(|participant| !participant.history_complete)
534 .map(|participant| participant.profile.id)
535 .collect();
536 (watched_by, unknown)
537}
538
539fn should_exclude_watched(
540 policy: WatchedPolicy,
541 participant_count: usize,
542 watched_count: usize,
543) -> bool {
544 match policy {
545 WatchedPolicy::AnyParticipant => watched_count > 0,
546 WatchedPolicy::AllParticipants => {
547 participant_count > 0 && watched_count == participant_count
548 }
549 WatchedPolicy::IncludeAll => false,
550 }
551}
552
553fn score_item(
554 item: &MediaItem,
555 family: &FamilyMediaPreferences,
556 participants: &[ParticipantData],
557 weights: &RecommendationWeights,
558) -> (f32, Vec<String>) {
559 let mut score = item.vote_average.unwrap_or(5.0) * weights.audience_rating_scale as f32;
560 let mut reasons = Vec::new();
561 let genres = item
562 .genres
563 .iter()
564 .map(|genre| normalize(genre))
565 .collect::<HashSet<_>>();
566
567 for genre in &family.liked_genres {
568 if genres.contains(&normalize(genre)) {
569 score += weights.family_genre_preference as f32;
570 reasons.push(format!("Matches shared family preference: {genre}"));
571 }
572 }
573 for genre in &family.disliked_genres {
574 if genres.contains(&normalize(genre)) {
575 score -= weights.family_genre_dislike_penalty as f32;
576 reasons.push(format!("Conflicts with shared family dislike: {genre}"));
577 }
578 }
579 if item.original_language.as_ref().is_some_and(|language| {
580 family
581 .preferred_languages
582 .iter()
583 .any(|value| normalize(value) == normalize(language))
584 }) {
585 score += weights.family_language_preference as f32;
586 reasons.push("Matches a shared family language preference".into());
587 }
588
589 for theme in preference_themes(family, participants) {
590 if !theme_matches(item, &theme) {
591 continue;
592 }
593 if family
594 .liked_themes
595 .iter()
596 .any(|liked| normalize(liked) == theme)
597 {
598 score += weights.family_theme_preference as f32;
599 reasons.push(format!("Matches shared family theme: {theme}"));
600 }
601 if family
602 .disliked_themes
603 .iter()
604 .any(|disliked| normalize(disliked) == theme)
605 {
606 score -= weights.family_theme_dislike_penalty as f32;
607 reasons.push(format!(
608 "Conflicts with shared family theme dislike: {theme}"
609 ));
610 }
611 let dislikers = participants
612 .iter()
613 .filter(|participant| {
614 participant
615 .preferences
616 .disliked_themes
617 .iter()
618 .any(|disliked| normalize(disliked) == theme)
619 })
620 .count();
621 if dislikers > 0 {
622 score -= weights.profile_theme_dislike_penalty as f32 * dislikers as f32;
623 for participant in participants {
624 if participant
625 .preferences
626 .disliked_themes
627 .iter()
628 .any(|disliked| normalize(disliked) == theme)
629 {
630 reasons.push(format!(
631 "Conflicts with {}'s theme dislike: {theme}",
632 participant.profile.name
633 ));
634 }
635 }
636 continue;
637 }
638 for participant in participants {
639 if participant
640 .preferences
641 .liked_themes
642 .iter()
643 .any(|liked| normalize(liked) == theme)
644 {
645 score += weights.profile_theme_preference as f32;
646 reasons.push(format!(
647 "Matches {}'s theme preference: {theme}",
648 participant.profile.name
649 ));
650 }
651 }
652 }
653
654 for participant in participants {
655 if item.original_language.as_ref().is_some_and(|language| {
656 participant
657 .preferences
658 .preferred_languages
659 .iter()
660 .any(|value| normalize(value) == normalize(language))
661 }) {
662 score += weights.profile_language_preference as f32;
663 }
664 }
665 for genre in &genres {
666 let dislikers = participants
667 .iter()
668 .filter(|participant| {
669 participant
670 .preferences
671 .disliked_genres
672 .iter()
673 .any(|disliked| normalize(disliked).as_str() == genre.as_str())
674 })
675 .count();
676 if dislikers > 0 {
677 score -= weights.profile_genre_dislike_penalty as f32 * dislikers as f32;
680 for participant in participants {
681 if participant
682 .preferences
683 .disliked_genres
684 .iter()
685 .any(|disliked| normalize(disliked).as_str() == genre.as_str())
686 {
687 reasons.push(format!(
688 "Conflicts with {}'s genre dislike: {genre}",
689 participant.profile.name
690 ));
691 }
692 }
693 continue;
694 }
695 for participant in participants {
696 if participant
697 .preferences
698 .liked_genres
699 .iter()
700 .any(|liked| normalize(liked).as_str() == genre.as_str())
701 {
702 score += weights.profile_genre_preference as f32;
703 reasons.push(format!(
704 "Matches {}'s preference: {}",
705 participant.profile.name, genre
706 ));
707 }
708 if let Some(average) = participant.genre_affinity.get(genre) {
709 score += (average - 2.5) * weights.rating_affinity_scale as f32;
710 }
711 }
712 }
713
714 if item.vote_average.is_some_and(|rating| rating >= 7.5)
715 && item.vote_count.is_some_and(|count| count >= 100)
716 {
717 score += weights.audience_quality_bonus as f32;
718 reasons.push("Strong TMDB audience rating".into());
719 }
720 if let Some(popularity) = item.popularity.filter(|popularity| *popularity > 0.0) {
721 score += popularity.log10().max(0.0) * weights.popularity_scale as f32;
722 }
723 if let Some(release_date) = item.release_date {
724 let age = chrono::Utc::now().year() - release_date.year();
725 if (0..=i32::from(weights.recent_release_years)).contains(&age) {
726 score += weights.recent_release_bonus as f32;
727 reasons.push("Recent release".into());
728 } else if (0..=i32::from(weights.older_release_years)).contains(&age) {
729 score += weights.older_release_bonus as f32;
730 }
731 }
732 (score, reasons)
733}
734
735fn apply_diversity(
736 mut recommendations: Vec<MediaRecommendation>,
737 limit: usize,
738 diversity_penalty: i32,
739) -> Vec<MediaRecommendation> {
740 recommendations.sort_by(|left, right| {
741 right
742 .score
743 .cmp(&left.score)
744 .then_with(|| left.item.title.cmp(&right.item.title))
745 });
746 let mut selected = Vec::new();
747 let mut used_genres = HashSet::new();
748 while !recommendations.is_empty() && selected.len() < limit {
749 let (best_index, _) = recommendations
750 .iter()
751 .enumerate()
752 .map(|(index, recommendation)| {
753 let overlap = recommendation
754 .item
755 .genres
756 .iter()
757 .filter(|genre| used_genres.contains(&normalize(genre)))
758 .count() as i32;
759 (
760 index,
761 recommendation.score
762 - (overlap as f32 * diversity_penalty as f32).round() as i32,
763 )
764 })
765 .max_by(|left, right| {
766 left.1.cmp(&right.1).then_with(|| {
767 recommendations[right.0]
768 .item
769 .title
770 .cmp(&recommendations[left.0].item.title)
771 })
772 })
773 .unwrap();
774 let mut recommendation = recommendations.remove(best_index);
775 let overlap = recommendation
776 .item
777 .genres
778 .iter()
779 .filter(|genre| used_genres.contains(&normalize(genre)))
780 .count() as i32;
781 recommendation.score -= (overlap as f32 * diversity_penalty as f32).round() as i32;
782 used_genres.extend(
783 recommendation
784 .item
785 .genres
786 .iter()
787 .map(|genre| normalize(genre)),
788 );
789 selected.push(recommendation);
790 }
791 selected
792}
793
794fn normalize(value: &str) -> String {
795 value.trim().to_lowercase()
796}
797
798#[cfg(test)]
799mod tests {
800 use super::*;
801 use crate::WatchHistorySource;
802
803 fn item() -> MediaItem {
804 MediaItem {
805 id: MediaItemId::from_external_id("tmdb", "1"),
806 kind: MediaKind::Movie,
807 title: "Example".into(),
808 original_title: None,
809 overview: None,
810 release_date: None,
811 original_language: Some("en".into()),
812 genres: vec!["Comedy".into()],
813 runtime_minutes: Some(100),
814 certification: Some("12".into()),
815 popularity: Some(50.0),
816 vote_average: Some(8.0),
817 vote_count: Some(500),
818 external_ids: vec![],
819 }
820 }
821
822 #[tokio::test]
823 async fn falls_back_to_tmdb_when_watchmode_has_no_title_match() {
824 use std::time::Duration;
825
826 use wiremock::{
827 Mock, MockServer, ResponseTemplate,
828 matchers::{method, path},
829 };
830
831 let tmdb_server = MockServer::start().await;
832 Mock::given(method("GET"))
833 .and(path("/movie/42/watch/providers"))
834 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
835 "results": {
836 "ES": {
837 "link": "https://www.themoviedb.org/movie/42/watch",
838 "flatrate": [{"provider_id": 8, "provider_name": "Netflix"}]
839 }
840 }
841 })))
842 .mount(&tmdb_server)
843 .await;
844 let watchmode_server = MockServer::start().await;
845 Mock::given(method("GET"))
846 .and(path("/search/"))
847 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
848 "title_results": []
849 })))
850 .mount(&watchmode_server)
851 .await;
852
853 let tmdb = TmdbClient::with_base_url("tmdb-key", "es-ES", "ES", tmdb_server.uri()).unwrap();
854 let watchmode = WatchmodeClient::with_options(
855 "watchmode-key",
856 watchmode_server.uri(),
857 Duration::from_secs(60),
858 )
859 .unwrap();
860 let service = RecommendationService::new(
861 MediaStore::open_in_memory().unwrap(),
862 tmdb,
863 Some(watchmode),
864 MediaConfig::default(),
865 )
866 .unwrap();
867 let mut item = item();
868 item.external_ids.push(crate::ExternalId {
869 provider: "tmdb".into(),
870 value: "42".into(),
871 });
872
873 let offers = service.availability(&item).await.unwrap();
874 assert_eq!(offers.len(), 1);
875 assert_eq!(offers[0].service_name, "Netflix");
876 assert_eq!(offers[0].offer_type, crate::OfferType::Subscription);
877 }
878
879 #[tokio::test]
880 async fn recommendation_e2e_uses_only_selected_profiles_and_requires_subscription_offer() {
881 use std::time::Duration;
882
883 use wiremock::{
884 Mock, MockServer, ResponseTemplate,
885 matchers::{method, path, query_param},
886 };
887
888 let tmdb_server = MockServer::start().await;
889 Mock::given(method("GET"))
890 .and(path("/genre/movie/list"))
891 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
892 "genres": [{"id": 35, "name": "Comedy"}]
893 })))
894 .mount(&tmdb_server)
895 .await;
896 Mock::given(method("GET"))
897 .and(path("/search/movie"))
898 .and(query_param("query", "comedy"))
899 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
900 "page": 1,
901 "total_pages": 1,
902 "total_results": 1,
903 "results": [{
904 "id": 42,
905 "title": "Family Comedy",
906 "genre_ids": [35],
907 "original_language": "en",
908 "release_date": "2025-01-01",
909 "popularity": 50.0,
910 "vote_average": 8.0,
911 "vote_count": 500
912 }]
913 })))
914 .mount(&tmdb_server)
915 .await;
916 Mock::given(method("GET"))
917 .and(path("/movie/42"))
918 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
919 "id": 42,
920 "title": "Family Comedy",
921 "release_date": "2025-01-01",
922 "original_language": "en",
923 "genres": [{"id": 35, "name": "Comedy"}],
924 "runtime": 100,
925 "popularity": 50.0,
926 "vote_average": 8.0,
927 "vote_count": 500,
928 "release_dates": {
929 "results": [{
930 "iso_3166_1": "ES",
931 "release_dates": [{"certification": "7"}]
932 }]
933 }
934 })))
935 .mount(&tmdb_server)
936 .await;
937
938 let watchmode_server = MockServer::start().await;
939 Mock::given(method("GET"))
940 .and(path("/search/"))
941 .and(query_param("search_field", "tmdb_movie_id"))
942 .and(query_param("search_value", "42"))
943 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
944 "title_results": [{"id": 9001}]
945 })))
946 .mount(&watchmode_server)
947 .await;
948 Mock::given(method("GET"))
949 .and(path("/title/9001/sources/"))
950 .and(query_param("regions", "ES"))
951 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
952 {"source_id": 203, "name": "Netflix", "type": "sub", "region": "ES", "web_url": "https://example.invalid/title"}
953 ])))
954 .mount(&watchmode_server)
955 .await;
956
957 let media = MediaStore::open_in_memory().unwrap();
958 let family_id = agent_storage::FamilyId::new();
959 let selected = MediaProfile::new(family_id, "Selected viewer");
960 let non_selected = MediaProfile::new(family_id, "Not watching");
961 media.save_profile(&selected).await.unwrap();
962 media.save_profile(&non_selected).await.unwrap();
963
964 let mut family_preferences = FamilyMediaPreferences::new(family_id);
965 family_preferences.liked_genres.push("Comedy".into());
966 media
967 .save_family_preferences(&family_preferences)
968 .await
969 .unwrap();
970
971 let mut non_selected_preferences = ProfilePreferences::new(non_selected.id);
972 non_selected_preferences
973 .disliked_genres
974 .push("Comedy".into());
975 media
976 .save_profile_preferences(&non_selected_preferences)
977 .await
978 .unwrap();
979
980 let candidate_id = MediaItemId::from_external_id("tmdb", "42");
981 let non_selected_watch = MediaWatchEvent {
982 profile_id: non_selected.id,
983 media_item_id: candidate_id,
984 watched_at: chrono::Utc::now(),
985 source: WatchHistorySource::Eme,
986 };
987 let minimal_item = MediaItem {
988 id: candidate_id,
989 kind: MediaKind::Movie,
990 title: "Family Comedy".into(),
991 original_title: None,
992 overview: None,
993 release_date: None,
994 original_language: None,
995 genres: Vec::new(),
996 runtime_minutes: None,
997 certification: None,
998 popularity: None,
999 vote_average: None,
1000 vote_count: None,
1001 external_ids: vec![],
1002 };
1003 media.save_media_item(&minimal_item).await.unwrap();
1004 media.record_watch_event(&non_selected_watch).await.unwrap();
1005
1006 let tmdb =
1007 TmdbClient::with_base_url("test-tmdb-key", "es-ES", "ES", tmdb_server.uri()).unwrap();
1008 let watchmode = WatchmodeClient::with_options(
1009 "test-watchmode-key",
1010 watchmode_server.uri(),
1011 Duration::from_secs(60),
1012 )
1013 .unwrap();
1014 let service =
1015 RecommendationService::new(media, tmdb, Some(watchmode), MediaConfig::default())
1016 .unwrap();
1017
1018 let recommendations = service
1019 .recommend(&RecommendationContext {
1020 family_id,
1021 participants: vec![selected.id],
1022 criteria: RecommendationCriteria {
1023 kinds: vec![MediaKind::Movie],
1024 genres: vec!["Comedy".into()],
1025 query: Some("comedy".into()),
1026 ..RecommendationCriteria::default()
1027 },
1028 watched_policy: None,
1029 })
1030 .await
1031 .unwrap();
1032
1033 assert_eq!(recommendations.len(), 1);
1034 let recommendation = &recommendations[0];
1035 assert_eq!(recommendation.item.title, "Family Comedy");
1036 assert!(recommendation.watched_by.is_empty());
1037 assert_eq!(recommendation.history_unknown_for, vec![selected.id]);
1038 assert_eq!(recommendation.offers.len(), 1);
1039 assert_eq!(recommendation.offers[0].service_name, "Netflix");
1040 assert!(recommendation.score >= 950);
1041 assert!(
1042 recommendation
1043 .reasons
1044 .iter()
1045 .any(|reason| reason.contains("shared family"))
1046 );
1047 assert!(
1048 !recommendation
1049 .reasons
1050 .iter()
1051 .any(|reason| reason.contains("Not watching"))
1052 );
1053 }
1054
1055 #[test]
1056 fn hard_restrictions_are_applied_before_ranking() {
1057 let item = item();
1058 let mut restrictions = ContentRestrictions::new(MediaProfileId::new());
1059 restrictions.disallowed_genres.push("Comedy".into());
1060 assert!(!passes_restrictions(&item, &restrictions));
1061
1062 restrictions.disallowed_genres.clear();
1063 restrictions.maximum_certification = Some("7".into());
1064 assert!(!passes_restrictions(&item, &restrictions));
1065 restrictions.maximum_certification = Some("16".into());
1066 assert!(passes_restrictions(&item, &restrictions));
1067 }
1068
1069 #[test]
1070 fn one_selected_participants_dislike_is_not_cancelled_by_another_profiles_like() {
1071 let family_id = agent_storage::FamilyId::new();
1072 let mut family = FamilyMediaPreferences::new(family_id);
1073 family.liked_genres.push("Comedy".into());
1074
1075 let liked_id = MediaProfileId::new();
1076 let mut liked_preferences = ProfilePreferences::new(liked_id);
1077 liked_preferences.liked_genres.push("Comedy".into());
1078 let liked = ParticipantData {
1079 profile: MediaProfile {
1080 id: liked_id,
1081 family_id: Some(family_id),
1082 owner_id: None,
1083 name: "Likes comedy".into(),
1084 user_id: None,
1085 active: true,
1086 },
1087 preferences: liked_preferences,
1088 restrictions: ContentRestrictions::new(liked_id),
1089 watched_items: HashSet::new(),
1090 history_complete: true,
1091 genre_affinity: HashMap::new(),
1092 };
1093
1094 let disliked_id = MediaProfileId::new();
1095 let mut disliked_preferences = ProfilePreferences::new(disliked_id);
1096 disliked_preferences.disliked_genres.push("Comedy".into());
1097 let disliked = ParticipantData {
1098 profile: MediaProfile {
1099 id: disliked_id,
1100 family_id: Some(family_id),
1101 owner_id: None,
1102 name: "Dislikes comedy".into(),
1103 user_id: None,
1104 active: true,
1105 },
1106 preferences: disliked_preferences,
1107 restrictions: ContentRestrictions::new(disliked_id),
1108 watched_items: HashSet::new(),
1109 history_complete: true,
1110 genre_affinity: HashMap::new(),
1111 };
1112
1113 let weights = RecommendationWeights::default();
1114 let (likes_only, _) = score_item(&item(), &family, &[liked.clone()], &weights);
1115 let (conflicting, reasons) = score_item(&item(), &family, &[disliked, liked], &weights);
1116
1117 assert!(conflicting < likes_only);
1118 assert!(
1119 reasons
1120 .iter()
1121 .any(|reason| reason.contains("shared family"))
1122 );
1123 assert!(!reasons.iter().any(|reason| reason.contains("Likes comedy")));
1124 }
1125
1126 #[test]
1127 fn unknown_certification_is_not_silently_treated_as_safe() {
1128 let mut item = item();
1129 item.certification = None;
1130 let mut restrictions = ContentRestrictions::new(MediaProfileId::new());
1131 restrictions.maximum_certification = Some("12".into());
1132 assert!(!passes_restrictions(&item, &restrictions));
1133 restrictions.allow_unrated = true;
1134 assert!(passes_restrictions(&item, &restrictions));
1135 }
1136
1137 #[test]
1138 fn theme_criteria_and_restrictions_match_title_and_overview() {
1139 let mut candidate = item();
1140 candidate.overview = Some("A story about space exploration".into());
1141 let criteria = RecommendationCriteria {
1142 themes: vec!["space".into()],
1143 ..RecommendationCriteria::default()
1144 };
1145 assert!(matches_criteria(&candidate, &criteria));
1146
1147 let mut restrictions = ContentRestrictions::new(MediaProfileId::new());
1148 restrictions.disallowed_themes.push("space".into());
1149 assert!(!passes_restrictions(&candidate, &restrictions));
1150 }
1151
1152 #[test]
1153 fn shared_and_profile_theme_preferences_contribute_to_score() {
1154 let family_id = agent_storage::FamilyId::new();
1155 let mut family = FamilyMediaPreferences::new(family_id);
1156 family.liked_themes.push("space".into());
1157 let profile_id = MediaProfileId::new();
1158 let mut preferences = ProfilePreferences::new(profile_id);
1159 preferences.liked_themes.push("space".into());
1160 let participant = ParticipantData {
1161 profile: MediaProfile {
1162 id: profile_id,
1163 family_id: Some(family_id),
1164 owner_id: None,
1165 name: "Selected".into(),
1166 user_id: None,
1167 active: true,
1168 },
1169 preferences,
1170 restrictions: ContentRestrictions::new(profile_id),
1171 watched_items: HashSet::new(),
1172 history_complete: true,
1173 genre_affinity: HashMap::new(),
1174 };
1175 let mut candidate = item();
1176 candidate.overview = Some("A story about space exploration".into());
1177 let (score, reasons) = score_item(
1178 &candidate,
1179 &family,
1180 &[participant],
1181 &RecommendationWeights::default(),
1182 );
1183 assert!(
1184 reasons
1185 .iter()
1186 .any(|reason| reason.contains("shared family theme"))
1187 );
1188 assert!(
1189 reasons
1190 .iter()
1191 .any(|reason| reason.contains("theme preference"))
1192 );
1193 assert!(score > 900.0);
1194 }
1195
1196 #[test]
1197 fn watched_policies_have_distinct_semantics() {
1198 assert!(should_exclude_watched(WatchedPolicy::AnyParticipant, 3, 1));
1199 assert!(!should_exclude_watched(
1200 WatchedPolicy::AllParticipants,
1201 3,
1202 1
1203 ));
1204 assert!(should_exclude_watched(WatchedPolicy::AllParticipants, 3, 3));
1205 assert!(!should_exclude_watched(WatchedPolicy::IncludeAll, 3, 3));
1206 }
1207
1208 #[test]
1209 fn unknown_history_is_reported_but_not_mistaken_for_unwatched_or_watched() {
1210 let profile_id = MediaProfileId::new();
1211 let participant = ParticipantData {
1212 profile: MediaProfile {
1213 id: profile_id,
1214 family_id: Some(agent_storage::FamilyId::new()),
1215 owner_id: None,
1216 name: "Viewer".into(),
1217 user_id: None,
1218 active: true,
1219 },
1220 preferences: ProfilePreferences::new(profile_id),
1221 restrictions: ContentRestrictions::new(profile_id),
1222 watched_items: HashSet::new(),
1223 history_complete: false,
1224 genre_affinity: HashMap::new(),
1225 };
1226 let (watched_by, unknown) = watched_evidence(item().id, &[participant]);
1227 assert!(watched_by.is_empty());
1228 assert_eq!(unknown, vec![profile_id]);
1229 assert!(!should_exclude_watched(WatchedPolicy::AnyParticipant, 1, 0));
1230 }
1231
1232 #[test]
1233 fn shared_preferences_and_selected_participant_preferences_contribute_to_score() {
1234 let mut family = FamilyMediaPreferences::new(agent_storage::FamilyId::new());
1235 family.liked_genres.push("Comedy".into());
1236 let profile = MediaProfile {
1237 id: MediaProfileId::new(),
1238 family_id: Some(family.family_id),
1239 owner_id: None,
1240 name: "Selected".into(),
1241 user_id: None,
1242 active: true,
1243 };
1244 let mut preferences = ProfilePreferences::new(profile.id);
1245 preferences.liked_genres.push("Comedy".into());
1246 let participant = ParticipantData {
1247 profile,
1248 preferences,
1249 restrictions: ContentRestrictions::new(MediaProfileId::new()),
1250 watched_items: HashSet::new(),
1251 history_complete: true,
1252 genre_affinity: HashMap::new(),
1253 };
1254
1255 let (score, reasons) = score_item(
1256 &item(),
1257 &family,
1258 &[participant],
1259 &RecommendationWeights::default(),
1260 );
1261 assert!(score > 600.0);
1262 assert!(
1263 reasons
1264 .iter()
1265 .any(|reason| reason.contains("shared family"))
1266 );
1267 assert!(reasons.iter().any(|reason| reason.contains("Selected")));
1268 }
1269}