redseat-api 0.3.0

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Calls on one library. Port of the media list, thumbnail and key parts of
//! `@redseat/api` `library.ts`; the next-page key follows the web app's
//! `MediasList.svelte`.

use std::sync::{Arc, Mutex, PoisonError};

use base64::Engine;
use serde_json::Value;

use std::time::Duration;

use crate::client::{AuthorizedUrl, RedseatClient};
use crate::crypto::{Iv, Key};
use crate::encrypted::EncryptedMediaReader;
use crate::error::{Error, Result};
use crate::transport::Request;
use crate::types::ItemWithRelations;
use crate::types::library::ServerLibrary;
use crate::types::media::{Media, MediaFileQuery, MediaQuery, RsSort};
use crate::types::person::Person;
use crate::types::tag::Tag;

/// Timeout of [`LibraryApi::get_media`]: a whole file can take long to download.
pub const MEDIA_TIMEOUT: Duration = Duration::from_secs(10 * 60);

/// A media of a list, with its relations (tags, people, series...).
pub type MediaItem = ItemWithRelations<Media>;

/// One page of medias.
#[derive(Debug, Clone)]
pub struct MediaPage {
    pub medias: Vec<MediaItem>,
    /// Put it in `MediaQuery::page_key` for the next page. `None`: no more pages.
    pub next_page_key: Option<String>,
}

/// Calls on one library. Cheap to clone; clones share the passphrase.
#[derive(Debug, Clone)]
pub struct LibraryApi {
    client: RedseatClient,
    library: ServerLibrary,
    key: Arc<Mutex<Option<Key>>>,
}

/// Reads a library as the server sends it. The server sends its `ServerLibraryForRead`,
/// which leaves out `settings` for users who do not administer the library; until that
/// type is shared, a missing `settings` reads as the defaults.
pub(crate) fn library_from_json(mut value: Value) -> Result<ServerLibrary> {
    if let Value::Object(map) = &mut value {
        map.entry("settings")
            .or_insert_with(|| Value::Object(Default::default()));
    }
    serde_json::from_value(value)
        .map_err(|e| Error::malformed(format!("unexpected library: {e}"), None))
}

/// Percent-encodes one path segment.
pub(crate) fn path_segment(segment: &str) -> String {
    url::form_urlencoded::byte_serialize(segment.as_bytes())
        .collect::<String>()
        .replace('+', "%20")
}

/// The key of the page after `last` for `sort`: `<sort value>|<id>`, the server's
/// keyset cursor. `None` for name and rating sorts, which the server cannot page (it
/// only reads integer cursors), or when `last` lacks the sort value.
pub fn next_page_key(sort: &RsSort, last: &Media) -> Option<String> {
    let value = match sort {
        RsSort::Added => last.added?,
        RsSort::Created => last.created?,
        RsSort::Modified => last.modified?,
        RsSort::Size => i64::try_from(last.size?).ok()?,
        RsSort::Name | RsSort::Rating => return None,
    };
    Some(format!("{value}|{}", last.id))
}

/// The query parameters of a media file request, as the server reads them
/// (`unsupportedMime` repeated, `page`, `raw`).
fn media_file_params(query: &MediaFileQuery) -> Vec<(String, String)> {
    let mut params: Vec<(String, String)> = query
        .unsupported_mime
        .iter()
        .map(|mime| ("unsupportedMime".to_owned(), mime.clone()))
        .collect();
    if let Some(page) = query.page {
        params.push(("page".to_owned(), page.to_string()));
    }
    if query.raw {
        params.push(("raw".to_owned(), "true".to_owned()));
    }
    params
}

fn decode_iv(iv: &str) -> Result<Iv> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(iv)
        .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(iv))
        .map_err(|e| Error::malformed(format!("media IV: {e}"), None))?;
    Ok(redseat_crypto::key::iv_from_slice(&bytes)?)
}

impl LibraryApi {
    pub fn new(client: RedseatClient, library: ServerLibrary) -> Self {
        LibraryApi {
            client,
            library,
            key: Arc::new(Mutex::new(None)),
        }
    }

    pub fn id(&self) -> &str {
        &self.library.id
    }

    pub fn library(&self) -> &ServerLibrary {
        &self.library
    }

