Skip to main content

redseat_api/
library.rs

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