1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use crate::clients::common::*;
use crate::divoom_contracts::divoom::*;
use crate::dto::*;
use std::time::Duration;

use serde::de::DeserializeOwned;
use serde::Serialize;

/// Divoom backend service client
///
/// This is the client that talks to Divoom online service for fetching information like device info in the same LAN etc.
///
/// It is very simple to start using it, simply creates the client without argument, and then start calling the APIs:
///
/// ```rust
/// use divoom::*;
/// let divoom = DivoomServiceClient::new();
/// // let devices = divoom.get_same_lan_devices().await?;
/// // devices.iter().for_each(|x| println!("{:?}", x));
/// ```
pub struct DivoomServiceClient {
    client: DivoomRestAPIClient,
}

impl Default for DivoomServiceClient {
    fn default() -> Self {
        DivoomServiceClient::new()
    }
}

impl DivoomServiceClient {
    /// Create new DivoomServiceClient
    pub fn new() -> DivoomServiceClient {
        DivoomServiceClient::with_options(None)
    }

    /// Create new DivoomServiceClient with options
    pub fn with_options(timeout: Option<Duration>) -> DivoomServiceClient {
        DivoomServiceClient::with_server_url_base("https://app.divoom-gz.com".into(), timeout)
    }

    /// Create new DivoomServiceClient with specific server URL
    pub fn with_server_url_base(
        server_url_base: String,
        timeout: Option<Duration>,
    ) -> DivoomServiceClient {
        DivoomServiceClient {
            client: DivoomRestAPIClient::new(server_url_base, timeout),
        }
    }

    /// Get the server url we send request to
    pub fn server_url_base(&self) -> &str {
        &self.client.server_url_base
    }

    #[doc = include_str!("../../divoom_contracts/divoom/api_return_same_lan_device.md")]
    pub async fn get_same_lan_devices(&self) -> DivoomAPIResult<Vec<DivoomDeviceInfo>> {
        self.send_request::<DivoomAPIResponseReturnSameLANDevice, Vec<DivoomDeviceInfo>>(
            DIVOOM_SERVICE_API_URL_RETURN_SAME_LAN_DEVICE,
        )
        .await
    }

    #[doc = include_str!("../../divoom_contracts/divoom/api_get_clock_type.md")]
    pub async fn get_clock_type(&self) -> DivoomAPIResult<Vec<String>> {
        self.send_request::<DivoomAPIResponseGetClockType, Vec<String>>(
            DIVOOM_SERVICE_API_URL_CHANNEL_GET_DIAL_TYPE,
        )
        .await
    }

    #[doc = include_str!("../../divoom_contracts/divoom/api_get_clock_list.md")]
    pub async fn get_clock_list(
        &self,
        dial_type: String,
        page_index: i32,
    ) -> DivoomAPIResult<DivoomClockInfoPage> {
        let request_body = DivoomAPIRequestGetClockList {
            dial_type,
            page: page_index,
        };
        self.send_read_request_with_body::<DivoomAPIRequestGetClockList, DivoomAPIResponseGetClockList, DivoomClockInfoPage>(
            DIVOOM_SERVICE_API_URL_GET_DIAL_LIST,
            request_body,
        )
        .await
    }

    #[doc = include_str!("../../divoom_contracts/divoom/api_get_dial_font_list.md")]
    pub async fn get_font_list(&self) -> DivoomAPIResult<Vec<DivoomFontInfo>> {
        self.send_request::<DivoomAPIResponseGetTimeDialFontList, Vec<DivoomFontInfo>>(
            DIVOOM_SERVICE_API_URL_GET_TIME_DIAL_FONT_LIST,
        )
        .await
    }

    async fn send_request<TResp: DeserializeOwned + DivoomServiceAPIResponseWithPayload<R>, R>(
        &self,
        url_path: &str,
    ) -> DivoomAPIResult<R> {
        let response: TResp = self.client.send_request(url_path).await?;
        self.check_divoom_api_result_code(response.result_details())?;
        let result = response.destructive_into();
        Ok(result)
    }

    async fn send_read_request_with_body<
        TReq: Serialize,
        TResp: DeserializeOwned + DivoomServiceAPIResponseWithPayload<R>,
        R,
    >(
        &self,
        url_path: &str,
        request_body: TReq,
    ) -> DivoomAPIResult<R> {
        let request_body_text = serde_json::to_string(&request_body)?;
        let response: TResp = self
            .client
            .send_request_with_body(url_path, request_body_text)
            .await?;
        self.check_divoom_api_result_code(response.result_details())?;
        let result = response.destructive_into();
        Ok(result)
    }

