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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! The user-facing API types
//!
//! This module provides a user-facing API for Odoo JSON-RPC methods.
//!
//! ##

pub use client::{AuthState, Authed, NotAuthed, OdooClient, RequestImpl};
pub use closure_async::ClosureResult as AsyncClosureResult;
pub use closure_blocking::ClosureResult as BlockingClosureResult;
pub use request::OdooRequest;

#[allow(clippy::module_inception)]
mod client {
    //! Internal module to make the `client.rs` file more readable

    use super::OdooRequest;
    use crate::jsonrpc::{JsonRpcParams, OdooId, OdooWebMethod};
    use crate::service::web::{SessionAuthenticate, SessionAuthenticateResponse};
    use crate::Result;
    use serde::Serialize;
    use serde_json::{from_str, to_string};
    use std::fmt::Debug;

    /// The "authentication" state of a client object
    ///
    /// This is used to allow API methods to require authentication, e.g., if they
    /// require some piece of auth data (e.g. database, login/uid, etc).
    pub trait AuthState {
        /// Get the current stored `session_id`, if available
        fn get_session_id(&self) -> Option<&str>;
    }

    /// Implemented by "authenticated" clients
    pub struct Authed {
        pub(crate) database: String,
        pub(crate) login: String,
        pub(crate) uid: OdooId,
        pub(crate) password: String,
        pub(crate) session_id: Option<String>,
    }
    impl AuthState for Authed {
        fn get_session_id(&self) -> Option<&str> {
            self.session_id.as_deref()
        }
    }

    /// Implemented by "non-authenticated" clients
    pub struct NotAuthed {}
    impl AuthState for NotAuthed {
        fn get_session_id(&self) -> Option<&str> {
            None
        }
    }

    /// The "request implementation" for a client
    ///
    /// This is used to allow different `client.authenticate()` and
    /// `request.send()` impls based on the chosen request provider.
    pub trait RequestImpl {}

    /// An Odoo API client
    ///
    /// This is the main public interface for the `odoo-api` crate. It provides
    /// methods to authenticate with an Odoo instance, and to call JSON-RPC methods
    /// (`execute`, `create_database`, etc), "Web" methods (`/web/session/authenticate`, etc)
    /// and ORM methods (`read_group`, `create`, etc).
    ///
    /// ## Usage:
    /// ```no_run
    /// use odoo_api::{OdooClient, jvec, jmap};
    ///
    /// # async fn test() -> odoo_api::Result<()> {
    /// let url = "https://demo.odoo.com";
    /// let client = OdooClient::new_reqwest_async(url)?
    ///     .authenticate(
    ///         "test-database",
    ///         "admin",
    ///         "password"
    ///     ).await?;
    ///
    /// let user_ids = client.execute(
    ///     "res.users",
    ///     "search",
    ///     jvec![
    ///         []
    ///     ]
    /// ).send().await?;
    ///
    /// println!("Found user IDs: {:?}", user_ids.data);
    /// # Ok(())
    /// # }
    /// ```
    pub struct OdooClient<S, I>
    where
        S: AuthState,
        I: RequestImpl,
    {
        pub(crate) url: String,
        pub(crate) url_jsonrpc: String,

        pub(crate) auth: S,
        pub(crate) _impl: I,
    }

    // Base client methods
    impl<S, I> OdooClient<S, I>
    where
        S: AuthState,
        I: RequestImpl,
    {
        /// Validate and parse URLs
        ///
        /// We cache the "/jsonrpc" endpoint because that's used across all of
        /// the JSON-RPC methods. We also store the bare URL, because that's
        /// used for "Web" methods
        pub(crate) fn build_urls(url: &str) -> (String, String) {
            let url = url.to_string();
            let url_jsonrpc = format!("{}/jsonrpc", url);

            (url, url_jsonrpc)
        }

        /// Build the data `T` into a request for the fully-qualified endpoint `url`
        ///
        /// This returns an [`OdooRequest`] typed to the Clients (`self`s) [`RequestImpl`],
        /// and to its auth state. The returned request is bound by lifetime `'a` to the client.
        /// The URL is converted into a full String, so no lifetimes apply there.
        pub(crate) fn build_request<'a, T>(&'a self, data: T, url: &str) -> OdooRequest<'a, T, I>
        where
            T: JsonRpcParams + Debug,
            T::Container<T>: Debug + Serialize,
            S: AuthState,
        {
            OdooRequest::new(data.build(), url.into(), self.session_id(), &self._impl)
        }

