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
use async_trait::async_trait;

use crate::Version;
use super::timeouts::Timeouts;
use super::clients::{ClientAuth, ClientCore, Xnat};

/// A building pattern type meant for constructing
/// an XNAT client.
#[allow(dead_code)]
pub struct XnatBuilder<V: Version> {
    hostname:   String,
    password:   Option<String>,
    timeouts:   Option<Timeouts>,
    username:   Option<String>,
    use_secure: bool,
    version:    Option<V>,
}

/// Internal usage only. Dictates how a URL should
/// be constructed.
enum UrlKind<'a> {
    Basic,
    Credentialed(&'a str, Option<&'a str>),
}

impl<V: Version + Clone> XnatBuilder<V> {
    fn base_url(&self, kind: UrlKind) -> anyhow::Result<reqwest::Url> {
        let mut host = reqwest::Url::parse("http://stud")?;
        host.set_host(Some(&self.hostname.clone()))?;
        host.set_scheme(if self.use_secure {
            "https"
        } else {
            "http"
        }).unwrap();

        Ok(match kind {
            UrlKind::Basic => host,
            UrlKind::Credentialed(u, p) => {
                host.set_password(p).unwrap();
                host.set_username(u).unwrap();
                host
            }
        })
    }

    fn credentials(&self) -> UrlKind {
        UrlKind::Credentialed(
            self.username.as_deref().unwrap(),
            self.password.as_deref()
        )
    }

    fn version(&self) -> anyhow::Result<V> {
        Ok(self.version.as_ref().cloned().unwrap())
    }
}

/// Core methods required by all subsequent
/// client building traits.
pub trait ClientBuilderCore {
    type Client;

    /// Attempt to build a client from this
    /// builder.
    /// 
    /// ```no_compile
    /// use oxinat_core::*;
    /// 
    /// #[derive(Clone, Version, FullUri)]
    /// #[version(root_uri = "xapi", data_uri = "data")]
    /// struct MyVersion;
    /// 
    /// let builder = XnatBuilder::new("xnat.host.org")
    ///     .with_version(MyVersion)
    ///     .with_password("my-password")
    ///     .with_username("my-username");
    /// ```
    fn build(&self) -> anyhow::Result<Self::Client>;
    /// Initialize a new builder instance.
    fn new(hostname: &str) -> Self;
}

impl<V: Version + Clone> ClientBuilderCore for XnatBuilder<V> {
    type Client = Xnat<V>;

    fn build(&self) -> anyhow::Result<Self::Client> {
        Ok(Xnat::new(
            &self.base_url(UrlKind::Basic)?,
            &self.timeouts,
            self.use_secure,
            &self.version()?,
        ))
    }

    fn new(hostname: &str) -> Self {
        XnatBuilder{
            hostname:   hostname.to_owned(),
            password:   None,
            timeouts:   None,
            username:   None,
            use_secure: false,
            version:    None
        }
    }
}

/// Trait dictates the methods used to customize
/// how the resulting clients are constructed.
pub trait ClientBuilderAttrs: ClientBuilderCore {
    type Version: Version + Clone;

    /// Set whether constructed clients should
    /// use secure protocols and verify SSL certs.
    fn use_secure(self, value: bool) -> Self;
    /// Set the host name that will be assigned
    /// to constructed clients.
    fn with_hostname(self, hostname: &str) -> Self;
    /// Set the auth password to be used for
    /// token acquisition for constructed clients.
    fn with_password(self, password: &str) -> Self;
    /// Set the timeout values (connect & read) to
    /// be assigned to constructed clients.
    fn with_timeouts(self, timeouts: &Timeouts) -> Self;
    /// Set the auth username to be used for
    /// token acquisition for constructed clients.
    fn with_username(self, username: &str) -> Self;
    /// Set the API version representation to be
    /// assigned to constructed clients.
    fn with_version(self, version: Self::Version) -> Self;
}

impl<V: Version + Clone> ClientBuilderAttrs for XnatBuilder<V> {
    type Version = V;

    fn use_secure(mut self, value: bool) -> Self {
        self.use_secure = value;
        self
    }

    fn with_hostname(mut self, hostname: &str) -> Self {
        hostname.clone_into(&mut self.hostname);
        self
    }

    fn with_password(mut self, password: &str) -> Self {
        self.password.clone_from(&Some(password.to_owned()));
        self
    }

    fn with_timeouts(mut self, timeouts: &Timeouts) -> Self {
        self.timeouts.clone_from(&Some(timeouts.to_owned()));
        self
    }

    fn with_username(mut self, username: &str) -> Self {
        self.username.clone_from(&Some(username.to_owned()));
        self
    }

    fn with_version(mut self, version: Self::Version) -> Self {
        self.version = Some(version);
        self
    }
}

#[async_trait(?Send)]
pub trait ClientBuilderToken: ClientBuilderCore
where
    Self::Client: ClientAuth,
{
    /// Brokers the acquisition of a `token` via
    /// user authentication when constructing a
    /// new client.
    /// 
    /// ```no_compile
    /// use oxinat_core::*;
    /// 
    /// #[derive(Clone, Version, FullUri)]
    /// #[version(root_uri = "xapi", data_uri = "data")]
    /// struct MyVersion;
    /// 
    /// let builder = XnatBuilder::new("xnat.host.org")
    ///     .with_version(MyVersion)
    ///     .with_password("my-password")
    ///     .with_username("my-username");
    /// 
    /// let client = builder.acquire().await?;
    /// ```
    async fn acquire(&self) -> anyhow::Result<Self::Client>;
}

#[async_trait(?Send)]
impl<V: Version + Clone> ClientBuilderToken for XnatBuilder<V>
where
    Self::Client: ClientAuth,
{
    async fn acquire(&self) -> anyhow::Result<Self::Client> {
        let mut client = self.build()?;
        let mut base_url = self.base_url(self.credentials())?;
        base_url.set_path(&client.auth_uri()?);

        let res = client
            .client()?
            .post(base_url)
            .send()
            .await?;

        super::clients::tokacq_validator(res)
            .await
            .map(|token| {
                client.set_session_id(&token);
                client
            })
    }
}