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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use crate::oss;

use self::builders::{
    DeleteBucketBuilder, GetBucketInfoBuilder, GetBucketLocationBuilder, GetBucketStatBuilder,
    ListObjectBuilder, ListObjectsV2Builder, PutBucketBuilder,
};

pub mod builders {
    use crate::oss::{
        self,
        api::{self, insert_custom_header, ApiResponseFrom},
        entities::{
            bucket::{
                BucketInfo, BucketStat, CreateBucketConfiguration, ListBucketResult,
                ListBucketResult2, LocationConstraint,
            },
            DataRedundancyType, OssAcl, StorageClass,
        },
        http,
    };
    use reqwest::header::HeaderMap;
    use serde::{Deserialize, Serialize};
    use std::fmt;

    #[derive(Debug)]
    pub struct PutBucketBuilder<'a> {
        client: &'a oss::Client<'a>,
        region: Option<&'a str>,
        bucket: Option<&'a str>,
        acl: Option<OssAcl>,
        group_id: Option<&'a str>,
        storage_class: Option<StorageClass>,
        data_redundancy_type: Option<DataRedundancyType>,
    }

    impl<'a> PutBucketBuilder<'a> {
        pub(crate) fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                region: None,
                bucket: None,
                acl: None,
                group_id: None,
                // config: None,
                storage_class: None,
                data_redundancy_type: None,
            }
        }

        pub fn with_region(mut self, value: &'a str) -> Self {
            self.region = Some(value);
            self
        }

        pub fn with_bucket(mut self, value: &'a str) -> Self {
            self.bucket = Some(value);
            self
        }

        pub fn with_acl(mut self, value: OssAcl) -> Self {
            self.acl = Some(value);
            self
        }

        pub fn with_group_id(mut self, value: &'a str) -> Self {
            self.group_id = Some(value);
            self
        }

        pub fn with_storage_class(mut self, value: StorageClass) -> Self {
            self.storage_class = Some(value);
            self
        }

        pub fn with_data_redundancy_type(mut self, value: DataRedundancyType) -> Self {
            self.data_redundancy_type = Some(value);
            self
        }

        fn headers(&self) -> HeaderMap {
            let mut headers = HeaderMap::default();
            if let Some(acl) = &self.acl {
                insert_custom_header(&mut headers, "x-oss-acl", acl.to_string());
            }
            if let Some(group_id) = &self.group_id {
                insert_custom_header(&mut headers, "x-oss-resource-group-id", group_id);
            }
            headers
        }

        fn config(&self) -> String {
            let config = CreateBucketConfiguration {
                storage_class: self.storage_class.to_owned(),
                data_redundancy_type: self.data_redundancy_type.to_owned(),
            };
            quick_xml::se::to_string(&config).unwrap()
        }

        /// 调用PutBucket接口创建存储空间(Bucket)。
        pub async fn execute(&self) -> api::ApiResult {
            let region = self.region.unwrap_or(self.client.options.region);
            let bucket = self.bucket.unwrap_or(self.client.bucket());
            let res = format!("/{}/", bucket);
            let url = format!(
                "{}://{}.{}",
                self.client.options.schema(),
                bucket,
                format!(
                    "{}{}.{}",
                    region,
                    match self.client.options.internal {
                        true => "-internal",
                        false => "",
                    },
                    oss::BASE_URL
                )
            );

            let headers = self.headers();
            let config = oss::Bytes::from(self.config());

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_method(http::Method::PUT)
                .with_resource(&res)
                .with_headers(headers)
                .with_body(config)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_empty().await)
        }
    }

    pub struct DeleteBucketBuilder<'a> {
        client: &'a oss::Client<'a>,
        region: Option<&'a str>,
        bucket: Option<&'a str>,
    }

    impl<'a> DeleteBucketBuilder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                region: None,
                bucket: None,
            }
        }

        pub fn with_region(mut self, region: &'a str) -> Self {
            self.region = Some(region);
            self
        }

        pub fn with_bucket(mut self, bucket: &'a str) -> Self {
            self.bucket = Some(bucket);
            self
        }

        pub async fn execute(&self) -> api::ApiResult {
            let region = self.region.unwrap_or(self.client.options.region);
            let bucket = self.bucket.unwrap_or(self.client.bucket());
            let res = format!("/{}/", bucket);
            let url = format!(
                "{}://{}.{}",
                self.client.options.schema(),
                bucket,
                format!(
                    "{}{}.{}",
                    region,
                    match self.client.options.internal {
                        true => "-internal",
                        false => "",
                    },
                    oss::BASE_URL
                )
            );
            // dbg!(&res);
            // dbg!(&url);

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_resource(&res)
                .with_method(http::Method::DELETE)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_empty().await)
        }
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub(crate) struct ListObjectQuery<'a> {
        delimiter: Option<&'a str>,
        marker: Option<&'a str>,
        #[serde(rename = "max-keys")]
        max_keys: Option<i32>,
        prefix: Option<&'a str>,
        #[serde(rename = "encoding-type")]
        encoding_type: Option<&'a str>,
    }

    impl<'a> fmt::Display for ListObjectQuery<'a> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", serde_qs::to_string(self).unwrap())
        }
    }

    impl<'a> Default for ListObjectQuery<'a> {
        fn default() -> Self {
            ListObjectQuery {
                delimiter: None,
                marker: None,
                max_keys: Some(100),
                prefix: None,
                encoding_type: None,
            }
        }
    }

    pub struct ListObjectBuilder<'a> {
        client: &'a oss::Client<'a>,
        query: ListObjectQuery<'a>,
    }

    impl<'a> ListObjectBuilder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                query: ListObjectQuery::default(),
            }
        }

        pub fn with_delimiter(mut self, value: &'a str) -> Self {
            self.query.delimiter = Some(value);
            self
        }

        pub fn with_marker(mut self, value: &'a str) -> Self {
            self.query.marker = Some(value);
            self
        }

        pub fn with_max_keys(mut self, value: i32) -> Self {
            self.query.max_keys = Some(value);
            self
        }

        pub fn with_prefix(mut self, value: &'a str) -> Self {
            self.query.prefix = Some(value);
            self
        }

        pub fn with_encoding_type(mut self, value: &'a str) -> Self {
            self.query.encoding_type = Some(value);
            self
        }

        pub async fn execute(&self) -> api::ApiResult<ListBucketResult> {
            let res = format!("/{}/", self.client.bucket());
            let mut url = self.client.base_url();
            let query = self.query.to_string();
            if !query.is_empty() {
                url = format!("{}?{}", url, query);
            }

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_resource(&res)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_type().await)
        }
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub(crate) struct ListObjectsV2Query<'a> {
        #[serde(rename = "list-type")]
        pub list_type: u8,
        pub delimiter: Option<&'a str>,
        #[serde(rename = "start-after")]
        pub start_after: Option<&'a str>,
        #[serde(rename = "continuation-token")]
        pub continuation_token: Option<&'a str>,
        #[serde(rename = "max-keys")]
        pub max_keys: Option<i32>,
        pub prefix: Option<&'a str>,
        #[serde(rename = "encoding-type")]
        pub encoding_type: Option<&'a str>,
        #[serde(rename = "fetch-owner")]
        pub fetch_owner: Option<bool>,
    }

    impl<'a> Default for ListObjectsV2Query<'a> {
        fn default() -> Self {
            ListObjectsV2Query {
                list_type: 2,
                delimiter: None,
                start_after: None,
                continuation_token: None,
                max_keys: Some(100),
                prefix: None,
                encoding_type: None,
                fetch_owner: None,
            }
        }
    }

    impl<'a> fmt::Display for ListObjectsV2Query<'a> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", serde_qs::to_string(self).unwrap())
        }
    }

    pub struct ListObjectsV2Builder<'a> {
        client: &'a oss::Client<'a>,
        query: ListObjectsV2Query<'a>,
    }

    impl<'a> ListObjectsV2Builder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                query: ListObjectsV2Query::default(),
            }
        }

        pub fn with_delimiter(mut self, value: &'a str) -> Self {
            self.query.delimiter = Some(value);
            self
        }

        pub fn with_start_after(mut self, value: &'a str) -> Self {
            self.query.delimiter = Some(value);
            self
        }

        pub fn with_continuation_token(mut self, value: Option<&'a str>) -> Self {
            self.query.continuation_token = value;
            self
        }

        pub fn with_max_keys(mut self, value: i32) -> Self {
            self.query.max_keys = Some(value);
            self
        }

        pub fn with_prefix(mut self, value: &'a str) -> Self {
            self.query.prefix = Some(value);
            self
        }

        pub fn with_encoding_type(mut self, value: &'a str) -> Self {
            self.query.encoding_type = Some(value);
            self
        }

        pub fn with_fetch_owner(mut self, value: bool) -> Self {
            self.query.fetch_owner = Some(value);
            self
        }

        pub async fn execute(&self) -> api::ApiResult<ListBucketResult2> {
            let mut res = format!("/{}/", self.client.bucket());
            let mut url = self.client.base_url();
            let query = self.query.to_string();
            if !query.is_empty() {
                if let Some(token) = self.query.continuation_token {
                    res = format!("{}?continuation-token={}", res, token);
                }
                url = format!("{}?{}", url, query);
            }

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_method(http::Method::GET)
                .with_resource(&res)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_type().await)
        }
    }

    pub struct GetBucketInfoBuilder<'a> {
        client: &'a oss::Client<'a>,
        bucket: Option<&'a str>,
    }

    impl<'a> GetBucketInfoBuilder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                bucket: None,
            }
        }

        pub fn with_bucket(mut self, value: &'a str) -> Self {
            self.bucket = Some(value);
            self
        }

        pub async fn execute(&self) -> api::ApiResult<BucketInfo> {
            let region = self.client.region();
            let bucket = self.bucket.unwrap_or(self.client.bucket());
            let res = format!("/{}/?bucketInfo", bucket);
            let url = format!(
                "{}://{}.{}?bucketInfo",
                self.client.options.schema(),
                bucket,
                format!(
                    "{}{}.{}",
                    region,
                    match self.client.options.internal {
                        true => "-internal",
                        false => "",
                    },
                    oss::BASE_URL
                )
            );

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_resource(&res)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_type().await)
        }
    }

    pub struct GetBucketLocationBuilder<'a> {
        client: &'a oss::Client<'a>,
        bucket: Option<&'a str>,
    }

    impl<'a> GetBucketLocationBuilder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                bucket: None,
            }
        }

        pub fn with_bucket(mut self, value: &'a str) -> Self {
            self.bucket = Some(value);
            self
        }

        pub async fn execute(&self) -> api::ApiResult<LocationConstraint> {
            let region = self.client.options.region;
            let bucket = self.bucket.unwrap_or(self.client.bucket());
            let res = format!("/{}/?location", bucket);
            let url = format!(
                "{}://{}.{}/?location",
                self.client.options.schema(),
                bucket,
                format!(
                    "{}{}.{}",
                    region,
                    match self.client.options.internal {
                        true => "-internal",
                        false => "",
                    },
                    oss::BASE_URL
                )
            );
            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_resource(&res)
                .with_method(http::Method::GET)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_type().await)
        }
    }

    pub struct GetBucketStatBuilder<'a> {
        client: &'a oss::Client<'a>,
        region: Option<&'a str>,
        bucket: Option<&'a str>,
    }

    impl<'a> GetBucketStatBuilder<'a> {
        pub fn new(client: &'a oss::Client) -> Self {
            Self {
                client,
                region: None,
                bucket: None,
            }
        }

        pub fn with_region(mut self, region: &'a str) -> Self {
            self.region = Some(region);
            self
        }

        pub fn with_bucket(mut self, bucket: &'a str) -> Self {
            self.bucket = Some(bucket);
            self
        }

        pub async fn execute(&self) -> api::ApiResult<BucketStat> {
            let region = self.region.unwrap_or(self.client.options.region);
            let bucket = self.bucket.unwrap_or(self.client.bucket());
            let res = format!("/{}/?stat", bucket);
            let url = format!(
                "{}://{}.{}/?stat",
                self.client.options.schema(),
                bucket,
                format!(
                    "{}{}.{}",
                    region,
                    match self.client.options.internal {
                        true => "-internal",
                        false => "",
                    },
                    oss::BASE_URL
                )
            );

            let resp = self
                .client
                .request
                .task()
                .with_url(&url)
                .with_resource(&res)
                .with_method(http::Method::GET)
                .execute()
                .await?;

            Ok(ApiResponseFrom(resp).to_type().await)
        }
    }
}

