BlueGit

ict rusty-teams

Files

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

window.rs

window.rs 6.6 KiB Download Raw
1use serde_json::Value;
2use session::Request;
3
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, Messages, encode, ensure_success};
6
7const EPOCH_SEGMENT: &str = "epochTimeStamp/";
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum WindowDirection {
11 Bidirectional,
12 Backward,
13 Forward,
14}
15
16impl WindowDirection {
17 fn query_value(self) -> &'static str {
18 match self {
19 WindowDirection::Bidirectional => "BIDIRECTIONAL",
20 WindowDirection::Backward => "BACKWARD",
21 WindowDirection::Forward => "FORWARD",
22 }
23 }
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct MessageWindow {
28 pub message_ids: Vec<String>,
29 pub older_cursor: Option<String>,
30 pub newer_cursor: Option<String>,
31}
32
33fn is_user_message(message: &Value) -> bool {
34 message
35 .get("messagetype")
36 .and_then(Value::as_str)
37 .is_some_and(|kind| kind == "Text" || kind.starts_with("RichText"))
38}
39
40fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
46}
47
48fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
49 let link = body.pointer(&format!("/_metadata/{link_key}"))?.as_str()?;
50 let tail = &link[link.find(EPOCH_SEGMENT)? + EPOCH_SEGMENT.len()..];
51 let number = tail.split(['?', '/']).next()?;
52 (!number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()))
53 .then(|| number.to_owned())
54}
55
56pub fn parse_message_window(body: &Value) -> Result<MessageWindow> {
57 let messages = body
58 .get("messages")
59 .and_then(Value::as_array)
60 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
61 Ok(MessageWindow {
62 message_ids: messages
63 .iter()
64 .filter(|message| is_user_message(message))
65 .filter_map(message_id)
66 .collect(),
67 older_cursor: cursor_of(body, "backwardLink"),
68 newer_cursor: cursor_of(body, "forwardLink"),
69 })
70}
71
72impl<T: MessageTransport> Messages<T> {
73 pub fn message_window_url(
74 &self,
75 chat_id: &str,
76 anchor_id: &str,
77 direction: WindowDirection,
78 page_size: usize,
79 ) -> String {
80 format!(
81 "{}/{}/messages/{EPOCH_SEGMENT}{}?pageSize={page_size}&direction={}&includeMetadata=true&locationType=Primary",
82 self.base_url,
83 encode(chat_id),
84 encode(anchor_id),
85 direction.query_value()
86 )
87 }
88
89 pub async fn message_window(
90 &self,
91 chat_id: &str,
92 anchor_id: &str,
93 direction: WindowDirection,
94 page_size: usize,
95 ) -> Result<MessageWindow> {
96 let url = self.message_window_url(chat_id, anchor_id, direction, page_size);
97 let answer = self.transport.send(Request::get(url)).await?;
98 ensure_success(&answer)?;
99 parse_message_window(&answer.body)
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use std::sync::Mutex;
106
107 use serde_json::json;
108 use session::{ApiResponse, Method};
109
110 use super::*;
111
112 struct Canned {
113 body: Value,
114 requests: Mutex<Vec<Request>>,
115 }
116
117 impl MessageTransport for Canned {
118 async fn send(&self, request: Request) -> Result<ApiResponse> {
119 self.requests.lock().unwrap().push(request);
120 Ok(ApiResponse {
121 status: 200,
122 body: self.body.clone(),
123 retry_after: None,
124 })
125 }
126 }
127
128 fn fixture() -> Value {
129 json!({
130 "messages": [
131 {"id": "1791368000030", "messagetype": "RichText/Html"},
132 {"id": "1791368000025", "messagetype": "ThreadActivity/AddMember"},
133 {"id": "1791368000020", "messagetype": "Text"},
134 {"id": "1791368000015", "messagetype": "Event/Call"},
135 {"id": 1791368000010u64, "messagetype": "RichText/Media_Card"},
136 ],
137 "_metadata": {
138 "backwardLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000009?pageSize=20&direction=BACKWARD&includeMetadata=true",
139 "forwardLink": "https://other.host/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000031?pageSize=20&direction=FORWARD",
140 }
141 })
142 }
143
144 #[test]
145 fn parses_user_messages_and_cursors() {
146 let window = parse_message_window(&fixture()).unwrap();
147 assert_eq!(
148 window.message_ids,
149 ["1791368000030", "1791368000020", "1791368000010"]
150 );
151 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
152 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
153 }
154
155 #[test]
156 fn absent_links_mean_no_more_pages() {
157 let window = parse_message_window(&json!({
158 "messages": [{"id": "1", "messagetype": "Text"}],
159 "_metadata": {}
160 }))
161 .unwrap();
162 assert_eq!(window.older_cursor, None);
163 assert_eq!(window.newer_cursor, None);
164 let without_metadata = parse_message_window(&json!({"messages": []})).unwrap();
165 assert_eq!(without_metadata.older_cursor, None);
166 }
167
168 #[test]
169 fn link_without_a_number_gives_no_cursor() {
170 let window = parse_message_window(&json!({
171 "messages": [],
172 "_metadata": {"backwardLink": "https://h/messages/epochTimeStamp/?x=1"}
173 }))
174 .unwrap();
175 assert_eq!(window.older_cursor, None);
176 }
177
178 #[test]
179 fn missing_messages_is_unexpected() {
180 assert!(matches!(
181 parse_message_window(&json!({})),
182 Err(Error::UnexpectedAnswer(_))
183 ));
184 }
185
186 #[tokio::test]
187 async fn requests_the_window_around_the_anchor() {
188 let messages = Messages::with_transport(
189 Canned {
190 body: fixture(),
191 requests: Mutex::new(Vec::new()),
192 },
193 "emea",
194 );
195 messages
196 .message_window(
197 "19:abc@thread.v2",
198 "1791368000020",
199 WindowDirection::Bidirectional,
200 20,
201 )
202 .await
203 .unwrap();
204 let requests = messages.transport.requests.lock().unwrap();
205 assert_eq!(requests[0].method, Method::Get);
206 assert_eq!(
207 requests[0].url,
208 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000020?pageSize=20&direction=BIDIRECTIONAL&includeMetadata=true&locationType=Primary"
209 );
210 }
211}