        /// Helper method to perform the 1st stage of the authentication request
        ///
        /// Implementors of [`RequestImpl`] will use this method to build an
        /// [`OdooRequest`], which they will then send using their own `send()` method.
        ///
        /// This is necessary because each `RequestImpl` has its own `send()` signature
        /// (i.e., some are `fn send()`, some are `async fn send()`).
        pub(crate) fn get_auth_request(
            &self,
            db: &str,
            login: &str,
            password: &str,
        ) -> OdooRequest<SessionAuthenticate, I> {
            let authenticate = crate::service::web::SessionAuthenticate {
                db: db.into(),
                login: login.into(),
                password: password.into(),
            };
            let url_frag = authenticate.describe();

            self.build_request(authenticate, &format!("{}{}", &self.url, url_frag))
        }

        /// Helper method to perform the 2nd stage of the authentication request
        ///
        /// At this point, the [`OdooRequest`] has been sent by the [`RequestImpl`],
        /// and the response data has been fetched and parsed.
        ///
        /// This method extracts the `uid` and `session_id` from the resulting request,
        /// and returns an `OdooClient<Authed, I>`, e.g., an "authenticated" client.
        pub(crate) fn parse_auth_response(
            self,
            db: &str,
            login: &str,
            password: &str,
            response: SessionAuthenticateResponse,
            session_id: Option<String>,
        ) -> Result<OdooClient<Authed, I>> {
            let uid = response
                .data
                .get("uid")
                .ok_or("Failed to parse UID from /web/session/authenticate call")?;
            //TODO: this is a bit awkward..
            let uid = from_str(&to_string(uid)?)?;
            let auth = Authed {
                database: db.into(),
                uid,
                login: login.into(),
                password: password.into(),
                session_id,
            };

            Ok(OdooClient {
                url: self.url,
                url_jsonrpc: self.url_jsonrpc,
                auth,
                _impl: self._impl,
            })
        }

        pub fn session_id(&self) -> Option<&str> {
            self.auth.get_session_id()
        }

        pub fn authenticate_manual(
            self,
            db: &str,
            login: &str,
            uid: OdooId,
            password: &str,
            session_id: Option<String>,
        ) -> OdooClient<Authed, I> {
            let auth = Authed {
                database: db.into(),
                uid,
                login: login.into(),
                password: password.into(),
                session_id,
            };

            OdooClient {
                url: self.url,
                url_jsonrpc: self.url_jsonrpc,
                auth,
                _impl: self._impl,
            }
        }
    }

    /// Methods for non-authenticated clients
    impl<I> OdooClient<NotAuthed, I>
    where
        I: RequestImpl,
    {
        /// Helper method to build a new client
        ///
        /// This isn't exposed via the public API - instead, users will call
        /// one of the impl-specific `new_xx()` functions, like:
        ///  - OdooClient::new_request_blocking()
        ///  - OdooClient::new_request_async()
        ///  - OdooClient::new_closure_blocking()
        ///  - OdooClient::new_closure_async()
        pub(crate) fn new(url: &str, _impl: I) -> Self {
            let (url, url_jsonrpc) = Self::build_urls(url);
            Self {
                url,
                url_jsonrpc,
                auth: NotAuthed {},
                _impl,
            }
        }
    }
}

mod request {
    use super::RequestImpl;
    use crate::jsonrpc::{JsonRpcParams, JsonRpcRequest, JsonRpcResponse};
    use crate::Result;
    use serde::de::DeserializeOwned;
    use serde::Serialize;
    use serde_json::from_str;
    use std::fmt::Debug;

    pub struct OdooRequest<'a, T, I>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
        I: RequestImpl,
    {
        pub(crate) data: JsonRpcRequest<T>,
        pub(crate) url: String,
        pub(crate) session_id: Option<&'a str>,
        pub(crate) _impl: &'a I,
    }

