Skip to main content

media_tools/
store.rs

1//! SQLite persistence for media profiles, preferences, catalogue and viewing activity.
2use std::{path::Path, sync::Arc};
3
4use agent_storage::{ExternalConnectionId, FamilyId, UserId};
5use chrono::{DateTime, Utc};
6use rusqlite::{Connection, OptionalExtension, params};
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use tokio::sync::Mutex;
10
11use crate::{
12    ContentRestrictions, FamilyMediaPreferences, MediaItem, MediaProfile, MediaProfileId,
13    MediaRating, MediaWatchEvent, MediaWatchlistItem, ProfilePreferences, ProviderSyncState,
14    StreamingOffer,
15};
16
17/// SQLite-backed persistence for media data.
18///
19/// Family membership remains owned by `agent-storage`; this store only scopes
20/// media records by the authoritative family ID supplied by the application.
21#[derive(Clone)]
22pub struct MediaStore {
23    connection: Arc<Mutex<Connection>>,
24}
25
26impl MediaStore {
27    /// Open or create a media database at `path`.
28    pub fn open(path: impl AsRef<Path>) -> Result<Self, MediaStoreError> {
29        let connection = Connection::open(path).map_err(storage)?;
30        Self::from_connection(connection)
31    }
32
33    /// Create an isolated in-memory media database (primarily useful in tests).
34    pub fn open_in_memory() -> Result<Self, MediaStoreError> {
35        Self::from_connection(Connection::open_in_memory().map_err(storage)?)
36    }
37
38    fn from_connection(connection: Connection) -> Result<Self, MediaStoreError> {
39        connection
40            .busy_timeout(std::time::Duration::from_secs(5))
41            .map_err(storage)?;
42        connection
43            .execute_batch(include_str!("../migrations/0001_media.sql"))
44            .map_err(storage)?;
45        connection
46            .execute_batch(include_str!(
47                "../migrations/0002_media_external_connections.sql"
48            ))
49            .map_err(storage)?;
50        connection
51            .execute_batch(include_str!("../migrations/0003_media_watchlist.sql"))
52            .map_err(storage)?;
53        let has_personal_owner_column = {
54            let mut statement = connection
55                .prepare("PRAGMA table_info(media_profiles)")
56                .map_err(storage)?;
57            let columns = statement
58                .query_map([], |row| row.get::<_, String>(1))
59                .map_err(storage)?;
60            columns
61                .collect::<Result<Vec<_>, _>>()
62                .map_err(storage)?
63                .iter()
64                .any(|column| column == "owner_id")
65        };
66        if !has_personal_owner_column {
67            connection
68                .execute_batch(include_str!(
69                    "../migrations/0004_personal_media_profiles.sql"
70                ))
71                .map_err(storage)?;
72        }
73        Ok(Self {
74            connection: Arc::new(Mutex::new(connection)),
75        })
76    }
77
78    /// Insert or update a media profile without changing its ownership scope.
79    pub async fn save_profile(&self, profile: &MediaProfile) -> Result<(), MediaStoreError> {
80        if profile.name.trim().is_empty() {
81            return Err(MediaStoreError::Invalid(
82                "profile name must not be empty".into(),
83            ));
84        }
85        let payload = encode(profile)?;
86        let now = Utc::now().to_rfc3339();
87        let connection = self.connection.lock().await;
88        let changed = connection
89            .execute(
90                "INSERT INTO media_profiles(id,family_id,owner_id,user_id,name,active,payload,created_at,updated_at)
91                 VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?8)
92                 ON CONFLICT(id) DO UPDATE SET
93                    owner_id=excluded.owner_id,
94                    user_id=excluded.user_id,
95                    name=excluded.name,
96                    active=excluded.active,
97                    payload=excluded.payload,
98                    updated_at=excluded.updated_at
99                 WHERE media_profiles.family_id IS excluded.family_id
100                   AND media_profiles.owner_id IS excluded.owner_id",
101                params![
102                    profile.id.to_string(),
103                    profile.family_id.map(|id| id.to_string()),
104                    profile.owner_id.map(|id| id.to_string()),
105                    profile.user_id.map(|id| id.to_string()),
106                    profile.name.trim(),
107                    profile.active,
108                    payload,
109                    now,
110                ],
111            )
112            .map_err(storage)?;
113        if changed == 0 {
114            return Err(MediaStoreError::ProfileFamilyMismatch);
115        }
116        Ok(())
117    }
118
119    /// Return the user's personal profile, creating it exactly once when absent.
120    pub async fn get_or_create_personal_profile(
121        &self,
122        owner_id: UserId,
123    ) -> Result<MediaProfile, MediaStoreError> {
124        let mut connection = self.connection.lock().await;
125        let transaction = connection.transaction().map_err(storage)?;
126        let existing = transaction
127            .query_row(
128                "SELECT payload FROM media_profiles WHERE owner_id=?1 AND family_id IS NULL",
129                [owner_id.to_string()],
130                |row| row.get::<_, String>(0),
131            )
132            .optional()
133            .map_err(storage)?;
134        if let Some(payload) = existing {
135            let profile = decode(&payload)?;
136            transaction.commit().map_err(storage)?;
137            return Ok(profile);
138        }
139
140        let profile = MediaProfile::new_personal(owner_id, "Personal");
141        let payload = encode(&profile)?;
142        let now = Utc::now().to_rfc3339();
143        transaction
144            .execute(
145                "INSERT INTO media_profiles(
146                    id,family_id,owner_id,user_id,name,active,payload,created_at,updated_at
147                 ) VALUES(?1,NULL,?2,NULL,?3,1,?4,?5,?5)",
148                params![
149                    profile.id.to_string(),
150                    owner_id.to_string(),
151                    profile.name,
152                    payload,
153                    now
154                ],
155            )
156            .map_err(storage)?;
157        transaction.commit().map_err(storage)?;
158        Ok(profile)
159    }
160
161    /// Load a personal profile only when it is owned by the requesting EME user.
162    pub async fn get_personal_profile(
163        &self,
164        owner_id: UserId,
165        profile_id: MediaProfileId,
166    ) -> Result<Option<MediaProfile>, MediaStoreError> {
167        let connection = self.connection.lock().await;
168        let payload = connection
169            .query_row(
170                "SELECT payload FROM media_profiles
171                 WHERE owner_id=?1 AND family_id IS NULL AND id=?2 AND active=1",
172                params![owner_id.to_string(), profile_id.to_string()],
173                |row| row.get::<_, String>(0),
174            )
175            .optional()
176            .map_err(storage)?;
177        payload.as_deref().map(decode).transpose()
178    }
179
180    /// List profiles belonging to one family; no membership data is duplicated here.
181    pub async fn list_profiles(
182        &self,
183        family_id: FamilyId,
184    ) -> Result<Vec<MediaProfile>, MediaStoreError> {
185        let connection = self.connection.lock().await;
186        let mut statement = connection
187            .prepare("SELECT payload FROM media_profiles WHERE family_id=?1 ORDER BY name,id")
188            .map_err(storage)?;
189        let rows = statement
190            .query_map([family_id.to_string()], |row| row.get::<_, String>(0))
191            .map_err(storage)?;
192        rows.map(|row| decode(&row.map_err(storage)?)).collect()
193    }
194
195    /// Load a profile only within the requested family boundary.
196    pub async fn get_profile(
197        &self,
198        family_id: FamilyId,
199        profile_id: MediaProfileId,
200    ) -> Result<Option<MediaProfile>, MediaStoreError> {
201        let connection = self.connection.lock().await;
202        let payload = connection
203            .query_row(
204                "SELECT payload FROM media_profiles WHERE family_id=?1 AND id=?2",
205                params![family_id.to_string(), profile_id.to_string()],
206                |row| row.get::<_, String>(0),
207            )
208            .optional()
209            .map_err(storage)?;
210        payload.as_deref().map(decode).transpose()
211    }
212
213    /// Remove a profile and its dependent preferences and activity.
214    pub async fn delete_profile(
215        &self,
216        family_id: FamilyId,
217        profile_id: MediaProfileId,
218    ) -> Result<(), MediaStoreError> {
219        let connection = self.connection.lock().await;
220        let changed = connection
221            .execute(
222                "DELETE FROM media_profiles WHERE family_id=?1 AND id=?2",
223                params![family_id.to_string(), profile_id.to_string()],
224            )
225            .map_err(storage)?;
226        if changed == 0 {
227            return Err(MediaStoreError::NotFound);
228        }
229        Ok(())
230    }
231
232    pub async fn save_profile_preferences(
233        &self,
234        preferences: &ProfilePreferences,
235    ) -> Result<(), MediaStoreError> {
236        let payload = encode(preferences)?;
237        let connection = self.connection.lock().await;
238        connection
239            .execute(
240                "INSERT INTO profile_preferences(profile_id,payload,updated_at) VALUES(?1,?2,?3)
241                 ON CONFLICT(profile_id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at",
242                params![preferences.profile_id.to_string(), payload, Utc::now().to_rfc3339()],
243            )
244            .map_err(storage)?;
245        Ok(())
246    }
247
248    pub async fn get_profile_preferences(
249        &self,
250        profile_id: MediaProfileId,
251    ) -> Result<Option<ProfilePreferences>, MediaStoreError> {
252        self.get_payload(
253            "SELECT payload FROM profile_preferences WHERE profile_id=?1",
254            profile_id.to_string(),
255        )
256        .await
257    }
258
259    pub async fn save_content_restrictions(
260        &self,
261        restrictions: &ContentRestrictions,
262    ) -> Result<(), MediaStoreError> {
263        let payload = encode(restrictions)?;
264        let connection = self.connection.lock().await;
265        connection
266            .execute(
267                "INSERT INTO profile_restrictions(profile_id,payload,updated_at) VALUES(?1,?2,?3)
268                 ON CONFLICT(profile_id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at",
269                params![restrictions.profile_id.to_string(), payload, Utc::now().to_rfc3339()],
270            )
271            .map_err(storage)?;
272        Ok(())
273    }
274
275    pub async fn get_content_restrictions(
276        &self,
277        profile_id: MediaProfileId,
278    ) -> Result<Option<ContentRestrictions>, MediaStoreError> {
279        self.get_payload(
280            "SELECT payload FROM profile_restrictions WHERE profile_id=?1",
281            profile_id.to_string(),
282        )
283        .await
284    }
285
286    pub async fn save_family_preferences(
287        &self,
288        preferences: &FamilyMediaPreferences,
289    ) -> Result<(), MediaStoreError> {
290        let payload = encode(preferences)?;
291        let connection = self.connection.lock().await;
292        connection
293            .execute(
294                "INSERT INTO family_preferences(family_id,payload,updated_at) VALUES(?1,?2,?3)
295                 ON CONFLICT(family_id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at",
296                params![preferences.family_id.to_string(), payload, Utc::now().to_rfc3339()],
297            )
298            .map_err(storage)?;
299        Ok(())
300    }
301
302    pub async fn get_family_preferences(
303        &self,
304        family_id: FamilyId,
305    ) -> Result<Option<FamilyMediaPreferences>, MediaStoreError> {
306        self.get_payload(
307            "SELECT payload FROM family_preferences WHERE family_id=?1",
308            family_id.to_string(),
309        )
310        .await
311    }
312
313    pub async fn save_media_item(&self, item: &MediaItem) -> Result<(), MediaStoreError> {
314        let payload = encode(item)?;
315        let connection = self.connection.lock().await;
316        connection
317            .execute(
318                "INSERT INTO media_items(id,kind,payload,updated_at) VALUES(?1,?2,?3,?4)
319                 ON CONFLICT(id) DO UPDATE SET kind=excluded.kind,payload=excluded.payload,updated_at=excluded.updated_at",
320                params![item.id.to_string(), format!("{:?}", item.kind).to_lowercase(), payload, Utc::now().to_rfc3339()],
321            )
322            .map_err(storage)?;
323        Ok(())
324    }
325
326    pub async fn get_media_item(
327        &self,
328        id: crate::MediaItemId,
329    ) -> Result<Option<MediaItem>, MediaStoreError> {
330        self.get_payload(
331            "SELECT payload FROM media_items WHERE id=?1",
332            id.to_string(),
333        )
334        .await
335    }
336
337    /// Record a viewing event idempotently (same profile, item, timestamp and source).
338    pub async fn record_watch_event(&self, event: &MediaWatchEvent) -> Result<(), MediaStoreError> {
339        let payload = encode(event)?;
340        let connection = self.connection.lock().await;
341        connection
342            .execute(
343                "INSERT OR IGNORE INTO watch_history(profile_id,media_item_id,watched_at,source,payload)
344                 VALUES(?1,?2,?3,?4,?5)",
345                params![
346                    event.profile_id.to_string(),
347                    event.media_item_id.to_string(),
348                    event.watched_at.to_rfc3339(),
349                    format!("{:?}", event.source).to_lowercase(),
350                    payload,
351                ],
352            )
353            .map_err(storage)?;
354        Ok(())
355    }
356
357    pub async fn list_watch_history(
358        &self,
359        profile_id: MediaProfileId,
360    ) -> Result<Vec<MediaWatchEvent>, MediaStoreError> {
361        self.list_payloads(
362            "SELECT payload FROM watch_history WHERE profile_id=?1 ORDER BY watched_at DESC,id DESC",
363            profile_id.to_string(),
364        )
365        .await
366    }
367
368    /// Store a profile rating, replacing the previous rating from the same source.
369    pub async fn save_rating(&self, rating: &MediaRating) -> Result<(), MediaStoreError> {
370        if !rating.value.is_finite() || !(0.0..=5.0).contains(&rating.value) {
371            return Err(MediaStoreError::Invalid(
372                "rating must be between 0 and 5".into(),
373            ));
374        }
375        let payload = encode(rating)?;
376        let connection = self.connection.lock().await;
377        connection
378            .execute(
379                "INSERT INTO media_ratings(profile_id,media_item_id,source,value,rated_at,payload)
380                 VALUES(?1,?2,?3,?4,?5,?6)
381                 ON CONFLICT(profile_id,media_item_id,source) DO UPDATE SET
382                    value=excluded.value,rated_at=excluded.rated_at,payload=excluded.payload",
383                params![
384                    rating.profile_id.to_string(),
385                    rating.media_item_id.to_string(),
386                    format!("{:?}", rating.source).to_lowercase(),
387                    rating.value,
388                    rating.rated_at.to_rfc3339(),
389                    payload,
390                ],
391            )
392            .map_err(storage)?;
393        Ok(())
394    }
395
396    pub async fn list_ratings(
397        &self,
398        profile_id: MediaProfileId,
399    ) -> Result<Vec<MediaRating>, MediaStoreError> {
400        self.list_payloads(
401            "SELECT payload FROM media_ratings WHERE profile_id=?1 ORDER BY rated_at DESC, CASE source WHEN 'eme' THEN 1 ELSE 0 END DESC",
402            profile_id.to_string(),
403        )
404        .await
405    }
406
407    pub async fn save_streaming_offer(
408        &self,
409        offer: &StreamingOffer,
410    ) -> Result<(), MediaStoreError> {
411        let payload = encode(offer)?;
412        let connection = self.connection.lock().await;
413        connection
414            .execute(
415                "INSERT INTO streaming_offers(media_item_id,service_id,offer_type,region,payload,updated_at)
416                 VALUES(?1,?2,?3,?4,?5,?6)
417                 ON CONFLICT(media_item_id,service_id,offer_type,region) DO UPDATE SET
418                    payload=excluded.payload,updated_at=excluded.updated_at",
419                params![
420                    offer.media_item_id.to_string(),
421                    offer.service_id,
422                    format!("{:?}", offer.offer_type).to_lowercase(),
423                    offer.region,
424                    payload,
425                    Utc::now().to_rfc3339(),
426                ],
427            )
428            .map_err(storage)?;
429        Ok(())
430    }
431
432    pub async fn list_streaming_offers(
433        &self,
434        item_id: crate::MediaItemId,
435        region: &str,
436    ) -> Result<Vec<StreamingOffer>, MediaStoreError> {
437        let connection = self.connection.lock().await;
438        let mut statement = connection
439            .prepare("SELECT payload FROM streaming_offers WHERE media_item_id=?1 AND region=?2 ORDER BY service_id,offer_type")
440            .map_err(storage)?;
441        let rows = statement
442            .query_map(params![item_id.to_string(), region], |row| {
443                row.get::<_, String>(0)
444            })
445            .map_err(storage)?;
446        rows.map(|row| decode(&row.map_err(storage)?)).collect()
447    }
448
449    /// Persist a short-lived, hashed OAuth state bound to the initiating user and profile.
450    pub async fn create_pending_trakt_link(
451        &self,
452        state: &str,
453        pending: &PendingTraktLink,
454        expires_at: DateTime<Utc>,
455    ) -> Result<(), MediaStoreError> {
456        if state.trim().is_empty() {
457            return Err(MediaStoreError::Invalid(
458                "OAuth state must not be empty".into(),
459            ));
460        }
461        let state_hash = hash_state(state);
462        let payload = encode(pending)?;
463        let now = Utc::now().to_rfc3339();
464        let connection = self.connection.lock().await;
465        connection
466            .execute(
467                "INSERT INTO pending_media_connections(state_hash,provider,payload,expires_at,created_at)
468                 VALUES(?1,'trakt',?2,?3,?4)",
469                params![state_hash, payload, expires_at.to_rfc3339(), now],
470            )
471            .map_err(storage)?;
472        Ok(())
473    }
474
475    pub async fn get_pending_trakt_link(
476        &self,
477        state: &str,
478    ) -> Result<PendingTraktLink, MediaStoreError> {
479        let state_hash = hash_state(state);
480        let connection = self.connection.lock().await;
481        let row = connection
482            .query_row(
483                "SELECT payload,expires_at FROM pending_media_connections
484                 WHERE state_hash=?1 AND provider='trakt'",
485                [state_hash.as_str()],
486                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
487            )
488            .optional()
489            .map_err(storage)?;
490        let Some((payload, expires_at)) = row else {
491            return Err(MediaStoreError::PendingNotFound);
492        };
493        let expires_at = DateTime::parse_from_rfc3339(&expires_at)
494            .map(|value| value.with_timezone(&Utc))
495            .map_err(|error| MediaStoreError::Storage(error.to_string()))?;
496        if Utc::now() > expires_at {
497            return Err(MediaStoreError::PendingExpired);
498        }
499        decode(&payload)
500    }
501
502    /// Consume a pending Trakt state exactly once and reject expired attempts.
503    pub async fn consume_pending_trakt_link(
504        &self,
505        state: &str,
506        now: DateTime<Utc>,
507    ) -> Result<PendingTraktLink, MediaStoreError> {
508        let state_hash = hash_state(state);
509        let mut connection = self.connection.lock().await;
510        let transaction = connection.transaction().map_err(storage)?;
511        let row = transaction
512            .query_row(
513                "SELECT payload,expires_at FROM pending_media_connections
514                 WHERE state_hash=?1 AND provider='trakt'",
515                [state_hash.as_str()],
516                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
517            )
518            .optional()
519            .map_err(storage)?;
520        let Some((payload, expires_at)) = row else {
521            return Err(MediaStoreError::PendingNotFound);
522        };
523        let expires_at = DateTime::parse_from_rfc3339(&expires_at)
524            .map(|value| value.with_timezone(&Utc))
525            .map_err(|error| MediaStoreError::Storage(error.to_string()))?;
526        transaction
527            .execute(
528                "DELETE FROM pending_media_connections WHERE state_hash=?1",
529                [state_hash.as_str()],
530            )
531            .map_err(storage)?;
532        transaction.commit().map_err(storage)?;
533        if now > expires_at {
534            return Err(MediaStoreError::PendingExpired);
535        }
536        decode(&payload)
537    }
538
539    /// Associate a profile with an existing encrypted EME external connection.
540    pub async fn save_external_connection_link(
541        &self,
542        link: &MediaExternalConnectionLink,
543    ) -> Result<(), MediaStoreError> {
544        let payload = encode(link)?;
545        let connection = self.connection.lock().await;
546        let profile_exists: bool = connection
547            .query_row(
548                "SELECT EXISTS(
549                    SELECT 1 FROM media_profiles
550                    WHERE id=?1 AND family_id IS ?2
551                      AND (owner_id=?3 OR user_id=?3)
552                 )",
553                params![
554                    link.profile_id.to_string(),
555                    link.family_id.map(|id| id.to_string()),
556                    link.owner_id.to_string()
557                ],
558                |row| row.get(0),
559            )
560            .map_err(storage)?;
561        if !profile_exists {
562            return Err(MediaStoreError::NotFound);
563        }
564        let already_linked: bool = connection
565            .query_row(
566                "SELECT EXISTS(
567                    SELECT 1 FROM media_external_connections
568                    WHERE external_connection_id=?1 AND profile_id<>?2
569                 )",
570                params![
571                    link.external_connection_id.to_string(),
572                    link.profile_id.to_string()
573                ],
574                |row| row.get(0),
575            )
576            .map_err(storage)?;
577        if already_linked {
578            return Err(MediaStoreError::Invalid(
579                "an external connection can only be linked to one media profile".into(),
580            ));
581        }
582        connection
583            .execute(
584                "INSERT INTO media_external_connections(
585                    profile_id,family_id,provider,external_connection_id,owner_id,
586                    provider_subject,display_name,linked_at,payload
587                 ) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9)
588                 ON CONFLICT(profile_id,provider) DO UPDATE SET
589                    family_id=excluded.family_id,
590                    external_connection_id=excluded.external_connection_id,
591                    owner_id=excluded.owner_id,
592                    provider_subject=excluded.provider_subject,
593                    display_name=excluded.display_name,
594                    linked_at=excluded.linked_at,
595                    payload=excluded.payload",
596                params![
597                    link.profile_id.to_string(),
598                    link.family_id.map(|id| id.to_string()),
599                    link.provider,
600                    link.external_connection_id.to_string(),
601                    link.owner_id.to_string(),
602                    link.provider_subject,
603                    link.display_name,
604                    link.linked_at.to_rfc3339(),
605                    payload,
606                ],
607            )
608            .map_err(storage)?;
609        Ok(())
610    }
611
612    pub async fn get_external_connection_link(
613        &self,
614        profile_id: MediaProfileId,
615        provider: &str,
616    ) -> Result<Option<MediaExternalConnectionLink>, MediaStoreError> {
617        let connection = self.connection.lock().await;
618        let payload = connection
619            .query_row(
620                "SELECT payload FROM media_external_connections WHERE profile_id=?1 AND provider=?2",
621                params![profile_id.to_string(), provider],
622                |row| row.get::<_, String>(0),
623            )
624            .optional()
625            .map_err(storage)?;
626        payload.as_deref().map(decode).transpose()
627    }
628
629    /// Remove a profile's provider link; token revocation remains the caller's responsibility.
630    pub async fn delete_external_connection_link(
631        &self,
632        profile_id: MediaProfileId,
633        provider: &str,
634    ) -> Result<(), MediaStoreError> {
635        let connection = self.connection.lock().await;
636        connection
637            .execute(
638                "DELETE FROM media_external_connections WHERE profile_id=?1 AND provider=?2",
639                params![profile_id.to_string(), provider],
640            )
641            .map_err(storage)?;
642        Ok(())
643    }
644
645    pub async fn save_watchlist_item(
646        &self,
647        item: &MediaWatchlistItem,
648    ) -> Result<(), MediaStoreError> {
649        let payload = encode(item)?;
650        let connection = self.connection.lock().await;
651        connection
652            .execute(
653                "INSERT INTO media_watchlist(profile_id,media_item_id,source,added_at,payload)
654                 VALUES(?1,?2,?3,?4,?5)
655                 ON CONFLICT(profile_id,media_item_id,source) DO UPDATE SET
656                    added_at=excluded.added_at,payload=excluded.payload",
657                params![
658                    item.profile_id.to_string(),
659                    item.media_item_id.to_string(),
660                    format!("{:?}", item.source).to_lowercase(),
661                    item.added_at.to_rfc3339(),
662                    payload,
663                ],
664            )
665            .map_err(storage)?;
666        Ok(())
667    }
668
669    pub async fn list_watchlist(
670        &self,
671        profile_id: MediaProfileId,
672    ) -> Result<Vec<MediaWatchlistItem>, MediaStoreError> {
673        self.list_payloads(
674            "SELECT payload FROM media_watchlist WHERE profile_id=?1 ORDER BY added_at DESC",
675            profile_id.to_string(),
676        )
677        .await
678    }
679
680    /// Replace a provider's watchlist atomically so removals are reflected locally.
681    pub async fn replace_watchlist(
682        &self,
683        profile_id: MediaProfileId,
684        source: crate::WatchHistorySource,
685        items: &[MediaWatchlistItem],
686    ) -> Result<(), MediaStoreError> {
687        if items
688            .iter()
689            .any(|item| item.profile_id != profile_id || item.source != source)
690        {
691            return Err(MediaStoreError::Invalid(
692                "watchlist items must match the target profile and source".into(),
693            ));
694        }
695        let mut connection = self.connection.lock().await;
696        let transaction = connection.transaction().map_err(storage)?;
697        transaction
698            .execute(
699                "DELETE FROM media_watchlist WHERE profile_id=?1 AND source=?2",
700                params![
701                    profile_id.to_string(),
702                    format!("{:?}", source).to_lowercase()
703                ],
704            )
705            .map_err(storage)?;
706        for item in items {
707            transaction
708                .execute(
709                    "INSERT INTO media_watchlist(profile_id,media_item_id,source,added_at,payload)
710                     VALUES(?1,?2,?3,?4,?5)",
711                    params![
712                        item.profile_id.to_string(),
713                        item.media_item_id.to_string(),
714                        format!("{:?}", item.source).to_lowercase(),
715                        item.added_at.to_rfc3339(),
716                        encode(item)?,
717                    ],
718                )
719                .map_err(storage)?;
720        }
721        transaction.commit().map_err(storage)?;
722        Ok(())
723    }
724
725    /// Replace all ratings from one provider after a full provider snapshot.
726    pub async fn replace_ratings(
727        &self,
728        profile_id: MediaProfileId,
729        source: crate::WatchHistorySource,
730        ratings: &[MediaRating],
731    ) -> Result<(), MediaStoreError> {
732        if ratings.iter().any(|rating| {
733            rating.profile_id != profile_id
734                || rating.source != source
735                || !rating.value.is_finite()
736                || !(0.0..=5.0).contains(&rating.value)
737        }) {
738            return Err(MediaStoreError::Invalid(
739                "ratings must match the target profile/source and use the 0–5 scale".into(),
740            ));
741        }
742        let mut connection = self.connection.lock().await;
743        let transaction = connection.transaction().map_err(storage)?;
744        transaction
745            .execute(
746                "DELETE FROM media_ratings WHERE profile_id=?1 AND source=?2",
747                params![
748                    profile_id.to_string(),
749                    format!("{:?}", source).to_lowercase()
750                ],
751            )
752            .map_err(storage)?;
753        for rating in ratings {
754            transaction
755                .execute(
756                    "INSERT INTO media_ratings(profile_id,media_item_id,source,value,rated_at,payload)
757                     VALUES(?1,?2,?3,?4,?5,?6)",
758                    params![
759                        rating.profile_id.to_string(),
760                        rating.media_item_id.to_string(),
761                        format!("{:?}", rating.source).to_lowercase(),
762                        rating.value,
763                        rating.rated_at.to_rfc3339(),
764                        encode(rating)?,
765                    ],
766                )
767                .map_err(storage)?;
768        }
769        transaction.commit().map_err(storage)?;
770        Ok(())
771    }
772
773    pub async fn get_provider_sync_state(
774        &self,
775        profile_id: MediaProfileId,
776        provider: &str,
777    ) -> Result<Option<ProviderSyncState>, MediaStoreError> {
778        let connection = self.connection.lock().await;
779        let row = connection
780            .query_row(
781                "SELECT cursor,last_synced_at,status FROM provider_sync_state
782                 WHERE profile_id=?1 AND provider=?2",
783                params![profile_id.to_string(), provider],
784                |row| {
785                    Ok((
786                        row.get::<_, Option<String>>(0)?,
787                        row.get::<_, Option<String>>(1)?,
788                        row.get::<_, String>(2)?,
789                    ))
790                },
791            )
792            .optional()
793            .map_err(storage)?;
794        row.map(|(cursor, last_synced_at, status)| {
795            let last_synced_at = last_synced_at
796                .map(|value| {
797                    DateTime::parse_from_rfc3339(&value)
798                        .map(|date| date.with_timezone(&Utc))
799                        .map_err(|error| MediaStoreError::Storage(error.to_string()))
800                })
801                .transpose()?;
802            Ok(ProviderSyncState {
803                profile_id,
804                provider: provider.to_owned(),
805                cursor,
806                last_synced_at,
807                status,
808            })
809        })
810        .transpose()
811    }
812
813    pub async fn save_provider_sync_state(
814        &self,
815        state: &ProviderSyncState,
816    ) -> Result<(), MediaStoreError> {
817        let connection = self.connection.lock().await;
818        connection
819            .execute(
820                "INSERT INTO provider_sync_state(profile_id,provider,cursor,last_synced_at,status)
821                 VALUES(?1,?2,?3,?4,?5)
822                 ON CONFLICT(profile_id,provider) DO UPDATE SET
823                    cursor=excluded.cursor,last_synced_at=excluded.last_synced_at,status=excluded.status",
824                params![
825                    state.profile_id.to_string(),
826                    state.provider,
827                    state.cursor,
828                    state.last_synced_at.as_ref().map(|value| value.to_rfc3339()),
829                    state.status,
830                ],
831            )
832            .map_err(storage)?;
833        Ok(())
834    }
835
836    async fn get_payload<T: serde::de::DeserializeOwned>(
837        &self,
838        sql: &str,
839        key: String,
840    ) -> Result<Option<T>, MediaStoreError> {
841        let connection = self.connection.lock().await;
842        let payload = connection
843            .query_row(sql, [key], |row| row.get::<_, String>(0))
844            .optional()
845            .map_err(storage)?;
846        payload.as_deref().map(decode).transpose()
847    }
848
849    async fn list_payloads<T: serde::de::DeserializeOwned>(
850        &self,
851        sql: &str,
852        key: String,
853    ) -> Result<Vec<T>, MediaStoreError> {
854        let connection = self.connection.lock().await;
855        let mut statement = connection.prepare(sql).map_err(storage)?;
856        let rows = statement
857            .query_map([key], |row| row.get::<_, String>(0))
858            .map_err(storage)?;
859        rows.map(|row| decode(&row.map_err(storage)?)).collect()
860    }
861}
862
863/// Pending profile association carried through a provider OAuth callback.
864#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
865pub struct PendingTraktLink {
866    pub owner_id: UserId,
867    #[serde(default)]
868    pub family_id: Option<FamilyId>,
869    pub profile_id: MediaProfileId,
870}
871
872/// Link from a media profile to a credential stored by agent-storage.
873#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
874pub struct MediaExternalConnectionLink {
875    pub owner_id: UserId,
876    #[serde(default)]
877    pub family_id: Option<FamilyId>,
878    pub profile_id: MediaProfileId,
879    pub provider: String,
880    pub external_connection_id: ExternalConnectionId,
881    pub provider_subject: String,
882    pub display_name: Option<String>,
883    pub linked_at: DateTime<Utc>,
884}
885
886fn hash_state(state: &str) -> String {
887    Sha256::digest(state.as_bytes())
888        .iter()
889        .map(|byte| format!("{byte:02x}"))
890        .collect()
891}
892
893fn encode<T: serde::Serialize>(value: &T) -> Result<String, MediaStoreError> {
894    serde_json::to_string(value).map_err(|error| MediaStoreError::Serialization(error.to_string()))
895}
896
897fn decode<T: serde::de::DeserializeOwned>(value: &str) -> Result<T, MediaStoreError> {
898    serde_json::from_str(value).map_err(|error| MediaStoreError::Serialization(error.to_string()))
899}
900
901fn storage(error: rusqlite::Error) -> MediaStoreError {
902    MediaStoreError::Storage(error.to_string())
903}
904
905/// Failures returned by the media SQLite store.
906#[derive(Debug, thiserror::Error)]
907pub enum MediaStoreError {
908    #[error("media record was not found")]
909    NotFound,
910    #[error("media profile cannot be moved to a different family")]
911    ProfileFamilyMismatch,
912    #[error("invalid media data: {0}")]
913    Invalid(String),
914    #[error("media storage failed: {0}")]
915    Storage(String),
916    #[error("media serialization failed: {0}")]
917    Serialization(String),
918    #[error("pending provider authorization was not found or was already consumed")]
919    PendingNotFound,
920    #[error("pending provider authorization has expired")]
921    PendingExpired,
922}
923
924#[cfg(test)]
925mod tests {
926    use chrono::Utc;
927
928    use super::*;
929    use crate::{ExternalId, MediaItemId, MediaKind, OfferType, WatchHistorySource};
930
931    fn item() -> MediaItem {
932        MediaItem {
933            id: MediaItemId::new(),
934            kind: MediaKind::Movie,
935            title: "Example".into(),
936            original_title: Some("Example Original".into()),
937            overview: None,
938            release_date: None,
939            original_language: Some("en".into()),
940            genres: vec!["Drama".into()],
941            runtime_minutes: Some(100),
942            certification: None,
943            popularity: None,
944            vote_average: None,
945            vote_count: None,
946            external_ids: vec![ExternalId {
947                provider: "tmdb".into(),
948                value: "42".into(),
949            }],
950        }
951    }
952
953    #[tokio::test]
954    async fn personal_profiles_are_created_once_and_scoped_to_their_owner() {
955        let store = MediaStore::open_in_memory().unwrap();
956        let owner = UserId::new();
957        let other = UserId::new();
958
959        let first = store.get_or_create_personal_profile(owner).await.unwrap();
960        let second = store.get_or_create_personal_profile(owner).await.unwrap();
961        assert_eq!(first.id, second.id);
962        assert_eq!(first.family_id, None);
963        assert_eq!(first.owner_id, Some(owner));
964        assert_eq!(
965            store.get_personal_profile(owner, first.id).await.unwrap(),
966            Some(first.clone())
967        );
968        assert!(
969            store
970                .get_personal_profile(other, first.id)
971                .await
972                .unwrap()
973                .is_none()
974        );
975    }
976
977    #[tokio::test]
978    async fn profiles_are_scoped_to_their_family_and_can_be_managed_without_users() {
979        let store = MediaStore::open_in_memory().unwrap();
980        let family = FamilyId::new();
981        let other_family = FamilyId::new();
982        let profile = MediaProfile::new(family, "Child");
983        store.save_profile(&profile).await.unwrap();
984
985        assert!(profile.user_id.is_none());
986        assert_eq!(
987            store.list_profiles(family).await.unwrap(),
988            vec![profile.clone()]
989        );
990        assert!(store.list_profiles(other_family).await.unwrap().is_empty());
991        assert!(
992            store
993                .get_profile(other_family, profile.id)
994                .await
995                .unwrap()
996                .is_none()
997        );
998    }
999
1000    #[tokio::test]
1001    async fn profile_preferences_and_restrictions_round_trip() {
1002        let store = MediaStore::open_in_memory().unwrap();
1003        let profile = MediaProfile::new(FamilyId::new(), "Adult");
1004        store.save_profile(&profile).await.unwrap();
1005
1006        let mut preferences = ProfilePreferences::new(profile.id);
1007        preferences.liked_genres.push("Science Fiction".into());
1008        store.save_profile_preferences(&preferences).await.unwrap();
1009        assert_eq!(
1010            store.get_profile_preferences(profile.id).await.unwrap(),
1011            Some(preferences)
1012        );
1013
1014        let mut restrictions = ContentRestrictions::new(profile.id);
1015        restrictions.maximum_certification = Some("12".into());
1016        store
1017            .save_content_restrictions(&restrictions)
1018            .await
1019            .unwrap();
1020        assert_eq!(
1021            store.get_content_restrictions(profile.id).await.unwrap(),
1022            Some(restrictions)
1023        );
1024    }
1025
1026    #[tokio::test]
1027    async fn family_preferences_are_stored_independently_of_profiles() {
1028        let store = MediaStore::open_in_memory().unwrap();
1029        let family_id = FamilyId::new();
1030        let mut preferences = FamilyMediaPreferences::new(family_id);
1031        preferences.liked_genres.push("Comedy".into());
1032        store.save_family_preferences(&preferences).await.unwrap();
1033        assert_eq!(
1034            store.get_family_preferences(family_id).await.unwrap(),
1035            Some(preferences)
1036        );
1037    }
1038
1039    #[tokio::test]
1040    async fn watch_history_is_idempotent_and_ratings_are_source_specific() {
1041        let store = MediaStore::open_in_memory().unwrap();
1042        let profile = MediaProfile::new(FamilyId::new(), "Viewer");
1043        store.save_profile(&profile).await.unwrap();
1044        let item = item();
1045        store.save_media_item(&item).await.unwrap();
1046        let event = MediaWatchEvent {
1047            profile_id: profile.id,
1048            media_item_id: item.id,
1049            watched_at: Utc::now(),
1050            source: WatchHistorySource::Trakt,
1051        };
1052        store.record_watch_event(&event).await.unwrap();
1053        store.record_watch_event(&event).await.unwrap();
1054        assert_eq!(store.list_watch_history(profile.id).await.unwrap().len(), 1);
1055
1056        let rating = MediaRating {
1057            profile_id: profile.id,
1058            media_item_id: item.id,
1059            value: 4.5,
1060            rated_at: Utc::now(),
1061            source: WatchHistorySource::Trakt,
1062        };
1063        store.save_rating(&rating).await.unwrap();
1064        assert_eq!(store.list_ratings(profile.id).await.unwrap(), vec![rating]);
1065    }
1066
1067    #[tokio::test]
1068    async fn streaming_offers_round_trip_by_region() {
1069        let store = MediaStore::open_in_memory().unwrap();
1070        let item = item();
1071        store.save_media_item(&item).await.unwrap();
1072        let offer = StreamingOffer {
1073            media_item_id: item.id,
1074            service_id: "netflix_es".into(),
1075            service_name: "Netflix".into(),
1076            offer_type: OfferType::Subscription,
1077            region: "ES".into(),
1078            url: Some("https://example.invalid/watch".into()),
1079        };
1080        store.save_streaming_offer(&offer).await.unwrap();
1081        assert_eq!(
1082            store.list_streaming_offers(item.id, "ES").await.unwrap(),
1083            vec![offer]
1084        );
1085        assert!(
1086            store
1087                .list_streaming_offers(item.id, "US")
1088                .await
1089                .unwrap()
1090                .is_empty()
1091        );
1092    }
1093
1094    #[tokio::test]
1095    async fn watchlist_replacement_removes_items_no_longer_present_at_provider() {
1096        let store = MediaStore::open_in_memory().unwrap();
1097        let profile = MediaProfile::new(FamilyId::new(), "Viewer");
1098        store.save_profile(&profile).await.unwrap();
1099        let first = item();
1100        let second = item();
1101        store.save_media_item(&first).await.unwrap();
1102        store.save_media_item(&second).await.unwrap();
1103        let first_entry = MediaWatchlistItem {
1104            profile_id: profile.id,
1105            media_item_id: first.id,
1106            added_at: Utc::now(),
1107            source: WatchHistorySource::Trakt,
1108        };
1109        let second_entry = MediaWatchlistItem {
1110            profile_id: profile.id,
1111            media_item_id: second.id,
1112            added_at: Utc::now(),
1113            source: WatchHistorySource::Trakt,
1114        };
1115
1116        store
1117            .replace_watchlist(
1118                profile.id,
1119                WatchHistorySource::Trakt,
1120                &[first_entry, second_entry.clone()],
1121            )
1122            .await
1123            .unwrap();
1124        store
1125            .replace_watchlist(
1126                profile.id,
1127                WatchHistorySource::Trakt,
1128                &[second_entry.clone()],
1129            )
1130            .await
1131            .unwrap();
1132
1133        assert_eq!(
1134            store.list_watchlist(profile.id).await.unwrap(),
1135            vec![second_entry]
1136        );
1137    }
1138
1139    #[tokio::test]
1140    async fn provider_sync_cursor_round_trips() {
1141        let store = MediaStore::open_in_memory().unwrap();
1142        let profile = MediaProfile::new(FamilyId::new(), "Viewer");
1143        store.save_profile(&profile).await.unwrap();
1144        let state = ProviderSyncState {
1145            profile_id: profile.id,
1146            provider: "trakt".into(),
1147            cursor: Some("{\"movies_watched_at\":\"2026-01-01T00:00:00Z\"}".into()),
1148            last_synced_at: Some(Utc::now()),
1149            status: "complete".into(),
1150        };
1151        store.save_provider_sync_state(&state).await.unwrap();
1152        assert_eq!(
1153            store
1154                .get_provider_sync_state(profile.id, "trakt")
1155                .await
1156                .unwrap(),
1157            Some(state)
1158        );
1159    }
1160
1161    #[tokio::test]
1162    async fn pending_trakt_authorization_is_hashed_and_consumed_once() {
1163        let store = MediaStore::open_in_memory().unwrap();
1164        let owner_id = UserId::new();
1165        let family_id = FamilyId::new();
1166        let profile = MediaProfile::new(family_id, "Child");
1167        store.save_profile(&profile).await.unwrap();
1168        let pending = PendingTraktLink {
1169            owner_id,
1170            family_id: Some(family_id),
1171            profile_id: profile.id,
1172        };
1173        let now = Utc::now();
1174        store
1175            .create_pending_trakt_link(
1176                "one-time-state",
1177                &pending,
1178                now + chrono::Duration::minutes(5),
1179            )
1180            .await
1181            .unwrap();
1182
1183        assert_eq!(
1184            store
1185                .consume_pending_trakt_link("one-time-state", now)
1186                .await
1187                .unwrap(),
1188            pending
1189        );
1190        assert!(matches!(
1191            store
1192                .consume_pending_trakt_link("one-time-state", now)
1193                .await,
1194            Err(MediaStoreError::PendingNotFound)
1195        ));
1196    }
1197
1198    #[tokio::test]
1199    async fn expired_trakt_authorization_state_is_rejected_and_removed() {
1200        let store = MediaStore::open_in_memory().unwrap();
1201        let family_id = FamilyId::new();
1202        let profile = MediaProfile::new(family_id, "Child");
1203        store.save_profile(&profile).await.unwrap();
1204        let now = Utc::now();
1205        store
1206            .create_pending_trakt_link(
1207                "expired-state",
1208                &PendingTraktLink {
1209                    owner_id: UserId::new(),
1210                    family_id: Some(family_id),
1211                    profile_id: profile.id,
1212                },
1213                now - chrono::Duration::seconds(1),
1214            )
1215            .await
1216            .unwrap();
1217
1218        assert!(matches!(
1219            store.consume_pending_trakt_link("expired-state", now).await,
1220            Err(MediaStoreError::PendingExpired)
1221        ));
1222        assert!(matches!(
1223            store.consume_pending_trakt_link("expired-state", now).await,
1224            Err(MediaStoreError::PendingNotFound)
1225        ));
1226    }
1227
1228    #[tokio::test]
1229    async fn rating_values_outside_normalized_range_are_rejected() {
1230        let store = MediaStore::open_in_memory().unwrap();
1231        let profile = MediaProfile::new(FamilyId::new(), "Viewer");
1232        store.save_profile(&profile).await.unwrap();
1233        let item = item();
1234        store.save_media_item(&item).await.unwrap();
1235        let rating = MediaRating {
1236            profile_id: profile.id,
1237            media_item_id: item.id,
1238            value: 6.0,
1239            rated_at: Utc::now(),
1240            source: WatchHistorySource::Eme,
1241        };
1242        assert!(matches!(
1243            store.save_rating(&rating).await,
1244            Err(MediaStoreError::Invalid(_))
1245        ));
1246    }
1247}