BlueGit

ict rusty-teams

fix(chat): sent images stay visible instead of flashing a loading placeholder

The server echo of a sent message points at a hostedContents URL that
was not cached yet. Seed the image cache with the uploaded bytes under
that URL before the record is announced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-12 · 7 weeks ago

Hash
46ed3a3cdc1546026da73ae7797df6d3c3b0c74b
Parent
9fb1b3d1
5 files changed +156 −16
crates/core/src/actions.rs +35 −4
@@ -2,11 +2,13 @@ use chatsvc::ConversationRef;
2 2 use chrono::{DateTime, Duration, Utc};
3 3 use graph::{
4 4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5 hosted_image_order,
5 6 };
6 7 use store::MessageRecord;
7 8
8 9 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9 10 use crate::error::{Error, Result};
11 use crate::external_image::external_image_url;
10 12 use crate::links::LinkPreview;
11 13 use crate::mapping::{chat_record, message_record};
12 14 use crate::markdown::markdown_to_html;
@@ -79,7 +81,7 @@ impl<R: Remote> SyncEngine<R> {
79 81 ));
80 82 }
81 83 };
82 self.cache_sent(conversation_id, &sent)
84 self.cache_sent(conversation_id, &sent, &html, extras)
83 85 }
84 86
85 87 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
@@ -145,7 +147,7 @@ impl<R: Remote> SyncEngine<R> {
145 147 .await?
146 148 }
147 149 };
148 self.cache_sent(conversation_id, &sent)
150 self.cache_sent(conversation_id, &sent, &html, extras)
149 151 }
150 152
151 153 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
@@ -211,7 +213,7 @@ impl<R: Remote> SyncEngine<R> {
211 213 .remote
212 214 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
213 215 .await?;
214 self.cache_sent(channel_id, &sent)
216 self.cache_sent(channel_id, &sent, &html, extras)
215 217 }
216 218
217 219 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
@@ -588,9 +590,38 @@ impl<R: Remote> SyncEngine<R> {
588 590 Ok(chat.id.clone())
589 591 }
590 592
591 fn cache_sent(&self, conversation_id: &str, sent: &graph::Message) -> Result<MessageRecord> {
593 fn seed_sent_images(
594 &self,
595 record: &MessageRecord,
596 html: &str,
597 extras: &MessageExtras,
598 ) -> Result<()> {
599 let uploaded: Vec<_> = crate::stored::images(record)
600 .into_iter()
601 .filter(|image| external_image_url(&image.url).is_none())
602 .collect();
603 let order = hosted_image_order(html, extras);
604 if uploaded.len() != order.len() {
605 return Ok(());
606 }
607 let seeds: Vec<_> = uploaded
608 .iter()
609 .zip(order)
610 .map(|(image, index)| (image.key(), &extras.images[index]))
611 .collect();
612 self.seed_images(&seeds)
613 }
614
615 fn cache_sent(
616 &self,
617 conversation_id: &str,
618 sent: &graph::Message,
619 html: &str,
620 extras: &MessageExtras,
621 ) -> Result<MessageRecord> {
592 622 let record = message_record(conversation_id, sent)
593 623 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
624 let _ = self.seed_sent_images(&record, html, extras);
594 625 self.store.upsert_messages(std::slice::from_ref(&record))?;
595 626 self.update_chat_preview(std::slice::from_ref(&record))?;
596 627 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
@@ -2,11 +2,13 @@ use chatsvc::ConversationRef;
2use chrono::{DateTime, Duration, Utc};
2use chrono::{DateTime, Duration, Utc};
3use graph::{
3use graph::{
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5 hosted_image_order,
5};
6};
6use store::MessageRecord;
7use store::MessageRecord;
7
8
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::external_image::external_image_url;
10use crate::links::LinkPreview;
12use crate::links::LinkPreview;
11use crate::mapping::{chat_record, message_record};
13use crate::mapping::{chat_record, message_record};
12use crate::markdown::markdown_to_html;
14use crate::markdown::markdown_to_html;
@@ -79,7 +81,7 @@ impl<R: Remote> SyncEngine<R> {
79 ));
81 ));
80 }
82 }
81 };
83 };
82 self.cache_sent(conversation_id, &sent)
84 self.cache_sent(conversation_id, &sent, &html, extras)
83 }
85 }
84
86
85 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
87 /// Chat: quoted reply (Graph beta `replyWithQuote`). Channel: reply in the thread of `message_id`.
@@ -145,7 +147,7 @@ impl<R: Remote> SyncEngine<R> {
145 .await?
147 .await?
146 }
148 }
147 };
149 };
148 self.cache_sent(conversation_id, &sent)
150 self.cache_sent(conversation_id, &sent, &html, extras)
149 }
151 }
150
152
151 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
153 /// Own and not deleted. Chat messages, channel posts and channel replies alike.
@@ -211,7 +213,7 @@ impl<R: Remote> SyncEngine<R> {
211 .remote
213 .remote
212 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
214 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
213 .await?;
215 .await?;
214 self.cache_sent(channel_id, &sent)
216 self.cache_sent(channel_id, &sent, &html, extras)
215 }
217 }
216
218
217 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
219 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
@@ -588,9 +590,38 @@ impl<R: Remote> SyncEngine<R> {
588 Ok(chat.id.clone())
590 Ok(chat.id.clone())
589 }
591 }
590
592
591 fn cache_sent(&self, conversation_id: &str, sent: &graph::Message) -> Result<MessageRecord> {
593 fn seed_sent_images(
594 &self,
595 record: &MessageRecord,
596 html: &str,
597 extras: &MessageExtras,
598 ) -> Result<()> {
599 let uploaded: Vec<_> = crate::stored::images(record)
600 .into_iter()
601 .filter(|image| external_image_url(&image.url).is_none())
602 .collect();
603 let order = hosted_image_order(html, extras);
604 if uploaded.len() != order.len() {
605 return Ok(());
606 }
607 let seeds: Vec<_> = uploaded
608 .iter()
609 .zip(order)
610 .map(|(image, index)| (image.key(), &extras.images[index]))
611 .collect();
612 self.seed_images(&seeds)
613 }
614
615 fn cache_sent(
616 &self,
617 conversation_id: &str,
618 sent: &graph::Message,
619 html: &str,
620 extras: &MessageExtras,
621 ) -> Result<MessageRecord> {
592 let record = message_record(conversation_id, sent)
622 let record = message_record(conversation_id, sent)
593 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
623 .ok_or(Error::Unsupported("a send answer without a creation time"))?;
624 let _ = self.seed_sent_images(&record, html, extras);
594 self.store.upsert_messages(std::slice::from_ref(&record))?;
625 self.store.upsert_messages(std::slice::from_ref(&record))?;
595 self.update_chat_preview(std::slice::from_ref(&record))?;
626 self.update_chat_preview(std::slice::from_ref(&record))?;
596 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
627 let mut state = self.store.sync_state(conversation_id)?.unwrap_or_default();
crates/core/src/images.rs +40 −11
@@ -1,6 +1,7 @@
1 1 use std::path::{Path, PathBuf};
2 2
3 3 use chrono::Utc;
4 use graph::HostedImage;
4 5 use store::{ImageFileCache, ImageRecord};
5 6
6 7 use crate::engine::SyncEngine;
@@ -78,28 +79,56 @@ impl<R: Remote> SyncEngine<R> {
78 79 Some(url) => self.remote.external_image(&url).await?,
79 80 None => self.remote.hosted_content(key).await?,
80 81 };
81 let path = match &self.image_files {
82 let path = self.store_image(key, photo.bytes, photo.content_type)?;
83 let _ = self.events.send(CoreEvent::ImagesChanged {
84 keys: vec![key.to_owned()],
85 });
86 Ok(path)
87 }
88
89 pub(crate) fn seed_images(&self, images: &[(&str, &HostedImage)]) -> Result<()> {
90 let mut seeded = Vec::new();
91 for (key, image) in images {
92 let cached = match &self.image_files {
93 Some(files) => files.path(key).is_some(),
94 None => self.store.has_image(key)?,
95 };
96 if cached {
97 continue;
98 }
99 self.store_image(key, image.bytes.to_vec(), image.content_type.clone())?;
100 seeded.push((*key).to_owned());
101 }
102 if !seeded.is_empty() {
103 let _ = self.events.send(CoreEvent::ImagesChanged { keys: seeded });
104 }
105 Ok(())
106 }
107
108 fn store_image(
109 &self,
110 key: &str,
111 bytes: Vec<u8>,
112 content_type: String,
113 ) -> Result<Option<PathBuf>> {
114 match &self.image_files {
82 115 Some(files) => {
83 let extension = file_extension(&photo.content_type, &photo.bytes);
84 Some(files.put(key, &photo.bytes, extension)?)
116 let extension = file_extension(&content_type, &bytes);
117 Ok(Some(files.put(key, &bytes, extension)?))
85 118 }
86 119 None => {
87 120 self.store.put_image(
88 121 &ImageRecord {
89 122 key: key.to_owned(),
90 bytes: photo.bytes,
91 content_type: photo.content_type,
123 bytes,
124 content_type,
92 125 fetched_at: Utc::now(),
93 126 },
94 127 IMAGE_CACHE_MAX_BYTES,
95 128 )?;
96 None
129 Ok(None)
97 130 }
98 };
99 let _ = self.events.send(CoreEvent::ImagesChanged {
100 keys: vec![key.to_owned()],
101 });
102 Ok(path)
131 }
103 132 }
104 133
105 134 fn claim_image(&self, key: &str) -> bool {
@@ -1,6 +1,7 @@
1use std::path::{Path, PathBuf};
1use std::path::{Path, PathBuf};
2
2
3use chrono::Utc;
3use chrono::Utc;
4use graph::HostedImage;
4use store::{ImageFileCache, ImageRecord};
5use store::{ImageFileCache, ImageRecord};
5
6
6use crate::engine::SyncEngine;
7use crate::engine::SyncEngine;
@@ -78,28 +79,56 @@ impl<R: Remote> SyncEngine<R> {
78 Some(url) => self.remote.external_image(&url).await?,
79 Some(url) => self.remote.external_image(&url).await?,
79 None => self.remote.hosted_content(key).await?,
80 None => self.remote.hosted_content(key).await?,
80 };
81 };
81 let path = match &self.image_files {
82 let path = self.store_image(key, photo.bytes, photo.content_type)?;
83 let _ = self.events.send(CoreEvent::ImagesChanged {
84 keys: vec![key.to_owned()],
85 });
86 Ok(path)
87 }
88
89 pub(crate) fn seed_images(&self, images: &[(&str, &HostedImage)]) -> Result<()> {
90 let mut seeded = Vec::new();
91 for (key, image) in images {
92 let cached = match &self.image_files {
93 Some(files) => files.path(key).is_some(),
94 None => self.store.has_image(key)?,
95 };
96 if cached {
97 continue;
98 }
99 self.store_image(key, image.bytes.to_vec(), image.content_type.clone())?;
100 seeded.push((*key).to_owned());
101 }
102 if !seeded.is_empty() {
103 let _ = self.events.send(CoreEvent::ImagesChanged { keys: seeded });
104 }
105 Ok(())
106 }
107
108 fn store_image(
109 &self,
110 key: &str,
111 bytes: Vec<u8>,
112 content_type: String,
113 ) -> Result<Option<PathBuf>> {
114 match &self.image_files {
82 Some(files) => {
115 Some(files) => {
83 let extension = file_extension(&photo.content_type, &photo.bytes);
116 let extension = file_extension(&content_type, &bytes);
84 Some(files.put(key, &photo.bytes, extension)?)
117 Ok(Some(files.put(key, &bytes, extension)?))
85 }
118 }
86 None => {
119 None => {
87 self.store.put_image(
120 self.store.put_image(
88 &ImageRecord {
121 &ImageRecord {
89 key: key.to_owned(),
122 key: key.to_owned(),
90 bytes: photo.bytes,
123 bytes,
91 content_type: photo.content_type,
124 content_type,
92 fetched_at: Utc::now(),
125 fetched_at: Utc::now(),
93 },
126 },
94 IMAGE_CACHE_MAX_BYTES,
127 IMAGE_CACHE_MAX_BYTES,
95 )?;
128 )?;
96 None
129 Ok(None)
97 }
130 }
98 };
131 }
99 let _ = self.events.send(CoreEvent::ImagesChanged {
100 keys: vec![key.to_owned()],
101 });
102 Ok(path)
103 }
132 }
104
133
105 fn claim_image(&self, key: &str) -> bool {
134 fn claim_image(&self, key: &str) -> bool {
crates/core/tests/engine.rs +43 −1
@@ -102,6 +102,7 @@ struct Fake {
102 102 external_requests: Mutex<Vec<String>>,
103 103 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
104 104 extras_sent: Mutex<Vec<MessageExtras>>,
105 send_answer_body: Mutex<Option<String>>,
105 106 folder_requests: Mutex<usize>,
106 107 directory_users: Mutex<Vec<User>>,
107 108 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
@@ -389,7 +390,13 @@ impl Remote for Handle {
389 390 self.sent.lock().unwrap().push(html.to_owned());
390 391 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
391 392 self.extras_sent.lock().unwrap().push(extras.clone());
392 Ok(message(9000, 500, html))
393 let body = self
394 .send_answer_body
395 .lock()
396 .unwrap()
397 .clone()
398 .unwrap_or_else(|| html.to_owned());
399 Ok(message(9000, 500, &body))
393 400 }
394 401
395 402 async fn send_channel_message(
@@ -2030,6 +2037,41 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2030 2037 assert!(sent[1].is_empty());
2031 2038 }
2032 2039
2040 #[tokio::test]
2041 async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2042 let directory = tempfile::tempdir().unwrap();
2043 let fake = Arc::new(Fake::default());
2044 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
2045 *fake.send_answer_body.lock().unwrap() = Some(format!("<p>look</p><img src=\"{HOSTED}\">"));
2046 let engine = engine_with(&fake, small_pages())
2047 .with_image_dir(directory.path(), 1024 * 1024)
2048 .unwrap();
2049 engine.refresh_sidebar().await.unwrap();
2050 let extras = MessageExtras {
2051 kept: Vec::new(),
2052 images: vec![HostedImage {
2053 content_type: "image/png".into(),
2054 bytes: Arc::new(vec![9, 8, 7]),
2055 }],
2056 files: Vec::new(),
2057 };
2058 let mut events = engine.subscribe();
2059
2060 engine
2061 .send_message_with_extras(CHAT, "look", None, &[], &extras)
2062 .await
2063 .unwrap();
2064
2065 assert_eq!(engine.image(HOSTED).unwrap().bytes, vec![9, 8, 7]);
2066 assert!(fake.hosted_requests.lock().unwrap().is_empty());
2067 let mut seeded = false;
2068 while let Ok(event) = events.try_recv() {
2069 seeded |=
2070 matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![HOSTED.to_owned()]);
2071 }
2072 assert!(seeded);
2073 }
2074
2033 2075 #[tokio::test]
2034 2076 async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2035 2077 let fake = Arc::new(Fake::default());
@@ -102,6 +102,7 @@ struct Fake {
102 external_requests: Mutex<Vec<String>>,
102 external_requests: Mutex<Vec<String>>,
103 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
103 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
104 extras_sent: Mutex<Vec<MessageExtras>>,
104 extras_sent: Mutex<Vec<MessageExtras>>,
105 send_answer_body: Mutex<Option<String>>,
105 folder_requests: Mutex<usize>,
106 folder_requests: Mutex<usize>,
106 directory_users: Mutex<Vec<User>>,
107 directory_users: Mutex<Vec<User>>,
107 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
108 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
@@ -389,7 +390,13 @@ impl Remote for Handle {
389 self.sent.lock().unwrap().push(html.to_owned());
390 self.sent.lock().unwrap().push(html.to_owned());
390 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
391 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
391 self.extras_sent.lock().unwrap().push(extras.clone());
392 self.extras_sent.lock().unwrap().push(extras.clone());
392 Ok(message(9000, 500, html))
393 let body = self
394 .send_answer_body
395 .lock()
396 .unwrap()
397 .clone()
398 .unwrap_or_else(|| html.to_owned());
399 Ok(message(9000, 500, &body))
393 }
400 }
394
401
395 async fn send_channel_message(
402 async fn send_channel_message(
@@ -2030,6 +2037,41 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2030 assert!(sent[1].is_empty());
2037 assert!(sent[1].is_empty());
2031}
2038}
2032
2039
2040#[tokio::test]
2041async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2042 let directory = tempfile::tempdir().unwrap();
2043 let fake = Arc::new(Fake::default());
2044 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
2045 *fake.send_answer_body.lock().unwrap() = Some(format!("<p>look</p><img src=\"{HOSTED}\">"));
2046 let engine = engine_with(&fake, small_pages())
2047 .with_image_dir(directory.path(), 1024 * 1024)
2048 .unwrap();
2049 engine.refresh_sidebar().await.unwrap();
2050 let extras = MessageExtras {
2051 kept: Vec::new(),
2052 images: vec![HostedImage {
2053 content_type: "image/png".into(),
2054 bytes: Arc::new(vec![9, 8, 7]),
2055 }],
2056 files: Vec::new(),
2057 };
2058 let mut events = engine.subscribe();
2059
2060 engine
2061 .send_message_with_extras(CHAT, "look", None, &[], &extras)
2062 .await
2063 .unwrap();
2064
2065 assert_eq!(engine.image(HOSTED).unwrap().bytes, vec![9, 8, 7]);
2066 assert!(fake.hosted_requests.lock().unwrap().is_empty());
2067 let mut seeded = false;
2068 while let Ok(event) = events.try_recv() {
2069 seeded |=
2070 matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![HOSTED.to_owned()]);
2071 }
2072 assert!(seeded);
2073}
2074
2033#[tokio::test]
2075#[tokio::test]
2034async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2076async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2035 let fake = Arc::new(Fake::default());
2077 let fake = Arc::new(Fake::default());
crates/graph/src/lib.rs +1 −0
@@ -27,6 +27,7 @@ pub use models::{
27 27 };
28 28 pub use outgoing::{
29 29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
30 hosted_image_order,
30 31 };
31 32 pub use page::Page;
32 33 pub use people::MAX_PRESENCE_IDS;
@@ -27,6 +27,7 @@ pub use models::{
27};
27};
28pub use outgoing::{
28pub use outgoing::{
29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
30 hosted_image_order,
30};
31};
31pub use page::Page;
32pub use page::Page;
32pub use people::MAX_PRESENCE_IDS;
33pub use people::MAX_PRESENCE_IDS;
crates/graph/src/outgoing.rs +37 −0
@@ -101,6 +101,27 @@ fn extras_html(html: &str, extras: &MessageExtras) -> String {
101 101 content
102 102 }
103 103
104 pub fn hosted_image_order(html: &str, extras: &MessageExtras) -> Vec<usize> {
105 const PREFIX: &str = "../hostedContents/";
106 const SUFFIX: &str = "/$value";
107 let content = extras_html(html, extras);
108 content
109 .match_indices(PREFIX)
110 .filter_map(|(position, _)| {
111 let rest = &content[position + PREFIX.len()..];
112 let (digits, tail) =
113 rest.split_at(rest.find(|character: char| !character.is_ascii_digit())?);
114 if !tail.starts_with(SUFFIX) {
115 return None;
116 }
117 let index = digits.parse::<usize>().ok()?;
118 (1..=extras.images.len())
119 .contains(&index)
120 .then(|| index - 1)
121 })
122 .collect()
123 }
124
104 125 pub(crate) fn message_body(
105 126 html: &str,
106 127 mentions: &[OutgoingMention],
@@ -266,6 +287,22 @@ mod tests {
266 287 assert!(body.get("attachments").is_none());
267 288 }
268 289
290 #[test]
291 fn hosted_image_order_follows_the_body_and_skips_other_images() {
292 let extras = MessageExtras {
293 kept: Vec::new(),
294 images: vec![
295 image("image/png", &[1]),
296 image("image/png", &[2]),
297 image("image/png", &[3]),
298 ],
299 files: Vec::new(),
300 };
301 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
303 assert_eq!(hosted_image_order("<p>none</p>", &extras), vec![0, 1, 2]);
304 }
305
269 306 #[test]
270 307 fn images_already_placed_in_the_text_are_not_appended_again() {
271 308 let extras = MessageExtras {
@@ -101,6 +101,27 @@ fn extras_html(html: &str, extras: &MessageExtras) -> String {
101 content
101 content
102}
102}
103
103
104pub fn hosted_image_order(html: &str, extras: &MessageExtras) -> Vec<usize> {
105 const PREFIX: &str = "../hostedContents/";
106 const SUFFIX: &str = "/$value";
107 let content = extras_html(html, extras);
108 content
109 .match_indices(PREFIX)
110 .filter_map(|(position, _)| {
111 let rest = &content[position + PREFIX.len()..];
112 let (digits, tail) =
113 rest.split_at(rest.find(|character: char| !character.is_ascii_digit())?);
114 if !tail.starts_with(SUFFIX) {
115 return None;
116 }
117 let index = digits.parse::<usize>().ok()?;
118 (1..=extras.images.len())
119 .contains(&index)
120 .then(|| index - 1)
121 })
122 .collect()
123}
124
104pub(crate) fn message_body(
125pub(crate) fn message_body(
105 html: &str,
126 html: &str,
106 mentions: &[OutgoingMention],
127 mentions: &[OutgoingMention],
@@ -266,6 +287,22 @@ mod tests {
266 assert!(body.get("attachments").is_none());
287 assert!(body.get("attachments").is_none());
267 }
288 }
268
289
290 #[test]
291 fn hosted_image_order_follows_the_body_and_skips_other_images() {
292 let extras = MessageExtras {
293 kept: Vec::new(),
294 images: vec![
295 image("image/png", &[1]),
296 image("image/png", &[2]),
297 image("image/png", &[3]),
298 ],
299 files: Vec::new(),
300 };
301 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
303 assert_eq!(hosted_image_order("<p>none</p>", &extras), vec![0, 1, 2]);
304 }
305
269 #[test]
306 #[test]
270 fn images_already_placed_in_the_text_are_not_appended_again() {
307 fn images_already_placed_in_the_text_are_not_appended_again() {
271 let extras = MessageExtras {
308 let extras = MessageExtras {