/// # 基础操作
#[allow(non_snake_case)]
impl<'a> oss::Client<'a> {
    /// 调用PutBucket接口创建存储空间`Bucket`。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/putbucket)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_put.rs)
    pub fn PutBucket(&self) -> PutBucketBuilder<'_> {
        PutBucketBuilder::new(self)
    }

    /// 调用DeleteBucket删除某个存储空间`Bucket`。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/deletebucket)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_del.rs)
    pub fn DeleteBucket(&self) -> DeleteBucketBuilder<'_> {
        DeleteBucketBuilder::new(self)
    }

    /// GetBucket (ListObjects)接口用于列举存储空间`Bucket`中所有文件
    /// `Object`的信息。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/listobjects)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_list_object.rs)
    pub fn ListObjects(&self) -> ListObjectBuilder<'_> {
        ListObjectBuilder::new(self)
    }

    /// ListObjectsV2`GetBucketV2`接口用于列举存储空间`Bucket`中所有文件
    ///`Object`的信息。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/listobjectsv2)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_list_object_v2.rs)
    pub fn ListObjectsV2(&self) -> ListObjectsV2Builder<'_> {
        ListObjectsV2Builder::new(self)
    }

    /// 调用GetBucketInfo接口查看存储空间`Bucket`的相关信息。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/getbucketinfo)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_get_info.rs)
    pub fn GetBucketInfo(&self) -> GetBucketInfoBuilder<'_> {
        GetBucketInfoBuilder::new(self)
    }

    /// GetBucketLocation接口用于查看存储空间`Bucket`的位置信息。
    /// 只有Bucket的拥有者才能查看Bucket的位置信息。
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/getbucketlocation)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_get_location.rs)
    pub fn GetBucketLocation(&self) -> GetBucketLocationBuilder<'_> {
        GetBucketLocationBuilder::new(self)
    }

    /// 调用GetBucketStat接口获取指定存储空间`Bucket`的存储容量以及文件
    /// `Object`数量
    ///
    /// - [official docs](https://help.aliyun.com/zh/oss/developer-reference/getbucketstat)
    /// - [xtoss example](https://github.com/isme-sun/xt_oss/blob/main/examples/api_bucket_stand_get_stat.rs)
    pub fn GetBucketStat(&self) -> GetBucketStatBuilder<'_> {
        GetBucketStatBuilder::new(self)
    }
}