BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / chat_listing.rs

chat_listing.rs

chat_listing.rs 7.6 KiB Download Raw
1use serde_json::Value;
2use session::{Request, Scope, Session};
3
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
6use crate::pins::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, DEFAULT_REGION, SessionTransport};
7
8const VIEW: &str = "view=msnp24Equivalent";
9const NEWEST_ANCHOR_SLACK_MS: i64 = 60_000;
10
11/// One page of the conversation list as the chat service sends it; `next_url` lists older conversations.
12#[derive(Debug, Clone, PartialEq)]
13pub struct ConversationPage {
14 pub conversations: Vec<Value>,
15 pub next_url: Option<String>,
16}
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct MessagePage {
20 pub messages: Vec<Value>,
21 pub has_older: bool,
22}
23
24/// One chat with its members and meeting details, from the chat service aggregator.
25pub async fn aggregator_chat(session: &Session, chat_id: &str) -> Result<Value> {
26 let url = format!(
27 "https://teams.cloud.microsoft/api/csa/{DEFAULT_REGION}/api/v1/teams/users/me/chats/{}",
28 encode(chat_id)
29 );
30 let transport = SessionTransport::with_scope(session, Scope::new(CSA_RESOURCE, CSA_SCOPE));
31 let answer = transport.send(Request::get(url)).await?;
32 ensure_success(&answer)?;
33 Ok(answer.body)
34}
35
36/// Raw reads of chats, threads and messages for the native chat path.
37pub struct ChatListing<T: MessageTransport = SessionMessageTransport> {
38 transport: T,
39 region: String,
40}
41
42impl ChatListing<SessionMessageTransport> {
43 pub fn new(session: &Session) -> Self {
44 ChatListing::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
45 }
46}
47
48impl<T: MessageTransport> ChatListing<T> {
49 pub fn with_transport(transport: T, region: &str) -> Self {
50 ChatListing {
51 transport,
52 region: region.to_owned(),
53 }
54 }
55
56 fn conversations_url(&self) -> String {
57 format!(
58 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/users/ME/conversations",
59 self.region
60 )
61 }
62
63 pub fn first_page_url(&self, page_size: usize) -> String {
64 format!("{}?{VIEW}&pageSize={page_size}", self.conversations_url())
65 }
66
67 pub async fn page(&self, url: &str) -> Result<ConversationPage> {
68 let body = self.get(url).await?;
69 let conversations = body
70 .get("conversations")
71 .and_then(Value::as_array)
72 .cloned()
73 .ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?;
74 let next_url = body
75 .pointer("/_metadata/backwardLink")
76 .and_then(Value::as_str)
77 .filter(|link| !link.is_empty() && *link != url && !conversations.is_empty())
78 .map(str::to_owned);
79 Ok(ConversationPage {
80 conversations,
81 next_url,
82 })
83 }
84
85 pub async fn conversation(&self, conversation_id: &str) -> Result<Value> {
86 let url = format!(
87 "{}/{}?{VIEW}",
88 self.conversations_url(),
89 encode(conversation_id)
90 );
91 self.get(&url).await
92 }
93
94 /// The thread with its members; members carry ids and roles but no names.
95 pub async fn thread(&self, thread_id: &str) -> Result<Value> {
96 let url = format!(
97 "https://teams.cloud.microsoft/api/chatsvc/{}/v1/threads/{}?{VIEW}",
98 self.region,
99 encode(thread_id)
100 );
101 self.get(&url).await
102 }
103
104 /// Newest arrival first; with `before_ms` only messages that arrived before it.
105 /// The plain message list is ordered by last change, so an edit would move an old message into the newest page.
106 pub async fn messages(
107 &self,
108 conversation_id: &str,
109 before_ms: Option<i64>,
110 page_size: usize,
111 ) -> Result<MessagePage> {
112 let base = format!(
113 "{}/{}/messages",
114 self.conversations_url(),
115 encode(conversation_id)
116 );
117 let anchor_ms = before_ms.map_or_else(
118 || chrono::Utc::now().timestamp_millis() + NEWEST_ANCHOR_SLACK_MS,
119 |before_ms| before_ms - 1,
120 );
121 let url = format!(
122 "{base}/epochTimeStamp/{anchor_ms}?pageSize={page_size}&direction=BACKWARD&includeMetadata=true&locationType=Primary"
123 );
124 let body = self.get(&url).await?;
125 let messages: Vec<Value> = body
126 .get("messages")
127 .and_then(Value::as_array)
128 .cloned()
129 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?
130 .into_iter()
131 .filter(|message| before_ms.is_none_or(|before| arrival_ms(message) < Some(before)))
132 .collect();
133 let has_older = body
134 .pointer("/_metadata/backwardLink")
135 .and_then(Value::as_str)
136 .is_some_and(|link| !link.is_empty())
137 && !messages.is_empty();
138 Ok(MessagePage {
139 messages,
140 has_older,
141 })
142 }
143
144 pub async fn message(&self, conversation_id: &str, message_id: &str) -> Result<Value> {
145 let url = format!(
146 "{}/{}/messages/{}?{VIEW}",
147 self.conversations_url(),
148 encode(conversation_id),
149 encode(message_id)
150 );
151 self.get(&url).await
152 }
153
154 async fn get(&self, url: &str) -> Result<Value> {
155 let answer = self.transport.send(Request::get(url)).await?;
156 ensure_success(&answer)?;
157 Ok(answer.body)
158 }
159}
160
161fn arrival_ms(message: &Value) -> Option<i64> {
162 crate::json_id::id_text(message.get("id")?)?.parse().ok()
163}
164
165#[cfg(test)]
166mod tests {
167 use std::collections::VecDeque;
168 use std::sync::Mutex;
169
170 use serde_json::json;
171 use session::ApiResponse;
172
173 use super::*;
174
175 struct Canned {
176 answers: Mutex<VecDeque<Value>>,
177 requests: Mutex<Vec<String>>,
178 }
179
180 impl MessageTransport for &Canned {
181 async fn send(&self, request: Request) -> Result<ApiResponse> {
182 self.requests.lock().unwrap().push(request.url.clone());
183 Ok(ApiResponse {
184 status: 200,
185 body: self.answers.lock().unwrap().pop_front().unwrap_or_default(),
186 retry_after: None,
187 })
188 }
189 }
190
191 fn canned(answers: Vec<Value>) -> Canned {
192 Canned {
193 answers: Mutex::new(answers.into()),
194 requests: Mutex::new(Vec::new()),
195 }
196 }
197
198 #[tokio::test]
199 async fn a_page_links_to_older_conversations() {
200 let transport = canned(vec![json!({
201 "conversations": [{"id": "19:a@thread.v2"}],
202 "_metadata": {"backwardLink": "https://next"},
203 })]);
204 let listing = ChatListing::with_transport(&transport, "emea");
205 let page = listing.page(&listing.first_page_url(50)).await.unwrap();
206 assert_eq!(page.conversations.len(), 1);
207 assert_eq!(page.next_url.as_deref(), Some("https://next"));
208 assert_eq!(
209 transport.requests.lock().unwrap()[0],
210 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations?view=msnp24Equivalent&pageSize=50"
211 );
212 }
213
214 #[tokio::test]
215 async fn older_messages_end_before_the_anchor() {
216 let transport = canned(vec![json!({
217 "messages": [{"id": "1000"}, {"id": "900"}],
218 "_metadata": {"backwardLink": "https://older"},
219 })]);
220 let listing = ChatListing::with_transport(&transport, "emea");
221 let page = listing
222 .messages("19:a@thread.v2", Some(1000), 20)
223 .await
224 .unwrap();
225 assert_eq!(page.messages, vec![json!({"id": "900"})]);
226 assert!(page.has_older);
227 assert!(transport.requests.lock().unwrap()[0].contains("/messages/epochTimeStamp/999?"));
228 }
229}