    fn check_divoom_api_result_code(
        &self,
        result_code: &DivoomServiceAPIResultDetails,
    ) -> DivoomAPIResult<()> {
        if result_code.return_code == 0 {
            Ok(())
        } else {
            Err(DivoomAPIError::ServerError(DivoomServerErrorInfo {
                http_status_code: reqwest::StatusCode::OK.as_u16(),
                error_code: result_code.return_code,
                error_message: result_code.return_message.clone(),
            }))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn divoom_service_should_have_default_server_url_base() {
        let divoom = DivoomServiceClient::new();
        assert_eq!(divoom.server_url_base(), "https://app.divoom-gz.com");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 5)]
    async fn divoom_service_should_get_same_lan_devices() {
        let _m = mockito::mock("POST", DIVOOM_SERVICE_API_URL_RETURN_SAME_LAN_DEVICE)
            .with_status(200)
            .with_header("Content-Type", "application/json; charset=UTF-8")
            .with_header("Server", "nginx")
            .with_body("{\"ReturnCode\":0,\"ReturnMessage\":\"\",\"DeviceList\":[{\"DeviceName\":\"Pixoo\",\"DeviceId\":300000001,\"DevicePrivateIP\":\"192.168.0.2\"}]}")
            .create();

        let divoom = DivoomServiceClient::with_server_url_base(mockito::server_url(), None);
        let devices = divoom.get_same_lan_devices().await.unwrap();
        assert_eq!(
            devices,
            vec![DivoomDeviceInfo {
                device_name: "Pixoo".into(),
                device_id: 300000001,
                device_private_ip: "192.168.0.2".into()
            }]
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 5)]
    async fn divoom_service_should_get_dial_type() {
        let _m = mockito::mock("POST", DIVOOM_SERVICE_API_URL_CHANNEL_GET_DIAL_TYPE)
            .with_status(200)
            .with_header("Content-Type", "application/json; charset=UTF-8")
            .with_header("Server", "nginx")
            .with_body("{\"ReturnCode\":0,\"ReturnMessage\":\"\",\"DialTypeList\":[\"Social\",\"financial\",\"Game\",\"normal\",\"HOLIDAYS\",\"TOOLS\",\"Sport\",\"Custom\",\"self\"]}")
            .create();

        let divoom = DivoomServiceClient::with_server_url_base(mockito::server_url(), None);
        let devices = divoom.get_clock_type().await.unwrap();
        assert_eq!(
            devices,
            vec![
                "Social",
                "financial",
                "Game",
                "normal",
                "HOLIDAYS",
                "TOOLS",
                "Sport",
                "Custom",
                "self"
            ]
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 5)]
    async fn divoom_service_should_get_dial_list() {
        let _m = mockito::mock("POST", DIVOOM_SERVICE_API_URL_GET_DIAL_LIST)
            .with_status(200)
            .with_header("Content-Type", "application/json; charset=UTF-8")
            .with_header("Server", "nginx")
            .with_body("{ \"ReturnCode\": 0, \"ReturnMessage\": \"\", \"TotalNum\": 100, \"DialList\": [ { \"ClockId\": 10, \"Name\": \"Classic Digital Clock\" } ]}")
            .create();

        let divoom = DivoomServiceClient::with_server_url_base(mockito::server_url(), None);
        let devices = divoom.get_clock_list("Social".into(), 1).await.unwrap();
        assert_eq!(
            devices,
            DivoomClockInfoPage {
                total_num: 100,
                dial_list: vec![DivoomClockInfo {
                    clock_id: 10,
                    name: "Classic Digital Clock".to_string()
                }]
            }
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 5)]
    async fn divoom_service_should_get_font_list() {
        let _m = mockito::mock("POST", DIVOOM_SERVICE_API_URL_GET_TIME_DIAL_FONT_LIST)
            .with_status(200)
            .with_header("Content-Type", "application/json; charset=UTF-8")
            .with_header("Server", "nginx")
            .with_body("{\"ReturnCode\":0,\"ReturnMessage\":\"\",\"FontList\":[{\"id\":2,\"name\":\"16*16 English letters, Arabic figures,punctuation\",\"width\":\"16\",\"high\":\"16\",\"charset\":\"\",\"type\":0}]}")
            .create();

        let divoom = DivoomServiceClient::with_server_url_base(mockito::server_url(), None);
        let devices = divoom.get_font_list().await.unwrap();
        assert_eq!(
            devices,
            vec![DivoomFontInfo {
                id: 2,
                name: "16*16 English letters, Arabic figures,punctuation".to_string(),
                width: 16,
                height: 16,
                charset: "".to_string(),
                font_type: DivoomFontType::Scrollable
            }]
        );
    }
}