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