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
248
249
250
251
252
253
254
255
256
257
use crate::espocrm_types::Params;
use crate::{debug_if, trace_if};
use hmac::{Hmac, Mac};
use serde::Serialize;
use sha2::Sha256;
use std::fmt::Debug;
use reqwest::{Client, RequestBuilder};
use tap::TapFallible;

type HmacSha256 = Hmac<Sha256>;

/// Used to indicate the required GenericType is not needed
/// Used when calling [request()](EspoApiClient::request) with the GET method
pub type NoGeneric = ();

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method {
    Get,
    Post,
    Put,
    Delete,
}

impl From<Method> for reqwest::Method {
    fn from(a: Method) -> reqwest::Method {
        match a {
            Method::Get => reqwest::Method::GET,
            Method::Post => reqwest::Method::POST,
            Method::Put => reqwest::Method::PUT,
            Method::Delete => reqwest::Method::DELETE,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EspoApiClient {
    pub(crate) url: String,
    pub(crate) username: Option<String>,
    pub(crate) password: Option<String>,
    pub(crate) api_key: Option<String>,
    pub(crate) secret_key: Option<String>,
    pub(crate) url_path: String,
}

impl EspoApiClient {
    /// Create an instance of EspoApiClient.
    pub fn new(url: &str) -> EspoApiClient {
        EspoApiClient {
            url: url.to_string(),
            username: None,
            password: None,
            api_key: None,
            secret_key: None,
            url_path: "/api/v1/".to_string(),
        }
    }

    pub fn build(&self) -> Self {
        self.clone()
    }

    /// Set the URL where EspoCRM is located.
    pub fn set_url<S: AsRef<str>>(&mut self, url: S) -> &mut EspoApiClient {
        let url = url.as_ref();

        let url = if url.ends_with("/") {
            let mut url = url.to_string();
            url.pop();
            url
        } else {
            url.to_string()
        };

        self.url = url;
        self
    }

    /// Set the username to use for authentication.
    /// If you use this you must also call [`Self::set_password()`]
    /// It is not recommended that you use this. Instead you should use API Key authorization or HMAC
    pub fn set_username<S: AsRef<str>>(&mut self, username: S) -> &mut EspoApiClient {
        self.username = Some(username.as_ref().to_string());
        self
    }

    /// Set the password to use for authentication
    /// If you use this you must also call [`Self::set_username()`]
    /// It is not recommended that you use this. Instead you should use API Key authorization or HMAC authorization
    pub fn set_password<S: AsRef<str>>(&mut self, password: S) -> &mut EspoApiClient {
        self.password = Some(password.as_ref().to_string());
        self
    }

    /// Set the API Key to use for authorization
    /// If you only provide the API key, and not the secret_key, API Key authorization will be used.
    /// If you wish to use HMAC authorization, you must also call [`Self::set_secret_key()`]
    pub fn set_api_key<S: AsRef<str>>(&mut self, api_key: S) -> &mut EspoApiClient {
        self.api_key = Some(api_key.as_ref().to_string());
        self
    }

    /// Set the Secret Key to use for HMAC authorization
    /// If you use this you must also call [`Self::set_api_key()`]
    pub fn set_secret_key<S: AsRef<str>>(&mut self, secret_key: S) -> &mut EspoApiClient {
        self.secret_key = Some(secret_key.as_ref().to_string());
        self
    }

    pub(crate) fn normalize_url<S: AsRef<str>>(&self, action: S) -> String {
        format!("{}{}{}", self.url, self.url_path, action.as_ref())
    }

    /// Make a POST request to EspoCRM to create an entity.
    /// This request will skip duplicate checks, which would otherwhise result in a HTTP `409`.
    ///
    /// For information about what the `data` and `action` should be, refer to the [EspoCRM API Documentation](https://docs.espocrm.com/development/).
    ///
    /// # Errors
    ///
    /// If the request fails
    pub async fn create_allow_duplicates<T, S>(&self, action: S, data: T) -> reqwest::Result<reqwest::Response> where T: Serialize + Clone + Debug, S: AsRef<str> {
        let url = self.normalize_url(&action);
        let client = Client::new();
        let mut request = client.post(url);
        request = self.configure_client_auth(request, reqwest::Method::POST, action.as_ref());

        #[allow(unused)] // `x` in the tap_ functions
        request
            .header("X-Skip-Duplicate-Check", "true")
            .json(&data)
            .send()
            .await
            .tap_err(|x| debug_if!("Got an error from EspoCRM: {x}"))
            .tap_ok(|x| debug_if!("Got response from EspoCRM with status code: {}", x.status()))

    }

    /// Make a POST request to EspoCRM to create an entity.
    /// This request will perform duplicate checks and return a HTTP `409` if one is found. If you want to avoid this use [Self::create_allow_duplicates].
    ///
    /// For information about what the `data` and `action` should be, refer to the [EspoCRM API Documentation](https://docs.espocrm.com/development/).
    ///
    /// # Errors
    ///
    /// If the request fails
    pub async fn create<T, S>(&self, action: S, data: T) -> reqwest::Result<reqwest::Response> where T: Serialize + Clone + Debug, S: AsRef<str> {
        let url = self.normalize_url(&action.as_ref());
        let client = Client::new();
        let mut request = client.post(url);
        request = self.configure_client_auth(request, reqwest::Method::POST, action.as_ref());

        #[allow(unused)] // `x` in the tap_ functions
        request
            .json(&data)
            .send()
            .await
            .tap_err(|x| debug_if!("Got an error from EspoCRM: {x}"))
            .tap_ok(|x| debug_if!("Got response from EspoCRM with status code: {}", x.status()))
    }

    /// Make a request to EspoCRM
    /// For more information, see the [EspoCRM API Documentation](https://docs.espocrm.com/development/)
    ///
    /// If you are making a GET request, you will still need to provide a type declaration for T. You can use the type NoGeneric for this.
    ///
    /// * method: The HTTP method to be used. E.g GET or POST
    /// * action: On what EspoCRM Object should the action be performed on. E.g "Contact" or "Contact/ID". Essentially this is everything after "/api/v1/" in the URL.
    /// * data_get: The filter to use on a GET request. Will be serialized according to PHP's http_build_query function.
    /// * data_post: The data to send on everything that is not a GET request. It will be serialized to JSON and send as the request body.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(data_get, data_post)))]
    pub async fn request<T, S>(
        &self,
        method: Method,
        action: S,
        data_get: Option<Params>,
        data_post: Option<T>,
    ) -> reqwest::Result<reqwest::Response>
    where
        T: Serialize + Clone + Debug,
        S: AsRef<str> + Debug,
    {
        let mut url = self.normalize_url(&action.as_ref());
        debug_if!("Using URL {url} to request from EspoCRM");

        let reqwest_method = reqwest::Method::from(method);

        url = if data_get.is_some() && reqwest_method == reqwest::Method::GET {
            format!(
                "{}?{}",
                url,
                crate::serializer::serialize(data_get.unwrap()).unwrap()
            )
        } else {
            url
        };

        let client = Client::new();
        let mut request_builder = client.request(reqwest_method.clone(), url);
        request_builder = self.configure_client_auth(request_builder, reqwest_method.clone(), action.as_ref());

        if data_post.is_some() {
            if reqwest_method != reqwest::Method::GET {
                request_builder = request_builder.json(&data_post.clone().unwrap());
                request_builder = request_builder.header("Content-Type", "application/json");
            }
        }

        trace_if!("Sending request to EspoCRM");
        #[allow(unused)]
        request_builder
            .send()
            .await
            .tap_err(|x| debug_if!("Got an error from EspoCRM: {x}"))
            .tap_ok(|x| debug_if!("Got response from EspoCRM with status code: {}", x.status()))
    }

    fn configure_client_auth(&self, mut request_builder: RequestBuilder, request_method: reqwest::Method, action: &str) -> RequestBuilder {
        //Basic authentication
        if self.username.is_some() && self.password.is_some() {
            trace_if!("Using basic authentication");
            request_builder =
                request_builder.basic_auth(self.username.clone().unwrap(), self.password.clone());

            //HMAC authentication
        } else if self.api_key.is_some() && self.secret_key.is_some() {
            trace_if!("Using HMAC authentication.");

            let str = format!(
                "{} /{}",
                request_method.clone().to_string(),
                action,
            );

            let mut mac = HmacSha256::new_from_slice(self.secret_key.clone().unwrap().as_bytes())
                .expect("Unable to create Hmac instance. Is your key valid?");
            mac.update(str.as_bytes());
            let mac_result = mac.finalize().into_bytes();

            let auth_part = format!(
                "{}{}{}",
                base64::encode(self.api_key.clone().unwrap().as_bytes()),
                "6", //: in base64, for some reason this works, and turning ':' into base64 does not.
                base64::encode(mac_result)
            );

            request_builder = request_builder.header("X-Hmac-Authorization", auth_part);

            //Basic api key authentication
        } else if self.api_key.is_some() {
            trace_if!("Authenticating with an API key");

            request_builder = request_builder.header("X-Api-Key", self.api_key.clone().unwrap());
        }

        request_builder
    }
}