Skip to main content

redseat_api/
server.rs

1//! Server-wide calls. Port of the start of `@redseat/api` `server.ts`.
2
3use crate::client::RedseatClient;
4use crate::error::Result;
5use crate::library::{LibraryApi, library_from_json};
6use crate::types::library::ServerLibrary;
7
8/// Calls on a whole server.
9#[derive(Debug, Clone)]
10pub struct ServerApi {
11    client: RedseatClient,
12}
13
14impl ServerApi {
15    pub fn new(client: RedseatClient) -> Self {
16        ServerApi { client }
17    }
18
19    pub fn client(&self) -> &RedseatClient {
20        &self.client
21    }
22
23    /// The libraries the user can read.
24    ///
25    /// The server leaves out `settings` and `root` for libraries the user does not
26    /// administer: those read as default settings and no root.
27    pub async fn get_libraries(&self) -> Result<Vec<ServerLibrary>> {
28        let values: Vec<serde_json::Value> = self.client.get_json("/libraries").await?;
29        values.into_iter().map(library_from_json).collect()
30    }
31
32    /// A [`LibraryApi`] for `library`.
33    pub fn library(&self, library: ServerLibrary) -> LibraryApi {
34        LibraryApi::new(self.client.clone(), library)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use crate::client::ClientOptions;
42    use crate::cloud::ServerToken;
43    use crate::test_support::FakeTransport;
44    use crate::types::library::LibraryType;
45
46    #[tokio::test]
47    async fn reads_libraries_with_and_without_settings() {
48        let fake = FakeTransport::new(|request| {
49            assert_eq!(request.path, "/libraries");
50            Ok(FakeTransport::json(serde_json::json!([
51                {"id": "a", "name": "Photos", "source": "PathProvider", "type": "photos",
52                 "crypt": true, "settings": {}, "roles": ["admin"], "passwordProtected": false},
53                {"id": "b", "name": "Movies", "source": "PathProvider", "type": "movies",
54                 "roles": ["read"], "passwordProtected": false, "hidden": true}
55            ])))
56        });
57        let client = crate::RedseatClient::new(ClientOptions::new(fake));
58        client.set_token(ServerToken {
59            token: "t".into(),
60            expires: i64::MAX,
61        });
62        let libraries = ServerApi::new(client).get_libraries().await.unwrap();
63        assert_eq!(libraries.len(), 2);
64        assert_eq!(libraries[0].crypt, Some(true));
65        assert_eq!(libraries[1].kind, LibraryType::Movies);
66        assert!(libraries[1].hidden);
67    }
68}