Skip to main content

redseat_api/
library.rs

1//! Calls on one library. Port of the media list, thumbnail and key parts of
2//! `@redseat/api` `library.ts`; the next-page key follows the web app's
3//! `MediasList.svelte`.
4
5use std::sync::{Arc, Mutex, PoisonError};
6
7use base64::Engine;
8use serde_json::Value;
9
10use std::time::Duration;
11
12use crate::client::{AuthorizedUrl, RedseatClient};
13use crate::crypto::{Iv, Key};
14use crate::error::{Error, Result};
15use crate::transport::Request;
16use crate::types::ItemWithRelations;
17use crate::types::library::ServerLibrary;
18use crate::types::media::{Media, MediaFileQuery, MediaQuery, RsSort};
19use crate::types::person::Person;
20use crate::types::tag::Tag;
21
22/// Timeout of [`LibraryApi::get_media`]: a whole file can take long to download.
23pub const MEDIA_TIMEOUT: Duration = Duration::from_secs(10 * 60);
24
25/// A media of a list, with its relations (tags, people, series...).
26pub type MediaItem = ItemWithRelations<Media>;
27
28/// One page of medias.
29#[derive(Debug, Clone)]
30pub struct MediaPage {
31    pub medias: Vec<MediaItem>,
32    /// Put it in `MediaQuery::page_key` for the next page. `None`: no more pages.
33    pub next_page_key: Option<String>,
34}
35
36/// Calls on one library. Cheap to clone; clones share the passphrase.
37#[derive(Debug, Clone)]
38pub struct LibraryApi {
39    client: RedseatClient,
40    library: ServerLibrary,
41    key: Arc<Mutex<Option<Key>>>,
42}
43
44/// Reads a library as the server sends it. The server sends its `ServerLibraryForRead`,
45/// which leaves out `settings` for users who do not administer the library; until that
46/// type is shared, a missing `settings` reads as the defaults.
47pub(crate) fn library_from_json(mut value: Value) -> Result<ServerLibrary> {
48    if let Value::Object(map) = &mut value {
49        map.entry("settings")
50            .or_insert_with(|| Value::Object(Default::default()));
51    }
52    serde_json::from_value(value)
53        .map_err(|e| Error::malformed(format!("unexpected library: {e}"), None))
54}
55
56/// Percent-encodes one path segment.
57pub(crate) fn path_segment(segment: &str) -> String {
58    url::form_urlencoded::byte_serialize(segment.as_bytes())
59        .collect::<String>()
60        .replace('+', "%20")
61}
62
63/// The key of the page after `last` for `sort`: `<sort value>|<id>`, the server's
64/// keyset cursor. `None` for name and rating sorts, which the server cannot page (it
65/// only reads integer cursors), or when `last` lacks the sort value.
66pub fn next_page_key(sort: &RsSort, last: &Media) -> Option<String> {
67    let value = match sort {
68        RsSort::Added => last.added?,
69        RsSort::Created => last.created?,
70        RsSort::Modified => last.modified?,
71        RsSort::Size => i64::try_from(last.size?).ok()?,
72        RsSort::Name | RsSort::Rating => return None,
73    };
74    Some(format!("{value}|{}", last.id))
75}
76
77/// The query parameters of a media file request, as the server reads them
78/// (`unsupportedMime` repeated, `page`, `raw`).
79fn media_file_params(query: &MediaFileQuery) -> Vec<(String, String)> {
80    let mut params: Vec<(String, String)> = query
81        .unsupported_mime
82        .iter()
83        .map(|mime| ("unsupportedMime".to_owned(), mime.clone()))
84        .collect();
85    if let Some(page) = query.page {
86        params.push(("page".to_owned(), page.to_string()));
87    }
88    if query.raw {
89        params.push(("raw".to_owned(), "true".to_owned()));
90    }
91    params
92}
93
94fn decode_iv(iv: &str) -> Result<Iv> {
95    let bytes = base64::engine::general_purpose::STANDARD
96        .decode(iv)
97        .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(iv))
98        .map_err(|e| Error::malformed(format!("media IV: {e}"), None))?;
99    Ok(redseat_crypto::key::iv_from_slice(&bytes)?)
100}
101
102impl LibraryApi {
103    pub fn new(client: RedseatClient, library: ServerLibrary) -> Self {
104        LibraryApi {
105            client,
106            library,
107            key: Arc::new(Mutex::new(None)),
108        }
109    }
110
111    pub fn id(&self) -> &str {
112        &self.library.id
113    }
114
115    pub fn library(&self) -> &ServerLibrary {
116        &self.library
117    }
118
119    /// The client of the library's server.
120    pub fn client(&self) -> &RedseatClient {
121        &self.client
122    }
123
124    /// Whether files are encrypted on the client side (`crypt`).
125    pub fn is_encrypted(&self) -> bool {
126        self.library.crypt == Some(true)
127    }
128
129    /// Whether the passphrase is set.
130    pub fn has_passphrase(&self) -> bool {
131        self.lock_key().is_some()
132    }
133
134    fn path(&self, rest: &str) -> String {
135        format!("/libraries/{}{rest}", path_segment(&self.library.id))
136    }
137
138    fn lock_key(&self) -> std::sync::MutexGuard<'_, Option<Key>> {
139        self.key.lock().unwrap_or_else(PoisonError::into_inner)
140    }
141
142    /// Medias matching `query`. Timestamps are Unix milliseconds.
143    pub async fn get_medias(&self, query: &MediaQuery) -> Result<Vec<MediaItem>> {
144        let filter = serde_json::to_string(query)
145            .map_err(|e| Error::transport(format!("invalid media query: {e}")))?;
146        let request = Request::get(self.path("/medias")).query("filter", filter);
147        self.client.get_json_with(request).await
148    }
149
150    /// A page of medias. Set `query.limit` to the page size, then pass
151    /// `next_page_key` back in `query.page_key` for the next page.
152    pub async fn get_medias_page(&self, query: &MediaQuery) -> Result<MediaPage> {
153        let medias = self.get_medias(query).await?;
154        let full = query
155            .limit
156            .is_some_and(|limit| medias.len() >= limit && limit > 0);
157        let next_page_key = if full {
158            medias
159                .last()
160                .and_then(|last| next_page_key(&query.sort, &last.item))
161        } else {
162            None
163        };
164        Ok(MediaPage {
165            medias,
166            next_page_key,
167        })
168    }
169
170    /// The thumbnail as the server stores it: encrypted in an encrypted library.
171    pub async fn get_thumb_raw(&self, media_id: &str) -> Result<Vec<u8>> {
172        let path = self.path(&format!("/medias/{}/image", path_segment(media_id)));
173        let response = self
174            .client
175            .request(Request::get(path).query("size", "thumb"))
176            .await?;
177        Ok(response.body)
178    }
179
180    /// The thumbnail of `media`, decrypted in an encrypted library (set the passphrase
181    /// first).
182    pub async fn get_thumb(&self, media: &Media) -> Result<Vec<u8>> {
183        if self.is_encrypted() && !self.has_passphrase() {
184            return Err(Error::PassphraseRequired);
185        }
186        let data = self.get_thumb_raw(&media.id).await?;
187        self.decrypt_thumb(media, &data)
188    }
189
190    /// Decrypts a thumbnail of `media` fetched with [`Self::get_thumb_raw`] (or its
191    /// file, fetched without `raw`: both are encrypted with the media's IV). Returns it
192    /// unchanged when the library is not encrypted.
193    pub fn decrypt_thumb(&self, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
194        if !self.is_encrypted() {
195            return Ok(data.to_vec());
196        }
197        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
198        let iv = media
199            .iv
200            .as_deref()
201            .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
202        Ok(redseat_crypto::decrypt_buffer(&key, &decode_iv(iv)?, data)?)
203    }
204
205    /// The file of a media, whole: decrypted in an encrypted library (set the
206    /// passphrase first). With `query.unsupported_mime`, the server converts photos
207    /// of those types (or of any type a browser cannot show, with `"all"`) to WebP;
208    /// it cannot in an encrypted library.
209    pub async fn get_media(&self, media: &Media, query: &MediaFileQuery) -> Result<Vec<u8>> {
210        let decrypt = self.is_encrypted() && !query.raw;
211        if decrypt && !self.has_passphrase() {
212            return Err(Error::PassphraseRequired);
213        }
214        let path = self.path(&format!("/medias/{}", path_segment(&media.id)));
215        let mut request = Request::get(path);
216        request.query = media_file_params(query);
217        request.timeout = Some(MEDIA_TIMEOUT);
218        let data = self.client.request(request).await?.body;
219        if decrypt {
220            self.decrypt_thumb(media, &data)
221        } else {
222            Ok(data)
223        }
224    }
225
226    /// The URL of a media file and a token to open it, for a player that streams it
227    /// itself with HTTP range requests. The bytes are the stored ones: in an encrypted
228    /// library they are encrypted, and the server does not answer range requests, so
229    /// use [`Self::get_media`] there.
230    pub async fn media_url(&self, media_id: &str, query: &MediaFileQuery) -> Result<AuthorizedUrl> {
231        let path = self.path(&format!("/medias/{}", path_segment(media_id)));
232        self.client
233            .authorized_url(&path, &media_file_params(query))
234            .await
235    }
236
237    /// The tags of the library.
238    pub async fn get_tags(&self) -> Result<Vec<Tag>> {
239        self.client.get_json(&self.path("/tags")).await
240    }
241
242    /// The people of the library.
243    pub async fn get_people(&self) -> Result<Vec<Person>> {
244        self.client.get_json(&self.path("/people")).await
245    }
246
247    /// Sets the passphrase of an encrypted library. It is checked on the thumbnail of
248    /// one media when there is one: a wrong passphrase gives
249    /// [`Error::InvalidPassphrase`], and a failure to fetch that thumbnail its own error.
250    pub async fn set_passphrase(&self, passphrase: &str) -> Result<()> {
251        let key = redseat_crypto::derive_key(passphrase);
252        if self.is_encrypted() {
253            let query = MediaQuery {
254                limit: Some(1),
255                ..Default::default()
256            };
257            let medias = self.get_medias(&query).await?;
258            let sample = medias
259                .first()
260                .map(|m| &m.item)
261                .filter(|media| media.thumbsize.unwrap_or(0) > 0 && media.iv.is_some());
262            if let Some(media) = sample {
263                let data = self.get_thumb_raw(&media.id).await?;
264                let iv = decode_iv(media.iv.as_deref().unwrap_or_default())?;
265                redseat_crypto::decrypt_buffer(&key, &iv, &data)
266                    .map_err(|_| Error::InvalidPassphrase)?;
267            }
268        }
269        *self.lock_key() = Some(key);
270        Ok(())
271    }
272
273    /// Forgets the passphrase.
274    pub fn clear_passphrase(&self) {
275        *self.lock_key() = None;
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use std::sync::Arc;
282
283    use super::*;
284    use crate::client::ClientOptions;
285    use crate::cloud::ServerToken;
286    use crate::test_support::FakeTransport;
287    use crate::transport::Transport;
288    use crate::types::media::{FileType, SqlOrder};
289
290    fn client(transport: Arc<dyn Transport>) -> RedseatClient {
291        let client = RedseatClient::new(ClientOptions::new(transport));
292        client.set_token(ServerToken {
293            token: "t".into(),
294            expires: i64::MAX,
295        });
296        client
297    }
298
299    fn library(crypt: bool) -> ServerLibrary {
300        library_from_json(serde_json::json!({
301            "id": "lib 1", "name": "Photos", "source": "PathProvider", "type": "photos", "crypt": crypt
302        }))
303        .unwrap()
304    }
305
306    fn media_json(id: &str, added: i64) -> serde_json::Value {
307        serde_json::json!({"id": id, "name": format!("{id}.jpg"), "type": "photo",
308            "mimetype": "image/jpeg", "added": added, "modified": added, "created": added})
309    }
310
311    fn filter_of(request: &Request) -> serde_json::Value {
312        let filter = request.query.iter().find(|(k, _)| k == "filter").unwrap();
313        serde_json::from_str(&filter.1).unwrap()
314    }
315
316    #[tokio::test]
317    async fn pages_through_medias() {
318        let fake = FakeTransport::new(|request| {
319            assert_eq!(request.path, "/libraries/lib%201/medias");
320            let filter = filter_of(request);
321            let medias = match filter["pageKey"].as_str() {
322                None => vec![media_json("m3", 300), media_json("m2", 200)],
323                Some("200|m2") => vec![media_json("m1", 100)],
324                Some(other) => panic!("unexpected page key {other}"),
325            };
326            Ok(FakeTransport::json(serde_json::Value::Array(medias)))
327        });
328        let api = LibraryApi::new(client(fake.clone()), library(false));
329        let mut query = MediaQuery {
330            sort: RsSort::Added,
331            order: SqlOrder::DESC,
332            limit: Some(2),
333            ..Default::default()
334        };
335
336        let first = api.get_medias_page(&query).await.unwrap();
337        assert_eq!(first.medias.len(), 2);
338        assert_eq!(first.next_page_key.as_deref(), Some("200|m2"));
339
340        query.page_key = first.next_page_key;
341        let second = api.get_medias_page(&query).await.unwrap();
342        assert_eq!(second.medias[0].item.id, "m1");
343        assert_eq!(second.next_page_key, None);
344
345        let sent = filter_of(&fake.requests()[1]);
346        assert_eq!(sent["sort"], "added");
347        assert_eq!(sent["order"], "DESC");
348        assert_eq!(sent["limit"], 2);
349    }
350
351    #[test]
352    fn page_keys_follow_the_sort() {
353        let media = Media {
354            id: "m".into(),
355            kind: FileType::Photo,
356            added: Some(1),
357            created: Some(2),
358            modified: Some(3),
359            size: Some(4),
360            ..Default::default()
361        };
362        assert_eq!(next_page_key(&RsSort::Added, &media).unwrap(), "1|m");
363        assert_eq!(next_page_key(&RsSort::Created, &media).unwrap(), "2|m");
364        assert_eq!(next_page_key(&RsSort::Modified, &media).unwrap(), "3|m");
365        assert_eq!(next_page_key(&RsSort::Size, &media).unwrap(), "4|m");
366        assert_eq!(next_page_key(&RsSort::Name, &media), None);
367    }
368
369    /// An encrypted library whose server holds one media with a thumb encrypted
370    /// with `passphrase`, built with redseat-crypto itself.
371    fn encrypted_server(passphrase: &str, thumb: &[u8]) -> Arc<FakeTransport> {
372        let key = redseat_crypto::derive_key(passphrase);
373        let iv = redseat_crypto::random_iv().unwrap();
374        let file = redseat_crypto::encrypt_file_bytes(
375            &key,
376            &iv,
377            b"file",
378            Some("image/jpeg"),
379            Some((thumb, "image/jpeg")),
380            None,
381        )
382        .unwrap();
383        // The server's thumb endpoint returns the encrypted thumb alone.
384        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
385        let range = header.thumb_range();
386        let encrypted_thumb = file[range.start as usize..range.end as usize].to_vec();
387        let media = serde_json::json!([{
388            "id": "m1", "name": "x", "type": "photo", "mimetype": "image/jpeg",
389            "thumbsize": encrypted_thumb.len(),
390            "iv": base64::engine::general_purpose::STANDARD.encode(iv)
391        }]);
392        FakeTransport::new(move |request| {
393            if request.path.ends_with("/medias") {
394                Ok(FakeTransport::json(media.clone()))
395            } else {
396                assert_eq!(request.path, "/libraries/lib%201/medias/m1/image");
397                assert_eq!(request.query, vec![("size".into(), "thumb".into())]);
398                Ok(FakeTransport::bytes(encrypted_thumb.clone()))
399            }
400        })
401    }
402
403    #[tokio::test]
404    async fn decrypts_thumbs_of_encrypted_libraries() {
405        let thumb = b"\xff\xd8 a jpeg thumbnail".to_vec();
406        let fake = encrypted_server("secret", &thumb);
407        let api = LibraryApi::new(client(fake), library(true));
408        let medias = api.get_medias(&MediaQuery::default()).await.unwrap();
409        let media = &medias[0].item;
410
411        let error = api.get_thumb(media).await.unwrap_err();
412        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
413
414        api.set_passphrase("secret").await.unwrap();
415        assert_eq!(api.get_thumb(media).await.unwrap(), thumb);
416    }
417
418    #[tokio::test]
419    async fn refuses_a_wrong_passphrase() {
420        let fake = encrypted_server("secret", b"thumb");
421        let api = LibraryApi::new(client(fake), library(true));
422        let error = api.set_passphrase("wrong").await.unwrap_err();
423        assert_eq!(error.kind(), crate::ErrorKind::InvalidPassphrase);
424        assert!(!api.has_passphrase());
425    }
426
427    #[tokio::test]
428    async fn downloads_and_decrypts_media_files() {
429        let key = redseat_crypto::derive_key("secret");
430        let iv = redseat_crypto::random_iv().unwrap();
431        let content = b"\x00\x00\x00\x18ftypmp42 a whole video file".repeat(40);
432        let file = redseat_crypto::encrypt_file_bytes(
433            &key,
434            &iv,
435            &content,
436            Some("video/mp4"),
437            Some((b"thumb", "image/jpeg")),
438            None,
439        )
440        .unwrap();
441        // Without `raw`, the server sends the file after its header and thumb.
442        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
443        let data = file[header.data_offset() as usize..].to_vec();
444        let fake = FakeTransport::new(move |request| {
445            assert_eq!(request.path, "/libraries/lib%201/medias/m%201");
446            Ok(FakeTransport::bytes(data.clone()))
447        });
448        let api = LibraryApi::new(client(fake.clone()), library(true));
449        let media = Media {
450            id: "m 1".into(),
451            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
452            ..Default::default()
453        };
454        let query = MediaFileQuery::default();
455        let error = api.get_media(&media, &query).await.unwrap_err();
456        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
457
458        *api.lock_key() = Some(key);
459        assert_eq!(api.get_media(&media, &query).await.unwrap(), content);
460        let request = &fake.requests()[0];
461        assert!(request.query.is_empty());
462        assert_eq!(request.timeout, Some(MEDIA_TIMEOUT));
463    }
464
465    #[tokio::test]
466    async fn asks_the_server_to_convert_unsupported_photos() {
467        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"webp".to_vec())));
468        let api = LibraryApi::new(client(fake.clone()), library(false));
469        let media = Media {
470            id: "m1".into(),
471            ..Default::default()
472        };
473        let query = MediaFileQuery {
474            unsupported_mime: vec!["image/heic".into(), "all".into()],
475            page: Some(2),
476            raw: true,
477        };
478        assert_eq!(api.get_media(&media, &query).await.unwrap(), b"webp");
479        let requests = fake.requests();
480        let pairs: Vec<(&str, &str)> = requests[0]
481            .query
482            .iter()
483            .map(|(k, v)| (k.as_str(), v.as_str()))
484            .collect();
485        assert_eq!(
486            pairs,
487            [
488                ("unsupportedMime", "image/heic"),
489                ("unsupportedMime", "all"),
490                ("page", "2"),
491                ("raw", "true")
492            ]
493        );
494    }
495
496    #[tokio::test]
497    async fn gives_media_urls_with_a_token() {
498        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
499        let api = LibraryApi::new(client(fake.clone()), library(false));
500        let query = MediaFileQuery::default();
501        // Not an HTTP transport: no URL.
502        assert!(api.media_url("m 1", &query).await.is_err());
503
504        fake.set_base_url("https://host:7080/");
505        let url = api.media_url("m 1", &query).await.unwrap();
506        assert_eq!(url.url, "https://host:7080/libraries/lib%201/medias/m%201");
507        assert_eq!(url.authorization(), "Bearer t");
508        assert_eq!(url.expires, i64::MAX);
509        assert_eq!(
510            url.with_token_query(),
511            "https://host:7080/libraries/lib%201/medias/m%201?token=t"
512        );
513        assert!(!format!("{url:?}").contains("Bearer"));
514    }
515
516    #[tokio::test]
517    async fn lists_tags_and_people() {
518        let fake = FakeTransport::new(|request| {
519            Ok(FakeTransport::json(match request.path.as_str() {
520                "/libraries/lib%201/tags" => serde_json::json!([
521                    {"id": "t1", "name": "beach", "parent": null, "alt": null, "modified": 1,
522                        "added": 1, "generated": false, "path": "/beach"}
523                ]),
524                "/libraries/lib%201/people" => serde_json::json!([serde_json::to_value(Person {
525                    id: "p1".into(),
526                    name: "Alice".into(),
527                    ..Default::default()
528                })
529                .unwrap()]),
530                other => panic!("unexpected {other}"),
531            }))
532        });
533        let api = LibraryApi::new(client(fake), library(false));
534        assert_eq!(api.get_tags().await.unwrap()[0].name, "beach");
535        assert_eq!(api.get_people().await.unwrap()[0].name, "Alice");
536    }
537
538    #[tokio::test]
539    async fn plain_libraries_return_thumbs_as_is() {
540        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"jpeg".to_vec())));
541        let api = LibraryApi::new(client(fake), library(false));
542        let media = Media {
543            id: "m1".into(),
544            ..Default::default()
545        };
546        assert_eq!(api.get_thumb(&media).await.unwrap(), b"jpeg");
547    }
548}