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