io_msgraph/v1/rest/users/messages/attachments/
create.rs1use alloc::{format, string::String, vec::Vec};
15
16use base64_codec::codec::Base64Codec;
17use io_http::rfc6750::bearer::HttpAuthBearer;
18use log::{debug, trace};
19use serde::Serialize;
20use url::Url;
21
22use crate::{
23 coroutine::*,
24 msgraph_try,
25 v1::{
26 rest::users::messages::attachments::MsgraphAttachment,
27 send::{
28 MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
29 user_path,
30 },
31 },
32};
33
34pub const MSGRAPH_ATTACHMENT_MAX_LEN: usize = 3 * 1024 * 1024;
38
39#[derive(Debug, Serialize)]
41#[serde(rename_all = "camelCase")]
42struct MsgraphAttachmentCreateRequest<'a> {
43 #[serde(rename = "@odata.type")]
44 odata_type: &'a str,
45 name: &'a str,
46 content_bytes: String,
47 #[serde(skip_serializing_if = "Option::is_none")]
48 content_type: Option<&'a str>,
49}
50
51pub struct MsgraphAttachmentCreate {
53 send: MsgraphSend<MsgraphAttachment>,
54}
55
56impl MsgraphAttachmentCreate {
57 pub fn new(
65 auth: &HttpAuthBearer,
66 user_id: &str,
67 message_id: &str,
68 name: &str,
69 content: &[u8],
70 content_type: Option<&str>,
71 ) -> Result<Self, MsgraphSendError> {
72 debug!("prepare microsoft graph attachment for creation");
73 trace!("message_id: {message_id:?}");
74 trace!("name: {name:?}");
75 trace!("content_type: {content_type:?}");
76
77 if content.len() > MSGRAPH_ATTACHMENT_MAX_LEN {
78 let len = content.len();
79 let reason = format!(
80 "an attachment of {len} octets is over the {MSGRAPH_ATTACHMENT_MAX_LEN} one request takes"
81 );
82 return Err(MsgraphSendError::InvalidRequest(reason));
83 }
84
85 let user = user_path(user_id)?;
86 let url = Url::parse(MSGRAPH_API_BASE)?.join(&format!(
87 "{user}/messages/{}/attachments",
88 path_segment(message_id)?
89 ))?;
90
91 let mut content_bytes = Vec::new();
92 Base64Codec::default().encode_vec(content, &mut content_bytes);
93 let content_bytes = String::from_utf8(content_bytes).unwrap_or_default();
95
96 let body = MsgraphAttachmentCreateRequest {
97 odata_type: "#microsoft.graph.fileAttachment",
98 name,
99 content_bytes,
100 content_type,
101 };
102 let send = MsgraphSend::post_json(auth, url, &body)?;
103
104 Ok(Self { send })
105 }
106}
107
108impl MsgraphCoroutine for MsgraphAttachmentCreate {
109 type Yield = MsgraphYield;
110 type Return = Result<MsgraphSendOutput<MsgraphAttachment>, MsgraphSendError>;
111
112 fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
113 let out = msgraph_try!(&mut self.send, arg);
114 debug!("attachment created");
115 trace!("out: {out:?}");
116 MsgraphCoroutineState::Complete(Ok(out))
117 }
118}