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
use anyhow::{anyhow, Result};
use base64::Engine;
use base64::engine::general_purpose;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use tracing::debug;
use crate::oss::{API, OSS, OSSInfo};
use crate::request::{RequestBuilder, RequestType, Seconds};
use crate::util::read_file;

pub trait ObjectAPI {
    /// 获取对象
    ///
    /// # 使用例子
    ///
    /// ```rust
    /// use aliyun_oss_rust_sdk::object::ObjectAPI;
    /// use aliyun_oss_rust_sdk::oss::OSS;
    /// use aliyun_oss_rust_sdk::request::RequestBuilder;
    /// let oss = OSS::from_env();
    /// let build = RequestBuilder::new();
    /// let bytes = oss.get_object("/hello.txt", build).unwrap();
    /// println!("file content: {}", String::from_utf8_lossy(bytes.as_slice()));
    /// ```
    fn get_object<S: AsRef<str>>(
        &self,
        key: S,
        build: &RequestBuilder,
    ) -> Result<Vec<u8>>;

    /// 获取上传对象的policy
    /// # 使用例子
    /// ```rust
    /// use aliyun_oss_rust_sdk::object::{ObjectAPI, PolicyBuilder};
    /// use aliyun_oss_rust_sdk::oss::OSS;
    /// let oss = OSS::from_env();
    /// let policy_builder = PolicyBuilder::new()
    ///             .with_expire(60 * 60)//1个小时过期
    ///             .with_upload_dir("upload/mydir/")//上传目录
    ///             .with_content_type("text/plain")//只允许上传文本.txt
    ///            .with_max_upload_size(100 * 1024 * 1024);//只允许文件上传大小1G以内
    /// let policy = oss.get_upload_object_policy(&policy_builder).unwrap();
    /// println!("policy: {:?}", policy);
    /// //使用postman测试上传
    /// //form-data的参数为OSSAccessKeyId、policy、signature、success_action_status、key、file
    /// //key为上传的文件名包含路径、例如:upload/mydir/test.txt
    /// //file为上传的文件,类型跟with_content_type一致
    /// ```
    fn get_upload_object_policy(&self, build: &PolicyBuilder) -> Result<PolicyResp>;


    /// 上传文件(本地文件)
    /// # 使用例子
    /// ```rust
    /// use aliyun_oss_rust_sdk::object::ObjectAPI;
    /// use aliyun_oss_rust_sdk::oss::OSS;
    /// use aliyun_oss_rust_sdk::request::RequestBuilder;
    /// let oss = OSS::from_env();
    /// let builder = RequestBuilder::new()
    ///     .with_expire(60);
    /// let file_path = "./hello.txt";
    /// oss.put_object_from_file("/hello.txt", file_path, &builder).unwrap();
    /// ```
    fn put_object_from_file<S: AsRef<str>>(
        &self,
        key: S,
        file_path: S,
        build: &RequestBuilder,
    ) -> Result<()>;

    /// 上传文件(内存)
    /// # 使用例子
    /// ```rust
    /// use aliyun_oss_rust_sdk::object::ObjectAPI;
    /// use aliyun_oss_rust_sdk::oss::OSS;
    /// use aliyun_oss_rust_sdk::request::RequestBuilder;
    /// let oss = OSS::from_env();
    /// let builder = RequestBuilder::new()
    ///     .with_expire(60);
    /// let file_path = "./hello.txt";
    /// let buffer = std::fs::read(file_path).unwrap();
    /// oss.pub_object_from_buffer("/hello.txt", buffer.as_slice(), &builder).unwrap();
    /// ```
    fn pub_object_from_buffer<S: AsRef<str>>(
        &self,
        key: S,
        buffer: &[u8],
        build: &RequestBuilder,
    ) -> Result<()>;

