affinidi_messaging_sdk/messages/
get.rs

1use super::GetMessagesRequest;
2use crate::{
3    ATM,
4    errors::ATMError,
5    messages::{GetMessagesResponse, SuccessResponse},
6    profiles::ATMProfile,
7};
8use std::sync::Arc;
9use tracing::{Instrument, Level, debug, span};
10
11impl ATM {
12    /// Returns a list of messages that are stored in the ATM
13    /// - messages : List of message IDs to retrieve
14    pub async fn get_messages(
15        &self,
16        profile: &Arc<ATMProfile>,
17        messages: &GetMessagesRequest,
18    ) -> Result<GetMessagesResponse, ATMError> {
19        let _span = span!(Level::DEBUG, "get_messages");
20
21        async move {
22            let (profile_did, mediator_did) = profile.dids()?;
23            // Check if authenticated
24            let tokens = self
25                .get_tdk()
26                .authentication
27                .authenticate(profile_did.to_string(), mediator_did.to_string(), 3, None)
28                .await?;
29
30            let body = serde_json::to_string(messages).map_err(|e| {
31                ATMError::TransportError(format!(
32                    "Could not serialize get message request: {:?}",
33                    e
34                ))
35            })?;
36
37            let Some(mediator_url) = profile.get_mediator_rest_endpoint() else {
38                return Err(ATMError::TransportError(
39                    "No mediator URL found".to_string(),
40                ));
41            };
42
43            debug!("Sending get_messages request: {:?}", body);
44
45            let res = self
46                .inner
47                .tdk_common
48                .client
49                .post([&mediator_url, "/outbound"].concat())
50                .header("Content-Type", "application/json")
51                .header("Authorization", format!("Bearer {}", tokens.access_token))
52                .body(body)
53                .send()
54                .await
55                .map_err(|e| {
56                    ATMError::TransportError(format!(
57                        "Could not send get_messages request: {:?}",
58                        e
59                    ))
60                })?;
61
62            let status = res.status();
63            debug!("API response: status({})", status);
64
65            let body = res
66                .text()
67                .await
68                .map_err(|e| ATMError::TransportError(format!("Couldn't get body: {:?}", e)))?;
69
70            if !status.is_success() {
71                return Err(ATMError::TransportError(format!(
72                    "Status not successful. status({}), response({})",
73                    status, body
74                )));
75            }
76
77            let body = serde_json::from_str::<SuccessResponse<GetMessagesResponse>>(&body)
78                .ok()
79                .unwrap();
80
81            let list = if let Some(list) = body.data {
82                list
83            } else {
84                return Err(ATMError::TransportError("No messages found".to_string()));
85            };
86
87            debug!(
88                "response: success({}) messages, failed({}) messages, failed_deleted({}) messages",
89                list.success.len(),
90                list.get_errors.len(),
91                list.delete_errors.len()
92            );
93            if !list.get_errors.is_empty() {
94                for (msg, err) in &list.get_errors {
95                    debug!("failed get: msg({}) error({})", msg, err);
96                }
97            }
98            if !list.delete_errors.is_empty() {
99                for (msg, err) in &list.delete_errors {
100                    debug!("failed delete: msg({}) error({})", msg, err);
101                }
102            }
103
104            Ok(list)
105        }
106        .instrument(_span)
107        .await
108    }
109}