    /// The client of the library's server.
    pub fn client(&self) -> &RedseatClient {
        &self.client
    }

    /// Whether files are encrypted on the client side (`crypt`).
    pub fn is_encrypted(&self) -> bool {
        self.library.crypt == Some(true)
    }

    /// Whether the passphrase is set.
    pub fn has_passphrase(&self) -> bool {
        self.lock_key().is_some()
    }

    fn path(&self, rest: &str) -> String {
        format!("/libraries/{}{rest}", path_segment(&self.library.id))
    }

    /// The path of a media's file.
    pub(crate) fn media_path(&self, media_id: &str) -> String {
        self.path(&format!("/medias/{}", path_segment(media_id)))
    }

    #[cfg(test)]
    pub(crate) fn set_key_for_tests(&self, key: Key) {
        *self.lock_key() = Some(key);
    }

    fn lock_key(&self) -> std::sync::MutexGuard<'_, Option<Key>> {
        self.key.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Medias matching `query`. Timestamps are Unix milliseconds.
    pub async fn get_medias(&self, query: &MediaQuery) -> Result<Vec<MediaItem>> {
        let filter = serde_json::to_string(query)
            .map_err(|e| Error::transport(format!("invalid media query: {e}")))?;
        let request = Request::get(self.path("/medias")).query("filter", filter);
        self.client.get_json_with(request).await
    }

    /// A page of medias. Set `query.limit` to the page size, then pass
    /// `next_page_key` back in `query.page_key` for the next page.
    pub async fn get_medias_page(&self, query: &MediaQuery) -> Result<MediaPage> {
        let medias = self.get_medias(query).await?;
        let full = query
            .limit
            .is_some_and(|limit| medias.len() >= limit && limit > 0);
        let next_page_key = if full {
            medias
                .last()
                .and_then(|last| next_page_key(&query.sort, &last.item))
        } else {
            None
        };
        Ok(MediaPage {
            medias,
            next_page_key,
        })
    }

    /// The thumbnail as the server stores it: encrypted in an encrypted library.
    pub async fn get_thumb_raw(&self, media_id: &str) -> Result<Vec<u8>> {
        let path = self.path(&format!("/medias/{}/image", path_segment(media_id)));
        let response = self
            .client
            .request(Request::get(path).query("size", "thumb"))
            .await?;
        Ok(response.body)
    }

    /// The thumbnail of `media`, decrypted in an encrypted library (set the passphrase
    /// first).
    pub async fn get_thumb(&self, media: &Media) -> Result<Vec<u8>> {
        if self.is_encrypted() && !self.has_passphrase() {
            return Err(Error::PassphraseRequired);
        }
        let data = self.get_thumb_raw(&media.id).await?;
        self.decrypt_thumb(media, &data)
    }

    /// Decrypts a thumbnail of `media` fetched with [`Self::get_thumb_raw`] (or its
    /// file, fetched without `raw`: both are encrypted with the media's IV). Returns it
    /// unchanged when the library is not encrypted.
    pub fn decrypt_thumb(&self, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
        if !self.is_encrypted() {
            return Ok(data.to_vec());
        }
        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
        let iv = media
            .iv
            .as_deref()
            .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
        Ok(redseat_crypto::decrypt_buffer(&key, &decode_iv(iv)?, data)?)
    }

    /// The file of a media, whole: decrypted in an encrypted library (set the
    /// passphrase first). With `query.unsupported_mime`, the server converts photos
    /// of those types (or of any type a browser cannot show, with `"all"`) to WebP;
    /// it cannot in an encrypted library.
    pub async fn get_media(&self, media: &Media, query: &MediaFileQuery) -> Result<Vec<u8>> {
        let decrypt = self.is_encrypted() && !query.raw;
        if decrypt && !self.has_passphrase() {
            return Err(Error::PassphraseRequired);
        }
        let path = self.path(&format!("/medias/{}", path_segment(&media.id)));
        let mut request = Request::get(path);
        request.query = media_file_params(query);
        request.timeout = Some(MEDIA_TIMEOUT);
        let data = self.client.request(request).await?.body;
        if decrypt {
            self.decrypt_thumb(media, &data)
        } else {
            Ok(data)
        }
    }

