Skip to main content

redseat_api/
server.rs

1//! Server-wide calls. Port of `@redseat/api` `server.ts`, for the calls the Redseat
2//! apps use.
3
4use std::time::Duration;
5
6use crate::client::RedseatClient;
7use crate::error::Result;
8use crate::library::LibraryApi;
9use crate::transport::Request;
10use crate::types::library::ServerLibraryForRead;
11use crate::types::watched::Watched;
12
13/// Calls on a whole server.
14#[derive(Debug, Clone)]
15pub struct ServerApi {
16    client: RedseatClient,
17}
18
19impl ServerApi {
20    pub fn new(client: RedseatClient) -> Self {
21        ServerApi { client }
22    }
23
24    pub fn client(&self) -> &RedseatClient {
25        &self.client
26    }
27
28    /// The libraries the user can read, as the user sees them: the server leaves out
29    /// `settings` and `root` for libraries the user does not administer.
30    pub async fn get_libraries(&self) -> Result<Vec<ServerLibraryForRead>> {
31        self.client.get_json("/libraries").await
32    }
33
34    /// Checks that the server answers, within `timeout` when given (else the
35    /// transport's own).
36    pub async fn ping(&self, timeout: Option<Duration>) -> Result<()> {
37        let mut request = Request::get("/ping");
38        request.timeout = timeout;
39        self.client.request(request).await?;
40        Ok(())
41    }
42
43    /// What the user watched or read, on all the libraries of the server: one entry
44    /// per movie, episode or book, with its date. An entry's `id` is a history id
45    /// (`movie:imdb/tt0078748`, `episode:imdb/tt0903747/1/2`...), not the id of an
46    /// item of a library.
47    pub async fn get_history(&self) -> Result<Vec<Watched>> {
48        self.client.get_json("/users/me/history").await
49    }
50
51    /// Hides `library` from the user's library lists (`hidden`), or shows it again: a
52    /// preference of the user, kept by the server. The library, and what its other
53    /// users see, do not change; [`ServerLibraryForRead::hidden`] says it in later
54    /// lists.
55    pub async fn set_library_hidden(&self, library: &str, hidden: bool) -> Result<()> {
56        let path = if hidden {
57            "/users/me/hidelibrary"
58        } else {
59            "/users/me/unhidelibrary"
60        };
61        let request = Request::post(path).json(serde_json::json!({ "library": library }));
62        self.client.request(request).await?;
63        Ok(())
64    }
65
66    /// A [`LibraryApi`] for `library`.
67    pub fn library(&self, library: ServerLibraryForRead) -> LibraryApi {
68        LibraryApi::new(self.client.clone(), library)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use crate::client::ClientOptions;
76    use crate::cloud::ServerToken;
77    use crate::test_support::FakeTransport;
78    use crate::transport::{Body, Method};
79    use crate::types::library::LibraryType;
80
81    #[tokio::test]
82    async fn hides_and_shows_a_library_again() {
83        let fake = FakeTransport::new(|_| Ok(FakeTransport::json(serde_json::json!({"ok": true}))));
84        let client = crate::RedseatClient::new(ClientOptions::new(fake.clone()));
85        client.set_token(ServerToken {
86            token: "t".into(),
87            expires: i64::MAX,
88        });
89        let server = ServerApi::new(client);
90        server.set_library_hidden("lib1", true).await.unwrap();
91        server.set_library_hidden("lib1", false).await.unwrap();
92
93        let requests = fake.requests();
94        let body = Some(Body::Json(serde_json::json!({"library": "lib1"})));
95        assert_eq!(requests[0].method, Method::Post);
96        assert_eq!(requests[0].path, "/users/me/hidelibrary");
97        assert_eq!(requests[0].body, body);
98        assert_eq!(requests[1].method, Method::Post);
99        assert_eq!(requests[1].path, "/users/me/unhidelibrary");
100        assert_eq!(requests[1].body, body);
101    }
102
103    #[tokio::test]
104    async fn pings_and_reads_the_history() {
105        let fake = FakeTransport::new(|request| {
106            Ok(FakeTransport::json(match request.path.as_str() {
107                "/ping" => serde_json::json!({"result": {"success": true}}),
108                "/users/me/history" => serde_json::json!([
109                    {"type": "movie", "id": "movie:imdb/tt0078748", "userRef": "u1",
110                     "date": 1700, "modified": 1800}
111                ]),
112                other => panic!("unexpected {other}"),
113            }))
114        });
115        let client = crate::RedseatClient::new(ClientOptions::new(fake.clone()));
116        client.set_token(ServerToken {
117            token: "t".into(),
118            expires: i64::MAX,
119        });
120        let server = ServerApi::new(client);
121        server.ping(None).await.unwrap();
122        server.ping(Some(Duration::from_secs(2))).await.unwrap();
123        let history = server.get_history().await.unwrap();
124        assert_eq!(
125            history[0].kind,
126            rs_plugin_common_interfaces::MediaType::Movie
127        );
128        assert_eq!(history[0].id, "movie:imdb/tt0078748");
129        assert_eq!(history[0].date, 1700);
130
131        let requests = fake.requests();
132        assert_eq!(requests[0].method, Method::Get);
133        assert_eq!(requests[0].path, "/ping");
134        assert_eq!(requests[0].timeout, None);
135        assert_eq!(requests[1].timeout, Some(Duration::from_secs(2)));
136        assert_eq!(requests[2].method, Method::Get);
137        assert_eq!(requests[2].path, "/users/me/history");
138        assert!(requests[2].query.is_empty());
139        assert_eq!(requests[2].body, None);
140    }
141
142    #[tokio::test]
143    async fn reads_libraries_with_and_without_settings() {
144        let fake = FakeTransport::new(|request| {
145            assert_eq!(request.path, "/libraries");
146            Ok(FakeTransport::json(serde_json::json!([
147                {"id": "a", "name": "Photos", "source": "PathProvider", "type": "photos",
148                 "crypt": true, "settings": {}, "roles": ["admin"], "passwordProtected": false},
149                {"id": "b", "name": "Movies", "source": "PathProvider", "type": "movies",
150                 "roles": ["read"], "passwordProtected": false, "hidden": true}
151            ])))
152        });
153        let client = crate::RedseatClient::new(ClientOptions::new(fake));
154        client.set_token(ServerToken {
155            token: "t".into(),
156            expires: i64::MAX,
157        });
158        let libraries = ServerApi::new(client).get_libraries().await.unwrap();
159        assert_eq!(libraries.len(), 2);
160        assert_eq!(libraries[0].crypt, Some(true));
161        assert!(libraries[0].settings.is_some());
162        assert!(libraries[1].settings.is_none());
163        assert_eq!(libraries[1].kind, LibraryType::Movies);
164        assert!(libraries[1].hidden);
165    }
166}