    impl<'a, T, I> OdooRequest<'a, T, I>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
        I: RequestImpl,
    {
        pub(crate) fn new(
            data: JsonRpcRequest<T>,
            url: String,
            session_id: Option<&'a str>,
            _impl: &'a I,
        ) -> Self {
            Self {
                data,
                url,
                session_id,
                _impl,
            }
        }

        pub(crate) fn parse_response<D: Debug + DeserializeOwned>(&self, data: &str) -> Result<D> {
            let response: JsonRpcResponse<D> = from_str(data)?;

            match response {
                JsonRpcResponse::Success(data) => Ok(data.result),
                JsonRpcResponse::Error(data) => Err(data.error.into()),
            }
        }
    }
}

mod closure_blocking {
    use super::{AuthState, Authed, NotAuthed, OdooClient, OdooRequest, RequestImpl};
    use crate::jsonrpc::JsonRpcParams;
    use crate::Result;
    use serde::Serialize;
    use serde_json::{to_value, Value};
    use std::fmt::Debug;

    /// Convenience typedef. Use this as the return value for your blocking closure
    pub type ClosureResult = Result<(String, Option<String>)>;
    type Closure = Box<dyn Fn(&str, Value, Option<&str>) -> ClosureResult>;

    pub struct ClosureBlocking {
        closure: Closure,
    }
    impl RequestImpl for ClosureBlocking {}

    impl OdooClient<NotAuthed, ClosureBlocking> {
        pub fn new_closure_blocking<
            F: Fn(&str, Value, Option<&str>) -> Result<(String, Option<String>)> + 'static,
        >(
            url: &str,
            closure: F,
        ) -> Self {
            Self::new(
                url,
                ClosureBlocking {
                    closure: Box::new(closure),
                },
            )
        }
    }

    impl<S> OdooClient<S, ClosureBlocking>
    where
        S: AuthState,
    {
        pub fn authenticate(
            self,
            db: &str,
            login: &str,
            password: &str,
        ) -> Result<OdooClient<Authed, ClosureBlocking>> {
            let request = self.get_auth_request(db, login, password);
            let (response, session_id) = request.send_internal()?;
            self.parse_auth_response(db, login, password, response, session_id)
        }
    }

    impl<'a, T> OdooRequest<'a, T, ClosureBlocking>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
    {
        pub fn send(self) -> Result<T::Response> {
            Ok(self.send_internal()?.0)
        }

        fn send_internal(self) -> Result<(T::Response, Option<String>)> {
            let data = to_value(&self.data)?;
            let (response, session_id) =
                self._impl.closure.as_ref()(&self.url, data, self.session_id)?;
            Ok((self.parse_response(&response)?, session_id))
        }
    }
}

mod closure_async {
    use super::{AuthState, Authed, NotAuthed, OdooClient, OdooRequest, RequestImpl};
    use crate::jsonrpc::JsonRpcParams;
    use crate::Result;
    use serde::Serialize;
    use serde_json::{to_value, Value};
    use std::fmt::Debug;
    use std::future::Future;
    use std::pin::Pin;

    /// Convenience typedef. Use this as the return value for your async closure
    pub type ClosureResult = Pin<Box<dyn Future<Output = Result<(String, Option<String>)>>>>;
    type Closure = Box<dyn Fn(String, Value, Option<String>) -> ClosureResult>;

    pub struct ClosureAsync {
        closure: Closure,
    }
    impl RequestImpl for ClosureAsync {}

    impl OdooClient<NotAuthed, ClosureAsync> {
        pub fn new_closure_async(
            url: &str,
            closure: impl 'static
                + Fn(
                    String,
                    Value,
                    Option<String>,
                )
                    -> Pin<Box<dyn Future<Output = Result<(String, Option<String>)>>>>,
        ) -> Self {
            Self::new(
                url,
                ClosureAsync {
                    closure: Box::new(closure),
                },
            )
        }
    }