    /// The URL of a media file and a token to open it, for a player that streams it
    /// itself with HTTP range requests. The bytes are the stored ones: in an encrypted
    /// library they are encrypted, and the server does not answer range requests, so
    /// use [`Self::get_media`] there.
    pub async fn media_url(&self, media_id: &str, query: &MediaFileQuery) -> Result<AuthorizedUrl> {
        let path = self.path(&format!("/medias/{}", path_segment(media_id)));
        self.client
            .authorized_url(&path, &media_file_params(query))
            .await
    }

    /// Opens a media of an encrypted library for reading by ranges, decrypted: for a
    /// player that streams and seeks (see [`EncryptedMediaReader`]). Set the
    /// passphrase first. Needs a server that answers range requests on encrypted
    /// files; an older one gives an error saying it needs an update.
    pub async fn open_encrypted_media(&self, media: &Media) -> Result<EncryptedMediaReader> {
        if !self.is_encrypted() {
            return Err(Error::transport(
                "this library is not encrypted: stream its files with media_url",
            ));
        }
        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
        let iv = media
            .iv
            .as_deref()
            .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
        EncryptedMediaReader::open(
            self.clone(),
            media.id.clone(),
            key,
            decode_iv(iv)?,
            media.size,
        )
        .await
    }

    /// The tags of the library.
    pub async fn get_tags(&self) -> Result<Vec<Tag>> {
        self.client.get_json(&self.path("/tags")).await
    }

    /// The people of the library.
    pub async fn get_people(&self) -> Result<Vec<Person>> {
        self.client.get_json(&self.path("/people")).await
    }

    /// Sets the passphrase of an encrypted library. It is checked on the thumbnail of
    /// one media when there is one: a wrong passphrase gives
    /// [`Error::InvalidPassphrase`], and a failure to fetch that thumbnail its own error.
    pub async fn set_passphrase(&self, passphrase: &str) -> Result<()> {
        let key = redseat_crypto::derive_key(passphrase);
        if self.is_encrypted() {
            let query = MediaQuery {
                limit: Some(1),
                ..Default::default()
            };
            let medias = self.get_medias(&query).await?;
            let sample = medias
                .first()
                .map(|m| &m.item)
                .filter(|media| media.thumbsize.unwrap_or(0) > 0 && media.iv.is_some());
            if let Some(media) = sample {
                let data = self.get_thumb_raw(&media.id).await?;
                let iv = decode_iv(media.iv.as_deref().unwrap_or_default())?;
                redseat_crypto::decrypt_buffer(&key, &iv, &data)
                    .map_err(|_| Error::InvalidPassphrase)?;
            }
        }
        *self.lock_key() = Some(key);
        Ok(())
    }

