BlueGit

ict rusty-teams

Files

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

window.rs

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