redseat-api 0.6.0

Rust client for Redseat media servers
Documentation
//! Server-wide calls. Port of `@redseat/api` `server.ts`, for the calls the Redseat
//! apps use.

use std::time::Duration;

use crate::client::RedseatClient;
use crate::error::Result;
use crate::library::LibraryApi;
use crate::types::library::ServerLibraryForRead;
use crate::types::watched::Watched;

/// Calls on a whole server.
#[derive(Debug, Clone)]
pub struct ServerApi {
    client: RedseatClient,
}

impl ServerApi {
    pub fn new(client: RedseatClient) -> Self {
        ServerApi { client }
    }

    pub fn client(&self) -> &RedseatClient {
        &self.client
    }

    /// The libraries the user can read, as the user sees them: the server leaves out
    /// `settings` and `root` for libraries the user does not administer.
    pub async fn get_libraries(&self) -> Result<Vec<ServerLibraryForRead>> {
        self.client.run(calls::get_libraries()).await
    }

    /// Checks that the server answers, within `timeout` when given (else the
    /// transport's own).
    pub async fn ping(&self, timeout: Option<Duration>) -> Result<()> {
        self.client.run(calls::ping(timeout)).await
    }

    /// What the user watched or read, on all the libraries of the server: one entry
    /// per movie, episode or book, with its date. An entry's `id` is a history id
    /// (`movie:imdb/tt0078748`, `episode:imdb/tt0903747/1/2`...), not the id of an
    /// item of a library.
    pub async fn get_history(&self) -> Result<Vec<Watched>> {
        self.client.run(calls::get_history()).await
    }

    /// Hides `library` from the user's library lists (`hidden`), or shows it again: a
    /// preference of the user, kept by the server. The library, and what its other
    /// users see, do not change; [`ServerLibraryForRead::hidden`] says it in later
    /// lists.
    pub async fn set_library_hidden(&self, library: &str, hidden: bool) -> Result<()> {
        self.client
            .run(calls::set_library_hidden(library, hidden))
            .await
    }

    /// A [`LibraryApi`] for `library`.
    pub fn library(&self, library: ServerLibraryForRead) -> LibraryApi {
        LibraryApi::new(self.client.clone(), library)
    }
}

/// The calls of [`ServerApi`] as [`Call`](crate::Call)s, for a host that sends
/// requests itself (see [`crate::call`]). Their requests carry no token.
pub mod calls {
    use std::time::Duration;

    use crate::call::Call;
    use crate::transport::Request;
    use crate::types::library::ServerLibraryForRead;
    use crate::types::watched::Watched;

    /// [`super::ServerApi::get_libraries`].
    pub fn get_libraries() -> Call<Vec<ServerLibraryForRead>> {
        Call::json(Request::get("/libraries"))
    }

    /// [`super::ServerApi::ping`].
    pub fn ping(timeout: Option<Duration>) -> Call<()> {
        let mut request = Request::get("/ping");
        request.timeout = timeout;
        Call::empty(request)
    }

    /// [`super::ServerApi::get_history`].
    pub fn get_history() -> Call<Vec<Watched>> {
        Call::json(Request::get("/users/me/history"))
    }

    /// [`super::ServerApi::set_library_hidden`].
    pub fn set_library_hidden(library: &str, hidden: bool) -> Call<()> {
        let path = if hidden {
            "/users/me/hidelibrary"
        } else {
            "/users/me/unhidelibrary"
        };
        Call::empty(Request::post(path).json(serde_json::json!({ "library": library })))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::ClientOptions;
    use crate::cloud::ServerToken;
    use crate::test_support::FakeTransport;
    use crate::transport::{Body, Method};
    use crate::types::library::LibraryType;

    #[tokio::test]
    async fn hides_and_shows_a_library_again() {
        let fake = FakeTransport::new(|_| Ok(FakeTransport::json(serde_json::json!({"ok": true}))));
        let client = crate::RedseatClient::new(ClientOptions::new(fake.clone()));
        client.set_token(ServerToken {
            token: "t".into(),
            expires: i64::MAX,
        });
        let server = ServerApi::new(client);
        server.set_library_hidden("lib1", true).await.unwrap();
        server.set_library_hidden("lib1", false).await.unwrap();

        let requests = fake.requests();
        let body = Some(Body::Json(serde_json::json!({"library": "lib1"})));
        assert_eq!(requests[0].method, Method::Post);
        assert_eq!(requests[0].path, "/users/me/hidelibrary");
        assert_eq!(requests[0].body, body);
        assert_eq!(requests[1].method, Method::Post);
        assert_eq!(requests[1].path, "/users/me/unhidelibrary");
        assert_eq!(requests[1].body, body);
    }

    #[tokio::test]
    async fn pings_and_reads_the_history() {
        let fake = FakeTransport::new(|request| {
            Ok(FakeTransport::json(match request.path.as_str() {
                "/ping" => serde_json::json!({"result": {"success": true}}),
                "/users/me/history" => serde_json::json!([
                    {"type": "movie", "id": "movie:imdb/tt0078748", "userRef": "u1",
                     "date": 1700, "modified": 1800}
                ]),
                other => panic!("unexpected {other}"),
            }))
        });
        let client = crate::RedseatClient::new(ClientOptions::new(fake.clone()));
        client.set_token(ServerToken {
            token: "t".into(),
            expires: i64::MAX,
        });
        let server = ServerApi::new(client);
        server.ping(None).await.unwrap();
        server.ping(Some(Duration::from_secs(2))).await.unwrap();
        let history = server.get_history().await.unwrap();
        assert_eq!(
            history[0].kind,
            rs_plugin_common_interfaces::MediaType::Movie
        );
        assert_eq!(history[0].id, "movie:imdb/tt0078748");
        assert_eq!(history[0].date, 1700);

        let requests = fake.requests();
        assert_eq!(requests[0].method, Method::Get);
        assert_eq!(requests[0].path, "/ping");
        assert_eq!(requests[0].timeout, None);
        assert_eq!(requests[1].timeout, Some(Duration::from_secs(2)));
        assert_eq!(requests[2].method, Method::Get);
        assert_eq!(requests[2].path, "/users/me/history");
        assert!(requests[2].query.is_empty());
        assert_eq!(requests[2].body, None);
    }

    #[tokio::test]
    async fn reads_libraries_with_and_without_settings() {
        let fake = FakeTransport::new(|request| {
            assert_eq!(request.path, "/libraries");
            Ok(FakeTransport::json(serde_json::json!([
                {"id": "a", "name": "Photos", "source": "PathProvider", "type": "photos",
                 "crypt": true, "settings": {}, "roles": ["admin"], "passwordProtected": false},
                {"id": "b", "name": "Movies", "source": "PathProvider", "type": "movies",
                 "roles": ["read"], "passwordProtected": false, "hidden": true}
            ])))
        });
        let client = crate::RedseatClient::new(ClientOptions::new(fake));
        client.set_token(ServerToken {
            token: "t".into(),
            expires: i64::MAX,
        });
        let libraries = ServerApi::new(client).get_libraries().await.unwrap();
        assert_eq!(libraries.len(), 2);
        assert_eq!(libraries[0].crypt, Some(true));
        assert!(libraries[0].settings.is_some());
        assert!(libraries[1].settings.is_none());
        assert_eq!(libraries[1].kind, LibraryType::Movies);
        assert!(libraries[1].hidden);
    }
}