    /// Forgets the passphrase.
    pub fn clear_passphrase(&self) {
        *self.lock_key() = None;
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::client::ClientOptions;
    use crate::cloud::ServerToken;
    use crate::test_support::FakeTransport;
    use crate::transport::Transport;
    use crate::types::media::{FileType, SqlOrder};

    fn client(transport: Arc<dyn Transport>) -> RedseatClient {
        let client = RedseatClient::new(ClientOptions::new(transport));
        client.set_token(ServerToken {
            token: "t".into(),
            expires: i64::MAX,
        });
        client
    }

    fn library(crypt: bool) -> ServerLibrary {
        library_from_json(serde_json::json!({
            "id": "lib 1", "name": "Photos", "source": "PathProvider", "type": "photos", "crypt": crypt
        }))
        .unwrap()
    }

    fn media_json(id: &str, added: i64) -> serde_json::Value {
        serde_json::json!({"id": id, "name": format!("{id}.jpg"), "type": "photo",
            "mimetype": "image/jpeg", "added": added, "modified": added, "created": added})
    }

    fn filter_of(request: &Request) -> serde_json::Value {
        let filter = request.query.iter().find(|(k, _)| k == "filter").unwrap();
        serde_json::from_str(&filter.1).unwrap()
    }

    #[tokio::test]
    async fn pages_through_medias() {
        let fake = FakeTransport::new(|request| {
            assert_eq!(request.path, "/libraries/lib%201/medias");
            let filter = filter_of(request);
            let medias = match filter["pageKey"].as_str() {
                None => vec![media_json("m3", 300), media_json("m2", 200)],
                Some("200|m2") => vec![media_json("m1", 100)],
                Some(other) => panic!("unexpected page key {other}"),
            };
            Ok(FakeTransport::json(serde_json::Value::Array(medias)))
        });
        let api = LibraryApi::new(client(fake.clone()), library(false));
        let mut query = MediaQuery {
            sort: RsSort::Added,
            order: SqlOrder::DESC,
            limit: Some(2),
            ..Default::default()
        };

        let first = api.get_medias_page(&query).await.unwrap();
        assert_eq!(first.medias.len(), 2);
        assert_eq!(first.next_page_key.as_deref(), Some("200|m2"));

        query.page_key = first.next_page_key;
        let second = api.get_medias_page(&query).await.unwrap();
        assert_eq!(second.medias[0].item.id, "m1");
        assert_eq!(second.next_page_key, None);

        let sent = filter_of(&fake.requests()[1]);
        assert_eq!(sent["sort"], "added");
        assert_eq!(sent["order"], "DESC");
        assert_eq!(sent["limit"], 2);
    }

    #[test]
    fn page_keys_follow_the_sort() {
        let media = Media {
            id: "m".into(),
            kind: FileType::Photo,
            added: Some(1),
            created: Some(2),
            modified: Some(3),
            size: Some(4),
            ..Default::default()
        };
        assert_eq!(next_page_key(&RsSort::Added, &media).unwrap(), "1|m");
        assert_eq!(next_page_key(&RsSort::Created, &media).unwrap(), "2|m");
        assert_eq!(next_page_key(&RsSort::Modified, &media).unwrap(), "3|m");
        assert_eq!(next_page_key(&RsSort::Size, &media).unwrap(), "4|m");
        assert_eq!(next_page_key(&RsSort::Name, &media), None);
    }

    /// An encrypted library whose server holds one media with a thumb encrypted
    /// with `passphrase`, built with redseat-crypto itself.
    fn encrypted_server(passphrase: &str, thumb: &[u8]) -> Arc<FakeTransport> {
        let key = redseat_crypto::derive_key(passphrase);
        let iv = redseat_crypto::random_iv().unwrap();
        let file = redseat_crypto::encrypt_file_bytes(
            &key,
            &iv,
            b"file",
            Some("image/jpeg"),
            Some((thumb, "image/jpeg")),
            None,
        )
        .unwrap();
        // The server's thumb endpoint returns the encrypted thumb alone.
        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
        let range = header.thumb_range();
        let encrypted_thumb = file[range.start as usize..range.end as usize].to_vec();
        let media = serde_json::json!([{
            "id": "m1", "name": "x", "type": "photo", "mimetype": "image/jpeg",
            "thumbsize": encrypted_thumb.len(),
            "iv": base64::engine::general_purpose::STANDARD.encode(iv)
        }]);
        FakeTransport::new(move |request| {
            if request.path.ends_with("/medias") {
                Ok(FakeTransport::json(media.clone()))
            } else {
                assert_eq!(request.path, "/libraries/lib%201/medias/m1/image");
                assert_eq!(request.query, vec![("size".into(), "thumb".into())]);
                Ok(FakeTransport::bytes(encrypted_thumb.clone()))
            }
        })
    }

    #[tokio::test]
    async fn decrypts_thumbs_of_encrypted_libraries() {
        let thumb = b"\xff\xd8 a jpeg thumbnail".to_vec();
        let fake = encrypted_server("secret", &thumb);
        let api = LibraryApi::new(client(fake), library(true));
        let medias = api.get_medias(&MediaQuery::default()).await.unwrap();
        let media = &medias[0].item;

        let error = api.get_thumb(media).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);

        api.set_passphrase("secret").await.unwrap();
        assert_eq!(api.get_thumb(media).await.unwrap(), thumb);
    }

