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