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