Skip to main content

redseat_api/
library.rs

1//! Calls on one library. Port of `@redseat/api` `library.ts`, for the calls the
2//! Redseat apps use; the next-page key follows the web app's `MediasList.svelte`.
3//! The server's routes are the reference for each call, not the TypeScript client.
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::encrypted::EncryptedMediaReader;
15use crate::error::{Error, Result};
16use crate::transport::{Body, Request};
17use crate::types::ItemWithRelations;
18use crate::types::book::{Book, BookForUpdate, BookQuery};
19use crate::types::channel::{Channel, ChannelQuery};
20use crate::types::deleted::{DeletedQuery, RsDeleted};
21use crate::types::episode::{Episode, EpisodeQuery};
22use crate::types::external_images::ImageType;
23use crate::types::image::{ImageRequestOptions, ImageSize};
24use crate::types::library::ServerLibraryForRead;
25use crate::types::media::{Media, MediaFileQuery, MediaForUpdate, MediaQuery, RsSort};
26use crate::types::media_progress::RsMediaProgress;
27use crate::types::movie::{Movie, MovieForUpdate, MovieQuery};
28use crate::types::person::{PeopleQuery, Person, PersonForAdd, PersonForUpdate, PersonWithRoles};
29use crate::types::request_processing::RsRequestProcessing;
30use crate::types::serie::{Serie, SerieForUpdate, SerieQuery};
31use crate::types::tag::{Tag, TagForAdd, TagForUpdate, TagQuery};
32use crate::types::view_progress::ViewProgressLigh;
33use crate::types::watched::WatchedLight;
34use rs_plugin_common_interfaces::request::{RsGroupDownload, RsRequest};
35
36/// Timeout of [`LibraryApi::get_media`]: a whole file can take long to download.
37pub const MEDIA_TIMEOUT: Duration = Duration::from_secs(10 * 60);
38
39/// Timeout of the calls that wait while the server downloads files itself (TS: 2 h).
40pub const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(2 * 60 * 60);
41
42/// A media of a list, with its relations (tags, people, series...).
43pub type MediaItem = ItemWithRelations<Media>;
44
45/// One page of medias.
46#[derive(Debug, Clone)]
47pub struct MediaPage {
48    pub medias: Vec<MediaItem>,
49    /// Put it in `MediaQuery::page_key` for the next page. `None`: no more pages.
50    pub next_page_key: Option<String>,
51}
52
53/// Calls on one library. Cheap to clone; clones share the passphrase.
54#[derive(Debug, Clone)]
55pub struct LibraryApi {
56    client: RedseatClient,
57    library: ServerLibraryForRead,
58    key: Arc<Mutex<Option<Key>>>,
59}
60
61/// The query parameters of a list request: each field of `query` as the server reads
62/// it (its serde name), leaving out unset ones. A list repeats its key.
63pub(crate) fn query_params<T: serde::Serialize>(query: &T) -> Result<Vec<(String, String)>> {
64    let value =
65        serde_json::to_value(query).map_err(|e| Error::transport(format!("invalid query: {e}")))?;
66    let Value::Object(fields) = value else {
67        return Err(Error::transport("invalid query: not an object"));
68    };
69    let mut params = Vec::new();
70    for (name, value) in fields {
71        match value {
72            Value::Null | Value::Object(_) => {}
73            Value::String(text) => params.push((name, text)),
74            Value::Array(items) => {
75                for item in items {
76                    match item {
77                        Value::String(text) => params.push((name.clone(), text)),
78                        Value::Number(_) | Value::Bool(_) => {
79                            params.push((name.clone(), item.to_string()))
80                        }
81                        _ => {}
82                    }
83                }
84            }
85            other => params.push((name, other.to_string())),
86        }
87    }
88    Ok(params)
89}
90
91/// Percent-encodes one path segment.
92pub(crate) fn path_segment(segment: &str) -> String {
93    url::form_urlencoded::byte_serialize(segment.as_bytes())
94        .collect::<String>()
95        .replace('+', "%20")
96}
97
98/// The key of the page after `last` for `sort`: `<sort value>|<id>`, the server's
99/// keyset cursor. `None` for name and rating sorts, which the server cannot page (it
100/// only reads integer cursors), or when `last` lacks the sort value.
101pub fn next_page_key(sort: &RsSort, last: &Media) -> Option<String> {
102    let value = match sort {
103        RsSort::Added => last.added?,
104        RsSort::Created => last.created?,
105        RsSort::Modified => last.modified?,
106        RsSort::Size => i64::try_from(last.size?).ok()?,
107        RsSort::Name | RsSort::Rating => return None,
108    };
109    Some(format!("{value}|{}", last.id))
110}
111
112/// The query parameters of a media file request, as the server reads them
113/// (`unsupportedMime` repeated, `page`, `raw`).
114fn media_file_params(query: &MediaFileQuery) -> Vec<(String, String)> {
115    let mut params: Vec<(String, String)> = query
116        .unsupported_mime
117        .iter()
118        .map(|mime| ("unsupportedMime".to_owned(), mime.clone()))
119        .collect();
120    if let Some(page) = query.page {
121        params.push(("page".to_owned(), page.to_string()));
122    }
123    if query.raw {
124        params.push(("raw".to_owned(), "true".to_owned()));
125    }
126    params
127}
128
129/// The query parameters of an image request, as the server reads them. A `Custom`
130/// size or type is an error: the server cannot read one from a query.
131fn image_params(options: &ImageRequestOptions) -> Result<Vec<(String, String)>> {
132    if matches!(options.size, Some(ImageSize::Custom(_)))
133        || matches!(options.kind, Some(ImageType::Custom(_)))
134    {
135        return Err(Error::transport(
136            "an image request takes no custom size or type",
137        ));
138    }
139    query_params(options)
140}
141
142/// `request` with `body` as its JSON body.
143fn with_json(request: Request, body: &impl serde::Serialize) -> Result<Request> {
144    let body = serde_json::to_value(body)
145        .map_err(|e| Error::transport(format!("invalid request body: {e}")))?;
146    Ok(request.json(body))
147}
148
149/// A `multipart/form-data` body with `data` as its one file: the form of the server's
150/// image uploads. The server reads the bytes only, not the part's name or type.
151fn multipart_file(data: &[u8]) -> Body {
152    // A boundary that the data does not contain.
153    let mut boundary = String::from("redseat-api-boundary");
154    while data
155        .windows(boundary.len())
156        .any(|window| window == boundary.as_bytes())
157    {
158        boundary.push('x');
159    }
160    let mut body = format!(
161        "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n\
162         Content-Type: application/octet-stream\r\n\r\n"
163    )
164    .into_bytes();
165    body.extend_from_slice(data);
166    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
167    Body::Bytes {
168        content_type: format!("multipart/form-data; boundary={boundary}"),
169        data: body,
170    }
171}
172
173fn decode_iv(iv: &str) -> Result<Iv> {
174    let bytes = base64::engine::general_purpose::STANDARD
175        .decode(iv)
176        .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(iv))
177        .map_err(|e| Error::malformed(format!("media IV: {e}"), None))?;
178    Ok(redseat_crypto::key::iv_from_slice(&bytes)?)
179}
180
181/// Decrypts data of `media` (its thumbnail, or its file) with `key` and the media's IV.
182pub(crate) fn decrypt_media_data(key: &Key, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
183    let iv = media
184        .iv
185        .as_deref()
186        .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
187    Ok(redseat_crypto::decrypt_buffer(key, &decode_iv(iv)?, data)?)
188}
189
190impl LibraryApi {
191    pub fn new(client: RedseatClient, library: ServerLibraryForRead) -> Self {
192        LibraryApi {
193            client,
194            library,
195            key: Arc::new(Mutex::new(None)),
196        }
197    }
198
199    pub fn id(&self) -> &str {
200        &self.library.id
201    }
202
203    pub fn library(&self) -> &ServerLibraryForRead {
204        &self.library
205    }
206
207    /// The client of the library's server.
208    pub fn client(&self) -> &RedseatClient {
209        &self.client
210    }
211
212    /// Whether files are encrypted on the client side (`crypt`).
213    pub fn is_encrypted(&self) -> bool {
214        self.library.crypt == Some(true)
215    }
216
217    /// Whether the passphrase is set.
218    pub fn has_passphrase(&self) -> bool {
219        self.lock_key().is_some()
220    }
221
222    fn path(&self, rest: &str) -> String {
223        format!("/libraries/{}{rest}", path_segment(&self.library.id))
224    }
225
226    /// The path of a media's file.
227    pub(crate) fn media_path(&self, media_id: &str) -> String {
228        self.path(&format!("/medias/{}", path_segment(media_id)))
229    }
230
231    /// The path of one item of a list (`kind`: `tags`, `people`...), or under it with
232    /// `rest` (`/merge`).
233    fn item_path(&self, kind: &str, id: &str, rest: &str) -> String {
234        self.path(&format!("/{kind}/{}{rest}", path_segment(id)))
235    }
236
237    /// The path of one episode, or under it with `rest` (`/watched`).
238    fn episode_path(&self, serie_id: &str, season: u32, number: u32, rest: &str) -> String {
239        let rest = format!("/seasons/{season}/episodes/{number}{rest}");
240        self.item_path("series", serie_id, &rest)
241    }
242
243    /// `POST path` with `date` as a watched date. The server answers with no body.
244    async fn post_watched(&self, path: String, date: i64) -> Result<()> {
245        let request = with_json(Request::post(path), &WatchedLight { date })?;
246        self.client.request(request).await?;
247        Ok(())
248    }
249
250    /// `POST path` with `progress` as a view progress. The server answers with no body.
251    async fn post_progress(&self, path: String, progress: u64) -> Result<()> {
252        let request = with_json(Request::post(path), &ViewProgressLigh { progress })?;
253        self.client.request(request).await?;
254        Ok(())
255    }
256
257    /// `POST path` with a request found by a source search: the server downloads it
258    /// and answers with the media created.
259    async fn post_searched_media(&self, path: String, request: &RsRequest) -> Result<Media> {
260        let mut http = with_json(Request::post(path), request)?;
261        http.timeout = Some(DOWNLOAD_TIMEOUT);
262        self.client.get_json_with(http).await
263    }
264
265    /// `DELETE` of a title (`kind`: `series`, `movies` or `books`), the answer read as
266    /// the title removed.
267    async fn remove_title<T: serde::de::DeserializeOwned>(
268        &self,
269        kind: &str,
270        id: &str,
271        delete_medias: bool,
272    ) -> Result<T> {
273        let request = Request::delete(self.item_path(kind, id, ""))
274            .query("deleteMedias", delete_medias.to_string());
275        self.client.get_json_with(request).await
276    }
277
278    /// `GET path`, the answer read as text: a share token.
279    async fn get_share_token(&self, request: Request) -> Result<String> {
280        let path = request.path.clone();
281        let response = self.client.request(request).await?;
282        String::from_utf8(response.body)
283            .map_err(|e| Error::malformed(format!("share token: {e}"), Some(&path)))
284    }
285
286    /// The URL of `path` on the server, with `query`. Needs an HTTP transport.
287    async fn url(&self, path: &str, query: &[(String, String)]) -> Result<String> {
288        Ok(self.client.authorized_url(path, query).await?.url)
289    }
290
291    /// `GET path` with `options` as its query: the bytes of an image.
292    async fn get_image(&self, path: String, options: &ImageRequestOptions) -> Result<Vec<u8>> {
293        let mut request = Request::get(path);
294        request.query = image_params(options)?;
295        Ok(self.client.request(request).await?.body)
296    }
297
298    /// Sets the key of the passphrase, already checked.
299    #[cfg(any(test, feature = "mirror"))]
300    pub(crate) fn set_key(&self, key: Key) {
301        *self.lock_key() = Some(key);
302    }
303
304    fn lock_key(&self) -> std::sync::MutexGuard<'_, Option<Key>> {
305        self.key.lock().unwrap_or_else(PoisonError::into_inner)
306    }
307
308    /// Medias matching `query`. Timestamps are Unix milliseconds.
309    pub async fn get_medias(&self, query: &MediaQuery) -> Result<Vec<MediaItem>> {
310        let filter = serde_json::to_string(query)
311            .map_err(|e| Error::transport(format!("invalid media query: {e}")))?;
312        let request = Request::get(self.path("/medias")).query("filter", filter);
313        self.client.get_json_with(request).await
314    }
315
316    /// A page of medias. Set `query.limit` to the page size, then pass
317    /// `next_page_key` back in `query.page_key` for the next page.
318    pub async fn get_medias_page(&self, query: &MediaQuery) -> Result<MediaPage> {
319        let medias = self.get_medias(query).await?;
320        let full = query
321            .limit
322            .is_some_and(|limit| medias.len() >= limit && limit > 0);
323        let next_page_key = if full {
324            medias
325                .last()
326                .and_then(|last| next_page_key(&query.sort, &last.item))
327        } else {
328            None
329        };
330        Ok(MediaPage {
331            medias,
332            next_page_key,
333        })
334    }
335
336    /// The thumbnail as the server stores it: encrypted in an encrypted library.
337    pub async fn get_thumb_raw(&self, media_id: &str) -> Result<Vec<u8>> {
338        let path = self.path(&format!("/medias/{}/image", path_segment(media_id)));
339        let response = self
340            .client
341            .request(Request::get(path).query("size", "thumb"))
342            .await?;
343        Ok(response.body)
344    }
345
346    /// The thumbnail of `media`, decrypted in an encrypted library (set the passphrase
347    /// first).
348    pub async fn get_thumb(&self, media: &Media) -> Result<Vec<u8>> {
349        if self.is_encrypted() && !self.has_passphrase() {
350            return Err(Error::PassphraseRequired);
351        }
352        let data = self.get_thumb_raw(&media.id).await?;
353        self.decrypt_thumb(media, &data)
354    }
355
356    /// Decrypts a thumbnail of `media` fetched with [`Self::get_thumb_raw`] (or its
357    /// file, fetched without `raw`: both are encrypted with the media's IV). Returns it
358    /// unchanged when the library is not encrypted.
359    pub fn decrypt_thumb(&self, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
360        if !self.is_encrypted() {
361            return Ok(data.to_vec());
362        }
363        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
364        decrypt_media_data(&key, media, data)
365    }
366
367    /// The file of a media, whole: decrypted in an encrypted library (set the
368    /// passphrase first). With `query.unsupported_mime`, the server converts photos
369    /// of those types (or of any type a browser cannot show, with `"all"`) to WebP;
370    /// it cannot in an encrypted library.
371    pub async fn get_media(&self, media: &Media, query: &MediaFileQuery) -> Result<Vec<u8>> {
372        let decrypt = self.is_encrypted() && !query.raw;
373        if decrypt && !self.has_passphrase() {
374            return Err(Error::PassphraseRequired);
375        }
376        let path = self.path(&format!("/medias/{}", path_segment(&media.id)));
377        let mut request = Request::get(path);
378        request.query = media_file_params(query);
379        request.timeout = Some(MEDIA_TIMEOUT);
380        let data = self.client.request(request).await?.body;
381        if decrypt {
382            self.decrypt_thumb(media, &data)
383        } else {
384            Ok(data)
385        }
386    }
387
388    /// The URL of a media file and a token to open it, for a player that streams it
389    /// itself with HTTP range requests. The bytes are the stored ones: in an encrypted
390    /// library they are encrypted, and the server does not answer range requests, so
391    /// use [`Self::get_media`] there.
392    pub async fn media_url(&self, media_id: &str, query: &MediaFileQuery) -> Result<AuthorizedUrl> {
393        let path = self.path(&format!("/medias/{}", path_segment(media_id)));
394        self.client
395            .authorized_url(&path, &media_file_params(query))
396            .await
397    }
398
399    /// Opens a media of an encrypted library for reading by ranges, decrypted: for a
400    /// player that streams and seeks (see [`EncryptedMediaReader`]). Set the
401    /// passphrase first. Needs a server that answers range requests on encrypted
402    /// files; an older one gives an error saying it needs an update.
403    pub async fn open_encrypted_media(&self, media: &Media) -> Result<EncryptedMediaReader> {
404        if !self.is_encrypted() {
405            return Err(Error::transport(
406                "this library is not encrypted: stream its files with media_url",
407            ));
408        }
409        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
410        let iv = media
411            .iv
412            .as_deref()
413            .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
414        EncryptedMediaReader::open(
415            self.clone(),
416            media.id.clone(),
417            key,
418            decode_iv(iv)?,
419            media.size,
420        )
421        .await
422    }
423
424    /// One media with its relations, its faces and its backups. `None` when the
425    /// library has no media with this id.
426    pub async fn get_media_metadata(&self, media_id: &str) -> Result<Option<MediaItem>> {
427        let request = Request::get(format!("{}/metadata", self.media_path(media_id)));
428        self.client.get_json_with(request).await
429    }
430
431    /// The media whose file has this hash: the one the server keeps in `Media::md5`, or
432    /// the hash of the original file when the server converted it. `None` when the
433    /// library has none.
434    pub async fn get_media_by_hash(&self, hash: &str) -> Result<Option<MediaItem>> {
435        #[derive(serde::Deserialize)]
436        struct Exist {
437            media: Option<MediaItem>,
438        }
439        let request = Request::get(self.path("/medias/exist")).query("hash", hash);
440        let exist: Exist = self.client.get_json_with(request).await?;
441        Ok(exist.media)
442    }
443
444    /// Changes a media and returns it. Only the set fields change; `add_tags`,
445    /// `remove_tags`, `add_people`, `add_series`... change its relations.
446    pub async fn update_media(&self, media_id: &str, update: &MediaForUpdate) -> Result<Media> {
447        let request = Request::patch(self.media_path(media_id));
448        self.client.get_json_with(with_json(request, update)?).await
449    }
450
451    /// Saves how far the user is in a media (a position in a video, a page of a
452    /// book...). The server stores `progress` as given.
453    pub async fn set_media_progress(
454        &self,
455        media_id: &str,
456        progress: u64,
457    ) -> Result<RsMediaProgress> {
458        let request = Request::patch(format!("{}/progress", self.media_path(media_id)))
459            .json(serde_json::json!({ "progress": progress }));
460        self.client.get_json_with(request).await
461    }
462
463    /// Removes medias, with their files. Returns those removed: an id the library does
464    /// not have is skipped.
465    pub async fn remove_medias(&self, media_ids: &[String]) -> Result<Vec<Media>> {
466        let request =
467            Request::delete(self.path("/medias")).json(serde_json::json!({ "ids": media_ids }));
468        self.client.get_json_with(request).await
469    }
470
471    /// A URL of a media file that anyone can open for 6 hours, without the user's
472    /// token: for a download manager, another app or a cast device. Needs an HTTP
473    /// transport.
474    pub async fn media_share_url(&self, media_id: &str) -> Result<String> {
475        let path = self.media_path(media_id);
476        let token = self
477            .get_share_token(Request::get(format!("{path}/sharetoken")))
478            .await?;
479        self.url(&path, &[("sharetoken".to_owned(), token)]).await
480    }
481
482    /// Adds medias from URLs: the server downloads the requests of `download` (as one
483    /// media with `group`) and returns the medias created. It can take long: see
484    /// [`Self::download_medias_in_background`]. When a request holds several files and
485    /// none is selected, the server asks for a selection and this is an error.
486    pub async fn download_medias(&self, download: &RsGroupDownload) -> Result<Vec<Media>> {
487        let path = self.path("/medias/download");
488        let mut request = with_json(Request::post(path.clone()), download)?;
489        request.timeout = Some(DOWNLOAD_TIMEOUT);
490        let answer: Value = self.client.get_json_with(request).await?;
491        if answer.get("needFileSelection").is_some() {
492            return Err(Error::malformed(
493                "the server needs a file selection: set selected_file on the request",
494                Some(&path),
495            ));
496        }
497        serde_json::from_value(answer)
498            .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), Some(&path)))
499    }
500
501    /// Like [`Self::download_medias`], without waiting: the server downloads in the
502    /// background, and the medias come with the `medias` events.
503    pub async fn download_medias_in_background(&self, download: &RsGroupDownload) -> Result<()> {
504        let request = Request::post(self.path("/medias/download")).query("spawn", "true");
505        self.client.request(with_json(request, download)?).await?;
506        Ok(())
507    }
508
509    /// `GET <path>` with the fields of `query` as parameters, read as JSON.
510    async fn get_list<T: serde::de::DeserializeOwned>(
511        &self,
512        path: &str,
513        query: &impl serde::Serialize,
514    ) -> Result<T> {
515        let mut request = Request::get(self.path(path));
516        request.query = query_params(query)?;
517        self.client.get_json_with(request).await
518    }
519
520    /// The number of medias matching `query` (its `limit` and `page_key` are ignored).
521    pub async fn count_medias(&self, query: &MediaQuery) -> Result<u64> {
522        #[derive(serde::Deserialize)]
523        struct Count {
524            count: u64,
525        }
526        let filter = serde_json::to_string(query)
527            .map_err(|e| Error::transport(format!("invalid media query: {e}")))?;
528        let request = Request::get(self.path("/medias/count")).query("filter", filter);
529        let count: Count = self.client.get_json_with(request).await?;
530        Ok(count.count)
531    }
532
533    /// The tags of the library matching `query`. With `after`, only those modified
534    /// strictly after it (Unix milliseconds); page with `limit` and `offset`.
535    pub async fn get_tags(&self, query: &TagQuery) -> Result<Vec<Tag>> {
536        self.get_list("/tags", query).await
537    }
538
539    /// Adds a tag to the library and returns it as created. The server chooses its
540    /// `id`; `parent` puts it under another tag.
541    pub async fn create_tag(&self, tag: &TagForAdd) -> Result<Tag> {
542        let request = with_json(Request::post(self.path("/tags")), tag)?;
543        self.client.get_json_with(request).await
544    }
545
546    /// Changes a tag and returns it. Only the set fields change: `name` renames it,
547    /// `parent` moves it under another tag (an empty id moves it to the root), and
548    /// `add_alts`, `remove_alts`, `add_otherids` and `remove_otherids` change its
549    /// alternative names and external ids. Needs the admin role on the library.
550    pub async fn update_tag(&self, tag_id: &str, update: &TagForUpdate) -> Result<Tag> {
551        let request = Request::patch(self.item_path("tags", tag_id, ""));
552        self.client.get_json_with(with_json(request, update)?).await
553    }
554
555    /// Merges the tag `tag_id` into the tag `into` and removes it. Returns the tag
556    /// kept.
557    pub async fn merge_tag(&self, tag_id: &str, into: &str) -> Result<Tag> {
558        let request = Request::patch(self.item_path("tags", tag_id, "/merge"))
559            .json(serde_json::json!({ "into": into }));
560        self.client.get_json_with(request).await
561    }
562
563    /// Removes a tag and returns it as it was.
564    pub async fn remove_tag(&self, tag_id: &str) -> Result<Tag> {
565        let request = Request::delete(self.item_path("tags", tag_id, ""));
566        self.client.get_json_with(request).await
567    }
568
569    /// The people of the library matching `query`, like [`Self::get_tags`].
570    pub async fn get_people(&self, query: &PeopleQuery) -> Result<Vec<Person>> {
571        self.get_list("/people", query).await
572    }
573
574    /// One person, `None` when the library has no person with this id.
575    pub async fn get_person(&self, person_id: &str) -> Result<Option<Person>> {
576        let request = Request::get(self.item_path("people", person_id, ""));
577        self.client.get_json_with(request).await
578    }
579
580    /// Adds a person to the library and returns them as created. The server chooses
581    /// their `id`.
582    pub async fn create_person(&self, person: &PersonForAdd) -> Result<Person> {
583        let request = with_json(Request::post(self.path("/people")), person)?;
584        self.client.get_json_with(request).await
585    }
586
587    /// Changes a person and returns them. Only the set fields change; `add_alts`,
588    /// `remove_alts`, `add_socials`, `add_otherids`... change their alternative names,
589    /// links and external ids.
590    pub async fn update_person(&self, person_id: &str, update: &PersonForUpdate) -> Result<Person> {
591        let request = Request::patch(self.item_path("people", person_id, ""));
592        self.client.get_json_with(with_json(request, update)?).await
593    }
594
595    /// The portrait of a person, as the bytes of an image file. The server has no
596    /// other image for a person: it does not read `defaulting`.
597    pub async fn get_person_image(
598        &self,
599        person_id: &str,
600        options: &ImageRequestOptions,
601    ) -> Result<Vec<u8>> {
602        self.get_image(self.item_path("people", person_id, "/image"), options)
603            .await
604    }
605
606    /// Removes a person and returns them as they were. Needs the admin role on the
607    /// library.
608    pub async fn remove_person(&self, person_id: &str) -> Result<Person> {
609        let request = Request::delete(self.item_path("people", person_id, ""));
610        self.client.get_json_with(request).await
611    }
612
613    /// Merges the person `source` into the person `target`, who gets their faces;
614    /// `source` is then removed. Returns the number of faces moved. Needs the admin
615    /// role on the library.
616    pub async fn merge_people(&self, source: &str, target: &str) -> Result<u64> {
617        #[derive(serde::Deserialize)]
618        struct Merged {
619            faces_transferred: u64,
620        }
621        let request = Request::post(self.path("/people/merge")).json(serde_json::json!({
622            "sourcePersonId": source,
623            "targetPersonId": target,
624        }));
625        let merged: Merged = self.client.get_json_with(request).await?;
626        Ok(merged.faces_transferred)
627    }
628
629    /// The people of a title (`kind`: `movies`, `series` or `books`), with their roles.
630    async fn get_title_people(&self, kind: &str, id: &str) -> Result<Vec<PersonWithRoles>> {
631        let request = Request::get(self.item_path(kind, id, "/people"));
632        self.client.get_json_with(request).await
633    }
634
635    /// The people of a movie (cast and crew), with their roles in it.
636    pub async fn get_movie_people(&self, movie_id: &str) -> Result<Vec<PersonWithRoles>> {
637        self.get_title_people("movies", movie_id).await
638    }
639
640    /// The people of a series (cast and crew), with their roles in it.
641    pub async fn get_serie_people(&self, serie_id: &str) -> Result<Vec<PersonWithRoles>> {
642        self.get_title_people("series", serie_id).await
643    }
644
645    /// The people of a book (authors...), with their roles in it.
646    pub async fn get_book_people(&self, book_id: &str) -> Result<Vec<PersonWithRoles>> {
647        self.get_title_people("books", book_id).await
648    }
649
650    /// The series of the library matching `query`, with their relations, like
651    /// [`Self::get_tags`].
652    pub async fn get_series(&self, query: &SerieQuery) -> Result<Vec<ItemWithRelations<Serie>>> {
653        self.get_list("/series", query).await
654    }
655
656    /// Adds a series to the library, with its relations (tags, people), and returns it
657    /// as created. The server chooses its `id`, and refuses a series whose external
658    /// ids (imdb, tmdb...) the library already has.
659    pub async fn create_serie(
660        &self,
661        serie: &ItemWithRelations<Serie>,
662    ) -> Result<ItemWithRelations<Serie>> {
663        let request = with_json(Request::post(self.path("/series")), serie)?;
664        self.client.get_json_with(request).await
665    }
666
667    /// Changes a series and returns it, with its relations. Only the set fields
668    /// change. Needs the admin role on the library.
669    pub async fn update_serie(
670        &self,
671        serie_id: &str,
672        update: &SerieForUpdate,
673    ) -> Result<ItemWithRelations<Serie>> {
674        let request = Request::patch(self.item_path("series", serie_id, ""));
675        self.client.get_json_with(with_json(request, update)?).await
676    }
677
678    /// An image of a series, as the bytes of an image file: its poster, or the
679    /// `options.kind` asked. With `defaulting`, the background stands in for a missing
680    /// card.
681    pub async fn get_serie_image(
682        &self,
683        serie_id: &str,
684        options: &ImageRequestOptions,
685    ) -> Result<Vec<u8>> {
686        self.get_image(self.item_path("series", serie_id, "/image"), options)
687            .await
688    }
689
690    /// The still of an episode, as the bytes of an image file. The server does not
691    /// read `options.kind`. With `defaulting`, the card of the series, or else its
692    /// background, stands in for a missing still.
693    pub async fn get_episode_image(
694        &self,
695        serie_id: &str,
696        season: u32,
697        number: u32,
698        options: &ImageRequestOptions,
699    ) -> Result<Vec<u8>> {
700        let path = self.episode_path(serie_id, season, number, "/image");
701        self.get_image(path, options).await
702    }
703
704    /// Removes a series and returns it as it was. With `delete_medias`, its medias are
705    /// removed too, with their files (a virtual file's source stays).
706    pub async fn remove_serie(&self, serie_id: &str, delete_medias: bool) -> Result<Serie> {
707        self.remove_title("series", serie_id, delete_medias).await
708    }
709
710    /// Marks an episode watched by the user at `date` (Unix milliseconds), or not
711    /// watched with a `date` of 0.
712    pub async fn set_episode_watched(
713        &self,
714        serie_id: &str,
715        season: u32,
716        number: u32,
717        date: i64,
718    ) -> Result<()> {
719        let path = self.episode_path(serie_id, season, number, "/watched");
720        self.post_watched(path, date).await
721    }
722
723    /// Saves how far the user is in an episode. The server stores `progress` as given.
724    pub async fn set_episode_progress(
725        &self,
726        serie_id: &str,
727        season: u32,
728        number: u32,
729        progress: u64,
730    ) -> Result<()> {
731        let path = self.episode_path(serie_id, season, number, "/progress");
732        self.post_progress(path, progress).await
733    }
734
735    /// Adds a file found by a source search to an episode: the server downloads
736    /// `request` and returns the media created.
737    pub async fn add_searched_episode_media(
738        &self,
739        serie_id: &str,
740        season: u32,
741        number: u32,
742        request: &RsRequest,
743    ) -> Result<Media> {
744        let path = self.episode_path(serie_id, season, number, "/search");
745        self.post_searched_media(path, request).await
746    }
747
748    /// The movies of the library matching `query`, with their relations, like
749    /// [`Self::get_tags`].
750    pub async fn get_movies(&self, query: &MovieQuery) -> Result<Vec<ItemWithRelations<Movie>>> {
751        self.get_list("/movies", query).await
752    }
753
754    /// Adds a movie to the library, with its relations (tags, people), and returns it
755    /// as created. The server chooses its `id`, and refuses a movie whose external
756    /// ids (imdb, tmdb...) the library already has.
757    pub async fn create_movie(
758        &self,
759        movie: &ItemWithRelations<Movie>,
760    ) -> Result<ItemWithRelations<Movie>> {
761        let request = with_json(Request::post(self.path("/movies")), movie)?;
762        self.client.get_json_with(request).await
763    }
764
765    /// Changes a movie and returns it, with its relations. Only the set fields change.
766    pub async fn update_movie(
767        &self,
768        movie_id: &str,
769        update: &MovieForUpdate,
770    ) -> Result<ItemWithRelations<Movie>> {
771        let request = Request::patch(self.item_path("movies", movie_id, ""));
772        self.client.get_json_with(with_json(request, update)?).await
773    }
774
775    /// An image of a movie, as the bytes of an image file: its poster, or the
776    /// `options.kind` asked. With `defaulting`, the background stands in for a missing
777    /// card.
778    pub async fn get_movie_image(
779        &self,
780        movie_id: &str,
781        options: &ImageRequestOptions,
782    ) -> Result<Vec<u8>> {
783        self.get_image(self.item_path("movies", movie_id, "/image"), options)
784            .await
785    }
786
787    /// Removes a movie and returns it as it was. With `delete_medias`, its medias are
788    /// removed too, with their files (a virtual file's source stays).
789    pub async fn remove_movie(&self, movie_id: &str, delete_medias: bool) -> Result<Movie> {
790        self.remove_title("movies", movie_id, delete_medias).await
791    }
792
793    /// Marks a movie watched by the user at `date` (Unix milliseconds), or not watched
794    /// with a `date` of 0.
795    pub async fn set_movie_watched(&self, movie_id: &str, date: i64) -> Result<()> {
796        let path = self.item_path("movies", movie_id, "/watched");
797        self.post_watched(path, date).await
798    }
799
800    /// Saves how far the user is in a movie. The server stores `progress` as given.
801    pub async fn set_movie_progress(&self, movie_id: &str, progress: u64) -> Result<()> {
802        let path = self.item_path("movies", movie_id, "/progress");
803        self.post_progress(path, progress).await
804    }
805
806    /// Adds a file found by a source search to a movie: the server downloads
807    /// `request` and returns the media created.
808    pub async fn add_searched_movie_media(
809        &self,
810        movie_id: &str,
811        request: &RsRequest,
812    ) -> Result<Media> {
813        let path = self.item_path("movies", movie_id, "/search");
814        self.post_searched_media(path, request).await
815    }
816
817    /// The episodes of the library matching `query` (of all series without
818    /// `serie_ref`), like [`Self::get_tags`]. An episode's id is
819    /// [`Episode::id`]: series, season and number.
820    pub async fn get_episodes(&self, query: &EpisodeQuery) -> Result<Vec<Episode>> {
821        self.get_list("/series/episodes", query).await
822    }
823
824    /// The books of the library matching `query`, with their relations, like
825    /// [`Self::get_tags`].
826    pub async fn get_books(&self, query: &BookQuery) -> Result<Vec<ItemWithRelations<Book>>> {
827        self.get_list("/books", query).await
828    }
829
830    /// One book, with its relations.
831    pub async fn get_book(&self, book_id: &str) -> Result<ItemWithRelations<Book>> {
832        let request = Request::get(self.item_path("books", book_id, ""));
833        self.client.get_json_with(request).await
834    }
835
836    /// Adds a book to the library, with its relations, and returns it as created. The
837    /// server chooses its `id`. With `upsert_tags`, `upsert_people` or `upsert_serie`,
838    /// the tags, people or series its relations give in full (`tags_details`,
839    /// `people_details`, `series_details`) are created when the library lacks them.
840    pub async fn create_book(
841        &self,
842        book: &ItemWithRelations<Book>,
843        upsert_tags: bool,
844        upsert_people: bool,
845        upsert_serie: bool,
846    ) -> Result<ItemWithRelations<Book>> {
847        let mut request = with_json(Request::post(self.path("/books")), book)?;
848        let options = [
849            ("upsertTags", upsert_tags),
850            ("upsertPeople", upsert_people),
851            ("upsertSerie", upsert_serie),
852        ];
853        for (name, _) in options.iter().filter(|(_, set)| *set) {
854            request = request.query(*name, "true");
855        }
856        self.client.get_json_with(request).await
857    }
858
859    /// Changes a book and returns it, with its relations. Only the set fields change.
860    pub async fn update_book(
861        &self,
862        book_id: &str,
863        update: &BookForUpdate,
864    ) -> Result<ItemWithRelations<Book>> {
865        let request = Request::patch(self.item_path("books", book_id, ""));
866        self.client.get_json_with(with_json(request, update)?).await
867    }
868
869    /// An image of a book, as the bytes of an image file: its poster, or the
870    /// `options.kind` asked. With `defaulting`, the poster stands in for a missing
871    /// image of another type.
872    pub async fn get_book_image(
873        &self,
874        book_id: &str,
875        options: &ImageRequestOptions,
876    ) -> Result<Vec<u8>> {
877        self.get_image(self.item_path("books", book_id, "/image"), options)
878            .await
879    }
880
881    /// Removes a book and returns it as it was. With `delete_medias`, its medias are
882    /// removed too, with their files (a virtual file's source stays).
883    pub async fn remove_book(&self, book_id: &str, delete_medias: bool) -> Result<Book> {
884        self.remove_title("books", book_id, delete_medias).await
885    }
886
887    /// Marks a book read by the user at `date` (Unix milliseconds), or not read with a
888    /// `date` of 0.
889    pub async fn set_book_watched(&self, book_id: &str, date: i64) -> Result<()> {
890        let path = self.item_path("books", book_id, "/watched");
891        self.post_watched(path, date).await
892    }
893
894    /// Sets the poster of a book to `image`, the bytes of an image file (JPEG, PNG,
895    /// WebP...): the server converts it.
896    pub async fn update_book_poster(&self, book_id: &str, image: &[u8]) -> Result<()> {
897        let mut request = Request::post(self.item_path("books", book_id, "/image"));
898        request.body = Some(multipart_file(image));
899        self.client.request(request).await?;
900        Ok(())
901    }
902
903    /// The channels of the library matching `query`, with their tags and their
904    /// variants (one per quality). Page with `limit` and `offset`.
905    pub async fn get_channels(&self, query: &ChannelQuery) -> Result<Vec<Channel>> {
906        self.get_list("/channels", query).await
907    }
908
909    /// The logo of a channel, as the bytes of an image file. The server has no other
910    /// image for a channel: it does not read `defaulting`.
911    pub async fn get_channel_image(
912        &self,
913        channel_id: &str,
914        options: &ImageRequestOptions,
915    ) -> Result<Vec<u8>> {
916        self.get_image(self.item_path("channels", channel_id, "/image"), options)
917            .await
918    }
919
920    /// The URL of a channel's logo and a token to open it, for an image view that
921    /// fetches it itself. Needs an HTTP transport.
922    pub async fn channel_image_url(
923        &self,
924        channel_id: &str,
925        options: &ImageRequestOptions,
926    ) -> Result<AuthorizedUrl> {
927        let path = self.item_path("channels", channel_id, "/image");
928        self.client
929            .authorized_url(&path, &image_params(options)?)
930            .await
931    }
932
933    /// Adds a tag to a channel.
934    pub async fn add_tag_to_channel(&self, channel_id: &str, tag_id: &str) -> Result<()> {
935        let request = Request::post(self.item_path("channels", channel_id, "/tags"))
936            .json(serde_json::json!({ "tagId": tag_id }));
937        self.client.request(request).await?;
938        Ok(())
939    }
940
941    /// Removes a tag from a channel.
942    pub async fn remove_tag_from_channel(&self, channel_id: &str, tag_id: &str) -> Result<()> {
943        let rest = format!("/tags/{}", path_segment(tag_id));
944        let request = Request::delete(self.item_path("channels", channel_id, &rest));
945        self.client.request(request).await?;
946        Ok(())
947    }
948
949    /// The URL of a channel's stream and a token to open it, for a player. `quality`
950    /// picks one of the channel's variants; without it the server picks the best.
951    /// Needs an HTTP transport.
952    pub async fn channel_stream_url(
953        &self,
954        channel_id: &str,
955        quality: Option<&str>,
956    ) -> Result<AuthorizedUrl> {
957        self.channel_url(channel_id, "/stream", quality).await
958    }
959
960    /// The URL of a channel's HLS playlist and a token to open it, for players that
961    /// need HLS: the server starts converting the stream when the playlist is read.
962    /// Stop it with [`Self::stop_channel_hls`]. Needs an HTTP transport.
963    pub async fn channel_hls_url(
964        &self,
965        channel_id: &str,
966        quality: Option<&str>,
967    ) -> Result<AuthorizedUrl> {
968        self.channel_url(channel_id, "/hls/playlist.m3u8", quality)
969            .await
970    }
971
972    async fn channel_url(
973        &self,
974        channel_id: &str,
975        rest: &str,
976        quality: Option<&str>,
977    ) -> Result<AuthorizedUrl> {
978        let query: Vec<(String, String)> = quality
979            .map(|quality| ("quality".to_owned(), quality.to_owned()))
980            .into_iter()
981            .collect();
982        let path = self.item_path("channels", channel_id, rest);
983        self.client.authorized_url(&path, &query).await
984    }
985
986    /// Stops the HLS conversion of a channel, started by reading
987    /// [`Self::channel_hls_url`].
988    pub async fn stop_channel_hls(&self, channel_id: &str) -> Result<()> {
989        let request = Request::delete(self.item_path("channels", channel_id, "/hls"));
990        self.client.request(request).await?;
991        Ok(())
992    }
993
994    /// Runs a request through the library's plugins and returns it processed: a link
995    /// turned into a direct one, a status that says what to do next
996    /// ([`RsRequest::status`])...
997    pub async fn process_request(&self, request: &RsRequest) -> Result<RsRequest> {
998        let path = self.path("/plugins/requests/process");
999        self.client
1000            .get_json_with(with_json(Request::post(path), request)?)
1001            .await
1002    }
1003
1004    /// Runs a request through the library's plugins and returns what it gives, whole:
1005    /// an image behind a protected link, for example.
1006    pub async fn process_request_bytes(&self, request: &RsRequest) -> Result<Vec<u8>> {
1007        let path = self.path("/plugins/requests/process/stream");
1008        let mut http = with_json(Request::post(path), request)?;
1009        http.timeout = Some(MEDIA_TIMEOUT);
1010        Ok(self.client.request(http).await?.body)
1011    }
1012
1013    /// Asks the library's plugins for a link to `request` that does not expire, to
1014    /// keep it. Returns the request with that link and `permanent` set.
1015    pub async fn check_request_permanent(&self, request: &RsRequest) -> Result<RsRequest> {
1016        let path = self.path("/plugins/requests/permanent");
1017        self.client
1018            .get_json_with(with_json(Request::post(path), request)?)
1019            .await
1020    }
1021
1022    /// Hands a request to a plugin that prepares it in the background (a debrid
1023    /// service fetching a torrent, for example). Returns the task; its progress comes
1024    /// with the `request_processing` events. `media_ref` ties it to a media.
1025    pub async fn add_request(
1026        &self,
1027        request: &RsRequest,
1028        media_ref: Option<&str>,
1029    ) -> Result<RsRequestProcessing> {
1030        let body = serde_json::json!({ "request": request, "mediaRef": media_ref });
1031        let http = Request::post(self.path("/plugins/requests/add")).json(body);
1032        self.client.get_json_with(http).await
1033    }
1034
1035    /// A URL that streams what the request URL `url` gives, through the server and
1036    /// its plugins, that anyone can open for 6 hours without the user's token: for a
1037    /// player. Needs an HTTP transport.
1038    pub async fn request_share_url(&self, url: &str) -> Result<String> {
1039        let token = Request::get(self.path("/plugins/requests/url/sharetoken")).query("url", url);
1040        let token = self.get_share_token(token).await?;
1041        let query = [
1042            ("sharetoken".to_owned(), token),
1043            ("url".to_owned(), url.to_owned()),
1044        ];
1045        self.url(&self.path("/plugins/requests/url/stream"), &query)
1046            .await
1047    }
1048
1049    /// What was deleted from the library: with `after`, strictly after it (Unix
1050    /// milliseconds). Page with `limit` and `offset`.
1051    pub async fn get_deleted(&self, query: &DeletedQuery) -> Result<Vec<RsDeleted>> {
1052        self.get_list("/deleted", query).await
1053    }
1054
1055    /// Sets the passphrase of an encrypted library. It is checked on the thumbnail of
1056    /// one media when there is one: a wrong passphrase gives
1057    /// [`Error::InvalidPassphrase`], and a failure to fetch that thumbnail its own error.
1058    pub async fn set_passphrase(&self, passphrase: &str) -> Result<()> {
1059        let key = redseat_crypto::derive_key(passphrase);
1060        if self.is_encrypted() {
1061            let query = MediaQuery {
1062                limit: Some(1),
1063                ..Default::default()
1064            };
1065            let medias = self.get_medias(&query).await?;
1066            let sample = medias
1067                .first()
1068                .map(|m| &m.item)
1069                .filter(|media| media.thumbsize.unwrap_or(0) > 0 && media.iv.is_some());
1070            if let Some(media) = sample {
1071                let data = self.get_thumb_raw(&media.id).await?;
1072                let iv = decode_iv(media.iv.as_deref().unwrap_or_default())?;
1073                redseat_crypto::decrypt_buffer(&key, &iv, &data)
1074                    .map_err(|_| Error::InvalidPassphrase)?;
1075            }
1076        }
1077        *self.lock_key() = Some(key);
1078        Ok(())
1079    }
1080
1081    /// Forgets the passphrase.
1082    pub fn clear_passphrase(&self) {
1083        *self.lock_key() = None;
1084    }
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089    use std::sync::Arc;
1090
1091    use super::*;
1092    use crate::client::ClientOptions;
1093    use crate::cloud::ServerToken;
1094    use crate::test_support::FakeTransport;
1095    use crate::transport::{Body, Method, Transport};
1096    use crate::types::media::{FileType, SqlOrder};
1097    use crate::types::person::PersonType;
1098
1099    fn client(transport: Arc<dyn Transport>) -> RedseatClient {
1100        let client = RedseatClient::new(ClientOptions::new(transport));
1101        client.set_token(ServerToken {
1102            token: "t".into(),
1103            expires: i64::MAX,
1104        });
1105        client
1106    }
1107
1108    fn library(crypt: bool) -> ServerLibraryForRead {
1109        serde_json::from_value(serde_json::json!({
1110            "id": "lib 1", "name": "Photos", "source": "PathProvider", "type": "photos", "crypt": crypt
1111        }))
1112        .unwrap()
1113    }
1114
1115    fn media_json(id: &str, added: i64) -> serde_json::Value {
1116        serde_json::json!({"id": id, "name": format!("{id}.jpg"), "type": "photo",
1117            "mimetype": "image/jpeg", "added": added, "modified": added, "created": added})
1118    }
1119
1120    /// A library on a server that answers every request with `answer`.
1121    fn api_answering(answer: serde_json::Value) -> (LibraryApi, Arc<FakeTransport>) {
1122        let fake = FakeTransport::new(move |_| Ok(FakeTransport::json(answer.clone())));
1123        (LibraryApi::new(client(fake.clone()), library(false)), fake)
1124    }
1125
1126    /// Checks the method, path, query and JSON body of a request.
1127    #[track_caller]
1128    fn assert_sent(
1129        request: &Request,
1130        method: Method,
1131        path: &str,
1132        query: &[(&str, &str)],
1133        body: Option<serde_json::Value>,
1134    ) {
1135        assert_eq!(request.method, method);
1136        assert_eq!(request.path, path);
1137        let sent: Vec<(&str, &str)> = request
1138            .query
1139            .iter()
1140            .map(|(k, v)| (k.as_str(), v.as_str()))
1141            .collect();
1142        assert_eq!(sent, query);
1143        assert_eq!(request.body, body.map(Body::Json));
1144    }
1145
1146    fn tag_json(id: &str, name: &str) -> serde_json::Value {
1147        serde_json::json!({"id": id, "name": name, "parent": null, "alt": ["sea"],
1148            "modified": 2, "added": 1, "generated": false, "path": "/"})
1149    }
1150
1151    fn filter_of(request: &Request) -> serde_json::Value {
1152        let filter = request.query.iter().find(|(k, _)| k == "filter").unwrap();
1153        serde_json::from_str(&filter.1).unwrap()
1154    }
1155
1156    #[tokio::test]
1157    async fn pages_through_medias() {
1158        let fake = FakeTransport::new(|request| {
1159            assert_eq!(request.path, "/libraries/lib%201/medias");
1160            let filter = filter_of(request);
1161            let medias = match filter["pageKey"].as_str() {
1162                None => vec![media_json("m3", 300), media_json("m2", 200)],
1163                Some("200|m2") => vec![media_json("m1", 100)],
1164                Some(other) => panic!("unexpected page key {other}"),
1165            };
1166            Ok(FakeTransport::json(serde_json::Value::Array(medias)))
1167        });
1168        let api = LibraryApi::new(client(fake.clone()), library(false));
1169        let mut query = MediaQuery {
1170            sort: RsSort::Added,
1171            order: SqlOrder::DESC,
1172            limit: Some(2),
1173            ..Default::default()
1174        };
1175
1176        let first = api.get_medias_page(&query).await.unwrap();
1177        assert_eq!(first.medias.len(), 2);
1178        assert_eq!(first.next_page_key.as_deref(), Some("200|m2"));
1179
1180        query.page_key = first.next_page_key;
1181        let second = api.get_medias_page(&query).await.unwrap();
1182        assert_eq!(second.medias[0].item.id, "m1");
1183        assert_eq!(second.next_page_key, None);
1184
1185        let sent = filter_of(&fake.requests()[1]);
1186        assert_eq!(sent["sort"], "added");
1187        assert_eq!(sent["order"], "DESC");
1188        assert_eq!(sent["limit"], 2);
1189    }
1190
1191    #[test]
1192    fn page_keys_follow_the_sort() {
1193        let media = Media {
1194            id: "m".into(),
1195            kind: FileType::Photo,
1196            added: Some(1),
1197            created: Some(2),
1198            modified: Some(3),
1199            size: Some(4),
1200            ..Default::default()
1201        };
1202        assert_eq!(next_page_key(&RsSort::Added, &media).unwrap(), "1|m");
1203        assert_eq!(next_page_key(&RsSort::Created, &media).unwrap(), "2|m");
1204        assert_eq!(next_page_key(&RsSort::Modified, &media).unwrap(), "3|m");
1205        assert_eq!(next_page_key(&RsSort::Size, &media).unwrap(), "4|m");
1206        assert_eq!(next_page_key(&RsSort::Name, &media), None);
1207    }
1208
1209    /// An encrypted library whose server holds one media with a thumb encrypted
1210    /// with `passphrase`, built with redseat-crypto itself.
1211    fn encrypted_server(passphrase: &str, thumb: &[u8]) -> Arc<FakeTransport> {
1212        let key = redseat_crypto::derive_key(passphrase);
1213        let iv = redseat_crypto::random_iv().unwrap();
1214        let file = redseat_crypto::encrypt_file_bytes(
1215            &key,
1216            &iv,
1217            b"file",
1218            Some("image/jpeg"),
1219            Some((thumb, "image/jpeg")),
1220            None,
1221        )
1222        .unwrap();
1223        // The server's thumb endpoint returns the encrypted thumb alone.
1224        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
1225        let range = header.thumb_range();
1226        let encrypted_thumb = file[range.start as usize..range.end as usize].to_vec();
1227        let media = serde_json::json!([{
1228            "id": "m1", "name": "x", "type": "photo", "mimetype": "image/jpeg",
1229            "thumbsize": encrypted_thumb.len(),
1230            "iv": base64::engine::general_purpose::STANDARD.encode(iv)
1231        }]);
1232        FakeTransport::new(move |request| {
1233            if request.path.ends_with("/medias") {
1234                Ok(FakeTransport::json(media.clone()))
1235            } else {
1236                assert_eq!(request.path, "/libraries/lib%201/medias/m1/image");
1237                assert_eq!(request.query, vec![("size".into(), "thumb".into())]);
1238                Ok(FakeTransport::bytes(encrypted_thumb.clone()))
1239            }
1240        })
1241    }
1242
1243    #[tokio::test]
1244    async fn decrypts_thumbs_of_encrypted_libraries() {
1245        let thumb = b"\xff\xd8 a jpeg thumbnail".to_vec();
1246        let fake = encrypted_server("secret", &thumb);
1247        let api = LibraryApi::new(client(fake), library(true));
1248        let medias = api.get_medias(&MediaQuery::default()).await.unwrap();
1249        let media = &medias[0].item;
1250
1251        let error = api.get_thumb(media).await.unwrap_err();
1252        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
1253
1254        api.set_passphrase("secret").await.unwrap();
1255        assert_eq!(api.get_thumb(media).await.unwrap(), thumb);
1256    }
1257
1258    #[tokio::test]
1259    async fn refuses_a_wrong_passphrase() {
1260        let fake = encrypted_server("secret", b"thumb");
1261        let api = LibraryApi::new(client(fake), library(true));
1262        let error = api.set_passphrase("wrong").await.unwrap_err();
1263        assert_eq!(error.kind(), crate::ErrorKind::InvalidPassphrase);
1264        assert!(!api.has_passphrase());
1265    }
1266
1267    #[tokio::test]
1268    async fn downloads_and_decrypts_media_files() {
1269        let key = redseat_crypto::derive_key("secret");
1270        let iv = redseat_crypto::random_iv().unwrap();
1271        let content = b"\x00\x00\x00\x18ftypmp42 a whole video file".repeat(40);
1272        let file = redseat_crypto::encrypt_file_bytes(
1273            &key,
1274            &iv,
1275            &content,
1276            Some("video/mp4"),
1277            Some((b"thumb", "image/jpeg")),
1278            None,
1279        )
1280        .unwrap();
1281        // Without `raw`, the server sends the file after its header and thumb.
1282        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
1283        let data = file[header.data_offset() as usize..].to_vec();
1284        let fake = FakeTransport::new(move |request| {
1285            assert_eq!(request.path, "/libraries/lib%201/medias/m%201");
1286            Ok(FakeTransport::bytes(data.clone()))
1287        });
1288        let api = LibraryApi::new(client(fake.clone()), library(true));
1289        let media = Media {
1290            id: "m 1".into(),
1291            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
1292            ..Default::default()
1293        };
1294        let query = MediaFileQuery::default();
1295        let error = api.get_media(&media, &query).await.unwrap_err();
1296        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
1297
1298        *api.lock_key() = Some(key);
1299        assert_eq!(api.get_media(&media, &query).await.unwrap(), content);
1300        let request = &fake.requests()[0];
1301        assert!(request.query.is_empty());
1302        assert_eq!(request.timeout, Some(MEDIA_TIMEOUT));
1303    }
1304
1305    #[tokio::test]
1306    async fn asks_the_server_to_convert_unsupported_photos() {
1307        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"webp".to_vec())));
1308        let api = LibraryApi::new(client(fake.clone()), library(false));
1309        let media = Media {
1310            id: "m1".into(),
1311            ..Default::default()
1312        };
1313        let query = MediaFileQuery {
1314            unsupported_mime: vec!["image/heic".into(), "all".into()],
1315            page: Some(2),
1316            raw: true,
1317        };
1318        assert_eq!(api.get_media(&media, &query).await.unwrap(), b"webp");
1319        let requests = fake.requests();
1320        let pairs: Vec<(&str, &str)> = requests[0]
1321            .query
1322            .iter()
1323            .map(|(k, v)| (k.as_str(), v.as_str()))
1324            .collect();
1325        assert_eq!(
1326            pairs,
1327            [
1328                ("unsupportedMime", "image/heic"),
1329                ("unsupportedMime", "all"),
1330                ("page", "2"),
1331                ("raw", "true")
1332            ]
1333        );
1334    }
1335
1336    #[tokio::test]
1337    async fn gives_media_urls_with_a_token() {
1338        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
1339        let api = LibraryApi::new(client(fake.clone()), library(false));
1340        let query = MediaFileQuery::default();
1341        // Not an HTTP transport: no URL.
1342        assert!(api.media_url("m 1", &query).await.is_err());
1343
1344        fake.set_base_url("https://host:7080/");
1345        let url = api.media_url("m 1", &query).await.unwrap();
1346        assert_eq!(url.url, "https://host:7080/libraries/lib%201/medias/m%201");
1347        assert_eq!(url.authorization(), "Bearer t");
1348        assert_eq!(url.expires, i64::MAX);
1349        assert_eq!(
1350            url.with_token_query(),
1351            "https://host:7080/libraries/lib%201/medias/m%201?token=t"
1352        );
1353        assert!(!format!("{url:?}").contains("Bearer"));
1354    }
1355
1356    #[tokio::test]
1357    async fn lists_tags_and_people() {
1358        let fake = FakeTransport::new(|request| {
1359            Ok(FakeTransport::json(match request.path.as_str() {
1360                "/libraries/lib%201/tags" => serde_json::json!([
1361                    {"id": "t1", "name": "beach", "parent": null, "alt": null, "modified": 1,
1362                        "added": 1, "generated": false, "path": "/beach"}
1363                ]),
1364                "/libraries/lib%201/people" => serde_json::json!([serde_json::to_value(Person {
1365                    id: "p1".into(),
1366                    name: "Alice".into(),
1367                    ..Default::default()
1368                })
1369                .unwrap()]),
1370                other => panic!("unexpected {other}"),
1371            }))
1372        });
1373        let api = LibraryApi::new(client(fake), library(false));
1374        assert_eq!(
1375            api.get_tags(&TagQuery::default()).await.unwrap()[0].name,
1376            "beach"
1377        );
1378        assert_eq!(
1379            api.get_people(&PeopleQuery::default()).await.unwrap()[0].name,
1380            "Alice"
1381        );
1382    }
1383
1384    #[tokio::test]
1385    async fn lists_with_after_and_pages() {
1386        let fake = FakeTransport::new(|request| {
1387            Ok(FakeTransport::json(match request.path.as_str() {
1388                "/libraries/lib%201/medias/count" => serde_json::json!({"count": 7}),
1389                _ => serde_json::json!([]),
1390            }))
1391        });
1392        let api = LibraryApi::new(client(fake.clone()), library(false));
1393        let pairs = |request: &Request| -> Vec<(String, String)> {
1394            let mut pairs = request.query.clone();
1395            pairs.sort();
1396            pairs
1397        };
1398        let owned = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
1399            pairs
1400                .iter()
1401                .map(|(k, v)| (k.to_string(), v.to_string()))
1402                .collect()
1403        };
1404
1405        let tags = TagQuery {
1406            after: Some(41),
1407            limit: Some(1000),
1408            offset: Some(2000),
1409            ..Default::default()
1410        };
1411        api.get_tags(&tags).await.unwrap();
1412        api.get_people(&PeopleQuery::from_after(5)).await.unwrap();
1413        api.get_series(&SerieQuery::from_after(6)).await.unwrap();
1414        api.get_movies(&MovieQuery::from_after(7)).await.unwrap();
1415        let episodes = EpisodeQuery {
1416            not_seasons: vec![0, 9],
1417            ..EpisodeQuery::from_after(8)
1418        };
1419        api.get_episodes(&episodes).await.unwrap();
1420        api.get_books(&BookQuery {
1421            after: Some(9),
1422            ..Default::default()
1423        })
1424        .await
1425        .unwrap();
1426        let deleted = DeletedQuery {
1427            after: Some(10),
1428            kind: Some(crate::types::element_type::ElementType::Media),
1429            order: SqlOrder::ASC,
1430            limit: Some(1000),
1431            offset: Some(0),
1432        };
1433        api.get_deleted(&deleted).await.unwrap();
1434        let count = api.count_medias(&MediaQuery::from_after(11)).await.unwrap();
1435        assert_eq!(count, 7);
1436
1437        let requests = fake.requests();
1438        let paths: Vec<&str> = requests.iter().map(|r| r.path.as_str()).collect();
1439        assert_eq!(
1440            paths,
1441            [
1442                "/libraries/lib%201/tags",
1443                "/libraries/lib%201/people",
1444                "/libraries/lib%201/series",
1445                "/libraries/lib%201/movies",
1446                "/libraries/lib%201/series/episodes",
1447                "/libraries/lib%201/books",
1448                "/libraries/lib%201/deleted",
1449                "/libraries/lib%201/medias/count",
1450            ]
1451        );
1452        assert_eq!(
1453            pairs(&requests[0]),
1454            owned(&[("after", "41"), ("limit", "1000"), ("offset", "2000")])
1455        );
1456        assert_eq!(pairs(&requests[1]), owned(&[("after", "5")]));
1457        // Defaults the server reads too; the movie sort's default is left out.
1458        assert_eq!(
1459            pairs(&requests[2]),
1460            owned(&[("after", "6"), ("order", "DESC"), ("sort", "modified")])
1461        );
1462        assert_eq!(pairs(&requests[3]), owned(&[("after", "7")]));
1463        assert_eq!(
1464            pairs(&requests[4]),
1465            owned(&[("after", "8"), ("notSeasons", "0"), ("notSeasons", "9")])
1466        );
1467        assert_eq!(
1468            pairs(&requests[5]),
1469            owned(&[("after", "9"), ("order", "DESC"), ("sort", "modified")])
1470        );
1471        assert_eq!(
1472            pairs(&requests[6]),
1473            owned(&[
1474                ("after", "10"),
1475                ("limit", "1000"),
1476                ("offset", "0"),
1477                ("order", "ASC"),
1478                ("type", "media")
1479            ])
1480        );
1481        assert_eq!(filter_of(&requests[7])["after"], 11);
1482    }
1483
1484    #[tokio::test]
1485    async fn changes_merges_and_removes_tags() {
1486        let (api, fake) = api_answering(tag_json("t 1", "beach"));
1487        let update = TagForUpdate {
1488            name: Some("beach".into()),
1489            parent: Some(String::new()),
1490            add_alts: Some(vec!["sea".into()]),
1491            ..Default::default()
1492        };
1493        assert_eq!(api.update_tag("t 1", &update).await.unwrap().name, "beach");
1494        assert_eq!(api.merge_tag("t 1", "t2").await.unwrap().id, "t 1");
1495        assert_eq!(
1496            api.remove_tag("t 1").await.unwrap().alt,
1497            Some(vec!["sea".to_owned()])
1498        );
1499
1500        let requests = fake.requests();
1501        assert_eq!(requests[0].method, Method::Patch);
1502        assert_eq!(requests[0].path, "/libraries/lib%201/tags/t%201");
1503        let Some(Body::Json(sent)) = &requests[0].body else {
1504            panic!("no JSON body");
1505        };
1506        assert_eq!(sent["name"], "beach");
1507        assert_eq!(sent["parent"], "");
1508        assert_eq!(sent["addAlts"], serde_json::json!(["sea"]));
1509        assert_eq!(sent["removeAlts"], serde_json::Value::Null);
1510        assert_sent(
1511            &requests[1],
1512            Method::Patch,
1513            "/libraries/lib%201/tags/t%201/merge",
1514            &[],
1515            Some(serde_json::json!({"into": "t2"})),
1516        );
1517        assert_sent(
1518            &requests[2],
1519            Method::Delete,
1520            "/libraries/lib%201/tags/t%201",
1521            &[],
1522            None,
1523        );
1524    }
1525
1526    #[tokio::test]
1527    async fn reads_removes_and_merges_people() {
1528        let fake = FakeTransport::new(|request| {
1529            Ok(FakeTransport::json(match request.path.as_str() {
1530                "/libraries/lib%201/people/missing" => serde_json::Value::Null,
1531                "/libraries/lib%201/people/merge" => {
1532                    serde_json::json!({"status": "merged", "faces_transferred": 4})
1533                }
1534                "/libraries/lib%201/people/p%201" => {
1535                    serde_json::json!({"id": "p 1", "name": "Alice", "socials": null,
1536                        "portrait": null, "params": null, "birthday": null, "modified": 2,
1537                        "added": 1, "posterv": 0, "generated": false, "type": "Actor"})
1538                }
1539                // A person of a title: the person, with their roles in it.
1540                _ => serde_json::json!([{"id": "p 1", "name": "Alice", "socials": null,
1541                    "portrait": null, "params": null, "birthday": null, "modified": 2,
1542                    "added": 1, "posterv": 0, "generated": false,
1543                    "roles": ["Actor"], "characters": ["Ripley"], "rank": 0}]),
1544            }))
1545        });
1546        let api = LibraryApi::new(client(fake.clone()), library(false));
1547        let person = api.get_person("p 1").await.unwrap().unwrap();
1548        assert_eq!(person.name, "Alice");
1549        assert_eq!(person.kind, Some(PersonType::Actor));
1550        assert_eq!(api.get_person("missing").await.unwrap(), None);
1551        assert_eq!(api.remove_person("p 1").await.unwrap().id, "p 1");
1552        assert_eq!(api.merge_people("p 1", "p2").await.unwrap(), 4);
1553        let cast = api.get_movie_people("m 1").await.unwrap();
1554        assert_eq!(cast[0].person.name, "Alice");
1555        assert_eq!(cast[0].roles, Some(vec![PersonType::Actor]));
1556        assert_eq!(cast[0].characters, Some(vec!["Ripley".to_owned()]));
1557        api.get_serie_people("s 1").await.unwrap();
1558        api.get_book_people("b 1").await.unwrap();
1559
1560        let requests = fake.requests();
1561        let person = "/libraries/lib%201/people/p%201";
1562        assert_sent(&requests[0], Method::Get, person, &[], None);
1563        assert_sent(&requests[2], Method::Delete, person, &[], None);
1564        assert_sent(
1565            &requests[3],
1566            Method::Post,
1567            "/libraries/lib%201/people/merge",
1568            &[],
1569            Some(serde_json::json!({"sourcePersonId": "p 1", "targetPersonId": "p2"})),
1570        );
1571        let people = [
1572            "/libraries/lib%201/movies/m%201/people",
1573            "/libraries/lib%201/series/s%201/people",
1574            "/libraries/lib%201/books/b%201/people",
1575        ];
1576        for (request, path) in requests[4..].iter().zip(people) {
1577            assert_sent(request, Method::Get, path, &[], None);
1578        }
1579    }
1580
1581    #[tokio::test]
1582    async fn creates_and_removes_series() {
1583        let (api, fake) = api_answering(serde_json::json!({"id": "s 1", "name": "Dark",
1584            "modified": 2, "added": 1, "posterv": 0, "backgroundv": 0, "cardv": 0,
1585            "relations": {"tags": [{"id": "t1"}]}}));
1586        let serie = ItemWithRelations {
1587            item: Serie {
1588                name: "Dark".into(),
1589                ..Default::default()
1590            },
1591            relations: None,
1592        };
1593        let created = api.create_serie(&serie).await.unwrap();
1594        assert_eq!(created.item.id, "s 1");
1595        assert!(created.relations.is_some());
1596        assert_eq!(api.remove_serie("s 1", true).await.unwrap().name, "Dark");
1597
1598        let requests = fake.requests();
1599        assert_eq!(requests[0].method, Method::Post);
1600        assert_eq!(requests[0].path, "/libraries/lib%201/series");
1601        let Some(Body::Json(sent)) = &requests[0].body else {
1602            panic!("no JSON body");
1603        };
1604        // The series and its relations are one flat object, as the server reads it.
1605        assert_eq!(sent["name"], "Dark");
1606        assert_sent(
1607            &requests[1],
1608            Method::Delete,
1609            "/libraries/lib%201/series/s%201",
1610            &[("deleteMedias", "true")],
1611            None,
1612        );
1613    }
1614
1615    #[tokio::test]
1616    async fn sets_episode_history_and_adds_a_searched_file() {
1617        let fake = FakeTransport::new(|request| {
1618            Ok(if request.path.ends_with("/search") {
1619                FakeTransport::json(media_json("m1", 100))
1620            } else {
1621                // The history routes answer with an empty body.
1622                FakeTransport::bytes(Vec::new())
1623            })
1624        });
1625        let api = LibraryApi::new(client(fake.clone()), library(false));
1626        api.set_episode_watched("s 1", 2, 3, 1700).await.unwrap();
1627        api.set_episode_progress("s 1", 2, 3, 42).await.unwrap();
1628        let request = RsRequest {
1629            url: "https://example.com/e.mkv".into(),
1630            ..Default::default()
1631        };
1632        let media = api
1633            .add_searched_episode_media("s 1", 2, 3, &request)
1634            .await
1635            .unwrap();
1636        assert_eq!(media.id, "m1");
1637
1638        let requests = fake.requests();
1639        let episode = "/libraries/lib%201/series/s%201/seasons/2/episodes/3";
1640        assert_sent(
1641            &requests[0],
1642            Method::Post,
1643            &format!("{episode}/watched"),
1644            &[],
1645            Some(serde_json::json!({"date": 1700})),
1646        );
1647        assert_sent(
1648            &requests[1],
1649            Method::Post,
1650            &format!("{episode}/progress"),
1651            &[],
1652            Some(serde_json::json!({"progress": 42})),
1653        );
1654        assert_eq!(requests[2].method, Method::Post);
1655        assert_eq!(requests[2].path, format!("{episode}/search"));
1656        assert_eq!(requests[2].timeout, Some(DOWNLOAD_TIMEOUT));
1657        let Some(Body::Json(sent)) = &requests[2].body else {
1658            panic!("no JSON body");
1659        };
1660        assert_eq!(sent["url"], "https://example.com/e.mkv");
1661    }
1662
1663    #[tokio::test]
1664    async fn creates_changes_and_removes_movies() {
1665        let (api, fake) = api_answering(serde_json::json!({"id": "m 1", "name": "Alien",
1666            "type": null, "year": 1979, "modified": 2, "added": 1, "posterv": 0,
1667            "backgroundv": 0, "cardv": 0, "relations": {"tags": [{"id": "t1"}]}}));
1668        let movie = ItemWithRelations {
1669            item: Movie {
1670                name: "Alien".into(),
1671                ..Default::default()
1672            },
1673            relations: None,
1674        };
1675        assert_eq!(api.create_movie(&movie).await.unwrap().item.id, "m 1");
1676        let update = MovieForUpdate {
1677            name: Some("Aliens".into()),
1678            ..Default::default()
1679        };
1680        let updated = api.update_movie("m 1", &update).await.unwrap();
1681        assert!(updated.relations.is_some());
1682        assert_eq!(
1683            api.remove_movie("m 1", false).await.unwrap().year,
1684            Some(1979)
1685        );
1686
1687        let requests = fake.requests();
1688        assert_eq!(requests[0].method, Method::Post);
1689        assert_eq!(requests[0].path, "/libraries/lib%201/movies");
1690        let Some(Body::Json(sent)) = &requests[0].body else {
1691            panic!("no JSON body");
1692        };
1693        assert_eq!(sent["name"], "Alien");
1694        assert_eq!(requests[1].method, Method::Patch);
1695        assert_eq!(requests[1].path, "/libraries/lib%201/movies/m%201");
1696        let Some(Body::Json(sent)) = &requests[1].body else {
1697            panic!("no JSON body");
1698        };
1699        assert_eq!(sent["name"], "Aliens");
1700        assert_sent(
1701            &requests[2],
1702            Method::Delete,
1703            "/libraries/lib%201/movies/m%201",
1704            &[("deleteMedias", "false")],
1705            None,
1706        );
1707    }
1708
1709    #[tokio::test]
1710    async fn sets_movie_history_and_adds_a_searched_file() {
1711        let fake = FakeTransport::new(|request| {
1712            Ok(if request.path.ends_with("/search") {
1713                FakeTransport::json(media_json("m1", 100))
1714            } else {
1715                FakeTransport::bytes(Vec::new())
1716            })
1717        });
1718        let api = LibraryApi::new(client(fake.clone()), library(false));
1719        api.set_movie_watched("m 1", 0).await.unwrap();
1720        api.set_movie_progress("m 1", 42).await.unwrap();
1721        let request = RsRequest {
1722            url: "https://example.com/m.mkv".into(),
1723            ..Default::default()
1724        };
1725        let media = api.add_searched_movie_media("m 1", &request).await.unwrap();
1726        assert_eq!(media.id, "m1");
1727
1728        let requests = fake.requests();
1729        let movie = "/libraries/lib%201/movies/m%201";
1730        assert_sent(
1731            &requests[0],
1732            Method::Post,
1733            &format!("{movie}/watched"),
1734            &[],
1735            Some(serde_json::json!({"date": 0})),
1736        );
1737        assert_sent(
1738            &requests[1],
1739            Method::Post,
1740            &format!("{movie}/progress"),
1741            &[],
1742            Some(serde_json::json!({"progress": 42})),
1743        );
1744        assert_eq!(requests[2].method, Method::Post);
1745        assert_eq!(requests[2].path, format!("{movie}/search"));
1746        assert_eq!(requests[2].timeout, Some(DOWNLOAD_TIMEOUT));
1747    }
1748
1749    #[tokio::test]
1750    async fn reads_creates_changes_and_removes_books() {
1751        let (api, fake) = api_answering(serde_json::json!({"id": "b 1", "name": "Dune",
1752            "year": 1965, "modified": 2, "added": 1, "relations": {"people": [{"id": "p1"}]}}));
1753        assert_eq!(api.get_book("b 1").await.unwrap().item.name, "Dune");
1754        let book = ItemWithRelations {
1755            item: Book {
1756                name: "Dune".into(),
1757                ..Default::default()
1758            },
1759            relations: None,
1760        };
1761        let created = api.create_book(&book, true, false, true).await.unwrap();
1762        assert_eq!(created.item.id, "b 1");
1763        api.create_book(&book, false, false, false).await.unwrap();
1764        let update = BookForUpdate {
1765            name: Some("Dune Messiah".into()),
1766            ..Default::default()
1767        };
1768        let updated = api.update_book("b 1", &update).await.unwrap();
1769        assert!(updated.relations.is_some());
1770        assert_eq!(api.remove_book("b 1", true).await.unwrap().year, Some(1965));
1771        api.set_book_watched("b 1", 1700).await.unwrap();
1772
1773        let requests = fake.requests();
1774        let one = "/libraries/lib%201/books/b%201";
1775        assert_sent(&requests[0], Method::Get, one, &[], None);
1776        assert_eq!(requests[1].method, Method::Post);
1777        assert_eq!(requests[1].path, "/libraries/lib%201/books");
1778        assert_eq!(
1779            requests[1].query,
1780            [
1781                ("upsertTags".to_owned(), "true".to_owned()),
1782                ("upsertSerie".to_owned(), "true".to_owned())
1783            ]
1784        );
1785        let Some(Body::Json(sent)) = &requests[1].body else {
1786            panic!("no JSON body");
1787        };
1788        assert_eq!(sent["name"], "Dune");
1789        assert!(requests[2].query.is_empty());
1790        assert_eq!(requests[3].method, Method::Patch);
1791        assert_eq!(requests[3].path, one);
1792        let Some(Body::Json(sent)) = &requests[3].body else {
1793            panic!("no JSON body");
1794        };
1795        assert_eq!(sent["name"], "Dune Messiah");
1796        assert_sent(
1797            &requests[4],
1798            Method::Delete,
1799            one,
1800            &[("deleteMedias", "true")],
1801            None,
1802        );
1803        assert_sent(
1804            &requests[5],
1805            Method::Post,
1806            &format!("{one}/watched"),
1807            &[],
1808            Some(serde_json::json!({"date": 1700})),
1809        );
1810    }
1811
1812    /// The files of a multipart body, read with the parser the server uses (multer,
1813    /// through axum).
1814    async fn multipart_files(body: &Body) -> Vec<Vec<u8>> {
1815        let Body::Bytes { content_type, data } = body else {
1816            panic!("not a bytes body");
1817        };
1818        let boundary = multer::parse_boundary(content_type).unwrap();
1819        let stream = futures_util::stream::iter([Ok::<_, std::convert::Infallible>(data.clone())]);
1820        let mut multipart = multer::Multipart::new(stream, boundary);
1821        let mut files = Vec::new();
1822        while let Some(field) = multipart.next_field().await.unwrap() {
1823            assert_eq!(field.name(), Some("file"));
1824            files.push(field.bytes().await.unwrap().to_vec());
1825        }
1826        files
1827    }
1828
1829    #[tokio::test]
1830    async fn uploads_a_book_poster_as_multipart() {
1831        let (api, fake) = api_answering(serde_json::json!({"data": "ok"}));
1832        // An image that holds line breaks, dashes and the usual boundary itself.
1833        let image = b"\xff\xd8\r\n--redseat-api-boundary--\r\n jpeg".to_vec();
1834        api.update_book_poster("b 1", &image).await.unwrap();
1835
1836        let request = &fake.requests()[0];
1837        assert_eq!(request.method, Method::Post);
1838        assert_eq!(request.path, "/libraries/lib%201/books/b%201/image");
1839        assert!(request.query.is_empty());
1840        let body = request.body.as_ref().unwrap();
1841        assert_eq!(multipart_files(body).await, [image]);
1842    }
1843
1844    #[tokio::test]
1845    async fn reads_changes_and_removes_medias() {
1846        let fake = FakeTransport::new(|request| {
1847            let media = media_json("m 1", 100);
1848            Ok(FakeTransport::json(match request.path.as_str() {
1849                "/libraries/lib%201/medias/m%201/metadata" => {
1850                    let mut media = media;
1851                    media["relations"] = serde_json::json!({"tags": [{"id": "t1"}]});
1852                    media["faces"] = serde_json::json!([]);
1853                    media
1854                }
1855                "/libraries/lib%201/medias/missing/metadata" => serde_json::Value::Null,
1856                "/libraries/lib%201/medias/exist" => {
1857                    let known = request.query[0].1 == "abc";
1858                    serde_json::json!({"exist": known, "media": known.then_some(media)})
1859                }
1860                "/libraries/lib%201/medias/m%201/progress" => serde_json::json!({
1861                    "mediaRef": "m 1", "userRef": "u1", "progress": 42, "modified": 5}),
1862                "/libraries/lib%201/medias" => serde_json::json!([media]),
1863                _ => media,
1864            }))
1865        });
1866        let api = LibraryApi::new(client(fake.clone()), library(false));
1867        let media = api.get_media_metadata("m 1").await.unwrap().unwrap();
1868        assert!(media.relations.is_some());
1869        assert_eq!(api.get_media_metadata("missing").await.unwrap(), None);
1870        let found = api.get_media_by_hash("abc").await.unwrap().unwrap();
1871        assert_eq!(found.item.id, "m 1");
1872        assert_eq!(api.get_media_by_hash("def").await.unwrap(), None);
1873        let update = MediaForUpdate {
1874            rating: Some(8),
1875            remove_tags: Some(vec!["t1".into()]),
1876            ..Default::default()
1877        };
1878        assert_eq!(api.update_media("m 1", &update).await.unwrap().id, "m 1");
1879        let progress = api.set_media_progress("m 1", 42).await.unwrap();
1880        assert_eq!(progress.progress, 42);
1881        let removed = api
1882            .remove_medias(&["m 1".to_owned(), "gone".to_owned()])
1883            .await
1884            .unwrap();
1885        assert_eq!(removed.len(), 1);
1886
1887        let requests = fake.requests();
1888        let one = "/libraries/lib%201/medias/m%201";
1889        assert_sent(
1890            &requests[0],
1891            Method::Get,
1892            &format!("{one}/metadata"),
1893            &[],
1894            None,
1895        );
1896        assert_sent(
1897            &requests[2],
1898            Method::Get,
1899            "/libraries/lib%201/medias/exist",
1900            &[("hash", "abc")],
1901            None,
1902        );
1903        assert_eq!(requests[4].method, Method::Patch);
1904        assert_eq!(requests[4].path, one);
1905        let Some(Body::Json(sent)) = &requests[4].body else {
1906            panic!("no JSON body");
1907        };
1908        assert_eq!(sent["rating"], 8);
1909        assert_eq!(sent["removeTags"], serde_json::json!(["t1"]));
1910        assert_sent(
1911            &requests[5],
1912            Method::Patch,
1913            &format!("{one}/progress"),
1914            &[],
1915            Some(serde_json::json!({"progress": 42})),
1916        );
1917        assert_sent(
1918            &requests[6],
1919            Method::Delete,
1920            "/libraries/lib%201/medias",
1921            &[],
1922            Some(serde_json::json!({"ids": ["m 1", "gone"]})),
1923        );
1924    }
1925
1926    #[tokio::test]
1927    async fn gives_share_urls_of_medias() {
1928        let fake = FakeTransport::new(|request| {
1929            assert_eq!(request.path, "/libraries/lib%201/medias/m%201/sharetoken");
1930            // The token is the whole body, as text.
1931            Ok(FakeTransport::bytes(b"v4.local.a+b".to_vec()))
1932        });
1933        let api = LibraryApi::new(client(fake.clone()), library(false));
1934        // Not an HTTP transport: no URL.
1935        assert!(api.media_share_url("m 1").await.is_err());
1936
1937        fake.set_base_url("https://host:7080");
1938        assert_eq!(
1939            api.media_share_url("m 1").await.unwrap(),
1940            "https://host:7080/libraries/lib%201/medias/m%201?sharetoken=v4.local.a%2Bb"
1941        );
1942    }
1943
1944    #[tokio::test]
1945    async fn downloads_medias_from_urls() {
1946        let fake = FakeTransport::new(|request| {
1947            let url = match &request.body {
1948                Some(Body::Json(body)) => body["requests"][0]["url"].as_str().unwrap().to_owned(),
1949                _ => panic!("no JSON body"),
1950            };
1951            Ok(FakeTransport::json(if !request.query.is_empty() {
1952                serde_json::json!({"downloading": true})
1953            } else if url.ends_with(".zip") {
1954                serde_json::json!({"needFileSelection": true, "request": {"url": url}})
1955            } else {
1956                serde_json::json!([media_json("m1", 100)])
1957            }))
1958        });
1959        let api = LibraryApi::new(client(fake.clone()), library(false));
1960        let download = |url: &str| RsGroupDownload {
1961            requests: vec![RsRequest {
1962                url: url.into(),
1963                ..Default::default()
1964            }],
1965            ..Default::default()
1966        };
1967        let medias = api.download_medias(&download("https://e.com/a.jpg")).await;
1968        assert_eq!(medias.unwrap()[0].id, "m1");
1969        let error = api
1970            .download_medias(&download("https://e.com/a.zip"))
1971            .await
1972            .unwrap_err();
1973        assert!(error.to_string().contains("file selection"));
1974        api.download_medias_in_background(&download("https://e.com/a.jpg"))
1975            .await
1976            .unwrap();
1977
1978        let requests = fake.requests();
1979        for request in &requests {
1980            assert_eq!(request.method, Method::Post);
1981            assert_eq!(request.path, "/libraries/lib%201/medias/download");
1982        }
1983        assert!(requests[0].query.is_empty());
1984        assert_eq!(requests[0].timeout, Some(DOWNLOAD_TIMEOUT));
1985        assert_eq!(requests[2].query, [("spawn".to_owned(), "true".to_owned())]);
1986        assert_eq!(requests[2].timeout, None);
1987    }
1988
1989    #[tokio::test]
1990    async fn tags_channels_and_gives_their_stream_urls() {
1991        let (api, fake) = api_answering(serde_json::json!({"status": "ok"}));
1992        api.add_tag_to_channel("c 1", "t 1").await.unwrap();
1993        api.remove_tag_from_channel("c 1", "t 1").await.unwrap();
1994        api.stop_channel_hls("c 1").await.unwrap();
1995
1996        let requests = fake.requests();
1997        let channel = "/libraries/lib%201/channels/c%201";
1998        assert_sent(
1999            &requests[0],
2000            Method::Post,
2001            &format!("{channel}/tags"),
2002            &[],
2003            Some(serde_json::json!({"tagId": "t 1"})),
2004        );
2005        assert_sent(
2006            &requests[1],
2007            Method::Delete,
2008            &format!("{channel}/tags/t%201"),
2009            &[],
2010            None,
2011        );
2012        assert_sent(
2013            &requests[2],
2014            Method::Delete,
2015            &format!("{channel}/hls"),
2016            &[],
2017            None,
2018        );
2019
2020        // Not an HTTP transport: no URL.
2021        assert!(api.channel_stream_url("c 1", None).await.is_err());
2022        fake.set_base_url("https://host:7080");
2023        let stream = api.channel_stream_url("c 1", None).await.unwrap();
2024        assert_eq!(stream.url, format!("https://host:7080{channel}/stream"));
2025        assert_eq!(stream.authorization(), "Bearer t");
2026        let hls = api.channel_hls_url("c 1", Some("720p")).await.unwrap();
2027        assert_eq!(
2028            hls.with_token_query(),
2029            format!("https://host:7080{channel}/hls/playlist.m3u8?quality=720p&token=t")
2030        );
2031    }
2032
2033    #[tokio::test]
2034    async fn processes_requests_through_plugins() {
2035        let fake = FakeTransport::new(|request| {
2036            Ok(match request.path.as_str() {
2037                "/libraries/lib%201/plugins/requests/process/stream" => {
2038                    FakeTransport::bytes(b"\xff\xd8 jpeg".to_vec())
2039                }
2040                "/libraries/lib%201/plugins/requests/url/sharetoken" => {
2041                    FakeTransport::bytes(b"v4.local.share".to_vec())
2042                }
2043                "/libraries/lib%201/plugins/requests/add" => {
2044                    FakeTransport::json(serde_json::json!({"id": "rp1", "processingId": "42",
2045                        "pluginId": "debrid", "progress": 0, "status": "pending",
2046                        "mediaRef": "m1", "modified": 2, "added": 1}))
2047                }
2048                _ => FakeTransport::json(serde_json::json!({"url": "https://cdn.e.com/f.mkv",
2049                    "status": "finalPublic", "permanent": true, "mime": "video/x-matroska"})),
2050            })
2051        });
2052        let api = LibraryApi::new(client(fake.clone()), library(false));
2053        let request = RsRequest {
2054            url: "https://e.com/f".into(),
2055            ..Default::default()
2056        };
2057        let processed = api.process_request(&request).await.unwrap();
2058        assert_eq!(processed.url, "https://cdn.e.com/f.mkv");
2059        assert_eq!(
2060            processed.status,
2061            rs_plugin_common_interfaces::request::RsRequestStatus::FinalPublic
2062        );
2063        let image = api.process_request_bytes(&request).await.unwrap();
2064        assert_eq!(image, b"\xff\xd8 jpeg");
2065        assert!(
2066            api.check_request_permanent(&request)
2067                .await
2068                .unwrap()
2069                .permanent
2070        );
2071        let task = api.add_request(&request, Some("m1")).await.unwrap();
2072        assert_eq!(task.id, "rp1");
2073        assert_eq!(task.media_ref.as_deref(), Some("m1"));
2074        api.add_request(&request, None).await.unwrap();
2075
2076        let requests = fake.requests();
2077        let plugins = "/libraries/lib%201/plugins/requests";
2078        for (request, rest) in requests
2079            .iter()
2080            .zip(["process", "process/stream", "permanent"])
2081        {
2082            assert_eq!(request.method, Method::Post);
2083            assert_eq!(request.path, format!("{plugins}/{rest}"));
2084            let Some(Body::Json(sent)) = &request.body else {
2085                panic!("no JSON body");
2086            };
2087            assert_eq!(sent["url"], "https://e.com/f");
2088        }
2089        assert_eq!(requests[3].method, Method::Post);
2090        assert_eq!(requests[3].path, format!("{plugins}/add"));
2091        let Some(Body::Json(sent)) = &requests[3].body else {
2092            panic!("no JSON body");
2093        };
2094        assert_eq!(sent["request"]["url"], "https://e.com/f");
2095        assert_eq!(sent["mediaRef"], "m1");
2096        let Some(Body::Json(sent)) = &requests[4].body else {
2097            panic!("no JSON body");
2098        };
2099        assert_eq!(sent["mediaRef"], serde_json::Value::Null);
2100
2101        // Not an HTTP transport: no URL.
2102        assert!(api.request_share_url("https://e.com/f?a=1").await.is_err());
2103        fake.set_base_url("https://host:7080");
2104        assert_eq!(
2105            api.request_share_url("https://e.com/f?a=1").await.unwrap(),
2106            format!(
2107                "https://host:7080{plugins}/url/stream?sharetoken=v4.local.share\
2108                 &url=https%3A%2F%2Fe.com%2Ff%3Fa%3D1"
2109            )
2110        );
2111        let token = fake.requests().pop().unwrap();
2112        assert_sent(
2113            &token,
2114            Method::Get,
2115            &format!("{plugins}/url/sharetoken"),
2116            &[("url", "https://e.com/f?a=1")],
2117            None,
2118        );
2119    }
2120
2121    fn person_json(id: &str, name: &str) -> serde_json::Value {
2122        serde_json::json!({"id": id, "name": name, "socials": null, "portrait": null,
2123            "params": null, "birthday": null, "modified": 2, "added": 1, "posterv": 0,
2124            "generated": false, "type": "Actor"})
2125    }
2126
2127    #[tokio::test]
2128    async fn creates_a_tag() {
2129        let (api, fake) = api_answering(tag_json("t 1", "beach"));
2130        let tag = TagForAdd {
2131            name: "beach".into(),
2132            parent: Some("t0".into()),
2133            alt: Some(vec!["sea".into()]),
2134            ..Default::default()
2135        };
2136        assert_eq!(api.create_tag(&tag).await.unwrap().id, "t 1");
2137
2138        let request = &fake.requests()[0];
2139        assert_eq!(request.method, Method::Post);
2140        assert_eq!(request.path, "/libraries/lib%201/tags");
2141        let Some(Body::Json(sent)) = &request.body else {
2142            panic!("no JSON body");
2143        };
2144        assert_eq!(sent["name"], "beach");
2145        assert_eq!(sent["parent"], "t0");
2146        assert_eq!(sent["alt"], serde_json::json!(["sea"]));
2147        assert_eq!(sent["generated"], false);
2148    }
2149
2150    #[tokio::test]
2151    async fn creates_and_changes_people() {
2152        let (api, fake) = api_answering(person_json("p 1", "Alice"));
2153        let person = PersonForAdd {
2154            name: "Alice".into(),
2155            kind: Some(PersonType::Actor),
2156            birthday: Some(0),
2157            ..Default::default()
2158        };
2159        assert_eq!(api.create_person(&person).await.unwrap().id, "p 1");
2160        let update = PersonForUpdate {
2161            name: Some("Alicia".into()),
2162            add_alts: Some(vec!["Al".into()]),
2163            ..Default::default()
2164        };
2165        let updated = api.update_person("p 1", &update).await.unwrap();
2166        assert_eq!(updated.kind, Some(PersonType::Actor));
2167
2168        let requests = fake.requests();
2169        assert_eq!(requests[0].method, Method::Post);
2170        assert_eq!(requests[0].path, "/libraries/lib%201/people");
2171        let Some(Body::Json(sent)) = &requests[0].body else {
2172            panic!("no JSON body");
2173        };
2174        assert_eq!(sent["name"], "Alice");
2175        assert_eq!(sent["type"], "Actor");
2176        assert_eq!(sent["birthday"], 0);
2177        assert_eq!(requests[1].method, Method::Patch);
2178        assert_eq!(requests[1].path, "/libraries/lib%201/people/p%201");
2179        let Some(Body::Json(sent)) = &requests[1].body else {
2180            panic!("no JSON body");
2181        };
2182        assert_eq!(sent["name"], "Alicia");
2183        assert_eq!(sent["addAlts"], serde_json::json!(["Al"]));
2184        assert_eq!(sent["removeAlts"], serde_json::Value::Null);
2185    }
2186
2187    #[tokio::test]
2188    async fn changes_a_serie() {
2189        let (api, fake) = api_answering(serde_json::json!({"id": "s 1", "name": "Dark",
2190            "modified": 2, "added": 1, "posterv": 0, "backgroundv": 0, "cardv": 0,
2191            "relations": {"tags": [{"id": "t1"}]}}));
2192        let update = SerieForUpdate {
2193            name: Some("Dark".into()),
2194            add_alts: Some(vec!["Dunkel".into()]),
2195            year: Some(2017),
2196            ..Default::default()
2197        };
2198        let updated = api.update_serie("s 1", &update).await.unwrap();
2199        assert_eq!(updated.item.name, "Dark");
2200        assert!(updated.relations.is_some());
2201
2202        let request = &fake.requests()[0];
2203        assert_eq!(request.method, Method::Patch);
2204        assert_eq!(request.path, "/libraries/lib%201/series/s%201");
2205        let Some(Body::Json(sent)) = &request.body else {
2206            panic!("no JSON body");
2207        };
2208        assert_eq!(sent["name"], "Dark");
2209        assert_eq!(sent["addAlts"], serde_json::json!(["Dunkel"]));
2210        assert_eq!(sent["year"], 2017);
2211    }
2212
2213    #[tokio::test]
2214    async fn lists_channels() {
2215        let (api, fake) = api_answering(serde_json::json!([{"id": "c1", "name": "TF1",
2216            "tvgId": "TF1.fr", "country": "FR", "tags": ["t1"], "channelNumber": 1,
2217            "posterv": 2, "modified": 2, "added": 1, "variants": [{"id": "v1",
2218            "channelRef": "c1", "quality": "HD", "streamUrl": "http://e.com/tf1"}]}]));
2219        let query = ChannelQuery {
2220            tag: Some("t1".into()),
2221            limit: Some(100),
2222            offset: Some(200),
2223            ..Default::default()
2224        };
2225        let channels = api.get_channels(&query).await.unwrap();
2226        assert_eq!(channels[0].name, "TF1");
2227        assert_eq!(channels[0].tags, Some(vec!["t1".to_owned()]));
2228        let variants = channels[0].variants.as_ref().unwrap();
2229        assert_eq!(variants[0].quality.as_deref(), Some("HD"));
2230
2231        let request = &fake.requests()[0];
2232        assert_eq!(request.method, Method::Get);
2233        assert_eq!(request.path, "/libraries/lib%201/channels");
2234        let mut sent = request.query.clone();
2235        sent.sort();
2236        let pair = |name: &str, value: &str| (name.to_owned(), value.to_owned());
2237        assert_eq!(
2238            sent,
2239            [
2240                pair("limit", "100"),
2241                pair("offset", "200"),
2242                pair("tag", "t1")
2243            ]
2244        );
2245    }
2246
2247    #[tokio::test]
2248    async fn fetches_images() {
2249        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"\xff\xd8 jpeg".to_vec())));
2250        let api = LibraryApi::new(client(fake.clone()), library(false));
2251        let thumb = ImageRequestOptions {
2252            size: Some(ImageSize::Thumb),
2253            ..Default::default()
2254        };
2255        let backdrop = ImageRequestOptions {
2256            size: Some(ImageSize::Large),
2257            kind: Some(ImageType::Background),
2258            defaulting: true,
2259        };
2260        let original = ImageRequestOptions::default();
2261        assert_eq!(
2262            api.get_serie_image("s 1", &backdrop).await.unwrap(),
2263            b"\xff\xd8 jpeg"
2264        );
2265        api.get_episode_image("s 1", 2, 3, &thumb).await.unwrap();
2266        api.get_movie_image("m 1", &original).await.unwrap();
2267        api.get_book_image("b 1", &thumb).await.unwrap();
2268        api.get_person_image("p 1", &thumb).await.unwrap();
2269        api.get_channel_image("c 1", &thumb).await.unwrap();
2270
2271        let requests = fake.requests();
2272        let sent: Vec<(&str, String)> = requests
2273            .iter()
2274            .map(|request| {
2275                assert_eq!(request.method, Method::Get);
2276                let mut query: Vec<String> = request
2277                    .query
2278                    .iter()
2279                    .map(|(name, value)| format!("{name}={value}"))
2280                    .collect();
2281                query.sort();
2282                (request.path.as_str(), query.join("&"))
2283            })
2284            .collect();
2285        let thumb_query = "defaulting=false&size=thumb".to_owned();
2286        assert_eq!(
2287            sent,
2288            [
2289                (
2290                    "/libraries/lib%201/series/s%201/image",
2291                    "defaulting=true&size=large&type=background".to_owned()
2292                ),
2293                (
2294                    "/libraries/lib%201/series/s%201/seasons/2/episodes/3/image",
2295                    thumb_query.clone()
2296                ),
2297                (
2298                    "/libraries/lib%201/movies/m%201/image",
2299                    "defaulting=false".to_owned()
2300                ),
2301                ("/libraries/lib%201/books/b%201/image", thumb_query.clone()),
2302                ("/libraries/lib%201/people/p%201/image", thumb_query.clone()),
2303                ("/libraries/lib%201/channels/c%201/image", thumb_query),
2304            ]
2305        );
2306
2307        // The server reads no custom size or type from a query.
2308        let custom = ImageRequestOptions {
2309            size: Some(ImageSize::Custom(300)),
2310            ..Default::default()
2311        };
2312        assert!(api.get_movie_image("m 1", &custom).await.is_err());
2313        let custom = ImageRequestOptions {
2314            kind: Some(ImageType::Custom("fanart".into())),
2315            ..Default::default()
2316        };
2317        assert!(api.get_movie_image("m 1", &custom).await.is_err());
2318        assert_eq!(fake.requests().len(), 6);
2319    }
2320
2321    #[tokio::test]
2322    async fn gives_the_url_of_a_channel_logo() {
2323        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
2324        let api = LibraryApi::new(client(fake.clone()), library(false));
2325        let options = ImageRequestOptions {
2326            size: Some(ImageSize::Thumb),
2327            ..Default::default()
2328        };
2329        // Not an HTTP transport: no URL.
2330        assert!(api.channel_image_url("c 1", &options).await.is_err());
2331
2332        fake.set_base_url("https://host:7080");
2333        let logo = api.channel_image_url("c 1", &options).await.unwrap();
2334        let url = url::Url::parse(&logo.url).unwrap();
2335        assert_eq!(url.path(), "/libraries/lib%201/channels/c%201/image");
2336        let mut query: Vec<(String, String)> = url.query_pairs().into_owned().collect();
2337        query.sort();
2338        assert_eq!(
2339            query,
2340            [
2341                ("defaulting".to_owned(), "false".to_owned()),
2342                ("size".to_owned(), "thumb".to_owned())
2343            ]
2344        );
2345        assert_eq!(logo.authorization(), "Bearer t");
2346        assert!(fake.requests().is_empty());
2347    }
2348
2349    #[tokio::test]
2350    async fn plain_libraries_return_thumbs_as_is() {
2351        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"jpeg".to_vec())));
2352        let api = LibraryApi::new(client(fake), library(false));
2353        let media = Media {
2354            id: "m1".into(),
2355            ..Default::default()
2356        };
2357        assert_eq!(api.get_thumb(&media).await.unwrap(), b"jpeg");
2358    }
2359}