    impl<S> OdooClient<S, ClosureAsync>
    where
        S: AuthState,
    {
        pub async fn authenticate(
            self,
            db: &str,
            login: &str,
            password: &str,
        ) -> Result<OdooClient<Authed, ClosureAsync>> {
            let request = self.get_auth_request(db, login, password);
            let (response, session_id) = request.send_internal().await?;
            self.parse_auth_response(db, login, password, response, session_id)
        }
    }

    impl<'a, T> OdooRequest<'a, T, ClosureAsync>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
    {
        pub async fn send(self) -> Result<T::Response> {
            Ok(self.send_internal().await?.0)
        }

        async fn send_internal(self) -> Result<(T::Response, Option<String>)> {
            let data = to_value(&self.data)?;
            let (response, session_id) = (self._impl.closure)(
                self.url.clone(),
                data,
                self.session_id.map(|s| s.to_string()),
            )
            .await?;
            Ok((self.parse_response(&response)?, session_id))
        }
    }
}

mod reqwest_blocking {
    use super::{AuthState, Authed, NotAuthed, OdooClient, OdooRequest, RequestImpl};
    use crate::jsonrpc::JsonRpcParams;
    use crate::Result;
    use reqwest::blocking::Client;
    use serde::Serialize;
    use std::fmt::Debug;

    pub struct ReqwestBlocking {
        client: Client,
    }
    impl RequestImpl for ReqwestBlocking {}

    impl OdooClient<NotAuthed, ReqwestBlocking> {
        pub fn new_reqwest_blocking(url: &str) -> Result<Self> {
            let client = Client::builder().cookie_store(true).build()?;

            Ok(Self::new(url, ReqwestBlocking { client }))
        }
    }

    impl<S> OdooClient<S, ReqwestBlocking>
    where
        S: AuthState,
    {
        pub fn authenticate(
            self,
            db: &str,
            login: &str,
            password: &str,
        ) -> Result<OdooClient<Authed, ReqwestBlocking>> {
            let request = self.get_auth_request(db, login, password);
            let (response, session_id) = request.send_internal()?;
            self.parse_auth_response(db, login, password, response, session_id)
        }
    }

    impl<'a, T> OdooRequest<'a, T, ReqwestBlocking>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
    {
        pub fn send(self) -> Result<T::Response> {
            Ok(self.send_internal()?.0)
        }

        fn send_internal(self) -> Result<(T::Response, Option<String>)> {
            let request = self._impl.client.post(&self.url).json(&self.data);
            let response = request.send()?;
            Ok((self.parse_response(&response.text()?)?, None))
        }
    }
}

mod reqwest_async {
    use super::{AuthState, Authed, NotAuthed, OdooClient, OdooRequest, RequestImpl};
    use crate::jsonrpc::JsonRpcParams;
    use crate::Result;
    use reqwest::Client;
    use serde::Serialize;
    use std::fmt::Debug;

    pub struct ReqwestAsync {
        client: Client,
    }
    impl RequestImpl for ReqwestAsync {}

    impl OdooClient<NotAuthed, ReqwestAsync> {
        pub fn new_reqwest_async(url: &str) -> Result<Self> {
            let client = Client::builder().cookie_store(true).build()?;

            Ok(Self::new(url, ReqwestAsync { client }))
        }
    }

    impl<S> OdooClient<S, ReqwestAsync>
    where
        S: AuthState,
    {
        pub async fn authenticate(
            self,
            db: &str,
            login: &str,
            password: &str,
        ) -> Result<OdooClient<Authed, ReqwestAsync>> {
            let request = self.get_auth_request(db, login, password);
            let (response, session_id) = request.send_internal().await?;
            self.parse_auth_response(db, login, password, response, session_id)
        }
    }

    impl<'a, T> OdooRequest<'a, T, ReqwestAsync>
    where
        T: JsonRpcParams + Debug + Serialize,
        T::Container<T>: Debug + Serialize,
    {
        pub async fn send(self) -> Result<T::Response> {
            Ok(self.send_internal().await?.0)
        }

        async fn send_internal(self) -> Result<(T::Response, Option<String>)> {
            let request = self._impl.client.post(&self.url).json(&self.data);
            let response = request.send().await?;
            Ok((self.parse_response(&response.text().await?)?, None))
        }
    }
}