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 futures_util::StreamExt;
9use serde_json::Value;
10
11use std::time::Duration;
12
13use crate::client::{AuthorizedUrl, RedseatClient};
14use crate::crypto::{Iv, Key};
15use crate::encrypted::EncryptedMediaReader;
16use crate::error::{Error, Result};
17use crate::transport::{Body, BoxStream, EventRequest, Request};
18use crate::types::ItemWithRelations;
19use crate::types::book::{Book, BookForUpdate, BookQuery};
20use crate::types::channel::{Channel, ChannelQuery};
21use crate::types::deleted::{DeletedQuery, RsDeleted};
22use crate::types::episode::{Episode, EpisodeQuery};
23use crate::types::external_images::ImageType;
24use crate::types::image::{ImageRequestOptions, ImageSize};
25use crate::types::library::ServerLibraryForRead;
26use crate::types::media::{Media, MediaFileQuery, MediaForUpdate, MediaQuery, RsSort};
27use crate::types::media_progress::RsMediaProgress;
28use crate::types::movie::{Movie, MovieForUpdate, MovieQuery};
29use crate::types::person::{PeopleQuery, Person, PersonForAdd, PersonForUpdate, PersonWithRoles};
30use crate::types::request_processing::RsRequestProcessing;
31use crate::types::serie::{Serie, SerieForUpdate, SerieQuery};
32use crate::types::tag::{Tag, TagForAdd, TagForUpdate, TagQuery};
33use rs_plugin_common_interfaces::lookup::{
34    RsLookupBook, RsLookupMovie, RsLookupPerson, RsLookupPersonFilter, RsLookupSerie,
35    RsLookupSerieFilter, RsLookupTagFilter, SearchResultGroup, SseLookupSearchEvent,
36};
37use rs_plugin_common_interfaces::request::{RsGroupDownload, RsRequest};
38
39/// The results of a search that the server runs through several sources (plugins): one
40/// item per answer of a source, as it arrives. An item is an error for results that
41/// could not be read (the stream goes on) or for a broken connection (the stream
42/// ends). The stream ends when every source answered; drop it to stop the search.
43pub type SearchStream<T> = BoxStream<Result<T>>;
44
45/// Timeout of [`LibraryApi::get_media`]: a whole file can take long to download.
46pub const MEDIA_TIMEOUT: Duration = Duration::from_secs(10 * 60);
47
48/// Timeout of the calls that wait while the server downloads files itself (TS: 2 h).
49pub const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(2 * 60 * 60);
50
51/// A media of a list, with its relations (tags, people, series...).
52pub type MediaItem = ItemWithRelations<Media>;
53
54/// One page of medias.
55#[derive(Debug, Clone)]
56pub struct MediaPage {
57    pub medias: Vec<MediaItem>,
58    /// Put it in `MediaQuery::page_key` for the next page. `None`: no more pages.
59    pub next_page_key: Option<String>,
60}
61
62/// Calls on one library. Cheap to clone; clones share the passphrase.
63#[derive(Debug, Clone)]
64pub struct LibraryApi {
65    client: RedseatClient,
66    library: ServerLibraryForRead,
67    key: Arc<Mutex<Option<Key>>>,
68}
69
70/// The query parameters of a list request: each field of `query` as the server reads
71/// it (its serde name), leaving out unset ones. A list repeats its key.
72pub(crate) fn query_params<T: serde::Serialize>(query: &T) -> Result<Vec<(String, String)>> {
73    let value =
74        serde_json::to_value(query).map_err(|e| Error::transport(format!("invalid query: {e}")))?;
75    let Value::Object(fields) = value else {
76        return Err(Error::transport("invalid query: not an object"));
77    };
78    let mut params = Vec::new();
79    for (name, value) in fields {
80        match value {
81            Value::Null | Value::Object(_) => {}
82            Value::String(text) => params.push((name, text)),
83            Value::Array(items) => {
84                for item in items {
85                    match item {
86                        Value::String(text) => params.push((name.clone(), text)),
87                        Value::Number(_) | Value::Bool(_) => {
88                            params.push((name.clone(), item.to_string()))
89                        }
90                        _ => {}
91                    }
92                }
93            }
94            other => params.push((name, other.to_string())),
95        }
96    }
97    Ok(params)
98}
99
100/// Percent-encodes one path segment.
101pub(crate) fn path_segment(segment: &str) -> String {
102    url::form_urlencoded::byte_serialize(segment.as_bytes())
103        .collect::<String>()
104        .replace('+', "%20")
105}
106
107/// The key of the page after `last` for `sort`: `<sort value>|<id>`, the server's
108/// keyset cursor. `None` for name and rating sorts, which the server cannot page (it
109/// only reads integer cursors), or when `last` lacks the sort value.
110pub fn next_page_key(sort: &RsSort, last: &Media) -> Option<String> {
111    let value = match sort {
112        RsSort::Added => last.added?,
113        RsSort::Created => last.created?,
114        RsSort::Modified => last.modified?,
115        RsSort::Size => i64::try_from(last.size?).ok()?,
116        RsSort::Name | RsSort::Rating => return None,
117    };
118    Some(format!("{value}|{}", last.id))
119}
120
121/// The query parameters of a media file request, as the server reads them
122/// (`unsupportedMime` repeated, `page`, `raw`).
123fn media_file_params(query: &MediaFileQuery) -> Vec<(String, String)> {
124    let mut params: Vec<(String, String)> = query
125        .unsupported_mime
126        .iter()
127        .map(|mime| ("unsupportedMime".to_owned(), mime.clone()))
128        .collect();
129    if let Some(page) = query.page {
130        params.push(("page".to_owned(), page.to_string()));
131    }
132    if query.raw {
133        params.push(("raw".to_owned(), "true".to_owned()));
134    }
135    params
136}
137
138/// The query parameters of an image request, as the server reads them. A `Custom`
139/// size or type is an error: the server cannot read one from a query.
140fn image_params(options: &ImageRequestOptions) -> Result<Vec<(String, String)>> {
141    if matches!(options.size, Some(ImageSize::Custom(_)))
142        || matches!(options.kind, Some(ImageType::Custom(_)))
143    {
144        return Err(Error::transport(
145            "an image request takes no custom size or type",
146        ));
147    }
148    query_params(options)
149}
150
151/// The query parameters of a search: those of `fields` that are set, then `sources`
152/// (source paths or plugin ids) joined in `source` when there are some.
153fn search_params(fields: &[(&str, Option<&str>)], sources: &[String]) -> Vec<(String, String)> {
154    let mut params: Vec<(String, String)> = fields
155        .iter()
156        .filter_map(|(name, value)| Some(((*name).to_owned(), (*value)?.to_owned())))
157        .collect();
158    if !sources.is_empty() {
159        params.push(("source".to_owned(), sources.join(",")));
160    }
161    params
162}
163
164/// The relation filters of a metadata search, as the JSON the server reads in its
165/// `filters` parameter. `None` without filters.
166fn lookup_filters(
167    people: &Option<Vec<RsLookupPersonFilter>>,
168    series: &Option<Vec<RsLookupSerieFilter>>,
169    tags: &Option<Vec<RsLookupTagFilter>>,
170) -> Option<String> {
171    if people.is_none() && series.is_none() && tags.is_none() {
172        return None;
173    }
174    Some(serde_json::json!({ "people": people, "series": series, "tags": tags }).to_string())
175}
176
177/// `request` with `body` as its JSON body.
178fn with_json(request: Request, body: &impl serde::Serialize) -> Result<Request> {
179    let body = serde_json::to_value(body)
180        .map_err(|e| Error::transport(format!("invalid request body: {e}")))?;
181    Ok(request.json(body))
182}
183
184/// A `multipart/form-data` body with `data` as its one file: the form of the server's
185/// image uploads. The server reads the bytes only, not the part's name or type.
186fn multipart_file(data: &[u8]) -> Body {
187    // A boundary that the data does not contain.
188    let mut boundary = String::from("redseat-api-boundary");
189    while data
190        .windows(boundary.len())
191        .any(|window| window == boundary.as_bytes())
192    {
193        boundary.push('x');
194    }
195    let mut body = format!(
196        "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n\
197         Content-Type: application/octet-stream\r\n\r\n"
198    )
199    .into_bytes();
200    body.extend_from_slice(data);
201    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
202    Body::Bytes {
203        content_type: format!("multipart/form-data; boundary={boundary}"),
204        data: body,
205    }
206}
207
208pub(crate) fn decode_iv(iv: &str) -> Result<Iv> {
209    let bytes = base64::engine::general_purpose::STANDARD
210        .decode(iv)
211        .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(iv))
212        .map_err(|e| Error::malformed(format!("media IV: {e}"), None))?;
213    Ok(redseat_crypto::key::iv_from_slice(&bytes)?)
214}
215
216/// The path of `rest` in the library.
217fn library_path(library: &str, rest: &str) -> String {
218    format!("/libraries/{}{rest}", path_segment(library))
219}
220
221/// The path of a media's file.
222fn media_path(library: &str, media_id: &str) -> String {
223    library_path(library, &format!("/medias/{}", path_segment(media_id)))
224}
225
226/// The path of one item of a list (`kind`: `tags`, `people`...), or under it with
227/// `rest` (`/merge`).
228fn item_path(library: &str, kind: &str, id: &str, rest: &str) -> String {
229    library_path(library, &format!("/{kind}/{}{rest}", path_segment(id)))
230}
231
232/// The path of one episode, or under it with `rest` (`/watched`).
233fn episode_path(library: &str, serie_id: &str, season: u32, number: u32, rest: &str) -> String {
234    let rest = format!("/seasons/{season}/episodes/{number}{rest}");
235    item_path(library, "series", serie_id, &rest)
236}
237
238/// Decrypts data of `media` (its thumbnail, or its file sent without `raw`) with `key`
239/// (from the library's passphrase, [`crate::crypto::derive_key`]) and the media's IV.
240pub fn decrypt_media_data(key: &Key, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
241    let iv = media
242        .iv
243        .as_deref()
244        .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
245    Ok(redseat_crypto::decrypt_buffer(key, &decode_iv(iv)?, data)?)
246}
247
248impl LibraryApi {
249    pub fn new(client: RedseatClient, library: ServerLibraryForRead) -> Self {
250        LibraryApi {
251            client,
252            library,
253            key: Arc::new(Mutex::new(None)),
254        }
255    }
256
257    pub fn id(&self) -> &str {
258        &self.library.id
259    }
260
261    pub fn library(&self) -> &ServerLibraryForRead {
262        &self.library
263    }
264
265    /// The client of the library's server.
266    pub fn client(&self) -> &RedseatClient {
267        &self.client
268    }
269
270    /// Whether files are encrypted on the client side (`crypt`).
271    pub fn is_encrypted(&self) -> bool {
272        self.library.crypt == Some(true)
273    }
274
275    /// Whether the passphrase is set.
276    pub fn has_passphrase(&self) -> bool {
277        self.lock_key().is_some()
278    }
279
280    fn path(&self, rest: &str) -> String {
281        library_path(self.id(), rest)
282    }
283
284    /// The path of a media's file.
285    pub(crate) fn media_path(&self, media_id: &str) -> String {
286        media_path(self.id(), media_id)
287    }
288
289    /// The path of one item of a list (`kind`: `tags`, `people`...), or under it with
290    /// `rest` (`/merge`).
291    fn item_path(&self, kind: &str, id: &str, rest: &str) -> String {
292        item_path(self.id(), kind, id, rest)
293    }
294
295    /// The path of one episode, or under it with `rest` (`/watched`).
296    fn episode_path(&self, serie_id: &str, season: u32, number: u32, rest: &str) -> String {
297        episode_path(self.id(), serie_id, season, number, rest)
298    }
299
300    /// The URL of `path` on the server, with `query`. Needs an HTTP transport.
301    async fn url(&self, path: &str, query: &[(String, String)]) -> Result<String> {
302        Ok(self.client.authorized_url(path, query).await?.url)
303    }
304
305    /// Opens the event stream of a search at `path` and reads its `results` events as
306    /// `T`. Other events are left out.
307    async fn search_stream<T: serde::de::DeserializeOwned + Send + 'static>(
308        &self,
309        path: String,
310        query: Vec<(String, String)>,
311    ) -> Result<SearchStream<T>> {
312        let request = EventRequest {
313            path: path.clone(),
314            query,
315            ..Default::default()
316        };
317        let raw = self.client.subscribe_raw(request).await?;
318        Ok(Box::pin(raw.filter_map(move |item| {
319            let item = match item {
320                Ok(event) if event.event == "results" => {
321                    Some(serde_json::from_str(&event.data).map_err(|e| {
322                        Error::malformed(format!("unexpected search results: {e}"), Some(&path))
323                    }))
324                }
325                Ok(_) => None,
326                Err(error) => Some(Err(error)),
327            };
328            std::future::ready(item)
329        })))
330    }
331
332    /// Sets the key of the passphrase, already checked.
333    #[cfg(any(test, feature = "mirror"))]
334    pub(crate) fn set_key(&self, key: Key) {
335        *self.lock_key() = Some(key);
336    }
337
338    fn lock_key(&self) -> std::sync::MutexGuard<'_, Option<Key>> {
339        self.key.lock().unwrap_or_else(PoisonError::into_inner)
340    }
341
342    /// Medias matching `query`. Timestamps are Unix milliseconds.
343    pub async fn get_medias(&self, query: &MediaQuery) -> Result<Vec<MediaItem>> {
344        self.client.run(calls::get_medias(self.id(), query)?).await
345    }
346
347    /// A page of medias. Set `query.limit` to the page size, then pass
348    /// `next_page_key` back in `query.page_key` for the next page.
349    pub async fn get_medias_page(&self, query: &MediaQuery) -> Result<MediaPage> {
350        self.client
351            .run(calls::get_medias_page(self.id(), query)?)
352            .await
353    }
354
355    /// The thumbnail as the server stores it: encrypted in an encrypted library.
356    pub async fn get_thumb_raw(&self, media_id: &str) -> Result<Vec<u8>> {
357        self.client
358            .run(calls::get_thumb_raw(self.id(), media_id))
359            .await
360    }
361
362    /// The thumbnail of `media`, decrypted in an encrypted library (set the passphrase
363    /// first).
364    pub async fn get_thumb(&self, media: &Media) -> Result<Vec<u8>> {
365        if self.is_encrypted() && !self.has_passphrase() {
366            return Err(Error::PassphraseRequired);
367        }
368        let data = self.get_thumb_raw(&media.id).await?;
369        self.decrypt_thumb(media, &data)
370    }
371
372    /// Decrypts a thumbnail of `media` fetched with [`Self::get_thumb_raw`] (or its
373    /// file, fetched without `raw`: both are encrypted with the media's IV). Returns it
374    /// unchanged when the library is not encrypted.
375    pub fn decrypt_thumb(&self, media: &Media, data: &[u8]) -> Result<Vec<u8>> {
376        if !self.is_encrypted() {
377            return Ok(data.to_vec());
378        }
379        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
380        decrypt_media_data(&key, media, data)
381    }
382
383    /// The file of a media, whole: decrypted in an encrypted library (set the
384    /// passphrase first). With `query.unsupported_mime`, the server converts photos
385    /// of those types (or of any type a browser cannot show, with `"all"`) to WebP;
386    /// it cannot in an encrypted library.
387    pub async fn get_media(&self, media: &Media, query: &MediaFileQuery) -> Result<Vec<u8>> {
388        let decrypt = self.is_encrypted() && !query.raw;
389        if decrypt && !self.has_passphrase() {
390            return Err(Error::PassphraseRequired);
391        }
392        let call = calls::get_media_file(self.id(), &media.id, query);
393        let data = self.client.run(call).await?;
394        if decrypt {
395            self.decrypt_thumb(media, &data)
396        } else {
397            Ok(data)
398        }
399    }
400
401    /// The URL of a media file and a token to open it, for a player that streams it
402    /// itself with HTTP range requests. The bytes are the stored ones: in an encrypted
403    /// library they are encrypted, and the server does not answer range requests, so
404    /// use [`Self::get_media`] there.
405    pub async fn media_url(&self, media_id: &str, query: &MediaFileQuery) -> Result<AuthorizedUrl> {
406        let path = self.media_path(media_id);
407        self.client
408            .authorized_url(&path, &media_file_params(query))
409            .await
410    }
411
412    /// Opens a media of an encrypted library for reading by ranges, decrypted: for a
413    /// player that streams and seeks (see [`EncryptedMediaReader`]). Set the
414    /// passphrase first. Needs a server that answers range requests on encrypted
415    /// files; an older one gives an error saying it needs an update.
416    pub async fn open_encrypted_media(&self, media: &Media) -> Result<EncryptedMediaReader> {
417        if !self.is_encrypted() {
418            return Err(Error::transport(
419                "this library is not encrypted: stream its files with media_url",
420            ));
421        }
422        let key = (*self.lock_key()).ok_or(Error::PassphraseRequired)?;
423        let iv = media
424            .iv
425            .as_deref()
426            .ok_or_else(|| Error::malformed("encrypted media without IV", None))?;
427        EncryptedMediaReader::open(
428            self.clone(),
429            media.id.clone(),
430            key,
431            decode_iv(iv)?,
432            media.size,
433        )
434        .await
435    }
436
437    /// One media with its relations, its faces and its backups. `None` when the
438    /// library has no media with this id.
439    pub async fn get_media_metadata(&self, media_id: &str) -> Result<Option<MediaItem>> {
440        self.client
441            .run(calls::get_media_metadata(self.id(), media_id))
442            .await
443    }
444
445    /// The media whose file has this hash: the one the server keeps in `Media::md5`, or
446    /// the hash of the original file when the server converted it. `None` when the
447    /// library has none.
448    pub async fn get_media_by_hash(&self, hash: &str) -> Result<Option<MediaItem>> {
449        self.client
450            .run(calls::get_media_by_hash(self.id(), hash))
451            .await
452    }
453
454    /// Changes a media and returns it. Only the set fields change; `add_tags`,
455    /// `remove_tags`, `add_people`, `add_series`... change its relations.
456    pub async fn update_media(&self, media_id: &str, update: &MediaForUpdate) -> Result<Media> {
457        self.client
458            .run(calls::update_media(self.id(), media_id, update)?)
459            .await
460    }
461
462    /// Saves how far the user is in a media (a position in a video, a page of a
463    /// book...). The server stores `progress` as given.
464    pub async fn set_media_progress(
465        &self,
466        media_id: &str,
467        progress: u64,
468    ) -> Result<RsMediaProgress> {
469        self.client
470            .run(calls::set_media_progress(self.id(), media_id, progress))
471            .await
472    }
473
474    /// Removes medias, with their files. Returns those removed: an id the library does
475    /// not have is skipped.
476    pub async fn remove_medias(&self, media_ids: &[String]) -> Result<Vec<Media>> {
477        self.client
478            .run(calls::remove_medias(self.id(), media_ids))
479            .await
480    }
481
482    /// A URL of a media file that anyone can open for 6 hours, without the user's
483    /// token: for a download manager, another app or a cast device. Needs an HTTP
484    /// transport.
485    pub async fn media_share_url(&self, media_id: &str) -> Result<String> {
486        let path = self.media_path(media_id);
487        let token = calls::share_token(Request::get(format!("{path}/sharetoken")));
488        let token = self.client.run(token).await?;
489        self.url(&path, &[("sharetoken".to_owned(), token)]).await
490    }
491
492    /// Adds medias from URLs: the server downloads the requests of `download` (as one
493    /// media with `group`) and returns the medias created. It can take long: see
494    /// [`Self::download_medias_in_background`]. When a request holds several files and
495    /// none is selected, the server asks for a selection and this is an error.
496    pub async fn download_medias(&self, download: &RsGroupDownload) -> Result<Vec<Media>> {
497        self.client
498            .run(calls::download_medias(self.id(), download)?)
499            .await
500    }
501
502    /// Like [`Self::download_medias`], without waiting: the server downloads in the
503    /// background, and the medias come with the `medias` events.
504    pub async fn download_medias_in_background(&self, download: &RsGroupDownload) -> Result<()> {
505        self.client
506            .run(calls::download_medias_in_background(self.id(), download)?)
507            .await
508    }
509
510    /// The number of medias matching `query` (its `limit` and `page_key` are ignored).
511    pub async fn count_medias(&self, query: &MediaQuery) -> Result<u64> {
512        self.client
513            .run(calls::count_medias(self.id(), query)?)
514            .await
515    }
516
517    /// The tags of the library matching `query`. With `after`, only those modified
518    /// strictly after it (Unix milliseconds); page with `limit` and `offset`.
519    pub async fn get_tags(&self, query: &TagQuery) -> Result<Vec<Tag>> {
520        self.client.run(calls::get_tags(self.id(), query)?).await
521    }
522
523    /// Adds a tag to the library and returns it as created. The server chooses its
524    /// `id`; `parent` puts it under another tag.
525    pub async fn create_tag(&self, tag: &TagForAdd) -> Result<Tag> {
526        self.client.run(calls::create_tag(self.id(), tag)?).await
527    }
528
529    /// Changes a tag and returns it. Only the set fields change: `name` renames it,
530    /// `parent` moves it under another tag (an empty id moves it to the root), and
531    /// `add_alts`, `remove_alts`, `add_otherids` and `remove_otherids` change its
532    /// alternative names and external ids. Needs the admin role on the library.
533    pub async fn update_tag(&self, tag_id: &str, update: &TagForUpdate) -> Result<Tag> {
534        self.client
535            .run(calls::update_tag(self.id(), tag_id, update)?)
536            .await
537    }
538
539    /// Merges the tag `tag_id` into the tag `into` and removes it. Returns the tag
540    /// kept.
541    pub async fn merge_tag(&self, tag_id: &str, into: &str) -> Result<Tag> {
542        self.client
543            .run(calls::merge_tag(self.id(), tag_id, into))
544            .await
545    }
546
547    /// Removes a tag and returns it as it was.
548    pub async fn remove_tag(&self, tag_id: &str) -> Result<Tag> {
549        self.client.run(calls::remove_tag(self.id(), tag_id)).await
550    }
551
552    /// The people of the library matching `query`, like [`Self::get_tags`].
553    pub async fn get_people(&self, query: &PeopleQuery) -> Result<Vec<Person>> {
554        self.client.run(calls::get_people(self.id(), query)?).await
555    }
556
557    /// One person, `None` when the library has no person with this id.
558    pub async fn get_person(&self, person_id: &str) -> Result<Option<Person>> {
559        self.client
560            .run(calls::get_person(self.id(), person_id))
561            .await
562    }
563
564    /// Adds a person to the library and returns them as created. The server chooses
565    /// their `id`.
566    pub async fn create_person(&self, person: &PersonForAdd) -> Result<Person> {
567        self.client
568            .run(calls::create_person(self.id(), person)?)
569            .await
570    }
571
572    /// Changes a person and returns them. Only the set fields change; `add_alts`,
573    /// `remove_alts`, `add_socials`, `add_otherids`... change their alternative names,
574    /// links and external ids.
575    pub async fn update_person(&self, person_id: &str, update: &PersonForUpdate) -> Result<Person> {
576        self.client
577            .run(calls::update_person(self.id(), person_id, update)?)
578            .await
579    }
580
581    /// The portrait of a person, as the bytes of an image file. The server has no
582    /// other image for a person: it does not read `defaulting`.
583    pub async fn get_person_image(
584        &self,
585        person_id: &str,
586        options: &ImageRequestOptions,
587    ) -> Result<Vec<u8>> {
588        self.client
589            .run(calls::get_person_image(self.id(), person_id, options)?)
590            .await
591    }
592
593    /// Removes a person and returns them as they were. Needs the admin role on the
594    /// library.
595    pub async fn remove_person(&self, person_id: &str) -> Result<Person> {
596        self.client
597            .run(calls::remove_person(self.id(), person_id))
598            .await
599    }
600
601    /// Merges the person `source` into the person `target`, who gets their faces;
602    /// `source` is then removed. Returns the number of faces moved. Needs the admin
603    /// role on the library.
604    pub async fn merge_people(&self, source: &str, target: &str) -> Result<u64> {
605        self.client
606            .run(calls::merge_people(self.id(), source, target))
607            .await
608    }
609
610    /// The people of a movie (cast and crew), with their roles in it.
611    pub async fn get_movie_people(&self, movie_id: &str) -> Result<Vec<PersonWithRoles>> {
612        self.client
613            .run(calls::get_movie_people(self.id(), movie_id))
614            .await
615    }
616
617    /// The people of a series (cast and crew), with their roles in it.
618    pub async fn get_serie_people(&self, serie_id: &str) -> Result<Vec<PersonWithRoles>> {
619        self.client
620            .run(calls::get_serie_people(self.id(), serie_id))
621            .await
622    }
623
624    /// The people of a book (authors...), with their roles in it.
625    pub async fn get_book_people(&self, book_id: &str) -> Result<Vec<PersonWithRoles>> {
626        self.client
627            .run(calls::get_book_people(self.id(), book_id))
628            .await
629    }
630
631    /// The series of the library matching `query`, with their relations, like
632    /// [`Self::get_tags`].
633    pub async fn get_series(&self, query: &SerieQuery) -> Result<Vec<ItemWithRelations<Serie>>> {
634        self.client.run(calls::get_series(self.id(), query)?).await
635    }
636
637    /// Adds a series to the library, with its relations (tags, people), and returns it
638    /// as created. The server chooses its `id`, and refuses a series whose external
639    /// ids (imdb, tmdb...) the library already has.
640    pub async fn create_serie(
641        &self,
642        serie: &ItemWithRelations<Serie>,
643    ) -> Result<ItemWithRelations<Serie>> {
644        self.client
645            .run(calls::create_serie(self.id(), serie)?)
646            .await
647    }
648
649    /// Changes a series and returns it, with its relations. Only the set fields
650    /// change. Needs the admin role on the library.
651    pub async fn update_serie(
652        &self,
653        serie_id: &str,
654        update: &SerieForUpdate,
655    ) -> Result<ItemWithRelations<Serie>> {
656        self.client
657            .run(calls::update_serie(self.id(), serie_id, update)?)
658            .await
659    }
660
661    /// An image of a series, as the bytes of an image file: its poster, or the
662    /// `options.kind` asked. With `defaulting`, the background stands in for a missing
663    /// card.
664    pub async fn get_serie_image(
665        &self,
666        serie_id: &str,
667        options: &ImageRequestOptions,
668    ) -> Result<Vec<u8>> {
669        self.client
670            .run(calls::get_serie_image(self.id(), serie_id, options)?)
671            .await
672    }
673
674    /// The still of an episode, as the bytes of an image file. The server does not
675    /// read `options.kind`. With `defaulting`, the card of the series, or else its
676    /// background, stands in for a missing still.
677    pub async fn get_episode_image(
678        &self,
679        serie_id: &str,
680        season: u32,
681        number: u32,
682        options: &ImageRequestOptions,
683    ) -> Result<Vec<u8>> {
684        let call = calls::get_episode_image(self.id(), serie_id, season, number, options)?;
685        self.client.run(call).await
686    }
687
688    /// Removes a series and returns it as it was. With `delete_medias`, its medias are
689    /// removed too, with their files (a virtual file's source stays).
690    pub async fn remove_serie(&self, serie_id: &str, delete_medias: bool) -> Result<Serie> {
691        self.client
692            .run(calls::remove_serie(self.id(), serie_id, delete_medias))
693            .await
694    }
695
696    /// Marks an episode watched by the user at `date` (Unix milliseconds), or not
697    /// watched with a `date` of 0.
698    pub async fn set_episode_watched(
699        &self,
700        serie_id: &str,
701        season: u32,
702        number: u32,
703        date: i64,
704    ) -> Result<()> {
705        let call = calls::set_episode_watched(self.id(), serie_id, season, number, date)?;
706        self.client.run(call).await
707    }
708
709    /// Saves how far the user is in an episode. The server stores `progress` as given.
710    pub async fn set_episode_progress(
711        &self,
712        serie_id: &str,
713        season: u32,
714        number: u32,
715        progress: u64,
716    ) -> Result<()> {
717        let call = calls::set_episode_progress(self.id(), serie_id, season, number, progress)?;
718        self.client.run(call).await
719    }
720
721    /// Adds a file found by a source search to an episode: the server downloads
722    /// `request` and returns the media created.
723    pub async fn add_searched_episode_media(
724        &self,
725        serie_id: &str,
726        season: u32,
727        number: u32,
728        request: &RsRequest,
729    ) -> Result<Media> {
730        let call = calls::add_searched_episode_media(self.id(), serie_id, season, number, request)?;
731        self.client.run(call).await
732    }
733
734    /// The movies of the library matching `query`, with their relations, like
735    /// [`Self::get_tags`].
736    pub async fn get_movies(&self, query: &MovieQuery) -> Result<Vec<ItemWithRelations<Movie>>> {
737        self.client.run(calls::get_movies(self.id(), query)?).await
738    }
739
740    /// Adds a movie to the library, with its relations (tags, people), and returns it
741    /// as created. The server chooses its `id`, and refuses a movie whose external
742    /// ids (imdb, tmdb...) the library already has.
743    pub async fn create_movie(
744        &self,
745        movie: &ItemWithRelations<Movie>,
746    ) -> Result<ItemWithRelations<Movie>> {
747        self.client
748            .run(calls::create_movie(self.id(), movie)?)
749            .await
750    }
751
752    /// Changes a movie and returns it, with its relations. Only the set fields change.
753    pub async fn update_movie(
754        &self,
755        movie_id: &str,
756        update: &MovieForUpdate,
757    ) -> Result<ItemWithRelations<Movie>> {
758        self.client
759            .run(calls::update_movie(self.id(), movie_id, update)?)
760            .await
761    }
762
763    /// An image of a movie, as the bytes of an image file: its poster, or the
764    /// `options.kind` asked. With `defaulting`, the background stands in for a missing
765    /// card.
766    pub async fn get_movie_image(
767        &self,
768        movie_id: &str,
769        options: &ImageRequestOptions,
770    ) -> Result<Vec<u8>> {
771        self.client
772            .run(calls::get_movie_image(self.id(), movie_id, options)?)
773            .await
774    }
775
776    /// Removes a movie and returns it as it was. With `delete_medias`, its medias are
777    /// removed too, with their files (a virtual file's source stays).
778    pub async fn remove_movie(&self, movie_id: &str, delete_medias: bool) -> Result<Movie> {
779        self.client
780            .run(calls::remove_movie(self.id(), movie_id, delete_medias))
781            .await
782    }
783
784    /// Marks a movie watched by the user at `date` (Unix milliseconds), or not watched
785    /// with a `date` of 0.
786    pub async fn set_movie_watched(&self, movie_id: &str, date: i64) -> Result<()> {
787        self.client
788            .run(calls::set_movie_watched(self.id(), movie_id, date)?)
789            .await
790    }
791
792    /// Saves how far the user is in a movie. The server stores `progress` as given.
793    pub async fn set_movie_progress(&self, movie_id: &str, progress: u64) -> Result<()> {
794        self.client
795            .run(calls::set_movie_progress(self.id(), movie_id, progress)?)
796            .await
797    }
798
799    /// Adds a file found by a source search to a movie: the server downloads
800    /// `request` and returns the media created.
801    pub async fn add_searched_movie_media(
802        &self,
803        movie_id: &str,
804        request: &RsRequest,
805    ) -> Result<Media> {
806        self.client
807            .run(calls::add_searched_movie_media(
808                self.id(),
809                movie_id,
810                request,
811            )?)
812            .await
813    }
814
815    /// The episodes of the library matching `query` (of all series without
816    /// `serie_ref`), like [`Self::get_tags`]. An episode's id is
817    /// [`Episode::id`]: series, season and number.
818    pub async fn get_episodes(&self, query: &EpisodeQuery) -> Result<Vec<Episode>> {
819        self.client
820            .run(calls::get_episodes(self.id(), query)?)
821            .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.client.run(calls::get_books(self.id(), query)?).await
828    }
829
830    /// One book, with its relations.
831    pub async fn get_book(&self, book_id: &str) -> Result<ItemWithRelations<Book>> {
832        self.client.run(calls::get_book(self.id(), book_id)).await
833    }
834
835    /// Adds a book to the library, with its relations, and returns it as created. The
836    /// server chooses its `id`. With `upsert_tags`, `upsert_people` or `upsert_serie`,
837    /// the tags, people or series its relations give in full (`tags_details`,
838    /// `people_details`, `series_details`) are created when the library lacks them.
839    pub async fn create_book(
840        &self,
841        book: &ItemWithRelations<Book>,
842        upsert_tags: bool,
843        upsert_people: bool,
844        upsert_serie: bool,
845    ) -> Result<ItemWithRelations<Book>> {
846        let call = calls::create_book(self.id(), book, upsert_tags, upsert_people, upsert_serie)?;
847        self.client.run(call).await
848    }
849
850    /// Changes a book and returns it, with its relations. Only the set fields change.
851    pub async fn update_book(
852        &self,
853        book_id: &str,
854        update: &BookForUpdate,
855    ) -> Result<ItemWithRelations<Book>> {
856        self.client
857            .run(calls::update_book(self.id(), book_id, update)?)
858            .await
859    }
860
861    /// An image of a book, as the bytes of an image file: its poster, or the
862    /// `options.kind` asked. With `defaulting`, the poster stands in for a missing
863    /// image of another type.
864    pub async fn get_book_image(
865        &self,
866        book_id: &str,
867        options: &ImageRequestOptions,
868    ) -> Result<Vec<u8>> {
869        self.client
870            .run(calls::get_book_image(self.id(), book_id, options)?)
871            .await
872    }
873
874    /// Removes a book and returns it as it was. With `delete_medias`, its medias are
875    /// removed too, with their files (a virtual file's source stays).
876    pub async fn remove_book(&self, book_id: &str, delete_medias: bool) -> Result<Book> {
877        self.client
878            .run(calls::remove_book(self.id(), book_id, delete_medias))
879            .await
880    }
881
882    /// Marks a book read by the user at `date` (Unix milliseconds), or not read with a
883    /// `date` of 0.
884    pub async fn set_book_watched(&self, book_id: &str, date: i64) -> Result<()> {
885        self.client
886            .run(calls::set_book_watched(self.id(), book_id, date)?)
887            .await
888    }
889
890    /// Sets the poster of a book to `image`, the bytes of an image file (JPEG, PNG,
891    /// WebP...): the server converts it.
892    pub async fn update_book_poster(&self, book_id: &str, image: &[u8]) -> Result<()> {
893        self.client
894            .run(calls::update_book_poster(self.id(), book_id, image))
895            .await
896    }
897
898    /// The channels of the library matching `query`, with their tags and their
899    /// variants (one per quality). Page with `limit` and `offset`.
900    pub async fn get_channels(&self, query: &ChannelQuery) -> Result<Vec<Channel>> {
901        self.client
902            .run(calls::get_channels(self.id(), query)?)
903            .await
904    }
905
906    /// The logo of a channel, as the bytes of an image file. The server has no other
907    /// image for a channel: it does not read `defaulting`.
908    pub async fn get_channel_image(
909        &self,
910        channel_id: &str,
911        options: &ImageRequestOptions,
912    ) -> Result<Vec<u8>> {
913        self.client
914            .run(calls::get_channel_image(self.id(), channel_id, options)?)
915            .await
916    }
917
918    /// The URL of a channel's logo and a token to open it, for an image view that
919    /// fetches it itself. Needs an HTTP transport.
920    pub async fn channel_image_url(
921        &self,
922        channel_id: &str,
923        options: &ImageRequestOptions,
924    ) -> Result<AuthorizedUrl> {
925        let path = self.item_path("channels", channel_id, "/image");
926        self.client
927            .authorized_url(&path, &image_params(options)?)
928            .await
929    }
930
931    /// Adds a tag to a channel.
932    pub async fn add_tag_to_channel(&self, channel_id: &str, tag_id: &str) -> Result<()> {
933        self.client
934            .run(calls::add_tag_to_channel(self.id(), channel_id, tag_id))
935            .await
936    }
937
938    /// Removes a tag from a channel.
939    pub async fn remove_tag_from_channel(&self, channel_id: &str, tag_id: &str) -> Result<()> {
940        self.client
941            .run(calls::remove_tag_from_channel(
942                self.id(),
943                channel_id,
944                tag_id,
945            ))
946            .await
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        self.client
990            .run(calls::stop_channel_hls(self.id(), channel_id))
991            .await
992    }
993
994    /// Searches the library's metadata sources (plugins) for movies: by `lookup.name`,
995    /// narrowed by its `people`, `series` and `tags`. Each item is what one source
996    /// found. `sources` keeps only these sources (source paths or plugin ids; empty:
997    /// all). For more results of a source, send its `next_page_key` back in
998    /// `lookup.page_key`, with that source alone in `sources`. The server reads no
999    /// `lookup.ids` here.
1000    pub async fn search_movies_stream(
1001        &self,
1002        lookup: &RsLookupMovie,
1003        sources: &[String],
1004    ) -> Result<SearchStream<SearchResultGroup>> {
1005        let filters = lookup_filters(&lookup.people, &lookup.series, &lookup.tags);
1006        let fields = [
1007            ("name", lookup.name.as_deref()),
1008            ("pageKey", lookup.page_key.as_deref()),
1009            ("filters", filters.as_deref()),
1010        ];
1011        let query = search_params(&fields, sources);
1012        self.search_stream(self.path("/movies/searchstream"), query)
1013            .await
1014    }
1015
1016    /// Searches the library's metadata sources for series, like
1017    /// [`Self::search_movies_stream`].
1018    pub async fn search_series_stream(
1019        &self,
1020        lookup: &RsLookupSerie,
1021        sources: &[String],
1022    ) -> Result<SearchStream<SearchResultGroup>> {
1023        let filters = lookup_filters(&lookup.people, &lookup.series, &lookup.tags);
1024        let fields = [
1025            ("name", lookup.name.as_deref()),
1026            ("pageKey", lookup.page_key.as_deref()),
1027            ("filters", filters.as_deref()),
1028        ];
1029        let query = search_params(&fields, sources);
1030        self.search_stream(self.path("/series/searchstream"), query)
1031            .await
1032    }
1033
1034    /// Searches the library's metadata sources for books, like
1035    /// [`Self::search_movies_stream`], also by `lookup.author` and by the ISBN-13 of
1036    /// `lookup.ids` (the only id the server reads here). The server refuses a search
1037    /// with none of a name, an author, an ISBN or a filter.
1038    pub async fn search_books_stream(
1039        &self,
1040        lookup: &RsLookupBook,
1041        sources: &[String],
1042    ) -> Result<SearchStream<SearchResultGroup>> {
1043        let filters = lookup_filters(&lookup.people, &lookup.series, &lookup.tags);
1044        let fields = [
1045            ("name", lookup.name.as_deref()),
1046            ("author", lookup.author.as_deref()),
1047            ("isbn13", lookup.ids.as_ref().and_then(|ids| ids.isbn13())),
1048            ("pageKey", lookup.page_key.as_deref()),
1049            ("filters", filters.as_deref()),
1050        ];
1051        let query = search_params(&fields, sources);
1052        self.search_stream(self.path("/books/searchstream"), query)
1053            .await
1054    }
1055
1056    /// Searches the library's metadata sources for people by `lookup.name`, like
1057    /// [`Self::search_movies_stream`], without filters.
1058    pub async fn search_people_stream(
1059        &self,
1060        lookup: &RsLookupPerson,
1061        sources: &[String],
1062    ) -> Result<SearchStream<SearchResultGroup>> {
1063        let fields = [
1064            ("name", lookup.name.as_deref()),
1065            ("pageKey", lookup.page_key.as_deref()),
1066        ];
1067        let query = search_params(&fields, sources);
1068        self.search_stream(self.path("/people/searchstream"), query)
1069            .await
1070    }
1071
1072    /// Searches the library's sources (plugins) for files of a movie. Each item is
1073    /// what one source found: its `downloads`, and their requests one by one in
1074    /// `results`. Add one to the library with [`Self::add_searched_movie_media`].
1075    /// `name` replaces the movie's name in the search. `sources` keeps only these
1076    /// sources (source paths or plugin ids; empty: all). For more results of a
1077    /// source, send its `next_page_key` back in `page_key`, with that source alone
1078    /// in `sources`: the server refuses a page key otherwise.
1079    pub async fn search_movie_medias_stream(
1080        &self,
1081        movie_id: &str,
1082        name: Option<&str>,
1083        sources: &[String],
1084        page_key: Option<&str>,
1085    ) -> Result<SearchStream<SseLookupSearchEvent>> {
1086        let query = search_params(&[("name", name), ("pageKey", page_key)], sources);
1087        self.search_stream(self.item_path("movies", movie_id, "/searchstream"), query)
1088            .await
1089    }
1090
1091    /// Searches the library's sources for files of an episode, like
1092    /// [`Self::search_movie_medias_stream`]; `name` replaces the name of the series.
1093    /// Add one with [`Self::add_searched_episode_media`].
1094    pub async fn search_episode_medias_stream(
1095        &self,
1096        serie_id: &str,
1097        season: u32,
1098        number: u32,
1099        name: Option<&str>,
1100        sources: &[String],
1101        page_key: Option<&str>,
1102    ) -> Result<SearchStream<SseLookupSearchEvent>> {
1103        let query = search_params(&[("name", name), ("pageKey", page_key)], sources);
1104        let path = self.episode_path(serie_id, season, number, "/searchstream");
1105        self.search_stream(path, query).await
1106    }
1107
1108    /// Searches the library's sources for files of a book, like
1109    /// [`Self::search_movie_medias_stream`]. Add one with [`Self::download_medias`].
1110    pub async fn search_book_medias_stream(
1111        &self,
1112        book_id: &str,
1113        name: Option<&str>,
1114        sources: &[String],
1115        page_key: Option<&str>,
1116    ) -> Result<SearchStream<SseLookupSearchEvent>> {
1117        let query = search_params(&[("name", name), ("pageKey", page_key)], sources);
1118        self.search_stream(self.item_path("books", book_id, "/searchstream"), query)
1119            .await
1120    }
1121
1122    /// Runs a request through the library's plugins and returns it processed: a link
1123    /// turned into a direct one, a status that says what to do next
1124    /// ([`RsRequest::status`])...
1125    pub async fn process_request(&self, request: &RsRequest) -> Result<RsRequest> {
1126        self.client
1127            .run(calls::process_request(self.id(), request)?)
1128            .await
1129    }
1130
1131    /// Runs a request through the library's plugins and returns what it gives, whole:
1132    /// an image behind a protected link, for example.
1133    pub async fn process_request_bytes(&self, request: &RsRequest) -> Result<Vec<u8>> {
1134        self.client
1135            .run(calls::process_request_bytes(self.id(), request)?)
1136            .await
1137    }
1138
1139    /// Asks the library's plugins for a link to `request` that does not expire, to
1140    /// keep it. Returns the request with that link and `permanent` set.
1141    pub async fn check_request_permanent(&self, request: &RsRequest) -> Result<RsRequest> {
1142        self.client
1143            .run(calls::check_request_permanent(self.id(), request)?)
1144            .await
1145    }
1146
1147    /// Hands a request to a plugin that prepares it in the background (a debrid
1148    /// service fetching a torrent, for example). Returns the task; its progress comes
1149    /// with the `request_processing` events. `media_ref` ties it to a media.
1150    pub async fn add_request(
1151        &self,
1152        request: &RsRequest,
1153        media_ref: Option<&str>,
1154    ) -> Result<RsRequestProcessing> {
1155        self.client
1156            .run(calls::add_request(self.id(), request, media_ref))
1157            .await
1158    }
1159
1160    /// A URL that streams what the request URL `url` gives, through the server and
1161    /// its plugins, that anyone can open for 6 hours without the user's token: for a
1162    /// player. Needs an HTTP transport.
1163    pub async fn request_share_url(&self, url: &str) -> Result<String> {
1164        let token = Request::get(self.path("/plugins/requests/url/sharetoken")).query("url", url);
1165        let token = self.client.run(calls::share_token(token)).await?;
1166        let query = [
1167            ("sharetoken".to_owned(), token),
1168            ("url".to_owned(), url.to_owned()),
1169        ];
1170        self.url(&self.path("/plugins/requests/url/stream"), &query)
1171            .await
1172    }
1173
1174    /// What was deleted from the library: with `after`, strictly after it (Unix
1175    /// milliseconds). Page with `limit` and `offset`.
1176    pub async fn get_deleted(&self, query: &DeletedQuery) -> Result<Vec<RsDeleted>> {
1177        self.client.run(calls::get_deleted(self.id(), query)?).await
1178    }
1179
1180    /// Sets the passphrase of an encrypted library. It is checked on the thumbnail of
1181    /// one media when there is one: a wrong passphrase gives
1182    /// [`Error::InvalidPassphrase`], and a failure to fetch that thumbnail its own error.
1183    pub async fn set_passphrase(&self, passphrase: &str) -> Result<()> {
1184        let key = redseat_crypto::derive_key(passphrase);
1185        if self.is_encrypted() {
1186            let query = MediaQuery {
1187                limit: Some(1),
1188                ..Default::default()
1189            };
1190            let medias = self.get_medias(&query).await?;
1191            let sample = medias
1192                .first()
1193                .map(|m| &m.item)
1194                .filter(|media| media.thumbsize.unwrap_or(0) > 0 && media.iv.is_some());
1195            if let Some(media) = sample {
1196                let data = self.get_thumb_raw(&media.id).await?;
1197                let iv = decode_iv(media.iv.as_deref().unwrap_or_default())?;
1198                redseat_crypto::decrypt_buffer(&key, &iv, &data)
1199                    .map_err(|_| Error::InvalidPassphrase)?;
1200            }
1201        }
1202        *self.lock_key() = Some(key);
1203        Ok(())
1204    }
1205
1206    /// Forgets the passphrase.
1207    pub fn clear_passphrase(&self) {
1208        *self.lock_key() = None;
1209    }
1210}
1211
1212/// The calls of [`LibraryApi`] as [`Call`](crate::Call)s, for a host that sends
1213/// requests itself (see [`crate::call`]). Each takes the library id first and is the
1214/// request of the [`LibraryApi`] method of the same name; their requests carry no token.
1215///
1216/// Files come as the server sends them: in an encrypted library, decrypt a thumbnail
1217/// ([`calls::get_thumb_raw`]) or a file ([`calls::get_media_file`] without `raw`) with
1218/// [`decrypt_media_data`] and the key of the passphrase
1219/// ([`crate::crypto::derive_key`]).
1220pub mod calls {
1221    use serde_json::Value;
1222
1223    use super::{
1224        DOWNLOAD_TIMEOUT, MEDIA_TIMEOUT, MediaItem, MediaPage, episode_path, image_params,
1225        item_path, library_path, media_file_params, media_path, multipart_file, next_page_key,
1226        path_segment, query_params, with_json,
1227    };
1228    use crate::call::Call;
1229    use crate::error::{Error, Result};
1230    use crate::transport::Request;
1231    use crate::types::ItemWithRelations;
1232    use crate::types::book::{Book, BookForUpdate, BookQuery};
1233    use crate::types::channel::{Channel, ChannelQuery};
1234    use crate::types::deleted::{DeletedQuery, RsDeleted};
1235    use crate::types::episode::{Episode, EpisodeQuery};
1236    use crate::types::image::ImageRequestOptions;
1237    use crate::types::media::{Media, MediaFileQuery, MediaForUpdate, MediaQuery};
1238    use crate::types::media_progress::RsMediaProgress;
1239    use crate::types::movie::{Movie, MovieForUpdate, MovieQuery};
1240    use crate::types::person::{
1241        PeopleQuery, Person, PersonForAdd, PersonForUpdate, PersonWithRoles,
1242    };
1243    use crate::types::request_processing::RsRequestProcessing;
1244    use crate::types::serie::{Serie, SerieForUpdate, SerieQuery};
1245    use crate::types::tag::{Tag, TagForAdd, TagForUpdate, TagQuery};
1246    use crate::types::view_progress::ViewProgressLigh;
1247    use crate::types::watched::WatchedLight;
1248    use rs_plugin_common_interfaces::request::{RsGroupDownload, RsRequest};
1249
1250    /// `GET <path>` of the library with the fields of `query` as parameters, read as
1251    /// JSON.
1252    fn list<T: serde::de::DeserializeOwned + 'static>(
1253        library: &str,
1254        path: &str,
1255        query: &impl serde::Serialize,
1256    ) -> Result<Call<T>> {
1257        let mut request = Request::get(library_path(library, path));
1258        request.query = query_params(query)?;
1259        Ok(Call::json(request))
1260    }
1261
1262    /// `GET path` of medias with `query` as JSON in `filter`.
1263    fn media_filter(library: &str, path: &str, query: &MediaQuery) -> Result<Request> {
1264        let filter = serde_json::to_string(query)
1265            .map_err(|e| Error::transport(format!("invalid media query: {e}")))?;
1266        Ok(Request::get(library_path(library, path)).query("filter", filter))
1267    }
1268
1269    /// `POST path` with `date` as a watched date. The server answers with no body.
1270    fn post_watched(path: String, date: i64) -> Result<Call<()>> {
1271        Ok(Call::empty(with_json(
1272            Request::post(path),
1273            &WatchedLight { date },
1274        )?))
1275    }
1276
1277    /// `POST path` with `progress` as a view progress. The server answers with no body.
1278    fn post_progress(path: String, progress: u64) -> Result<Call<()>> {
1279        Ok(Call::empty(with_json(
1280            Request::post(path),
1281            &ViewProgressLigh { progress },
1282        )?))
1283    }
1284
1285    /// `POST path` with a request found by a source search: the server downloads it
1286    /// and answers with the media created.
1287    fn post_searched_media(path: String, request: &RsRequest) -> Result<Call<Media>> {
1288        let mut http = with_json(Request::post(path), request)?;
1289        http.timeout = Some(DOWNLOAD_TIMEOUT);
1290        Ok(Call::json(http))
1291    }
1292
1293    /// `DELETE` of a title (`kind`: `series`, `movies` or `books`), the answer read as
1294    /// the title removed.
1295    fn remove_title<T: serde::de::DeserializeOwned + 'static>(
1296        library: &str,
1297        kind: &str,
1298        id: &str,
1299        delete_medias: bool,
1300    ) -> Call<T> {
1301        let request = Request::delete(item_path(library, kind, id, ""))
1302            .query("deleteMedias", delete_medias.to_string());
1303        Call::json(request)
1304    }
1305
1306    /// `GET path` with `options` as its query: the bytes of an image.
1307    fn image(path: String, options: &ImageRequestOptions) -> Result<Call<Vec<u8>>> {
1308        let mut request = Request::get(path);
1309        request.query = image_params(options)?;
1310        Ok(Call::bytes(request))
1311    }
1312
1313    /// `request`, its answer read as text: a share token.
1314    pub(crate) fn share_token(request: Request) -> Call<String> {
1315        let path = request.path.clone();
1316        Call::new(request, move |result| {
1317            String::from_utf8(result?.body)
1318                .map_err(|e| Error::malformed(format!("share token: {e}"), Some(&path)))
1319        })
1320    }
1321
1322    /// [`super::LibraryApi::get_medias`].
1323    pub fn get_medias(library: &str, query: &MediaQuery) -> Result<Call<Vec<MediaItem>>> {
1324        Ok(Call::json(media_filter(library, "/medias", query)?))
1325    }
1326
1327    /// [`super::LibraryApi::get_medias_page`].
1328    pub fn get_medias_page(library: &str, query: &MediaQuery) -> Result<Call<MediaPage>> {
1329        let limit = query.limit;
1330        let sort = query.sort.clone();
1331        Ok(get_medias(library, query)?.map(move |medias| {
1332            let full = limit.is_some_and(|limit| medias.len() >= limit && limit > 0);
1333            let next_page_key = if full {
1334                medias
1335                    .last()
1336                    .and_then(|last| next_page_key(&sort, &last.item))
1337            } else {
1338                None
1339            };
1340            Ok(MediaPage {
1341                medias,
1342                next_page_key,
1343            })
1344        }))
1345    }
1346
1347    /// [`super::LibraryApi::get_thumb_raw`]: encrypted in an encrypted library.
1348    pub fn get_thumb_raw(library: &str, media_id: &str) -> Call<Vec<u8>> {
1349        let path = format!("{}/image", media_path(library, media_id));
1350        Call::bytes(Request::get(path).query("size", "thumb"))
1351    }
1352
1353    /// The file of a media as the server sends it: [`super::LibraryApi::get_media`]
1354    /// without the decryption.
1355    pub fn get_media_file(library: &str, media_id: &str, query: &MediaFileQuery) -> Call<Vec<u8>> {
1356        let mut request = Request::get(media_path(library, media_id));
1357        request.query = media_file_params(query);
1358        request.timeout = Some(MEDIA_TIMEOUT);
1359        Call::bytes(request)
1360    }
1361
1362    /// [`super::LibraryApi::get_media_metadata`].
1363    pub fn get_media_metadata(library: &str, media_id: &str) -> Call<Option<MediaItem>> {
1364        let path = format!("{}/metadata", media_path(library, media_id));
1365        Call::json(Request::get(path))
1366    }
1367
1368    /// [`super::LibraryApi::get_media_by_hash`].
1369    pub fn get_media_by_hash(library: &str, hash: &str) -> Call<Option<MediaItem>> {
1370        #[derive(serde::Deserialize)]
1371        struct Exist {
1372            media: Option<MediaItem>,
1373        }
1374        let request = Request::get(library_path(library, "/medias/exist")).query("hash", hash);
1375        Call::json(request).map(|exist: Exist| Ok(exist.media))
1376    }
1377
1378    /// [`super::LibraryApi::update_media`].
1379    pub fn update_media(
1380        library: &str,
1381        media_id: &str,
1382        update: &MediaForUpdate,
1383    ) -> Result<Call<Media>> {
1384        let request = Request::patch(media_path(library, media_id));
1385        Ok(Call::json(with_json(request, update)?))
1386    }
1387
1388    /// [`super::LibraryApi::set_media_progress`].
1389    pub fn set_media_progress(
1390        library: &str,
1391        media_id: &str,
1392        progress: u64,
1393    ) -> Call<RsMediaProgress> {
1394        let request = Request::patch(format!("{}/progress", media_path(library, media_id)))
1395            .json(serde_json::json!({ "progress": progress }));
1396        Call::json(request)
1397    }
1398
1399    /// [`super::LibraryApi::remove_medias`].
1400    pub fn remove_medias(library: &str, media_ids: &[String]) -> Call<Vec<Media>> {
1401        let request = Request::delete(library_path(library, "/medias"))
1402            .json(serde_json::json!({ "ids": media_ids }));
1403        Call::json(request)
1404    }
1405
1406    /// [`super::LibraryApi::download_medias`].
1407    pub fn download_medias(library: &str, download: &RsGroupDownload) -> Result<Call<Vec<Media>>> {
1408        let path = library_path(library, "/medias/download");
1409        let mut request = with_json(Request::post(path.clone()), download)?;
1410        request.timeout = Some(DOWNLOAD_TIMEOUT);
1411        Ok(Call::json(request).map(move |answer: Value| {
1412            if answer.get("needFileSelection").is_some() {
1413                return Err(Error::malformed(
1414                    "the server needs a file selection: set selected_file on the request",
1415                    Some(&path),
1416                ));
1417            }
1418            serde_json::from_value(answer)
1419                .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), Some(&path)))
1420        }))
1421    }
1422
1423    /// [`super::LibraryApi::download_medias_in_background`].
1424    pub fn download_medias_in_background(
1425        library: &str,
1426        download: &RsGroupDownload,
1427    ) -> Result<Call<()>> {
1428        let request =
1429            Request::post(library_path(library, "/medias/download")).query("spawn", "true");
1430        Ok(Call::empty(with_json(request, download)?))
1431    }
1432
1433    /// [`super::LibraryApi::count_medias`].
1434    pub fn count_medias(library: &str, query: &MediaQuery) -> Result<Call<u64>> {
1435        #[derive(serde::Deserialize)]
1436        struct Count {
1437            count: u64,
1438        }
1439        let request = media_filter(library, "/medias/count", query)?;
1440        Ok(Call::json(request).map(|count: Count| Ok(count.count)))
1441    }
1442
1443    /// [`super::LibraryApi::get_tags`].
1444    pub fn get_tags(library: &str, query: &TagQuery) -> Result<Call<Vec<Tag>>> {
1445        list(library, "/tags", query)
1446    }
1447
1448    /// [`super::LibraryApi::create_tag`].
1449    pub fn create_tag(library: &str, tag: &TagForAdd) -> Result<Call<Tag>> {
1450        Ok(Call::json(with_json(
1451            Request::post(library_path(library, "/tags")),
1452            tag,
1453        )?))
1454    }
1455
1456    /// [`super::LibraryApi::update_tag`].
1457    pub fn update_tag(library: &str, tag_id: &str, update: &TagForUpdate) -> Result<Call<Tag>> {
1458        let request = Request::patch(item_path(library, "tags", tag_id, ""));
1459        Ok(Call::json(with_json(request, update)?))
1460    }
1461
1462    /// [`super::LibraryApi::merge_tag`].
1463    pub fn merge_tag(library: &str, tag_id: &str, into: &str) -> Call<Tag> {
1464        let request = Request::patch(item_path(library, "tags", tag_id, "/merge"))
1465            .json(serde_json::json!({ "into": into }));
1466        Call::json(request)
1467    }
1468
1469    /// [`super::LibraryApi::remove_tag`].
1470    pub fn remove_tag(library: &str, tag_id: &str) -> Call<Tag> {
1471        Call::json(Request::delete(item_path(library, "tags", tag_id, "")))
1472    }
1473
1474    /// [`super::LibraryApi::get_people`].
1475    pub fn get_people(library: &str, query: &PeopleQuery) -> Result<Call<Vec<Person>>> {
1476        list(library, "/people", query)
1477    }
1478
1479    /// [`super::LibraryApi::get_person`].
1480    pub fn get_person(library: &str, person_id: &str) -> Call<Option<Person>> {
1481        Call::json(Request::get(item_path(library, "people", person_id, "")))
1482    }
1483
1484    /// [`super::LibraryApi::create_person`].
1485    pub fn create_person(library: &str, person: &PersonForAdd) -> Result<Call<Person>> {
1486        Ok(Call::json(with_json(
1487            Request::post(library_path(library, "/people")),
1488            person,
1489        )?))
1490    }
1491
1492    /// [`super::LibraryApi::update_person`].
1493    pub fn update_person(
1494        library: &str,
1495        person_id: &str,
1496        update: &PersonForUpdate,
1497    ) -> Result<Call<Person>> {
1498        let request = Request::patch(item_path(library, "people", person_id, ""));
1499        Ok(Call::json(with_json(request, update)?))
1500    }
1501
1502    /// [`super::LibraryApi::get_person_image`].
1503    pub fn get_person_image(
1504        library: &str,
1505        person_id: &str,
1506        options: &ImageRequestOptions,
1507    ) -> Result<Call<Vec<u8>>> {
1508        image(item_path(library, "people", person_id, "/image"), options)
1509    }
1510
1511    /// [`super::LibraryApi::remove_person`].
1512    pub fn remove_person(library: &str, person_id: &str) -> Call<Person> {
1513        Call::json(Request::delete(item_path(library, "people", person_id, "")))
1514    }
1515
1516    /// [`super::LibraryApi::merge_people`].
1517    pub fn merge_people(library: &str, source: &str, target: &str) -> Call<u64> {
1518        #[derive(serde::Deserialize)]
1519        struct Merged {
1520            faces_transferred: u64,
1521        }
1522        let request = Request::post(library_path(library, "/people/merge"))
1523            .json(serde_json::json!({ "sourcePersonId": source, "targetPersonId": target }));
1524        Call::json(request).map(|merged: Merged| Ok(merged.faces_transferred))
1525    }
1526
1527    /// [`super::LibraryApi::get_movie_people`].
1528    pub fn get_movie_people(library: &str, movie_id: &str) -> Call<Vec<PersonWithRoles>> {
1529        Call::json(Request::get(item_path(
1530            library, "movies", movie_id, "/people",
1531        )))
1532    }
1533
1534    /// [`super::LibraryApi::get_serie_people`].
1535    pub fn get_serie_people(library: &str, serie_id: &str) -> Call<Vec<PersonWithRoles>> {
1536        Call::json(Request::get(item_path(
1537            library, "series", serie_id, "/people",
1538        )))
1539    }
1540
1541    /// [`super::LibraryApi::get_book_people`].
1542    pub fn get_book_people(library: &str, book_id: &str) -> Call<Vec<PersonWithRoles>> {
1543        Call::json(Request::get(item_path(
1544            library, "books", book_id, "/people",
1545        )))
1546    }
1547
1548    /// [`super::LibraryApi::get_series`].
1549    pub fn get_series(
1550        library: &str,
1551        query: &SerieQuery,
1552    ) -> Result<Call<Vec<ItemWithRelations<Serie>>>> {
1553        list(library, "/series", query)
1554    }
1555
1556    /// [`super::LibraryApi::create_serie`].
1557    pub fn create_serie(
1558        library: &str,
1559        serie: &ItemWithRelations<Serie>,
1560    ) -> Result<Call<ItemWithRelations<Serie>>> {
1561        Ok(Call::json(with_json(
1562            Request::post(library_path(library, "/series")),
1563            serie,
1564        )?))
1565    }
1566
1567    /// [`super::LibraryApi::update_serie`].
1568    pub fn update_serie(
1569        library: &str,
1570        serie_id: &str,
1571        update: &SerieForUpdate,
1572    ) -> Result<Call<ItemWithRelations<Serie>>> {
1573        let request = Request::patch(item_path(library, "series", serie_id, ""));
1574        Ok(Call::json(with_json(request, update)?))
1575    }
1576
1577    /// [`super::LibraryApi::get_serie_image`].
1578    pub fn get_serie_image(
1579        library: &str,
1580        serie_id: &str,
1581        options: &ImageRequestOptions,
1582    ) -> Result<Call<Vec<u8>>> {
1583        image(item_path(library, "series", serie_id, "/image"), options)
1584    }
1585
1586    /// [`super::LibraryApi::get_episode_image`].
1587    pub fn get_episode_image(
1588        library: &str,
1589        serie_id: &str,
1590        season: u32,
1591        number: u32,
1592        options: &ImageRequestOptions,
1593    ) -> Result<Call<Vec<u8>>> {
1594        let path = episode_path(library, serie_id, season, number, "/image");
1595        image(path, options)
1596    }
1597
1598    /// [`super::LibraryApi::remove_serie`].
1599    pub fn remove_serie(library: &str, serie_id: &str, delete_medias: bool) -> Call<Serie> {
1600        remove_title(library, "series", serie_id, delete_medias)
1601    }
1602
1603    /// [`super::LibraryApi::set_episode_watched`].
1604    pub fn set_episode_watched(
1605        library: &str,
1606        serie_id: &str,
1607        season: u32,
1608        number: u32,
1609        date: i64,
1610    ) -> Result<Call<()>> {
1611        let path = episode_path(library, serie_id, season, number, "/watched");
1612        post_watched(path, date)
1613    }
1614
1615    /// [`super::LibraryApi::set_episode_progress`].
1616    pub fn set_episode_progress(
1617        library: &str,
1618        serie_id: &str,
1619        season: u32,
1620        number: u32,
1621        progress: u64,
1622    ) -> Result<Call<()>> {
1623        let path = episode_path(library, serie_id, season, number, "/progress");
1624        post_progress(path, progress)
1625    }
1626
1627    /// [`super::LibraryApi::add_searched_episode_media`].
1628    pub fn add_searched_episode_media(
1629        library: &str,
1630        serie_id: &str,
1631        season: u32,
1632        number: u32,
1633        request: &RsRequest,
1634    ) -> Result<Call<Media>> {
1635        let path = episode_path(library, serie_id, season, number, "/search");
1636        post_searched_media(path, request)
1637    }
1638
1639    /// [`super::LibraryApi::get_movies`].
1640    pub fn get_movies(
1641        library: &str,
1642        query: &MovieQuery,
1643    ) -> Result<Call<Vec<ItemWithRelations<Movie>>>> {
1644        list(library, "/movies", query)
1645    }
1646
1647    /// [`super::LibraryApi::create_movie`].
1648    pub fn create_movie(
1649        library: &str,
1650        movie: &ItemWithRelations<Movie>,
1651    ) -> Result<Call<ItemWithRelations<Movie>>> {
1652        Ok(Call::json(with_json(
1653            Request::post(library_path(library, "/movies")),
1654            movie,
1655        )?))
1656    }
1657
1658    /// [`super::LibraryApi::update_movie`].
1659    pub fn update_movie(
1660        library: &str,
1661        movie_id: &str,
1662        update: &MovieForUpdate,
1663    ) -> Result<Call<ItemWithRelations<Movie>>> {
1664        let request = Request::patch(item_path(library, "movies", movie_id, ""));
1665        Ok(Call::json(with_json(request, update)?))
1666    }
1667
1668    /// [`super::LibraryApi::get_movie_image`].
1669    pub fn get_movie_image(
1670        library: &str,
1671        movie_id: &str,
1672        options: &ImageRequestOptions,
1673    ) -> Result<Call<Vec<u8>>> {
1674        image(item_path(library, "movies", movie_id, "/image"), options)
1675    }
1676
1677    /// [`super::LibraryApi::remove_movie`].
1678    pub fn remove_movie(library: &str, movie_id: &str, delete_medias: bool) -> Call<Movie> {
1679        remove_title(library, "movies", movie_id, delete_medias)
1680    }
1681
1682    /// [`super::LibraryApi::set_movie_watched`].
1683    pub fn set_movie_watched(library: &str, movie_id: &str, date: i64) -> Result<Call<()>> {
1684        post_watched(item_path(library, "movies", movie_id, "/watched"), date)
1685    }
1686
1687    /// [`super::LibraryApi::set_movie_progress`].
1688    pub fn set_movie_progress(library: &str, movie_id: &str, progress: u64) -> Result<Call<()>> {
1689        post_progress(
1690            item_path(library, "movies", movie_id, "/progress"),
1691            progress,
1692        )
1693    }
1694
1695    /// [`super::LibraryApi::add_searched_movie_media`].
1696    pub fn add_searched_movie_media(
1697        library: &str,
1698        movie_id: &str,
1699        request: &RsRequest,
1700    ) -> Result<Call<Media>> {
1701        post_searched_media(item_path(library, "movies", movie_id, "/search"), request)
1702    }
1703
1704    /// [`super::LibraryApi::get_episodes`].
1705    pub fn get_episodes(library: &str, query: &EpisodeQuery) -> Result<Call<Vec<Episode>>> {
1706        list(library, "/series/episodes", query)
1707    }
1708
1709    /// [`super::LibraryApi::get_books`].
1710    pub fn get_books(
1711        library: &str,
1712        query: &BookQuery,
1713    ) -> Result<Call<Vec<ItemWithRelations<Book>>>> {
1714        list(library, "/books", query)
1715    }
1716
1717    /// [`super::LibraryApi::get_book`].
1718    pub fn get_book(library: &str, book_id: &str) -> Call<ItemWithRelations<Book>> {
1719        Call::json(Request::get(item_path(library, "books", book_id, "")))
1720    }
1721
1722    /// [`super::LibraryApi::create_book`].
1723    pub fn create_book(
1724        library: &str,
1725        book: &ItemWithRelations<Book>,
1726        upsert_tags: bool,
1727        upsert_people: bool,
1728        upsert_serie: bool,
1729    ) -> Result<Call<ItemWithRelations<Book>>> {
1730        let mut request = with_json(Request::post(library_path(library, "/books")), book)?;
1731        let options = [
1732            ("upsertTags", upsert_tags),
1733            ("upsertPeople", upsert_people),
1734            ("upsertSerie", upsert_serie),
1735        ];
1736        for (name, _) in options.iter().filter(|(_, set)| *set) {
1737            request = request.query(*name, "true");
1738        }
1739        Ok(Call::json(request))
1740    }
1741
1742    /// [`super::LibraryApi::update_book`].
1743    pub fn update_book(
1744        library: &str,
1745        book_id: &str,
1746        update: &BookForUpdate,
1747    ) -> Result<Call<ItemWithRelations<Book>>> {
1748        let request = Request::patch(item_path(library, "books", book_id, ""));
1749        Ok(Call::json(with_json(request, update)?))
1750    }
1751
1752    /// [`super::LibraryApi::get_book_image`].
1753    pub fn get_book_image(
1754        library: &str,
1755        book_id: &str,
1756        options: &ImageRequestOptions,
1757    ) -> Result<Call<Vec<u8>>> {
1758        image(item_path(library, "books", book_id, "/image"), options)
1759    }
1760
1761    /// [`super::LibraryApi::remove_book`].
1762    pub fn remove_book(library: &str, book_id: &str, delete_medias: bool) -> Call<Book> {
1763        remove_title(library, "books", book_id, delete_medias)
1764    }
1765
1766    /// [`super::LibraryApi::set_book_watched`].
1767    pub fn set_book_watched(library: &str, book_id: &str, date: i64) -> Result<Call<()>> {
1768        post_watched(item_path(library, "books", book_id, "/watched"), date)
1769    }
1770
1771    /// [`super::LibraryApi::update_book_poster`].
1772    pub fn update_book_poster(library: &str, book_id: &str, image: &[u8]) -> Call<()> {
1773        let mut request = Request::post(item_path(library, "books", book_id, "/image"));
1774        request.body = Some(multipart_file(image));
1775        Call::empty(request)
1776    }
1777
1778    /// [`super::LibraryApi::get_channels`].
1779    pub fn get_channels(library: &str, query: &ChannelQuery) -> Result<Call<Vec<Channel>>> {
1780        list(library, "/channels", query)
1781    }
1782
1783    /// [`super::LibraryApi::get_channel_image`].
1784    pub fn get_channel_image(
1785        library: &str,
1786        channel_id: &str,
1787        options: &ImageRequestOptions,
1788    ) -> Result<Call<Vec<u8>>> {
1789        image(
1790            item_path(library, "channels", channel_id, "/image"),
1791            options,
1792        )
1793    }
1794
1795    /// [`super::LibraryApi::add_tag_to_channel`].
1796    pub fn add_tag_to_channel(library: &str, channel_id: &str, tag_id: &str) -> Call<()> {
1797        let request = Request::post(item_path(library, "channels", channel_id, "/tags"))
1798            .json(serde_json::json!({ "tagId": tag_id }));
1799        Call::empty(request)
1800    }
1801
1802    /// [`super::LibraryApi::remove_tag_from_channel`].
1803    pub fn remove_tag_from_channel(library: &str, channel_id: &str, tag_id: &str) -> Call<()> {
1804        let rest = format!("/tags/{}", path_segment(tag_id));
1805        Call::empty(Request::delete(item_path(
1806            library, "channels", channel_id, &rest,
1807        )))
1808    }
1809
1810    /// [`super::LibraryApi::stop_channel_hls`].
1811    pub fn stop_channel_hls(library: &str, channel_id: &str) -> Call<()> {
1812        Call::empty(Request::delete(item_path(
1813            library, "channels", channel_id, "/hls",
1814        )))
1815    }
1816
1817    /// [`super::LibraryApi::process_request`].
1818    pub fn process_request(library: &str, request: &RsRequest) -> Result<Call<RsRequest>> {
1819        let path = library_path(library, "/plugins/requests/process");
1820        Ok(Call::json(with_json(Request::post(path), request)?))
1821    }
1822
1823    /// [`super::LibraryApi::process_request_bytes`].
1824    pub fn process_request_bytes(library: &str, request: &RsRequest) -> Result<Call<Vec<u8>>> {
1825        let path = library_path(library, "/plugins/requests/process/stream");
1826        let mut http = with_json(Request::post(path), request)?;
1827        http.timeout = Some(MEDIA_TIMEOUT);
1828        Ok(Call::bytes(http))
1829    }
1830
1831    /// [`super::LibraryApi::check_request_permanent`].
1832    pub fn check_request_permanent(library: &str, request: &RsRequest) -> Result<Call<RsRequest>> {
1833        let path = library_path(library, "/plugins/requests/permanent");
1834        Ok(Call::json(with_json(Request::post(path), request)?))
1835    }
1836
1837    /// [`super::LibraryApi::add_request`].
1838    pub fn add_request(
1839        library: &str,
1840        request: &RsRequest,
1841        media_ref: Option<&str>,
1842    ) -> Call<RsRequestProcessing> {
1843        let body = serde_json::json!({ "request": request, "mediaRef": media_ref });
1844        Call::json(Request::post(library_path(library, "/plugins/requests/add")).json(body))
1845    }
1846
1847    /// [`super::LibraryApi::get_deleted`].
1848    pub fn get_deleted(library: &str, query: &DeletedQuery) -> Result<Call<Vec<RsDeleted>>> {
1849        list(library, "/deleted", query)
1850    }
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855    use std::sync::Arc;
1856
1857    use super::*;
1858    use crate::client::ClientOptions;
1859    use crate::cloud::ServerToken;
1860    use crate::test_support::FakeTransport;
1861    use crate::transport::{Body, Method, RawEvent, Transport};
1862    use crate::types::media::{FileType, SqlOrder};
1863    use crate::types::person::PersonType;
1864    use rs_plugin_common_interfaces::lookup::{RsLookupMatchType, RsLookupMetadataResult};
1865
1866    fn client(transport: Arc<dyn Transport>) -> RedseatClient {
1867        let client = RedseatClient::new(ClientOptions::new(transport));
1868        client.set_token(ServerToken {
1869            token: "t".into(),
1870            expires: i64::MAX,
1871        });
1872        client
1873    }
1874
1875    fn library(crypt: bool) -> ServerLibraryForRead {
1876        serde_json::from_value(serde_json::json!({
1877            "id": "lib 1", "name": "Photos", "source": "PathProvider", "type": "photos", "crypt": crypt
1878        }))
1879        .unwrap()
1880    }
1881
1882    fn media_json(id: &str, added: i64) -> serde_json::Value {
1883        serde_json::json!({"id": id, "name": format!("{id}.jpg"), "type": "photo",
1884            "mimetype": "image/jpeg", "added": added, "modified": added, "created": added})
1885    }
1886
1887    /// A library on a server that answers every request with `answer`.
1888    fn api_answering(answer: serde_json::Value) -> (LibraryApi, Arc<FakeTransport>) {
1889        let fake = FakeTransport::new(move |_| Ok(FakeTransport::json(answer.clone())));
1890        (LibraryApi::new(client(fake.clone()), library(false)), fake)
1891    }
1892
1893    /// Checks the method, path, query and JSON body of a request.
1894    #[track_caller]
1895    fn assert_sent(
1896        request: &Request,
1897        method: Method,
1898        path: &str,
1899        query: &[(&str, &str)],
1900        body: Option<serde_json::Value>,
1901    ) {
1902        assert_eq!(request.method, method);
1903        assert_eq!(request.path, path);
1904        let sent: Vec<(&str, &str)> = request
1905            .query
1906            .iter()
1907            .map(|(k, v)| (k.as_str(), v.as_str()))
1908            .collect();
1909        assert_eq!(sent, query);
1910        assert_eq!(request.body, body.map(Body::Json));
1911    }
1912
1913    fn tag_json(id: &str, name: &str) -> serde_json::Value {
1914        serde_json::json!({"id": id, "name": name, "parent": null, "alt": ["sea"],
1915            "modified": 2, "added": 1, "generated": false, "path": "/"})
1916    }
1917
1918    fn filter_of(request: &Request) -> serde_json::Value {
1919        let filter = request.query.iter().find(|(k, _)| k == "filter").unwrap();
1920        serde_json::from_str(&filter.1).unwrap()
1921    }
1922
1923    #[tokio::test]
1924    async fn pages_through_medias() {
1925        let fake = FakeTransport::new(|request| {
1926            assert_eq!(request.path, "/libraries/lib%201/medias");
1927            let filter = filter_of(request);
1928            let medias = match filter["pageKey"].as_str() {
1929                None => vec![media_json("m3", 300), media_json("m2", 200)],
1930                Some("200|m2") => vec![media_json("m1", 100)],
1931                Some(other) => panic!("unexpected page key {other}"),
1932            };
1933            Ok(FakeTransport::json(serde_json::Value::Array(medias)))
1934        });
1935        let api = LibraryApi::new(client(fake.clone()), library(false));
1936        let mut query = MediaQuery {
1937            sort: RsSort::Added,
1938            order: SqlOrder::DESC,
1939            limit: Some(2),
1940            ..Default::default()
1941        };
1942
1943        let first = api.get_medias_page(&query).await.unwrap();
1944        assert_eq!(first.medias.len(), 2);
1945        assert_eq!(first.next_page_key.as_deref(), Some("200|m2"));
1946
1947        query.page_key = first.next_page_key;
1948        let second = api.get_medias_page(&query).await.unwrap();
1949        assert_eq!(second.medias[0].item.id, "m1");
1950        assert_eq!(second.next_page_key, None);
1951
1952        let sent = filter_of(&fake.requests()[1]);
1953        assert_eq!(sent["sort"], "added");
1954        assert_eq!(sent["order"], "DESC");
1955        assert_eq!(sent["limit"], 2);
1956    }
1957
1958    #[test]
1959    fn page_keys_follow_the_sort() {
1960        let media = Media {
1961            id: "m".into(),
1962            kind: FileType::Photo,
1963            added: Some(1),
1964            created: Some(2),
1965            modified: Some(3),
1966            size: Some(4),
1967            ..Default::default()
1968        };
1969        assert_eq!(next_page_key(&RsSort::Added, &media).unwrap(), "1|m");
1970        assert_eq!(next_page_key(&RsSort::Created, &media).unwrap(), "2|m");
1971        assert_eq!(next_page_key(&RsSort::Modified, &media).unwrap(), "3|m");
1972        assert_eq!(next_page_key(&RsSort::Size, &media).unwrap(), "4|m");
1973        assert_eq!(next_page_key(&RsSort::Name, &media), None);
1974    }
1975
1976    /// An encrypted library whose server holds one media with a thumb encrypted
1977    /// with `passphrase`, built with redseat-crypto itself.
1978    fn encrypted_server(passphrase: &str, thumb: &[u8]) -> Arc<FakeTransport> {
1979        let key = redseat_crypto::derive_key(passphrase);
1980        let iv = redseat_crypto::random_iv().unwrap();
1981        let file = redseat_crypto::encrypt_file_bytes(
1982            &key,
1983            &iv,
1984            b"file",
1985            Some("image/jpeg"),
1986            Some((thumb, "image/jpeg")),
1987            None,
1988        )
1989        .unwrap();
1990        // The server's thumb endpoint returns the encrypted thumb alone.
1991        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
1992        let range = header.thumb_range();
1993        let encrypted_thumb = file[range.start as usize..range.end as usize].to_vec();
1994        let media = serde_json::json!([{
1995            "id": "m1", "name": "x", "type": "photo", "mimetype": "image/jpeg",
1996            "thumbsize": encrypted_thumb.len(),
1997            "iv": base64::engine::general_purpose::STANDARD.encode(iv)
1998        }]);
1999        FakeTransport::new(move |request| {
2000            if request.path.ends_with("/medias") {
2001                Ok(FakeTransport::json(media.clone()))
2002            } else {
2003                assert_eq!(request.path, "/libraries/lib%201/medias/m1/image");
2004                assert_eq!(request.query, vec![("size".into(), "thumb".into())]);
2005                Ok(FakeTransport::bytes(encrypted_thumb.clone()))
2006            }
2007        })
2008    }
2009
2010    #[tokio::test]
2011    async fn decrypts_thumbs_of_encrypted_libraries() {
2012        let thumb = b"\xff\xd8 a jpeg thumbnail".to_vec();
2013        let fake = encrypted_server("secret", &thumb);
2014        let api = LibraryApi::new(client(fake), library(true));
2015        let medias = api.get_medias(&MediaQuery::default()).await.unwrap();
2016        let media = &medias[0].item;
2017
2018        let error = api.get_thumb(media).await.unwrap_err();
2019        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
2020
2021        api.set_passphrase("secret").await.unwrap();
2022        assert_eq!(api.get_thumb(media).await.unwrap(), thumb);
2023    }
2024
2025    #[tokio::test]
2026    async fn refuses_a_wrong_passphrase() {
2027        let fake = encrypted_server("secret", b"thumb");
2028        let api = LibraryApi::new(client(fake), library(true));
2029        let error = api.set_passphrase("wrong").await.unwrap_err();
2030        assert_eq!(error.kind(), crate::ErrorKind::InvalidPassphrase);
2031        assert!(!api.has_passphrase());
2032    }
2033
2034    #[tokio::test]
2035    async fn downloads_and_decrypts_media_files() {
2036        let key = redseat_crypto::derive_key("secret");
2037        let iv = redseat_crypto::random_iv().unwrap();
2038        let content = b"\x00\x00\x00\x18ftypmp42 a whole video file".repeat(40);
2039        let file = redseat_crypto::encrypt_file_bytes(
2040            &key,
2041            &iv,
2042            &content,
2043            Some("video/mp4"),
2044            Some((b"thumb", "image/jpeg")),
2045            None,
2046        )
2047        .unwrap();
2048        // Without `raw`, the server sends the file after its header and thumb.
2049        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
2050        let data = file[header.data_offset() as usize..].to_vec();
2051        let fake = FakeTransport::new(move |request| {
2052            assert_eq!(request.path, "/libraries/lib%201/medias/m%201");
2053            Ok(FakeTransport::bytes(data.clone()))
2054        });
2055        let api = LibraryApi::new(client(fake.clone()), library(true));
2056        let media = Media {
2057            id: "m 1".into(),
2058            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
2059            ..Default::default()
2060        };
2061        let query = MediaFileQuery::default();
2062        let error = api.get_media(&media, &query).await.unwrap_err();
2063        assert_eq!(error.kind(), crate::ErrorKind::PassphraseRequired);
2064
2065        *api.lock_key() = Some(key);
2066        assert_eq!(api.get_media(&media, &query).await.unwrap(), content);
2067        let request = &fake.requests()[0];
2068        assert!(request.query.is_empty());
2069        assert_eq!(request.timeout, Some(MEDIA_TIMEOUT));
2070    }
2071
2072    #[tokio::test]
2073    async fn asks_the_server_to_convert_unsupported_photos() {
2074        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"webp".to_vec())));
2075        let api = LibraryApi::new(client(fake.clone()), library(false));
2076        let media = Media {
2077            id: "m1".into(),
2078            ..Default::default()
2079        };
2080        let query = MediaFileQuery {
2081            unsupported_mime: vec!["image/heic".into(), "all".into()],
2082            page: Some(2),
2083            raw: true,
2084        };
2085        assert_eq!(api.get_media(&media, &query).await.unwrap(), b"webp");
2086        let requests = fake.requests();
2087        let pairs: Vec<(&str, &str)> = requests[0]
2088            .query
2089            .iter()
2090            .map(|(k, v)| (k.as_str(), v.as_str()))
2091            .collect();
2092        assert_eq!(
2093            pairs,
2094            [
2095                ("unsupportedMime", "image/heic"),
2096                ("unsupportedMime", "all"),
2097                ("page", "2"),
2098                ("raw", "true")
2099            ]
2100        );
2101    }
2102
2103    #[tokio::test]
2104    async fn gives_media_urls_with_a_token() {
2105        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
2106        let api = LibraryApi::new(client(fake.clone()), library(false));
2107        let query = MediaFileQuery::default();
2108        // Not an HTTP transport: no URL.
2109        assert!(api.media_url("m 1", &query).await.is_err());
2110
2111        fake.set_base_url("https://host:7080/");
2112        let url = api.media_url("m 1", &query).await.unwrap();
2113        assert_eq!(url.url, "https://host:7080/libraries/lib%201/medias/m%201");
2114        assert_eq!(url.authorization(), "Bearer t");
2115        assert_eq!(url.expires, i64::MAX);
2116        assert_eq!(
2117            url.with_token_query(),
2118            "https://host:7080/libraries/lib%201/medias/m%201?token=t"
2119        );
2120        assert!(!format!("{url:?}").contains("Bearer"));
2121    }
2122
2123    #[tokio::test]
2124    async fn lists_tags_and_people() {
2125        let fake = FakeTransport::new(|request| {
2126            Ok(FakeTransport::json(match request.path.as_str() {
2127                "/libraries/lib%201/tags" => serde_json::json!([
2128                    {"id": "t1", "name": "beach", "parent": null, "alt": null, "modified": 1,
2129                        "added": 1, "generated": false, "path": "/beach"}
2130                ]),
2131                "/libraries/lib%201/people" => serde_json::json!([serde_json::to_value(Person {
2132                    id: "p1".into(),
2133                    name: "Alice".into(),
2134                    ..Default::default()
2135                })
2136                .unwrap()]),
2137                other => panic!("unexpected {other}"),
2138            }))
2139        });
2140        let api = LibraryApi::new(client(fake), library(false));
2141        assert_eq!(
2142            api.get_tags(&TagQuery::default()).await.unwrap()[0].name,
2143            "beach"
2144        );
2145        assert_eq!(
2146            api.get_people(&PeopleQuery::default()).await.unwrap()[0].name,
2147            "Alice"
2148        );
2149    }
2150
2151    #[tokio::test]
2152    async fn lists_with_after_and_pages() {
2153        let fake = FakeTransport::new(|request| {
2154            Ok(FakeTransport::json(match request.path.as_str() {
2155                "/libraries/lib%201/medias/count" => serde_json::json!({"count": 7}),
2156                _ => serde_json::json!([]),
2157            }))
2158        });
2159        let api = LibraryApi::new(client(fake.clone()), library(false));
2160        let pairs = |request: &Request| -> Vec<(String, String)> {
2161            let mut pairs = request.query.clone();
2162            pairs.sort();
2163            pairs
2164        };
2165        let owned = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
2166            pairs
2167                .iter()
2168                .map(|(k, v)| (k.to_string(), v.to_string()))
2169                .collect()
2170        };
2171
2172        let tags = TagQuery {
2173            after: Some(41),
2174            limit: Some(1000),
2175            offset: Some(2000),
2176            ..Default::default()
2177        };
2178        api.get_tags(&tags).await.unwrap();
2179        api.get_people(&PeopleQuery::from_after(5)).await.unwrap();
2180        api.get_series(&SerieQuery::from_after(6)).await.unwrap();
2181        api.get_movies(&MovieQuery::from_after(7)).await.unwrap();
2182        let episodes = EpisodeQuery {
2183            not_seasons: vec![0, 9],
2184            ..EpisodeQuery::from_after(8)
2185        };
2186        api.get_episodes(&episodes).await.unwrap();
2187        api.get_books(&BookQuery {
2188            after: Some(9),
2189            ..Default::default()
2190        })
2191        .await
2192        .unwrap();
2193        let deleted = DeletedQuery {
2194            after: Some(10),
2195            kind: Some(crate::types::element_type::ElementType::Media),
2196            order: SqlOrder::ASC,
2197            limit: Some(1000),
2198            offset: Some(0),
2199        };
2200        api.get_deleted(&deleted).await.unwrap();
2201        let count = api.count_medias(&MediaQuery::from_after(11)).await.unwrap();
2202        assert_eq!(count, 7);
2203
2204        let requests = fake.requests();
2205        let paths: Vec<&str> = requests.iter().map(|r| r.path.as_str()).collect();
2206        assert_eq!(
2207            paths,
2208            [
2209                "/libraries/lib%201/tags",
2210                "/libraries/lib%201/people",
2211                "/libraries/lib%201/series",
2212                "/libraries/lib%201/movies",
2213                "/libraries/lib%201/series/episodes",
2214                "/libraries/lib%201/books",
2215                "/libraries/lib%201/deleted",
2216                "/libraries/lib%201/medias/count",
2217            ]
2218        );
2219        assert_eq!(
2220            pairs(&requests[0]),
2221            owned(&[("after", "41"), ("limit", "1000"), ("offset", "2000")])
2222        );
2223        assert_eq!(pairs(&requests[1]), owned(&[("after", "5")]));
2224        // Defaults the server reads too; the movie sort's default is left out.
2225        assert_eq!(
2226            pairs(&requests[2]),
2227            owned(&[("after", "6"), ("order", "DESC"), ("sort", "modified")])
2228        );
2229        assert_eq!(pairs(&requests[3]), owned(&[("after", "7")]));
2230        assert_eq!(
2231            pairs(&requests[4]),
2232            owned(&[("after", "8"), ("notSeasons", "0"), ("notSeasons", "9")])
2233        );
2234        assert_eq!(
2235            pairs(&requests[5]),
2236            owned(&[("after", "9"), ("order", "DESC"), ("sort", "modified")])
2237        );
2238        assert_eq!(
2239            pairs(&requests[6]),
2240            owned(&[
2241                ("after", "10"),
2242                ("limit", "1000"),
2243                ("offset", "0"),
2244                ("order", "ASC"),
2245                ("type", "media")
2246            ])
2247        );
2248        assert_eq!(filter_of(&requests[7])["after"], 11);
2249    }
2250
2251    #[tokio::test]
2252    async fn changes_merges_and_removes_tags() {
2253        let (api, fake) = api_answering(tag_json("t 1", "beach"));
2254        let update = TagForUpdate {
2255            name: Some("beach".into()),
2256            parent: Some(String::new()),
2257            add_alts: Some(vec!["sea".into()]),
2258            ..Default::default()
2259        };
2260        assert_eq!(api.update_tag("t 1", &update).await.unwrap().name, "beach");
2261        assert_eq!(api.merge_tag("t 1", "t2").await.unwrap().id, "t 1");
2262        assert_eq!(
2263            api.remove_tag("t 1").await.unwrap().alt,
2264            Some(vec!["sea".to_owned()])
2265        );
2266
2267        let requests = fake.requests();
2268        assert_eq!(requests[0].method, Method::Patch);
2269        assert_eq!(requests[0].path, "/libraries/lib%201/tags/t%201");
2270        let Some(Body::Json(sent)) = &requests[0].body else {
2271            panic!("no JSON body");
2272        };
2273        assert_eq!(sent["name"], "beach");
2274        assert_eq!(sent["parent"], "");
2275        assert_eq!(sent["addAlts"], serde_json::json!(["sea"]));
2276        assert_eq!(sent["removeAlts"], serde_json::Value::Null);
2277        assert_sent(
2278            &requests[1],
2279            Method::Patch,
2280            "/libraries/lib%201/tags/t%201/merge",
2281            &[],
2282            Some(serde_json::json!({"into": "t2"})),
2283        );
2284        assert_sent(
2285            &requests[2],
2286            Method::Delete,
2287            "/libraries/lib%201/tags/t%201",
2288            &[],
2289            None,
2290        );
2291    }
2292
2293    #[tokio::test]
2294    async fn reads_removes_and_merges_people() {
2295        let fake = FakeTransport::new(|request| {
2296            Ok(FakeTransport::json(match request.path.as_str() {
2297                "/libraries/lib%201/people/missing" => serde_json::Value::Null,
2298                "/libraries/lib%201/people/merge" => {
2299                    serde_json::json!({"status": "merged", "faces_transferred": 4})
2300                }
2301                "/libraries/lib%201/people/p%201" => {
2302                    serde_json::json!({"id": "p 1", "name": "Alice", "socials": null,
2303                        "portrait": null, "params": null, "birthday": null, "modified": 2,
2304                        "added": 1, "posterv": 0, "generated": false, "type": "Actor"})
2305                }
2306                // A person of a title: the person, with their roles in it.
2307                _ => serde_json::json!([{"id": "p 1", "name": "Alice", "socials": null,
2308                    "portrait": null, "params": null, "birthday": null, "modified": 2,
2309                    "added": 1, "posterv": 0, "generated": false,
2310                    "roles": ["Actor"], "characters": ["Ripley"], "rank": 0}]),
2311            }))
2312        });
2313        let api = LibraryApi::new(client(fake.clone()), library(false));
2314        let person = api.get_person("p 1").await.unwrap().unwrap();
2315        assert_eq!(person.name, "Alice");
2316        assert_eq!(person.kind, Some(PersonType::Actor));
2317        assert_eq!(api.get_person("missing").await.unwrap(), None);
2318        assert_eq!(api.remove_person("p 1").await.unwrap().id, "p 1");
2319        assert_eq!(api.merge_people("p 1", "p2").await.unwrap(), 4);
2320        let cast = api.get_movie_people("m 1").await.unwrap();
2321        assert_eq!(cast[0].person.name, "Alice");
2322        assert_eq!(cast[0].roles, Some(vec![PersonType::Actor]));
2323        assert_eq!(cast[0].characters, Some(vec!["Ripley".to_owned()]));
2324        api.get_serie_people("s 1").await.unwrap();
2325        api.get_book_people("b 1").await.unwrap();
2326
2327        let requests = fake.requests();
2328        let person = "/libraries/lib%201/people/p%201";
2329        assert_sent(&requests[0], Method::Get, person, &[], None);
2330        assert_sent(&requests[2], Method::Delete, person, &[], None);
2331        assert_sent(
2332            &requests[3],
2333            Method::Post,
2334            "/libraries/lib%201/people/merge",
2335            &[],
2336            Some(serde_json::json!({"sourcePersonId": "p 1", "targetPersonId": "p2"})),
2337        );
2338        let people = [
2339            "/libraries/lib%201/movies/m%201/people",
2340            "/libraries/lib%201/series/s%201/people",
2341            "/libraries/lib%201/books/b%201/people",
2342        ];
2343        for (request, path) in requests[4..].iter().zip(people) {
2344            assert_sent(request, Method::Get, path, &[], None);
2345        }
2346    }
2347
2348    #[tokio::test]
2349    async fn creates_and_removes_series() {
2350        let (api, fake) = api_answering(serde_json::json!({"id": "s 1", "name": "Dark",
2351            "modified": 2, "added": 1, "posterv": 0, "backgroundv": 0, "cardv": 0,
2352            "relations": {"tags": [{"id": "t1"}]}}));
2353        let serie = ItemWithRelations {
2354            item: Serie {
2355                name: "Dark".into(),
2356                ..Default::default()
2357            },
2358            relations: None,
2359        };
2360        let created = api.create_serie(&serie).await.unwrap();
2361        assert_eq!(created.item.id, "s 1");
2362        assert!(created.relations.is_some());
2363        assert_eq!(api.remove_serie("s 1", true).await.unwrap().name, "Dark");
2364
2365        let requests = fake.requests();
2366        assert_eq!(requests[0].method, Method::Post);
2367        assert_eq!(requests[0].path, "/libraries/lib%201/series");
2368        let Some(Body::Json(sent)) = &requests[0].body else {
2369            panic!("no JSON body");
2370        };
2371        // The series and its relations are one flat object, as the server reads it.
2372        assert_eq!(sent["name"], "Dark");
2373        assert_sent(
2374            &requests[1],
2375            Method::Delete,
2376            "/libraries/lib%201/series/s%201",
2377            &[("deleteMedias", "true")],
2378            None,
2379        );
2380    }
2381
2382    #[tokio::test]
2383    async fn sets_episode_history_and_adds_a_searched_file() {
2384        let fake = FakeTransport::new(|request| {
2385            Ok(if request.path.ends_with("/search") {
2386                FakeTransport::json(media_json("m1", 100))
2387            } else {
2388                // The history routes answer with an empty body.
2389                FakeTransport::bytes(Vec::new())
2390            })
2391        });
2392        let api = LibraryApi::new(client(fake.clone()), library(false));
2393        api.set_episode_watched("s 1", 2, 3, 1700).await.unwrap();
2394        api.set_episode_progress("s 1", 2, 3, 42).await.unwrap();
2395        let request = RsRequest {
2396            url: "https://example.com/e.mkv".into(),
2397            ..Default::default()
2398        };
2399        let media = api
2400            .add_searched_episode_media("s 1", 2, 3, &request)
2401            .await
2402            .unwrap();
2403        assert_eq!(media.id, "m1");
2404
2405        let requests = fake.requests();
2406        let episode = "/libraries/lib%201/series/s%201/seasons/2/episodes/3";
2407        assert_sent(
2408            &requests[0],
2409            Method::Post,
2410            &format!("{episode}/watched"),
2411            &[],
2412            Some(serde_json::json!({"date": 1700})),
2413        );
2414        assert_sent(
2415            &requests[1],
2416            Method::Post,
2417            &format!("{episode}/progress"),
2418            &[],
2419            Some(serde_json::json!({"progress": 42})),
2420        );
2421        assert_eq!(requests[2].method, Method::Post);
2422        assert_eq!(requests[2].path, format!("{episode}/search"));
2423        assert_eq!(requests[2].timeout, Some(DOWNLOAD_TIMEOUT));
2424        let Some(Body::Json(sent)) = &requests[2].body else {
2425            panic!("no JSON body");
2426        };
2427        assert_eq!(sent["url"], "https://example.com/e.mkv");
2428    }
2429
2430    #[tokio::test]
2431    async fn creates_changes_and_removes_movies() {
2432        let (api, fake) = api_answering(serde_json::json!({"id": "m 1", "name": "Alien",
2433            "type": null, "year": 1979, "modified": 2, "added": 1, "posterv": 0,
2434            "backgroundv": 0, "cardv": 0, "relations": {"tags": [{"id": "t1"}]}}));
2435        let movie = ItemWithRelations {
2436            item: Movie {
2437                name: "Alien".into(),
2438                ..Default::default()
2439            },
2440            relations: None,
2441        };
2442        assert_eq!(api.create_movie(&movie).await.unwrap().item.id, "m 1");
2443        let update = MovieForUpdate {
2444            name: Some("Aliens".into()),
2445            ..Default::default()
2446        };
2447        let updated = api.update_movie("m 1", &update).await.unwrap();
2448        assert!(updated.relations.is_some());
2449        assert_eq!(
2450            api.remove_movie("m 1", false).await.unwrap().year,
2451            Some(1979)
2452        );
2453
2454        let requests = fake.requests();
2455        assert_eq!(requests[0].method, Method::Post);
2456        assert_eq!(requests[0].path, "/libraries/lib%201/movies");
2457        let Some(Body::Json(sent)) = &requests[0].body else {
2458            panic!("no JSON body");
2459        };
2460        assert_eq!(sent["name"], "Alien");
2461        assert_eq!(requests[1].method, Method::Patch);
2462        assert_eq!(requests[1].path, "/libraries/lib%201/movies/m%201");
2463        let Some(Body::Json(sent)) = &requests[1].body else {
2464            panic!("no JSON body");
2465        };
2466        assert_eq!(sent["name"], "Aliens");
2467        assert_sent(
2468            &requests[2],
2469            Method::Delete,
2470            "/libraries/lib%201/movies/m%201",
2471            &[("deleteMedias", "false")],
2472            None,
2473        );
2474    }
2475
2476    #[tokio::test]
2477    async fn sets_movie_history_and_adds_a_searched_file() {
2478        let fake = FakeTransport::new(|request| {
2479            Ok(if request.path.ends_with("/search") {
2480                FakeTransport::json(media_json("m1", 100))
2481            } else {
2482                FakeTransport::bytes(Vec::new())
2483            })
2484        });
2485        let api = LibraryApi::new(client(fake.clone()), library(false));
2486        api.set_movie_watched("m 1", 0).await.unwrap();
2487        api.set_movie_progress("m 1", 42).await.unwrap();
2488        let request = RsRequest {
2489            url: "https://example.com/m.mkv".into(),
2490            ..Default::default()
2491        };
2492        let media = api.add_searched_movie_media("m 1", &request).await.unwrap();
2493        assert_eq!(media.id, "m1");
2494
2495        let requests = fake.requests();
2496        let movie = "/libraries/lib%201/movies/m%201";
2497        assert_sent(
2498            &requests[0],
2499            Method::Post,
2500            &format!("{movie}/watched"),
2501            &[],
2502            Some(serde_json::json!({"date": 0})),
2503        );
2504        assert_sent(
2505            &requests[1],
2506            Method::Post,
2507            &format!("{movie}/progress"),
2508            &[],
2509            Some(serde_json::json!({"progress": 42})),
2510        );
2511        assert_eq!(requests[2].method, Method::Post);
2512        assert_eq!(requests[2].path, format!("{movie}/search"));
2513        assert_eq!(requests[2].timeout, Some(DOWNLOAD_TIMEOUT));
2514    }
2515
2516    #[tokio::test]
2517    async fn reads_creates_changes_and_removes_books() {
2518        let (api, fake) = api_answering(serde_json::json!({"id": "b 1", "name": "Dune",
2519            "year": 1965, "modified": 2, "added": 1, "relations": {"people": [{"id": "p1"}]}}));
2520        assert_eq!(api.get_book("b 1").await.unwrap().item.name, "Dune");
2521        let book = ItemWithRelations {
2522            item: Book {
2523                name: "Dune".into(),
2524                ..Default::default()
2525            },
2526            relations: None,
2527        };
2528        let created = api.create_book(&book, true, false, true).await.unwrap();
2529        assert_eq!(created.item.id, "b 1");
2530        api.create_book(&book, false, false, false).await.unwrap();
2531        let update = BookForUpdate {
2532            name: Some("Dune Messiah".into()),
2533            ..Default::default()
2534        };
2535        let updated = api.update_book("b 1", &update).await.unwrap();
2536        assert!(updated.relations.is_some());
2537        assert_eq!(api.remove_book("b 1", true).await.unwrap().year, Some(1965));
2538        api.set_book_watched("b 1", 1700).await.unwrap();
2539
2540        let requests = fake.requests();
2541        let one = "/libraries/lib%201/books/b%201";
2542        assert_sent(&requests[0], Method::Get, one, &[], None);
2543        assert_eq!(requests[1].method, Method::Post);
2544        assert_eq!(requests[1].path, "/libraries/lib%201/books");
2545        assert_eq!(
2546            requests[1].query,
2547            [
2548                ("upsertTags".to_owned(), "true".to_owned()),
2549                ("upsertSerie".to_owned(), "true".to_owned())
2550            ]
2551        );
2552        let Some(Body::Json(sent)) = &requests[1].body else {
2553            panic!("no JSON body");
2554        };
2555        assert_eq!(sent["name"], "Dune");
2556        assert!(requests[2].query.is_empty());
2557        assert_eq!(requests[3].method, Method::Patch);
2558        assert_eq!(requests[3].path, one);
2559        let Some(Body::Json(sent)) = &requests[3].body else {
2560            panic!("no JSON body");
2561        };
2562        assert_eq!(sent["name"], "Dune Messiah");
2563        assert_sent(
2564            &requests[4],
2565            Method::Delete,
2566            one,
2567            &[("deleteMedias", "true")],
2568            None,
2569        );
2570        assert_sent(
2571            &requests[5],
2572            Method::Post,
2573            &format!("{one}/watched"),
2574            &[],
2575            Some(serde_json::json!({"date": 1700})),
2576        );
2577    }
2578
2579    /// The files of a multipart body, read with the parser the server uses (multer,
2580    /// through axum).
2581    async fn multipart_files(body: &Body) -> Vec<Vec<u8>> {
2582        let Body::Bytes { content_type, data } = body else {
2583            panic!("not a bytes body");
2584        };
2585        let boundary = multer::parse_boundary(content_type).unwrap();
2586        let stream = futures_util::stream::iter([Ok::<_, std::convert::Infallible>(data.clone())]);
2587        let mut multipart = multer::Multipart::new(stream, boundary);
2588        let mut files = Vec::new();
2589        while let Some(field) = multipart.next_field().await.unwrap() {
2590            assert_eq!(field.name(), Some("file"));
2591            files.push(field.bytes().await.unwrap().to_vec());
2592        }
2593        files
2594    }
2595
2596    #[tokio::test]
2597    async fn uploads_a_book_poster_as_multipart() {
2598        let (api, fake) = api_answering(serde_json::json!({"data": "ok"}));
2599        // An image that holds line breaks, dashes and the usual boundary itself.
2600        let image = b"\xff\xd8\r\n--redseat-api-boundary--\r\n jpeg".to_vec();
2601        api.update_book_poster("b 1", &image).await.unwrap();
2602
2603        let request = &fake.requests()[0];
2604        assert_eq!(request.method, Method::Post);
2605        assert_eq!(request.path, "/libraries/lib%201/books/b%201/image");
2606        assert!(request.query.is_empty());
2607        let body = request.body.as_ref().unwrap();
2608        assert_eq!(multipart_files(body).await, [image]);
2609    }
2610
2611    #[tokio::test]
2612    async fn reads_changes_and_removes_medias() {
2613        let fake = FakeTransport::new(|request| {
2614            let media = media_json("m 1", 100);
2615            Ok(FakeTransport::json(match request.path.as_str() {
2616                "/libraries/lib%201/medias/m%201/metadata" => {
2617                    let mut media = media;
2618                    media["relations"] = serde_json::json!({"tags": [{"id": "t1"}]});
2619                    media["faces"] = serde_json::json!([]);
2620                    media
2621                }
2622                "/libraries/lib%201/medias/missing/metadata" => serde_json::Value::Null,
2623                "/libraries/lib%201/medias/exist" => {
2624                    let known = request.query[0].1 == "abc";
2625                    serde_json::json!({"exist": known, "media": known.then_some(media)})
2626                }
2627                "/libraries/lib%201/medias/m%201/progress" => serde_json::json!({
2628                    "mediaRef": "m 1", "userRef": "u1", "progress": 42, "modified": 5}),
2629                "/libraries/lib%201/medias" => serde_json::json!([media]),
2630                _ => media,
2631            }))
2632        });
2633        let api = LibraryApi::new(client(fake.clone()), library(false));
2634        let media = api.get_media_metadata("m 1").await.unwrap().unwrap();
2635        assert!(media.relations.is_some());
2636        assert_eq!(api.get_media_metadata("missing").await.unwrap(), None);
2637        let found = api.get_media_by_hash("abc").await.unwrap().unwrap();
2638        assert_eq!(found.item.id, "m 1");
2639        assert_eq!(api.get_media_by_hash("def").await.unwrap(), None);
2640        let update = MediaForUpdate {
2641            rating: Some(8),
2642            remove_tags: Some(vec!["t1".into()]),
2643            ..Default::default()
2644        };
2645        assert_eq!(api.update_media("m 1", &update).await.unwrap().id, "m 1");
2646        let progress = api.set_media_progress("m 1", 42).await.unwrap();
2647        assert_eq!(progress.progress, 42);
2648        let removed = api
2649            .remove_medias(&["m 1".to_owned(), "gone".to_owned()])
2650            .await
2651            .unwrap();
2652        assert_eq!(removed.len(), 1);
2653
2654        let requests = fake.requests();
2655        let one = "/libraries/lib%201/medias/m%201";
2656        assert_sent(
2657            &requests[0],
2658            Method::Get,
2659            &format!("{one}/metadata"),
2660            &[],
2661            None,
2662        );
2663        assert_sent(
2664            &requests[2],
2665            Method::Get,
2666            "/libraries/lib%201/medias/exist",
2667            &[("hash", "abc")],
2668            None,
2669        );
2670        assert_eq!(requests[4].method, Method::Patch);
2671        assert_eq!(requests[4].path, one);
2672        let Some(Body::Json(sent)) = &requests[4].body else {
2673            panic!("no JSON body");
2674        };
2675        assert_eq!(sent["rating"], 8);
2676        assert_eq!(sent["removeTags"], serde_json::json!(["t1"]));
2677        assert_sent(
2678            &requests[5],
2679            Method::Patch,
2680            &format!("{one}/progress"),
2681            &[],
2682            Some(serde_json::json!({"progress": 42})),
2683        );
2684        assert_sent(
2685            &requests[6],
2686            Method::Delete,
2687            "/libraries/lib%201/medias",
2688            &[],
2689            Some(serde_json::json!({"ids": ["m 1", "gone"]})),
2690        );
2691    }
2692
2693    #[tokio::test]
2694    async fn gives_share_urls_of_medias() {
2695        let fake = FakeTransport::new(|request| {
2696            assert_eq!(request.path, "/libraries/lib%201/medias/m%201/sharetoken");
2697            // The token is the whole body, as text.
2698            Ok(FakeTransport::bytes(b"v4.local.a+b".to_vec()))
2699        });
2700        let api = LibraryApi::new(client(fake.clone()), library(false));
2701        // Not an HTTP transport: no URL.
2702        assert!(api.media_share_url("m 1").await.is_err());
2703
2704        fake.set_base_url("https://host:7080");
2705        assert_eq!(
2706            api.media_share_url("m 1").await.unwrap(),
2707            "https://host:7080/libraries/lib%201/medias/m%201?sharetoken=v4.local.a%2Bb"
2708        );
2709    }
2710
2711    #[tokio::test]
2712    async fn downloads_medias_from_urls() {
2713        let fake = FakeTransport::new(|request| {
2714            let url = match &request.body {
2715                Some(Body::Json(body)) => body["requests"][0]["url"].as_str().unwrap().to_owned(),
2716                _ => panic!("no JSON body"),
2717            };
2718            Ok(FakeTransport::json(if !request.query.is_empty() {
2719                serde_json::json!({"downloading": true})
2720            } else if url.ends_with(".zip") {
2721                serde_json::json!({"needFileSelection": true, "request": {"url": url}})
2722            } else {
2723                serde_json::json!([media_json("m1", 100)])
2724            }))
2725        });
2726        let api = LibraryApi::new(client(fake.clone()), library(false));
2727        let download = |url: &str| RsGroupDownload {
2728            requests: vec![RsRequest {
2729                url: url.into(),
2730                ..Default::default()
2731            }],
2732            ..Default::default()
2733        };
2734        let medias = api.download_medias(&download("https://e.com/a.jpg")).await;
2735        assert_eq!(medias.unwrap()[0].id, "m1");
2736        let error = api
2737            .download_medias(&download("https://e.com/a.zip"))
2738            .await
2739            .unwrap_err();
2740        assert!(error.to_string().contains("file selection"));
2741        api.download_medias_in_background(&download("https://e.com/a.jpg"))
2742            .await
2743            .unwrap();
2744
2745        let requests = fake.requests();
2746        for request in &requests {
2747            assert_eq!(request.method, Method::Post);
2748            assert_eq!(request.path, "/libraries/lib%201/medias/download");
2749        }
2750        assert!(requests[0].query.is_empty());
2751        assert_eq!(requests[0].timeout, Some(DOWNLOAD_TIMEOUT));
2752        assert_eq!(requests[2].query, [("spawn".to_owned(), "true".to_owned())]);
2753        assert_eq!(requests[2].timeout, None);
2754    }
2755
2756    #[tokio::test]
2757    async fn tags_channels_and_gives_their_stream_urls() {
2758        let (api, fake) = api_answering(serde_json::json!({"status": "ok"}));
2759        api.add_tag_to_channel("c 1", "t 1").await.unwrap();
2760        api.remove_tag_from_channel("c 1", "t 1").await.unwrap();
2761        api.stop_channel_hls("c 1").await.unwrap();
2762
2763        let requests = fake.requests();
2764        let channel = "/libraries/lib%201/channels/c%201";
2765        assert_sent(
2766            &requests[0],
2767            Method::Post,
2768            &format!("{channel}/tags"),
2769            &[],
2770            Some(serde_json::json!({"tagId": "t 1"})),
2771        );
2772        assert_sent(
2773            &requests[1],
2774            Method::Delete,
2775            &format!("{channel}/tags/t%201"),
2776            &[],
2777            None,
2778        );
2779        assert_sent(
2780            &requests[2],
2781            Method::Delete,
2782            &format!("{channel}/hls"),
2783            &[],
2784            None,
2785        );
2786
2787        // Not an HTTP transport: no URL.
2788        assert!(api.channel_stream_url("c 1", None).await.is_err());
2789        fake.set_base_url("https://host:7080");
2790        let stream = api.channel_stream_url("c 1", None).await.unwrap();
2791        assert_eq!(stream.url, format!("https://host:7080{channel}/stream"));
2792        assert_eq!(stream.authorization(), "Bearer t");
2793        let hls = api.channel_hls_url("c 1", Some("720p")).await.unwrap();
2794        assert_eq!(
2795            hls.with_token_query(),
2796            format!("https://host:7080{channel}/hls/playlist.m3u8?quality=720p&token=t")
2797        );
2798    }
2799
2800    #[tokio::test]
2801    async fn processes_requests_through_plugins() {
2802        let fake = FakeTransport::new(|request| {
2803            Ok(match request.path.as_str() {
2804                "/libraries/lib%201/plugins/requests/process/stream" => {
2805                    FakeTransport::bytes(b"\xff\xd8 jpeg".to_vec())
2806                }
2807                "/libraries/lib%201/plugins/requests/url/sharetoken" => {
2808                    FakeTransport::bytes(b"v4.local.share".to_vec())
2809                }
2810                "/libraries/lib%201/plugins/requests/add" => {
2811                    FakeTransport::json(serde_json::json!({"id": "rp1", "processingId": "42",
2812                        "pluginId": "debrid", "progress": 0, "status": "pending",
2813                        "mediaRef": "m1", "modified": 2, "added": 1}))
2814                }
2815                _ => FakeTransport::json(serde_json::json!({"url": "https://cdn.e.com/f.mkv",
2816                    "status": "finalPublic", "permanent": true, "mime": "video/x-matroska"})),
2817            })
2818        });
2819        let api = LibraryApi::new(client(fake.clone()), library(false));
2820        let request = RsRequest {
2821            url: "https://e.com/f".into(),
2822            ..Default::default()
2823        };
2824        let processed = api.process_request(&request).await.unwrap();
2825        assert_eq!(processed.url, "https://cdn.e.com/f.mkv");
2826        assert_eq!(
2827            processed.status,
2828            rs_plugin_common_interfaces::request::RsRequestStatus::FinalPublic
2829        );
2830        let image = api.process_request_bytes(&request).await.unwrap();
2831        assert_eq!(image, b"\xff\xd8 jpeg");
2832        assert!(
2833            api.check_request_permanent(&request)
2834                .await
2835                .unwrap()
2836                .permanent
2837        );
2838        let task = api.add_request(&request, Some("m1")).await.unwrap();
2839        assert_eq!(task.id, "rp1");
2840        assert_eq!(task.media_ref.as_deref(), Some("m1"));
2841        api.add_request(&request, None).await.unwrap();
2842
2843        let requests = fake.requests();
2844        let plugins = "/libraries/lib%201/plugins/requests";
2845        for (request, rest) in requests
2846            .iter()
2847            .zip(["process", "process/stream", "permanent"])
2848        {
2849            assert_eq!(request.method, Method::Post);
2850            assert_eq!(request.path, format!("{plugins}/{rest}"));
2851            let Some(Body::Json(sent)) = &request.body else {
2852                panic!("no JSON body");
2853            };
2854            assert_eq!(sent["url"], "https://e.com/f");
2855        }
2856        assert_eq!(requests[3].method, Method::Post);
2857        assert_eq!(requests[3].path, format!("{plugins}/add"));
2858        let Some(Body::Json(sent)) = &requests[3].body else {
2859            panic!("no JSON body");
2860        };
2861        assert_eq!(sent["request"]["url"], "https://e.com/f");
2862        assert_eq!(sent["mediaRef"], "m1");
2863        let Some(Body::Json(sent)) = &requests[4].body else {
2864            panic!("no JSON body");
2865        };
2866        assert_eq!(sent["mediaRef"], serde_json::Value::Null);
2867
2868        // Not an HTTP transport: no URL.
2869        assert!(api.request_share_url("https://e.com/f?a=1").await.is_err());
2870        fake.set_base_url("https://host:7080");
2871        assert_eq!(
2872            api.request_share_url("https://e.com/f?a=1").await.unwrap(),
2873            format!(
2874                "https://host:7080{plugins}/url/stream?sharetoken=v4.local.share\
2875                 &url=https%3A%2F%2Fe.com%2Ff%3Fa%3D1"
2876            )
2877        );
2878        let token = fake.requests().pop().unwrap();
2879        assert_sent(
2880            &token,
2881            Method::Get,
2882            &format!("{plugins}/url/sharetoken"),
2883            &[("url", "https://e.com/f?a=1")],
2884            None,
2885        );
2886    }
2887
2888    fn person_json(id: &str, name: &str) -> serde_json::Value {
2889        serde_json::json!({"id": id, "name": name, "socials": null, "portrait": null,
2890            "params": null, "birthday": null, "modified": 2, "added": 1, "posterv": 0,
2891            "generated": false, "type": "Actor"})
2892    }
2893
2894    #[tokio::test]
2895    async fn creates_a_tag() {
2896        let (api, fake) = api_answering(tag_json("t 1", "beach"));
2897        let tag = TagForAdd {
2898            name: "beach".into(),
2899            parent: Some("t0".into()),
2900            alt: Some(vec!["sea".into()]),
2901            ..Default::default()
2902        };
2903        assert_eq!(api.create_tag(&tag).await.unwrap().id, "t 1");
2904
2905        let request = &fake.requests()[0];
2906        assert_eq!(request.method, Method::Post);
2907        assert_eq!(request.path, "/libraries/lib%201/tags");
2908        let Some(Body::Json(sent)) = &request.body else {
2909            panic!("no JSON body");
2910        };
2911        assert_eq!(sent["name"], "beach");
2912        assert_eq!(sent["parent"], "t0");
2913        assert_eq!(sent["alt"], serde_json::json!(["sea"]));
2914        assert_eq!(sent["generated"], false);
2915    }
2916
2917    #[tokio::test]
2918    async fn creates_and_changes_people() {
2919        let (api, fake) = api_answering(person_json("p 1", "Alice"));
2920        let person = PersonForAdd {
2921            name: "Alice".into(),
2922            kind: Some(PersonType::Actor),
2923            birthday: Some(0),
2924            ..Default::default()
2925        };
2926        assert_eq!(api.create_person(&person).await.unwrap().id, "p 1");
2927        let update = PersonForUpdate {
2928            name: Some("Alicia".into()),
2929            add_alts: Some(vec!["Al".into()]),
2930            ..Default::default()
2931        };
2932        let updated = api.update_person("p 1", &update).await.unwrap();
2933        assert_eq!(updated.kind, Some(PersonType::Actor));
2934
2935        let requests = fake.requests();
2936        assert_eq!(requests[0].method, Method::Post);
2937        assert_eq!(requests[0].path, "/libraries/lib%201/people");
2938        let Some(Body::Json(sent)) = &requests[0].body else {
2939            panic!("no JSON body");
2940        };
2941        assert_eq!(sent["name"], "Alice");
2942        assert_eq!(sent["type"], "Actor");
2943        assert_eq!(sent["birthday"], 0);
2944        assert_eq!(requests[1].method, Method::Patch);
2945        assert_eq!(requests[1].path, "/libraries/lib%201/people/p%201");
2946        let Some(Body::Json(sent)) = &requests[1].body else {
2947            panic!("no JSON body");
2948        };
2949        assert_eq!(sent["name"], "Alicia");
2950        assert_eq!(sent["addAlts"], serde_json::json!(["Al"]));
2951        assert_eq!(sent["removeAlts"], serde_json::Value::Null);
2952    }
2953
2954    #[tokio::test]
2955    async fn changes_a_serie() {
2956        let (api, fake) = api_answering(serde_json::json!({"id": "s 1", "name": "Dark",
2957            "modified": 2, "added": 1, "posterv": 0, "backgroundv": 0, "cardv": 0,
2958            "relations": {"tags": [{"id": "t1"}]}}));
2959        let update = SerieForUpdate {
2960            name: Some("Dark".into()),
2961            add_alts: Some(vec!["Dunkel".into()]),
2962            year: Some(2017),
2963            ..Default::default()
2964        };
2965        let updated = api.update_serie("s 1", &update).await.unwrap();
2966        assert_eq!(updated.item.name, "Dark");
2967        assert!(updated.relations.is_some());
2968
2969        let request = &fake.requests()[0];
2970        assert_eq!(request.method, Method::Patch);
2971        assert_eq!(request.path, "/libraries/lib%201/series/s%201");
2972        let Some(Body::Json(sent)) = &request.body else {
2973            panic!("no JSON body");
2974        };
2975        assert_eq!(sent["name"], "Dark");
2976        assert_eq!(sent["addAlts"], serde_json::json!(["Dunkel"]));
2977        assert_eq!(sent["year"], 2017);
2978    }
2979
2980    #[tokio::test]
2981    async fn lists_channels() {
2982        let (api, fake) = api_answering(serde_json::json!([{"id": "c1", "name": "TF1",
2983            "tvgId": "TF1.fr", "country": "FR", "tags": ["t1"], "channelNumber": 1,
2984            "posterv": 2, "modified": 2, "added": 1, "variants": [{"id": "v1",
2985            "channelRef": "c1", "quality": "HD", "streamUrl": "http://e.com/tf1"}]}]));
2986        let query = ChannelQuery {
2987            tag: Some("t1".into()),
2988            limit: Some(100),
2989            offset: Some(200),
2990            ..Default::default()
2991        };
2992        let channels = api.get_channels(&query).await.unwrap();
2993        assert_eq!(channels[0].name, "TF1");
2994        assert_eq!(channels[0].tags, Some(vec!["t1".to_owned()]));
2995        let variants = channels[0].variants.as_ref().unwrap();
2996        assert_eq!(variants[0].quality.as_deref(), Some("HD"));
2997
2998        let request = &fake.requests()[0];
2999        assert_eq!(request.method, Method::Get);
3000        assert_eq!(request.path, "/libraries/lib%201/channels");
3001        let mut sent = request.query.clone();
3002        sent.sort();
3003        let pair = |name: &str, value: &str| (name.to_owned(), value.to_owned());
3004        assert_eq!(
3005            sent,
3006            [
3007                pair("limit", "100"),
3008                pair("offset", "200"),
3009                pair("tag", "t1")
3010            ]
3011        );
3012    }
3013
3014    #[tokio::test]
3015    async fn fetches_images() {
3016        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"\xff\xd8 jpeg".to_vec())));
3017        let api = LibraryApi::new(client(fake.clone()), library(false));
3018        let thumb = ImageRequestOptions {
3019            size: Some(ImageSize::Thumb),
3020            ..Default::default()
3021        };
3022        let backdrop = ImageRequestOptions {
3023            size: Some(ImageSize::Large),
3024            kind: Some(ImageType::Background),
3025            defaulting: true,
3026        };
3027        let original = ImageRequestOptions::default();
3028        assert_eq!(
3029            api.get_serie_image("s 1", &backdrop).await.unwrap(),
3030            b"\xff\xd8 jpeg"
3031        );
3032        api.get_episode_image("s 1", 2, 3, &thumb).await.unwrap();
3033        api.get_movie_image("m 1", &original).await.unwrap();
3034        api.get_book_image("b 1", &thumb).await.unwrap();
3035        api.get_person_image("p 1", &thumb).await.unwrap();
3036        api.get_channel_image("c 1", &thumb).await.unwrap();
3037
3038        let requests = fake.requests();
3039        let sent: Vec<(&str, String)> = requests
3040            .iter()
3041            .map(|request| {
3042                assert_eq!(request.method, Method::Get);
3043                let mut query: Vec<String> = request
3044                    .query
3045                    .iter()
3046                    .map(|(name, value)| format!("{name}={value}"))
3047                    .collect();
3048                query.sort();
3049                (request.path.as_str(), query.join("&"))
3050            })
3051            .collect();
3052        let thumb_query = "defaulting=false&size=thumb".to_owned();
3053        assert_eq!(
3054            sent,
3055            [
3056                (
3057                    "/libraries/lib%201/series/s%201/image",
3058                    "defaulting=true&size=large&type=background".to_owned()
3059                ),
3060                (
3061                    "/libraries/lib%201/series/s%201/seasons/2/episodes/3/image",
3062                    thumb_query.clone()
3063                ),
3064                (
3065                    "/libraries/lib%201/movies/m%201/image",
3066                    "defaulting=false".to_owned()
3067                ),
3068                ("/libraries/lib%201/books/b%201/image", thumb_query.clone()),
3069                ("/libraries/lib%201/people/p%201/image", thumb_query.clone()),
3070                ("/libraries/lib%201/channels/c%201/image", thumb_query),
3071            ]
3072        );
3073
3074        // The server reads no custom size or type from a query.
3075        let custom = ImageRequestOptions {
3076            size: Some(ImageSize::Custom(300)),
3077            ..Default::default()
3078        };
3079        assert!(api.get_movie_image("m 1", &custom).await.is_err());
3080        let custom = ImageRequestOptions {
3081            kind: Some(ImageType::Custom("fanart".into())),
3082            ..Default::default()
3083        };
3084        assert!(api.get_movie_image("m 1", &custom).await.is_err());
3085        assert_eq!(fake.requests().len(), 6);
3086    }
3087
3088    #[tokio::test]
3089    async fn gives_the_url_of_a_channel_logo() {
3090        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
3091        let api = LibraryApi::new(client(fake.clone()), library(false));
3092        let options = ImageRequestOptions {
3093            size: Some(ImageSize::Thumb),
3094            ..Default::default()
3095        };
3096        // Not an HTTP transport: no URL.
3097        assert!(api.channel_image_url("c 1", &options).await.is_err());
3098
3099        fake.set_base_url("https://host:7080");
3100        let logo = api.channel_image_url("c 1", &options).await.unwrap();
3101        let url = url::Url::parse(&logo.url).unwrap();
3102        assert_eq!(url.path(), "/libraries/lib%201/channels/c%201/image");
3103        let mut query: Vec<(String, String)> = url.query_pairs().into_owned().collect();
3104        query.sort();
3105        assert_eq!(
3106            query,
3107            [
3108                ("defaulting".to_owned(), "false".to_owned()),
3109                ("size".to_owned(), "thumb".to_owned())
3110            ]
3111        );
3112        assert_eq!(logo.authorization(), "Bearer t");
3113        assert!(fake.requests().is_empty());
3114    }
3115
3116    fn results_event(data: serde_json::Value) -> Result<RawEvent> {
3117        Ok(RawEvent {
3118            event: "results".into(),
3119            data: data.to_string(),
3120            ..Default::default()
3121        })
3122    }
3123
3124    /// A library on a server whose next event stream gives `events`.
3125    fn api_streaming(events: Vec<Result<RawEvent>>) -> (LibraryApi, Arc<FakeTransport>) {
3126        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(Vec::new())));
3127        fake.set_events(events);
3128        (LibraryApi::new(client(fake.clone()), library(false)), fake)
3129    }
3130
3131    /// The path and the query of the last event stream opened.
3132    fn subscribed(fake: &FakeTransport) -> (String, Vec<(String, String)>) {
3133        let request = fake.subscriptions().pop().unwrap();
3134        assert!(
3135            request
3136                .headers
3137                .contains(&("Authorization".to_owned(), "Bearer t".to_owned()))
3138        );
3139        (request.path, request.query)
3140    }
3141
3142    fn pairs(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
3143        pairs
3144            .iter()
3145            .map(|(name, value)| (name.to_string(), value.to_string()))
3146            .collect()
3147    }
3148
3149    #[tokio::test]
3150    async fn streams_the_results_of_a_movie_search() {
3151        let (api, fake) = api_streaming(vec![
3152            results_event(serde_json::json!({
3153                "sourceId": "plugin-1", "sourceName": "TMDB",
3154                "results": [{
3155                    "metadata": {"movie": {"id": "tmdb:348", "name": "Alien", "type": null,
3156                        "year": 1979, "modified": 0, "added": 0, "posterv": 0,
3157                        "backgroundv": 0, "cardv": 0}},
3158                    "relations": {"tags": [{"id": "t1"}]},
3159                    "matchType": "exactText"
3160                }],
3161                "nextPageKey": "2"
3162            })),
3163            // Not results: left out.
3164            Ok(RawEvent {
3165                event: "other".into(),
3166                data: "{}".into(),
3167                ..Default::default()
3168            }),
3169            // Results that cannot be read: an error, and the stream goes on.
3170            results_event(serde_json::json!({"sourceId": "plugin-2"})),
3171            results_event(serde_json::json!({
3172                "sourceId": "plugin-3", "sourceName": "IMDb", "results": []
3173            })),
3174            Err(Error::transport("connection lost")),
3175        ]);
3176        let lookup = RsLookupMovie {
3177            name: Some("Alien".into()),
3178            people: Some(vec![RsLookupPersonFilter {
3179                name: Some("Ridley Scott".into()),
3180                role: Some(PersonType::Director),
3181                ..Default::default()
3182            }]),
3183            page_key: Some("1".into()),
3184            ..Default::default()
3185        };
3186        let sources = ["plugin-1".to_owned()];
3187        let stream = api.search_movies_stream(&lookup, &sources).await.unwrap();
3188        let items: Vec<_> = stream.collect().await;
3189
3190        assert_eq!(items.len(), 4);
3191        let first = items[0].as_ref().unwrap();
3192        assert_eq!(first.source_id, "plugin-1");
3193        assert_eq!(first.source_name, "TMDB");
3194        assert_eq!(first.data.next_page_key.as_deref(), Some("2"));
3195        let result = &first.data.results[0];
3196        let RsLookupMetadataResult::Movie(movie) = &result.metadata else {
3197            panic!("not a movie");
3198        };
3199        assert_eq!(movie.name, "Alien");
3200        assert_eq!(result.match_type, Some(RsLookupMatchType::ExactText));
3201        assert!(result.relations.is_some());
3202        assert!(items[1].is_err());
3203        let third = items[2].as_ref().unwrap();
3204        assert_eq!(third.source_name, "IMDb");
3205        assert_eq!(third.data.next_page_key, None);
3206        assert!(items[3].is_err());
3207
3208        let (path, query) = subscribed(&fake);
3209        assert_eq!(path, "/libraries/lib%201/movies/searchstream");
3210        assert_eq!(query[0], ("name".to_owned(), "Alien".to_owned()));
3211        assert_eq!(query[1], ("pageKey".to_owned(), "1".to_owned()));
3212        assert_eq!(query[2].0, "filters");
3213        // The filters, as the server reads them: JSON in one parameter.
3214        let filters: serde_json::Value = serde_json::from_str(&query[2].1).unwrap();
3215        assert_eq!(
3216            filters,
3217            serde_json::json!({
3218                "people": [{"name": "Ridley Scott", "role": "Director"}],
3219                "series": null, "tags": null
3220            })
3221        );
3222        assert_eq!(query[3], ("source".to_owned(), "plugin-1".to_owned()));
3223        assert_eq!(query.len(), 4);
3224        assert!(fake.requests().is_empty());
3225    }
3226
3227    #[tokio::test]
3228    async fn searches_series_books_and_people() {
3229        let serie = serde_json::json!({"serie": {"id": "s1", "name": "Dark", "modified": 0,
3230            "added": 0, "posterv": 0, "backgroundv": 0, "cardv": 0}});
3231        let book = serde_json::json!({"book": {"id": "b1", "name": "Dune", "year": 1965,
3232            "modified": 0, "added": 0}});
3233        let person = serde_json::json!({ "person": person_json("p1", "Frank Herbert") });
3234        let event = |metadata: &serde_json::Value| {
3235            vec![results_event(serde_json::json!({
3236                "sourceId": "plugin-1", "sourceName": "Source",
3237                "results": [{"metadata": metadata}]
3238            }))]
3239        };
3240        let (api, fake) = api_streaming(event(&serie));
3241
3242        let lookup = RsLookupSerie {
3243            name: Some("Dark".into()),
3244            ..Default::default()
3245        };
3246        let stream = api.search_series_stream(&lookup, &[]).await.unwrap();
3247        let items: Vec<_> = stream.collect().await;
3248        let found = &items[0].as_ref().unwrap().data.results[0].metadata;
3249        assert!(matches!(found, RsLookupMetadataResult::Serie(serie) if serie.name == "Dark"));
3250        assert_eq!(
3251            subscribed(&fake),
3252            (
3253                "/libraries/lib%201/series/searchstream".to_owned(),
3254                pairs(&[("name", "Dark")])
3255            )
3256        );
3257
3258        fake.set_events(event(&book));
3259        let mut ids = crate::types::rs_ids::RsIds::default();
3260        ids.set("isbn13", "9780441172719");
3261        let lookup = RsLookupBook {
3262            author: Some("Frank Herbert".into()),
3263            ids: Some(ids),
3264            tags: Some(vec![RsLookupTagFilter {
3265                name: Some("Science fiction".into()),
3266                ..Default::default()
3267            }]),
3268            ..Default::default()
3269        };
3270        let sources = ["plugin-1".to_owned(), "plugin-2".to_owned()];
3271        let stream = api.search_books_stream(&lookup, &sources).await.unwrap();
3272        let items: Vec<_> = stream.collect().await;
3273        let found = &items[0].as_ref().unwrap().data.results[0].metadata;
3274        assert!(matches!(found, RsLookupMetadataResult::Book(book) if book.name == "Dune"));
3275        let (path, query) = subscribed(&fake);
3276        assert_eq!(path, "/libraries/lib%201/books/searchstream");
3277        assert_eq!(
3278            query,
3279            pairs(&[
3280                ("author", "Frank Herbert"),
3281                ("isbn13", "9780441172719"),
3282                (
3283                    "filters",
3284                    r#"{"people":null,"series":null,"tags":[{"name":"Science fiction"}]}"#
3285                ),
3286                ("source", "plugin-1,plugin-2"),
3287            ])
3288        );
3289
3290        fake.set_events(event(&person));
3291        let lookup = RsLookupPerson {
3292            name: Some("Frank Herbert".into()),
3293            page_key: Some("2".into()),
3294            ..Default::default()
3295        };
3296        let stream = api.search_people_stream(&lookup, &[]).await.unwrap();
3297        let items: Vec<_> = stream.collect().await;
3298        let found = &items[0].as_ref().unwrap().data.results[0].metadata;
3299        assert!(matches!(found, RsLookupMetadataResult::Person(person) if person.id == "p1"));
3300        assert_eq!(
3301            subscribed(&fake),
3302            (
3303                "/libraries/lib%201/people/searchstream".to_owned(),
3304                pairs(&[("name", "Frank Herbert"), ("pageKey", "2")])
3305            )
3306        );
3307    }
3308
3309    #[tokio::test]
3310    async fn streams_the_files_found_for_a_movie_an_episode_and_a_book() {
3311        // One source's answer, as the server sends it: the downloads, and their
3312        // requests one by one.
3313        let found = || {
3314            vec![
3315                results_event(serde_json::json!({
3316                    "sourceId": "plugin-1", "sourceName": "Indexer",
3317                    "results": [
3318                        {"request": {"url": "https://e.com/a.cd1.mkv", "movie": "m 1"},
3319                            "matchType": "exactId"},
3320                        {"request": {"url": "https://e.com/a.cd2.mkv", "movie": "m 1"},
3321                            "matchType": "exactId"}
3322                    ],
3323                    "downloads": [{
3324                        "group": true,
3325                        "requests": [
3326                            {"url": "https://e.com/a.cd1.mkv", "movie": "m 1"},
3327                            {"url": "https://e.com/a.cd2.mkv", "movie": "m 1"}
3328                        ],
3329                        "infos": {"movie": "m 1"},
3330                        "matchType": "exactId"
3331                    }],
3332                    "nextPageKey": "cursor-2"
3333                })),
3334                results_event(serde_json::json!({
3335                    "sourceId": "plugin-2", "sourceName": "Other",
3336                    "results": [{"request": {"url": "https://e.com/b.mkv"}, "matchType": null}],
3337                    "downloads": [{"group": false, "requests": [{"url": "https://e.com/b.mkv"}]}]
3338                })),
3339            ]
3340        };
3341        let (api, fake) = api_streaming(found());
3342
3343        let stream = api.search_movie_medias_stream("m 1", None, &[], None);
3344        let items: Vec<_> = stream.await.unwrap().collect().await;
3345        assert_eq!(items.len(), 2);
3346        let first = items[0].as_ref().unwrap();
3347        assert_eq!(first.source_name, "Indexer");
3348        assert_eq!(first.next_page_key.as_deref(), Some("cursor-2"));
3349        assert_eq!(first.results.len(), 2);
3350        assert_eq!(first.results[1].request.url, "https://e.com/a.cd2.mkv");
3351        assert_eq!(
3352            first.results[1].match_type,
3353            Some(RsLookupMatchType::ExactId)
3354        );
3355        assert!(first.downloads[0].group);
3356        assert_eq!(first.downloads[0].requests.len(), 2);
3357        let infos = first.downloads[0].infos.as_ref().unwrap();
3358        assert_eq!(infos.movie.as_deref(), Some("m 1"));
3359        let second = items[1].as_ref().unwrap();
3360        assert_eq!(second.results[0].match_type, None);
3361        assert_eq!(second.next_page_key, None);
3362        assert_eq!(
3363            subscribed(&fake),
3364            (
3365                "/libraries/lib%201/movies/m%201/searchstream".to_owned(),
3366                Vec::new()
3367            )
3368        );
3369
3370        // The next results of one source, with another name.
3371        fake.set_events(found());
3372        let sources = ["plugin-1".to_owned()];
3373        let stream = api
3374            .search_episode_medias_stream("s 1", 2, 3, Some("Dark (2017)"), &sources, Some("c2"))
3375            .await
3376            .unwrap();
3377        assert_eq!(stream.collect::<Vec<_>>().await.len(), 2);
3378        assert_eq!(
3379            subscribed(&fake),
3380            (
3381                "/libraries/lib%201/series/s%201/seasons/2/episodes/3/searchstream".to_owned(),
3382                pairs(&[
3383                    ("name", "Dark (2017)"),
3384                    ("pageKey", "c2"),
3385                    ("source", "plugin-1")
3386                ])
3387            )
3388        );
3389
3390        fake.set_events(found());
3391        let stream = api.search_book_medias_stream("b 1", None, &sources, None);
3392        assert_eq!(stream.await.unwrap().collect::<Vec<_>>().await.len(), 2);
3393        assert_eq!(
3394            subscribed(&fake),
3395            (
3396                "/libraries/lib%201/books/b%201/searchstream".to_owned(),
3397                pairs(&[("source", "plugin-1")])
3398            )
3399        );
3400    }
3401
3402    #[tokio::test]
3403    async fn plain_libraries_return_thumbs_as_is() {
3404        let fake = FakeTransport::new(|_| Ok(FakeTransport::bytes(b"jpeg".to_vec())));
3405        let api = LibraryApi::new(client(fake), library(false));
3406        let media = Media {
3407            id: "m1".into(),
3408            ..Default::default()
3409        };
3410        assert_eq!(api.get_thumb(&media).await.unwrap(), b"jpeg");
3411    }
3412
3413    fn answer(status: u16, body: &[u8]) -> crate::transport::Response {
3414        crate::transport::Response {
3415            status,
3416            headers: Vec::new(),
3417            body: body.to_vec(),
3418        }
3419    }
3420
3421    #[test]
3422    fn calls_build_requests_and_read_answers_without_a_transport() {
3423        // A list.
3424        let query = TagQuery {
3425            after: Some(41),
3426            limit: Some(10),
3427            ..Default::default()
3428        };
3429        let call = calls::get_tags("lib 1", &query).unwrap();
3430        assert_sent(
3431            &call.request,
3432            Method::Get,
3433            "/libraries/lib%201/tags",
3434            &[("after", "41"), ("limit", "10")],
3435            None,
3436        );
3437        assert!(
3438            call.request.headers.is_empty(),
3439            "no token in a built request"
3440        );
3441        let body = serde_json::json!([tag_json("t1", "sea")]).to_string();
3442        let tags = call.parse(answer(200, body.as_bytes())).unwrap();
3443        assert_eq!(tags[0].name, "sea");
3444
3445        // An update with a JSON body.
3446        let update = TagForUpdate {
3447            name: Some("beach".into()),
3448            ..Default::default()
3449        };
3450        let call = calls::update_tag("lib 1", "t 1", &update).unwrap();
3451        assert_eq!(call.request.method, Method::Patch);
3452        assert_eq!(call.request.path, "/libraries/lib%201/tags/t%201");
3453        let Some(Body::Json(sent)) = &call.request.body else {
3454            panic!("no JSON body");
3455        };
3456        assert_eq!(sent["name"], "beach");
3457        let body = tag_json("t 1", "beach").to_string();
3458        assert_eq!(
3459            call.parse(answer(200, body.as_bytes())).unwrap().name,
3460            "beach"
3461        );
3462
3463        // Bytes.
3464        let call = calls::get_thumb_raw("lib 1", "m 1");
3465        assert_sent(
3466            &call.request,
3467            Method::Get,
3468            "/libraries/lib%201/medias/m%201/image",
3469            &[("size", "thumb")],
3470            None,
3471        );
3472        assert_eq!(call.parse(answer(200, b"jpeg")).unwrap(), b"jpeg");
3473        assert_eq!(
3474            call.parse(answer(404, b"")).unwrap_err().kind(),
3475            crate::ErrorKind::NotFound
3476        );
3477
3478        // An optional answer.
3479        let call = calls::get_media_by_hash("lib 1", "abc");
3480        assert_sent(
3481            &call.request,
3482            Method::Get,
3483            "/libraries/lib%201/medias/exist",
3484            &[("hash", "abc")],
3485            None,
3486        );
3487        assert!(call.parse(answer(200, b"{}")).unwrap().is_none());
3488        let body = serde_json::json!({ "media": media_json("m1", 5) }).to_string();
3489        let found = call.parse(answer(200, body.as_bytes())).unwrap();
3490        assert_eq!(found.unwrap().item.id, "m1");
3491        let call = calls::get_person("lib 1", "p1");
3492        assert!(call.parse(answer(200, b"null")).unwrap().is_none());
3493
3494        // A page, read with the query's limit and sort.
3495        let query = MediaQuery {
3496            limit: Some(1),
3497            ..Default::default()
3498        };
3499        let call = calls::get_medias_page("lib 1", &query).unwrap();
3500        let body = serde_json::json!([media_json("m1", 5)]).to_string();
3501        let page = call.parse(answer(200, body.as_bytes())).unwrap();
3502        assert_eq!(page.next_page_key.as_deref(), Some("5|m1"));
3503    }
3504
3505    #[test]
3506    fn a_host_adds_the_token_and_sends_again_after_a_refusal() {
3507        let call = calls::get_person("lib 1", "p1");
3508        let first = call.request.clone().bearer("old");
3509        assert!(
3510            first
3511                .headers
3512                .contains(&("Authorization".into(), "Bearer old".into()))
3513        );
3514        let refused = call.parse(answer(401, b"")).unwrap_err();
3515        assert_eq!(refused.kind(), crate::ErrorKind::Unauthorized);
3516        // The same call reads the answer to the request sent again with a new token.
3517        let body = person_json("p1", "Ann").to_string();
3518        let person = call.parse(answer(200, body.as_bytes())).unwrap();
3519        assert_eq!(person.unwrap().name, "Ann");
3520    }
3521}