Skip to main content

io_msgraph/v1/rest/users/messages/attachments/
create.rs

1//! Add a file attachment to a Microsoft Graph message
2//! (`POST /me/messages/{id}/attachments`); returns the created
3//! attachment.
4//!
5//! Only the `fileAttachment` subtype is created here: the raw content is
6//! base64-encoded into `contentBytes`, as Graph requires.
7//!
8//! One request takes a file under 3 MB
9//! ([`MSGRAPH_ATTACHMENT_MAX_LEN`]). Graph takes a larger one through an
10//! upload session, which this crate does not model yet.
11//!
12//! <https://learn.microsoft.com/en-us/graph/api/message-post-attachments>
13
14use 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
34/// Longest content, in octets, one attachment create request takes.
35///
36/// <https://learn.microsoft.com/en-us/graph/outlook-large-attachments>
37pub const MSGRAPH_ATTACHMENT_MAX_LEN: usize = 3 * 1024 * 1024;
38
39/// Body of the file attachment create request.
40#[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
51/// Adds a file attachment to a Microsoft Graph message.
52pub struct MsgraphAttachmentCreate {
53    send: MsgraphSend<MsgraphAttachment>,
54}
55
56impl MsgraphAttachmentCreate {
57    /// Adds a `fileAttachment` named `name` carrying `content`, with
58    /// an optional MIME `content_type`.
59    ///
60    /// The raw content bytes are base64-encoded into `contentBytes`,
61    /// as Graph requires. A content over
62    /// [`MSGRAPH_ATTACHMENT_MAX_LEN`] is refused with
63    /// [`MsgraphSendError::InvalidRequest`].
64    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        // NOTE: the base64 alphabet is ASCII, so this never falls back.
94        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}