BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / stored.rs

stored.rs

stored.rs 14.7 KiB Download Raw
1use scraper::{ElementRef, Html};
2use serde::{Deserialize, Serialize};
3use store::MessageRecord;
4
5use crate::spans::{Span, html_to_spans};
6
7const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct AttachmentInfo {
11 pub content_type: Option<String>,
12 pub name: Option<String>,
13 pub url: Option<String>,
14 pub text: Option<String>,
15 #[serde(default)]
16 pub size: Option<u64>,
17 #[serde(default)]
18 pub quote: Option<QuoteInfo>,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum FileKind {
23 Word,
24 Excel,
25 PowerPoint,
26 Pdf,
27 Image,
28 Archive,
29 Other,
30}
31
32impl FileKind {
33 pub fn from_name(name: &str) -> FileKind {
34 let Some((_, extension)) = name.rsplit_once('.') else {
35 return FileKind::Other;
36 };
37 match extension.to_ascii_lowercase().as_str() {
38 "doc" | "docx" | "docm" | "dot" | "dotx" | "rtf" | "odt" => FileKind::Word,
39 "xls" | "xlsx" | "xlsm" | "xlsb" | "csv" | "ods" => FileKind::Excel,
40 "ppt" | "pptx" | "pptm" | "pps" | "ppsx" | "odp" => FileKind::PowerPoint,
41 "pdf" => FileKind::Pdf,
42 "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "svg" | "heic" | "tif" | "tiff" => {
43 FileKind::Image
44 }
45 "zip" | "rar" | "7z" | "tar" | "gz" | "tgz" => FileKind::Archive,
46 _ => FileKind::Other,
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct QuoteInfo {
53 pub message_id: String,
54 pub preview: String,
55 pub sender_name: Option<String>,
56}
57
58/// Image inside a message body. `key()` is the image cache key.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct ImageRef {
61 pub id: String,
62 pub url: String,
63 pub width: Option<u32>,
64 pub height: Option<u32>,
65}
66
67impl ImageRef {
68 pub fn key(&self) -> &str {
69 &self.url
70 }
71}
72
73impl AttachmentInfo {
74 pub fn is_card(&self) -> bool {
75 self.content_type
76 .as_deref()
77 .is_some_and(|content_type| content_type.contains("card"))
78 }
79
80 pub fn file_kind(&self) -> FileKind {
81 match self.name.as_deref().map(FileKind::from_name) {
82 Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image,
83 Some(kind) => kind,
84 None => FileKind::Other,
85 }
86 }
87
88 fn has_image_content_type(&self) -> bool {
89 self.content_type
90 .as_deref()
91 .is_some_and(|content_type| content_type.starts_with("image/"))
92 }
93
94 pub fn is_file(&self) -> bool {
95 self.content_type.as_deref() == Some("reference") && self.url.is_some()
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct ReactionInfo {
101 pub reaction_type: String,
102 pub user_id: Option<String>,
103 pub user_name: Option<String>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct MentionInfo {
108 pub user_id: Option<String>,
109 pub name: String,
110}
111
112pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
113 serde_json::from_str(&record.attachments_json).unwrap_or_default()
114}
115
116pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {
117 serde_json::from_str(&record.reactions_json).unwrap_or_default()
118}
119
120pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {
121 serde_json::from_str(&record.mentions_json).unwrap_or_default()
122}
123
124pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {
125 attachments(record)
126 .into_iter()
127 .filter_map(|attachment| attachment.quote)
128 .collect()
129}
130
131pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
132 if record.deleted {
133 return Vec::new();
134 }
135 let fragment = Html::parse_fragment(&record.body_html);
136 let mut found: Vec<ImageRef> = Vec::new();
137 for element in fragment
138 .root_element()
139 .descendants()
140 .filter_map(ElementRef::wrap)
141 {
142 let value = element.value();
143 let is_emoji = value
144 .attr("itemtype")
145 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
146 let Some(url) = value
147 .attr("src")
148 .filter(|url| value.name() == "img" && !is_emoji && !url.is_empty())
149 else {
150 continue;
151 };
152 if found.iter().any(|image| image.url == url) {
153 continue;
154 }
155 let style = value.attr("style").unwrap_or_default();
156 found.push(ImageRef {
157 id: image_id(url),
158 url: url.to_owned(),
159 width: dimension(value.attr("width"), style, "width"),
160 height: dimension(value.attr("height"), style, "height"),
161 });
162 }
163 found
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct FileCard {
168 pub name: String,
169 pub kind: FileKind,
170 pub content_type: Option<String>,
171 pub size: Option<u64>,
172 pub open_url: String,
173}
174
175/// File attachments (`reference` type) with a name and a URL. `size` is rarely known; Graph does not send it for these.
176pub fn files(record: &MessageRecord) -> Vec<FileCard> {
177 attachments(record)
178 .into_iter()
179 .filter(AttachmentInfo::is_file)
180 .map(|attachment| FileCard {
181 kind: attachment.file_kind(),
182 name: attachment.name.clone().unwrap_or_default(),
183 content_type: attachment.content_type.clone(),
184 size: attachment.size,
185 open_url: attachment.url.clone().unwrap_or_default(),
186 })
187 .collect()
188}
189
190/// Text for the clipboard: body and card text, mentions as `@name`, no markup.
191pub fn copy_text(record: &MessageRecord) -> String {
192 let mut text = String::new();
193 push_plain(&mut text, &message_spans(record));
194 text.trim().to_owned()
195}
196
197fn push_plain(text: &mut String, spans: &[Span]) {
198 for span in spans {
199 match span {
200 Span::Text(value) | Span::Code(value) => text.push_str(value),
201 Span::CodeBlock { code, .. } => {
202 text.push_str(code);
203 text.push('\n');
204 }
205 Span::Bold(children)
206 | Span::Italic(children)
207 | Span::Strike(children)
208 | Span::Underline(children)
209 | Span::Colored { children, .. }
210 | Span::Quote(children)
211 | Span::BlockQuote(children)
212 | Span::Link { children, .. } => push_plain(text, children),
213 Span::Heading { children, .. } => {
214 push_plain(text, children);
215 text.push('\n');
216 }
217 Span::Mention { name } => {
218 text.push('@');
219 text.push_str(name);
220 }
221 Span::LineBreak | Span::Rule => text.push('\n'),
222 Span::List {
223 ordered,
224 start,
225 items,
226 } => {
227 for (offset, item) in items.iter().enumerate() {
228 if *ordered {
229 text.push_str(&format!("{}. ", *start as usize + offset));
230 } else {
231 text.push_str("- ");
232 }
233 push_plain(text, item);
234 text.push('\n');
235 }
236 }
237 Span::Table { rows, .. } => {
238 for row in rows {
239 for (index, cell) in row.iter().enumerate() {
240 if index > 0 {
241 text.push('\t');
242 }
243 push_plain(text, cell);
244 }
245 text.push('\n');
246 }
247 }
248 Span::Image { .. } => {}
249 }
250 }
251}
252
253/// Own, not deleted. Whether the conversation supports the write is the engine's call.
254pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool {
255 !record.deleted && record.sender_id.as_deref() == Some(my_user_id)
256}
257
258pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool {
259 can_edit(record, my_user_id)
260}
261
262fn image_id(url: &str) -> String {
263 let path = url.split(['?', '#']).next().unwrap_or(url);
264 let segments: Vec<&str> = path
265 .split('/')
266 .filter(|segment| !segment.is_empty())
267 .collect();
268 segments
269 .iter()
270 .position(|segment| matches!(*segment, "hostedContents" | "objects"))
271 .and_then(|index| segments.get(index + 1))
272 .or(segments.last())
273 .map_or_else(String::new, |segment| (*segment).to_owned())
274}
275
276fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> {
277 let from_style = || {
278 style.split(';').find_map(|declaration| {
279 let (name, value) = declaration.split_once(':')?;
280 (name.trim() == property).then(|| leading_number(value))?
281 })
282 };
283 attribute
284 .and_then(leading_number)
285 .or_else(from_style)
286 .filter(|pixels| *pixels > 0)
287}
288
289fn leading_number(text: &str) -> Option<u32> {
290 let digits: String = text
291 .trim()
292 .chars()
293 .take_while(char::is_ascii_digit)
294 .collect();
295 digits.parse().ok()
296}
297
298/// Body spans followed by the flattened text of adaptive-card attachments.
299pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
300 let mut spans = html_to_spans(&record.body_html);
301 for card_text in attachments(record)
302 .iter()
303 .filter(|attachment| attachment.is_card())
304 .filter_map(|attachment| attachment.text.as_deref())
305 {
306 if !spans.is_empty() {
307 spans.push(Span::LineBreak);
308 }
309 for (index, line) in card_text.lines().enumerate() {
310 if index > 0 {
311 spans.push(Span::LineBreak);
312 }
313 spans.push(Span::Text(line.to_owned()));
314 }
315 }
316 spans
317}
318
319#[cfg(test)]
320mod tests {
321 use chrono::Utc;
322
323 use super::*;
324
325 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
326 MessageRecord {
327 conversation_id: "c".to_owned(),
328 message_id: "m".to_owned(),
329 reply_to_id: None,
330 sender_id: Some("u".to_owned()),
331 sender_name: None,
332 created_at: Utc::now(),
333 edited_at: None,
334 deleted: false,
335 body_html: body_html.to_owned(),
336 attachments_json: attachments_json.to_owned(),
337 reactions_json: "[]".to_owned(),
338 mentions_json: "[]".to_owned(),
339 }
340 }
341
342 #[test]
343 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
344 let html = concat!(
345 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
346 r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#,
347 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
348 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
349 );
350 let found = images(&record(html, "[]"));
351 assert_eq!(found.len(), 2);
352 assert_eq!(
353 (found[0].id.as_str(), found[0].width, found[0].height),
354 ("aWQ9", Some(300), Some(120))
355 );
356 assert_eq!(
357 (found[1].id.as_str(), found[1].width, found[1].height),
358 ("0-weu-d1-abc", Some(64), None)
359 );
360 }
361
362 #[test]
363 fn deleted_messages_have_no_images() {
364 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
365 deleted.deleted = true;
366 assert!(images(&deleted).is_empty());
367 }
368
369 #[test]
370 fn file_kind_follows_the_extension_then_the_content_type() {
371 let kind = |name: Option<&str>, content_type: &str| {
372 AttachmentInfo {
373 content_type: Some(content_type.to_owned()),
374 name: name.map(str::to_owned),
375 url: None,
376 text: None,
377 size: None,
378 quote: None,
379 }
380 .file_kind()
381 };
382 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
383 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
384 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
385 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
386 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
387 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
388 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
389 assert_eq!(kind(None, "image/png"), FileKind::Image);
390 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
391 }
392
393 #[test]
394 fn files_expose_name_kind_and_open_url() {
395 let json = r#"[{"content_type":"reference","name":"Plan.docx","url":"https://x/Plan.docx","text":null},{"content_type":"messageReference","name":null,"url":null,"text":null}]"#;
396 let found = files(&record("", json));
397 assert_eq!(found.len(), 1);
398 assert_eq!(
399 (found[0].name.as_str(), found[0].kind),
400 ("Plan.docx", FileKind::Word)
401 );
402 assert_eq!(found[0].open_url, "https://x/Plan.docx");
403 assert_eq!(found[0].size, None);
404 }
405
406 #[test]
407 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
408 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
409 let text = copy_text(&record(html, "[]"));
410 assert!(text.starts_with("Hi @Ada, look"), "{text}");
411 assert!(text.contains("second link"), "{text}");
412 assert!(text.contains('\n'));
413 }
414
415 #[test]
416 fn old_cached_attachments_still_parse() {
417 let parsed = attachments(&record(
418 "",
419 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
420 ));
421 assert_eq!(parsed.len(), 1);
422 assert!(parsed[0].is_file());
423 assert_eq!(parsed[0].size, None);
424 }
425
426 #[test]
427 fn quote_references_are_extracted_from_the_message_reference_attachment() {
428 let attachment = graph::Attachment {
429 id: Some("1".to_owned()),
430 content_type: Some("messageReference".to_owned()),
431 content_url: None,
432 name: None,
433 content: Some(
434 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
435 ),
436 };
437 let info = crate::mapping::attachment_info(&attachment);
438 assert_eq!(
439 info.quote,
440 Some(QuoteInfo {
441 message_id: "1728".to_owned(),
442 preview: "Hello".to_owned(),
443 sender_name: Some("Adele".to_owned())
444 })
445 );
446 let stored = record("", &serde_json::to_string(&[info]).unwrap());
447 assert_eq!(quotes(&stored).len(), 1);
448 }
449}