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
use std::{collections::HashMap, time::Duration};

use reqwest::{header::HeaderMap, Body, Method, Response};

use crate::{
    auth::Authorization,
    bucket::Bucket,
    config::{Config, SecurityHolder, SignatureType},
    error::ObsError,
};

#[derive(Debug)]
pub struct Client {
    config: Config,
    http_client: reqwest::Client,
}

impl Client {
    /// endpoint 格式: https[http]://obs.cn-north-4.myhuaweicloud.com
    pub fn new<S: ToString>(
        access_key_id: S,
        secret_access_key: S,
        endpoint: &str,
    ) -> Result<Client, ObsError> {
        ClientBuilder::new()
            .security_provider(access_key_id, secret_access_key)
            .endpoint(endpoint)
            .build()
    }

    pub fn security(&self) -> Option<SecurityHolder> {
        if !self.config().security_providers().is_empty() {
            for sh in self.config().security_providers() {
                if !sh.sk().is_empty() && !sh.ak().is_empty() {
                    return Some(sh.clone());
                }
            }
            None
        } else {
            None
        }
    }
    pub fn bucket<'a>(&'a self, name: &'a str) -> Bucket {
        Bucket::new(name, self)
    }

    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    pub fn config(&self) -> &Config {
        &self.config
    }

    pub async fn do_action<T>(
        &self,
        method: Method,
        bucket_name: &str,
        uri: &str,
        with_headers: Option<HeaderMap>,
        body: Option<T>,
    ) -> Result<Response, ObsError>
    where
        T: Into<Body>,
    {
        let url = format!(
            "https://{}.{}/{}",
            bucket_name,
            self.config().endpoint(),
            uri
        );

        let mut auth_headers = HashMap::new();
        let mut headers = if let Some(wh) = with_headers {
            for (k, v) in &wh {
                if let Ok(v) = v.to_str() {
                    auth_headers.insert(k.as_str().to_string(), vec![v.to_string()]);
                }
            }
            wh
        } else {
            HeaderMap::new()
        };

        let canonicalized_url = self.config().canonicalized_url(bucket_name, uri);
        let auth_headers = self.auth(
            method.as_str(),
            bucket_name,
            HashMap::new(),
            auth_headers,
            canonicalized_url,
        )?;
        headers.extend(auth_headers);

        let mut req = self.http_client.request(method, url).headers(headers);

        if let Some(body) = body {
            req = req.body(body);
        }
        let res = req.send().await?;
        Ok(res)
    }

    pub async fn do_action_without_bucket_name<T>(
        &self,
        method: Method,
        uri: &str,
        with_headers: Option<HeaderMap>,
        body: Option<T>,
    ) -> Result<Response, ObsError>
    where
        T: Into<Body>,
    {
        let url = format!("https://{}/{}", self.config().endpoint(), uri);

        let canonicalized_url = self.config().canonicalized_url("", uri);
        let mut headers = self.auth(
            method.as_str(),
            "",
            HashMap::new(),
            HashMap::new(),
            canonicalized_url,
        )?;
        if let Some(wh) = with_headers {
            headers.extend(wh);
        }

        let mut req = self.http_client.request(method, url).headers(headers);

        if let Some(body) = body {
            req = req.body(body);
        }
        let res = req.send().await?;
        Ok(res)
    }
}

#[derive(Debug)]
pub struct ClientBuilder {
    config: Config,
}

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

impl ClientBuilder {
    fn new() -> ClientBuilder {
        ClientBuilder {
            config: Config {
                security_providers: vec![],
                endpoint: "".into(),
                is_secure: false,
                region: "".into(),
                timeout: Duration::from_secs(3),
                signature_type: SignatureType::V2,
            },
        }
    }
    pub fn signature_type(mut self, st: SignatureType) -> ClientBuilder {
        self.config.set_signature_type(st);
        self
    }

    pub fn security_providers(mut self, sps: Vec<SecurityHolder>) -> ClientBuilder {
        self.config.set_security_providers(sps);
        self
    }

    /// 节点,支持以下三种格式:
    ///
    /// 1. http://your-endpoint
    /// 2. https://your-endpoint
    /// 3. your-endpoint
    pub fn endpoint<S: ToString>(mut self, value: S) -> ClientBuilder {
        let mut value = value.to_string();
        if value.starts_with("https://") {
            value = value.replace("https://", "");
        } else if value.starts_with("http://") {
            value = value.replace("http://", "");
        }
        self.config.set_endpoint(value);
        self
    }

    pub fn security_provider<S: ToString>(mut self, ak: S, sk: S) -> ClientBuilder {
        self.config.security_providers.push(SecurityHolder::new(
            ak.to_string(),
            sk.to_string(),
            "".to_string(),
        ));
        self
    }

    pub fn timeout(mut self, duration: Duration) -> ClientBuilder {
        self.config.set_timeout(duration);
        self
    }

    pub fn region<S: ToString>(mut self, value: S) -> ClientBuilder {
        self.config.set_region(value.to_string());
        self
    }

    pub fn is_secure(mut self, value: bool) -> ClientBuilder {
        self.config.set_is_secure(value);
        self
    }

    pub fn build(self) -> Result<Client, ObsError> {
        let req_client = reqwest::ClientBuilder::new()
            .timeout(self.config.timeout())
            .build();
        Ok(Client {
            config: self.config,
            http_client: req_client?,
        })
    }
}