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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::rc::Rc;

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::cross_platform_http_client::{Body, CurrentPlatformClient, HttpClient};
use crate::error::WildlandHttpClientError;
use crate::response_handler::check_status_code;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConfirmTokenReq {
    pub session_id: String,
    pub email: String,
    pub verification_token: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GetStorageReq {
    pub session_id: Option<String>,
    pub email: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StorageCredentials {
    pub id: Uuid,
    #[serde(rename = "credentialID")]
    pub credential_id: String,
    #[serde(rename = "credentialSecret")]
    pub credential_secret: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "state")]
pub enum GetStorageRes {
    #[serde(rename = "started")]
    Started { session_id: String },
    #[serde(rename = "ongoing")]
    Ongoing,
    #[serde(rename = "finished")]
    Finished { template: serde_json::Value },
}

impl GetStorageRes {
    pub fn state(&self) -> &str {
        match self {
            GetStorageRes::Started { .. } => "started",
            GetStorageRes::Ongoing => "ongoing",
            GetStorageRes::Finished { .. } => "finished",
        }
    }
}

#[derive(Clone)]
pub struct EvsClient {
    http_client: Rc<dyn HttpClient>,
    base_url: String,
}

impl EvsClient {
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn new(base_url: String) -> Self {
        let http_client = Rc::new(CurrentPlatformClient {});

        Self {
            http_client,
            base_url,
        }
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn confirm_token(&self, request: ConfirmTokenReq) -> Result<(), WildlandHttpClientError> {
        let request = http::Request::put(format!("{}/confirm_token", self.base_url))
            .body(Body::json(request))?;
        let response = self.http_client.send(request)?;
        check_status_code(response)?;
        Ok(())
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn get_storage(
        &self,
        request: GetStorageReq,
    ) -> Result<GetStorageRes, WildlandHttpClientError> {
        let request = http::Request::put(format!("{}/get_storage", self.base_url))
            .body(Body::json(request))?;

        let response = self.http_client.send(request)?;
        check_status_code(response)?
            .map(|body| serde_json::from_slice(&body))
            .into_body()
            .map_err(Into::into)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::cross_platform_http_client::MockHttpClient;
    use crate::evs::constants::test_utilities::{EMAIL, VERIFICATION_TOKEN};

    #[test]
    fn should_confirm_token() {
        let mut http_client = Box::new(MockHttpClient::new());

        let request = ConfirmTokenReq {
            email: EMAIL.into(),
            verification_token: VERIFICATION_TOKEN.into(),
            session_id: "some uuid".to_string(),
        };

        let http_request = http::Request::put("/confirm_token")
            .body(Body::json(request.clone()))
            .unwrap();

        http_client
            .as_mut()
            .expect_send()
            .withf(move |request| {
                request.method() == http_request.method()
                    && request.uri() == http_request.uri()
                    && request.headers() == http_request.headers()
                    && request.body() == http_request.body()
            })
            .times(1)
            .returning(|_| {
                Ok(http::Response::builder()
                    .status(200)
                    .body(Vec::default())
                    .unwrap())
            });

        let response = EvsClient {
            http_client: Rc::from(http_client as Box<_>),
            base_url: "".into(),
        }
        .confirm_token(request);

        assert!(response.is_ok());
    }

    #[test]
    fn should_get_storage() {
        let mut http_client = Box::new(MockHttpClient::new());

        let request = GetStorageReq {
            email: EMAIL.into(),
            session_id: Some("some uuid".to_string()),
        };

        let http_request = http::Request::put("/get_storage")
            .body(Body::json(request.clone()))
            .unwrap();

        let expected_template = json!({
            "login": "bar",
            "credentials": "foo",
        });

        http_client
            .as_mut()
            .expect_send()
            .withf(move |request| {
                request.method() == http_request.method()
                    && request.uri() == http_request.uri()
                    && request.headers() == http_request.headers()
                    && request.body() == http_request.body()
            })
            .times(1)
            .returning({
                let expected_template = expected_template.clone();
                move |_| {
                    Ok(http::Response::builder()
                        .status(200)
                        .body(
                            serde_json::to_vec(&serde_json::json!(
                                {
                                    "state": "finished",
                                    "template": expected_template,
                                }
                            ))
                            .unwrap(),
                        )
                        .unwrap())
                }
            });

        if let GetStorageRes::Finished { template } = (EvsClient {
            http_client: Rc::from(http_client as Box<_>),
            base_url: "".into(),
        })
        .get_storage(request)
        .unwrap()
        {
            assert_eq!(template, expected_template);
        } else {
            panic!("invalid enum variant");
        }
    }
}