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