    /// 删除文件
    /// # 使用例子
    /// ```rust
    /// use aliyun_oss_rust_sdk::object::ObjectAPI;
    /// use aliyun_oss_rust_sdk::oss::OSS;
    /// use aliyun_oss_rust_sdk::request::RequestBuilder;
    /// let oss = OSS::from_env();
    /// let builder = RequestBuilder::new()
    ///    .with_expire(60);
    /// oss.delete_object("/hello.txt", &builder).unwrap();
    /// ```
    fn delete_object<S: AsRef<str>>(
        &self,
        key: S,
        build: &RequestBuilder,
    ) -> Result<()>;
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PolicyResp {
    access_id: String,
    host: String,
    policy: String,
    signature: String,
    success_action_status: u8,
}

/// Policy构建器
/// # 使用例子
/// ```rust
///
#[derive(Debug)]
pub struct PolicyBuilder {
    expire: Seconds,
    upload_dir: String,
    content_type: String,
    max_upload_size: i64,
}

impl PolicyBuilder {
    pub fn new() -> Self {
        Self {
            expire: 60,//60秒
            upload_dir: "".to_string(),
            content_type: "text/plain".to_string(),//文本.txt
            max_upload_size: 100 * 1024 * 1024,//100m
        }
    }
    pub fn with_expire(mut self, expire: Seconds) -> Self {
        self.expire = expire;
        self
    }
    pub fn with_upload_dir<S: AsRef<str>>(mut self, upload_dir: S) -> Self {
        self.upload_dir = upload_dir.as_ref().to_string();
        self
    }
    pub fn with_content_type<S: AsRef<str>>(mut self, content_type: S) -> Self {
        self.content_type = content_type.as_ref().to_string();
        self
    }
    pub fn with_max_upload_size(mut self, max_upload_size: i64) -> Self {
        self.max_upload_size = max_upload_size;
        self
    }
}

impl ObjectAPI for OSS {
    fn get_object<S: AsRef<str>>(&self, key: S, build: &RequestBuilder) -> Result<Vec<u8>> {
        let key = self.format_key(key);
        let (url, headers) = self.build_request(key.as_str(), build)?;
        debug!("get object url: {} headers: {:?}", url,headers);
        let client = reqwest::blocking::Client::new();
        let response = client.get(url)
            .headers(headers).send()?;
        return if response.status().is_success() {
            let result = response.bytes()?;
            Ok(result.to_vec())
        } else {
            let status = response.status();
            let result = response.text()?;
            debug!("get object status: {} error: {}", status,result);
            Err(anyhow!(format!("get object status: {} error: {}", status,result)))
        };
    }

    fn get_upload_object_policy(&self, build: &PolicyBuilder) -> Result<PolicyResp> {
        let date = chrono::Local::now().naive_local() + chrono::Duration::seconds(build.expire);
        let date_str = date.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let mut json_data = r#"
        {
            "expiration": "{time}",
            "conditions": [
                {"bucket": "{bucket}" },
                ["content-length-range", 1, {size}],
                ["eq", "$success_action_status", "{success_action_status}"],
                ["starts-with", "$key", "{prefix}"],
                ["in", "$content-type", ["{content_type}"]]
            ]
        }
        "#.to_string();
        let success_action_status = 200;
        json_data = json_data.replacen("{time}", &date_str, 1);
        json_data = json_data.replacen("{bucket}", &self.bucket(), 1);
        //limit 1GB bytes
        json_data = json_data.replacen("{size}", &build.max_upload_size.to_string(), 1);//允许上传的最大文件大小
        //success status
        json_data = json_data.replacen("{success_action_status}", success_action_status.to_string().as_str(), 1);
        json_data = json_data.replacen("{prefix}", &build.upload_dir, 1);//只允许上传到哪个目录上
        //text file
        json_data = json_data.replacen("{content_type}", &build.content_type, 1);
        //只允许上传哪个类型文件
        debug!("policy json: {}", json_data);
        let base64_policy = general_purpose::STANDARD.encode(json_data.as_bytes());
        let mut hasher: Hmac<sha1::Sha1> = Hmac::new_from_slice(self.key_secret().as_bytes()).unwrap();
        hasher.update(base64_policy.as_bytes());
        let signature = general_purpose::STANDARD.encode(&hasher.finalize().into_bytes());
        Ok(PolicyResp {
            access_id: self.key_id().to_string(),
            host: format!("https://{}.{}", self.bucket(), self.endpoint()),
            policy: base64_policy,
            signature,
            success_action_status,
        })
    }