    #[tokio::test]
    async fn refuses_a_wrong_passphrase() {
        let fake = encrypted_server("secret", b"thumb");
        let api = LibraryApi::new(client(fake), library(true));
        let error = api.set_passphrase("wrong").await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::InvalidPassphrase);
        assert!(!api.has_passphrase());
    }

    #[tokio::test]
    async fn downloads_and_decrypts_media_files() {
        let key = redseat_crypto::derive_key("secret");
        let iv = redseat_crypto::random_iv().unwrap();
        let content = b"\x00\x00\x00\x18ftypmp42 a whole video file".repeat(40);
        let file = redseat_crypto::encrypt_file_bytes(
            &key,
            &iv,
            &content,
            Some("video/mp4"),
            Some((b"thumb", "image/jpeg")),
            None,
        )
        .unwrap();
        // Without `raw`, the server sends the file after its header and thumb.
        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
        let data = file[header.data_offset() as usize..].to_vec();
        let fake = FakeTransport::new(move |request| {
            assert_eq!(request.path, "/libraries/lib%201/medias/m%201");
            Ok(FakeTransport::bytes(data.clone()))
        });
        let api = LibraryApi::new(client(fake.clone()), library(true));
        let media = Media {
            id: "m 1".into(),
            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
            ..Default::default()
        };
        let query = MediaFileQuery::default();
        let error = api.get_media(&media, &query).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);

        *api.lock_key() = Some(key);
        assert_eq!(api.get_media(&media, &query).await.unwrap(), content);
        let request = &fake.requests()[0];
        assert!(request.query.is_empty());
        assert_eq!(request.timeout, Some(MEDIA_TIMEOUT));
    }

    #[tokio::test]
    async fn asks_the_server_to_convert_unsupported_photos() {
        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"webp".to_vec())));
        let api = LibraryApi::new(client(fake.clone()), library(false));
        let media = Media {
            id: "m1".into(),
            ..Default::default()
        };
        let query = MediaFileQuery {
            unsupported_mime: vec!["image/heic".into(), "all".into()],
            page: Some(2),
            raw: true,
        };
        assert_eq!(api.get_media(&media, &query).await.unwrap(), b"webp");
        let requests = fake.requests();
        let pairs: Vec<(&str, &str)> = requests[0]
            .query
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        assert_eq!(
            pairs,
            [
                ("unsupportedMime", "image/heic"),
                ("unsupportedMime", "all"),
                ("page", "2"),
                ("raw", "true")
            ]
        );
    }

    #[tokio::test]
    async fn gives_media_urls_with_a_token() {
        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
        let api = LibraryApi::new(client(fake.clone()), library(false));
        let query = MediaFileQuery::default();
        // Not an HTTP transport: no URL.
        assert!(api.media_url("m 1", &query).await.is_err());

        fake.set_base_url("https://host:7080/");
        let url = api.media_url("m 1", &query).await.unwrap();
        assert_eq!(url.url, "https://host:7080/libraries/lib%201/medias/m%201");
        assert_eq!(url.authorization(), "Bearer t");
        assert_eq!(url.expires, i64::MAX);
        assert_eq!(
            url.with_token_query(),
            "https://host:7080/libraries/lib%201/medias/m%201?token=t"
        );
        assert!(!format!("{url:?}").contains("Bearer"));
    }

    #[tokio::test]
    async fn lists_tags_and_people() {
        let fake = FakeTransport::new(|request| {
            Ok(FakeTransport::json(match request.path.as_str() {
                "/libraries/lib%201/tags" => serde_json::json!([
                    {"id": "t1", "name": "beach", "parent": null, "alt": null, "modified": 1,
                        "added": 1, "generated": false, "path": "/beach"}
                ]),
                "/libraries/lib%201/people" => serde_json::json!([serde_json::to_value(Person {
                    id: "p1".into(),
                    name: "Alice".into(),
                    ..Default::default()
                })
                .unwrap()]),
                other => panic!("unexpected {other}"),
            }))
        });
        let api = LibraryApi::new(client(fake), library(false));
        assert_eq!(api.get_tags().await.unwrap()[0].name, "beach");
        assert_eq!(api.get_people().await.unwrap()[0].name, "Alice");
    }

    #[tokio::test]
    async fn plain_libraries_return_thumbs_as_is() {
        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"jpeg".to_vec())));
        let api = LibraryApi::new(client(fake), library(false));
        let media = Media {
            id: "m1".into(),
            ..Default::default()
        };
        assert_eq!(api.get_thumb(&media).await.unwrap(), b"jpeg");
    }
}