jmap_client/blob/
copy.rs

1/*
2 * Copyright Stalwart Labs Ltd. See the COPYING
3 * file at the top-level directory of this distribution.
4 *
5 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 * option. This file may not be copied, modified, or distributed
9 * except according to those terms.
10 */
11
12use ahash::AHashMap;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16    core::{set::SetError, RequestParams},
17    Error,
18};
19
20#[derive(Debug, Clone, Serialize)]
21pub struct CopyBlobRequest {
22    #[serde(rename = "fromAccountId")]
23    from_account_id: String,
24    #[serde(rename = "accountId")]
25    account_id: String,
26    #[serde(rename = "blobIds")]
27    blob_ids: Vec<String>,
28}
29
30#[derive(Debug, Clone, Deserialize)]
31pub struct CopyBlobResponse {
32    #[serde(rename = "fromAccountId")]
33    from_account_id: String,
34    #[serde(rename = "accountId")]
35    account_id: String,
36    #[serde(rename = "copied")]
37    copied: Option<AHashMap<String, String>>,
38    #[serde(rename = "notCopied")]
39    not_copied: Option<AHashMap<String, SetError<String>>>,
40}
41
42impl CopyBlobRequest {
43    pub fn new(params: RequestParams, from_account_id: impl Into<String>) -> Self {
44        CopyBlobRequest {
45            from_account_id: from_account_id.into(),
46            account_id: params.account_id,
47            blob_ids: vec![],
48        }
49    }
50
51    pub fn blob_id(&mut self, blob_id: impl Into<String>) -> &mut Self {
52        self.blob_ids.push(blob_id.into());
53        self
54    }
55}
56
57impl CopyBlobResponse {
58    pub fn from_account_id(&self) -> &str {
59        &self.from_account_id
60    }
61
62    pub fn account_id(&self) -> &str {
63        &self.account_id
64    }
65
66    pub fn copied(&mut self, id: &str) -> crate::Result<String> {
67        if let Some(result) = self.copied.as_mut().and_then(|r| r.remove(id)) {
68            Ok(result)
69        } else if let Some(error) = self.not_copied.as_mut().and_then(|r| r.remove(id)) {
70            Err(error.to_string_error().into())
71        } else {
72            Err(Error::Internal(format!("Id {} not found.", id)))
73        }
74    }
75
76    pub fn copied_ids(&self) -> Option<impl Iterator<Item = &String>> {
77        self.copied.as_ref().map(|map| map.keys())
78    }
79
80    pub fn not_copied_ids(&self) -> Option<impl Iterator<Item = &String>> {
81        self.not_copied.as_ref().map(|map| map.keys())
82    }
83
84    pub fn not_copied_reason(&self, id: &str) -> Option<&SetError<String>> {
85        self.not_copied.as_ref().and_then(|map| map.get(id))
86    }
87}