    fn put_object_from_file<S: AsRef<str>>(&self, key: S, file_path: S, build: &RequestBuilder) -> Result<()> {
        let buffer = read_file(file_path)?;
        let mut build = build.clone();
        build.method = RequestType::Put;
        let key = self.format_key(key);
        let (url, headers) = self.build_request(key.as_str(), &build)?;
        debug!("put object from file: {} headers: {:?}", url,headers);
        let client = reqwest::blocking::Client::new();
        let response = client.put(url)
            .headers(headers)
            .body(buffer)
            .send()?;
        return if response.status().is_success() {
            Ok(())
        } else {
            let status = response.status();
            let result = response.text()?;
            debug!("get object status: {} error: {}", status,result);
            Err(anyhow!(format!("get object status: {} error: {}", status,result)))
        };
    }

    fn pub_object_from_buffer<S: AsRef<str>>(&self, key: S, buffer: &[u8], build: &RequestBuilder) -> Result<()> {
        let mut build = build.clone();
        build.method = RequestType::Put;
        let key = self.format_key(key);
        let (url, headers) = self.build_request(key.as_str(), &build)?;
        debug!("put object from file: {} headers: {:?}", url,headers);
        let client = reqwest::blocking::Client::new();
        let response = client.put(url)
            .headers(headers)
            .body(buffer.to_owned())
            .send()?;
        return if response.status().is_success() {
            Ok(())
        } else {
            let status = response.status();
            let result = response.text()?;
            debug!("get object status: {} error: {}", status,result);
            Err(anyhow!(format!("get object status: {} error: {}", status,result)))
        };
    }

    fn delete_object<S: AsRef<str>>(&self, key: S, build: &RequestBuilder) -> Result<()> {
        let mut build = build.clone();
        build.method = RequestType::Delete;
        let key = self.format_key(key);
        let (url, headers) = self.build_request(key.as_str(), &build)?;
        debug!("put object from file: {} headers: {:?}", url,headers);
        let client = reqwest::blocking::Client::new();
        let response = client.delete(url)
            .headers(headers)
            .send()?;
        return if response.status().is_success() {
            Ok(())
        } else {
            let status = response.status();
            let result = response.text()?;
            debug!("get object status: {} error: {}", status,result);
            Err(anyhow!(format!("get object status: {} error: {}", status,result)))
        };
    }
}

#[cfg(test)]
mod tests {
    use crate::object::{ObjectAPI, PolicyBuilder};
    use crate::oss::OSS;
    use crate::request::RequestBuilder;

    #[inline]
    fn init_log() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .with_line_number(true)
            .init();
    }

    #[test]
    fn test_get_upload_object_policy() {
        init_log();
        let oss = OSS::from_env();
        let policy_builder = PolicyBuilder::new()
            .with_expire(60 * 60)//1个小时过期
            .with_upload_dir("upload/mydir/")//上传目录
            .with_content_type("text/plain")//只允许上传文本.txt
            .with_max_upload_size(100 * 1024 * 1024);//只允许文件上传大小1G以内
        let policy = oss.get_upload_object_policy(&policy_builder).unwrap();
        println!("policy: {:?}", policy);
        //使用postman测试上传
        //form-data的参数为OSSAccessKeyId、policy、signature、success_action_status、key、file
        //key为上传的文件名包含路径、例如:upload/mydir/test.txt
        //file为上传的文件,类型跟with_content_type一致
    }

    #[test]
    fn test_put_object_from_file() {
        init_log();
        let oss = OSS::from_env();
        let builder = RequestBuilder::new()
            .with_expire(60);
        let file_path = "./Cargo.toml";
        oss.put_object_from_file("/cargo.toml", file_path, &builder).unwrap();
    }

    #[test]
    fn test_put_object_from_buffer() {
        init_log();
        let oss = OSS::from_env();
        let builder = RequestBuilder::new()
            .with_expire(60);
        let file_path = "./Cargo.toml";
        let buffer = std::fs::read(file_path).unwrap();
        oss.pub_object_from_buffer("/cargo.toml", buffer.as_slice(), &builder).unwrap();
    }

    #[test]
    fn test_delete_object() {
        init_log();
        let oss = OSS::from_env();
        let builder = RequestBuilder::new()
            .with_expire(60);
        oss.delete_object("/cargo.toml", &builder).unwrap();
    }

    #[test]
    fn test_get_object() {
        init_log();
        let oss = OSS::from_env();
        let build = RequestBuilder::new()
            .with_cdn("http://cdn.ipadump.com");
        let bytes = oss.get_object("/hello.txt", &build).unwrap();
        println!("file content: {}", String::from_utf8_lossy(bytes.as_slice()));
    }
}