BlueGit

ict rusty-teams

feat(app): attach files, paste or drag images

- Paperclip, Ctrl+V and drag and drop add items to a tray in the composer
- Images up to 1 MiB (2.5 MiB per message) go inline via hostedContents
- Other files upload in 1.25 MiB chunks with resume, to OneDrive (shared
  with chat members) or the channel's Files folder
- Upload progress, failure and Retry per item; Send waits for uploads
- Edits keep images, files and quotes of the original message
- Demo mode simulates uploads

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
eba4ad949f4dab31b44926b404c03da803433804
Parent
ebb533cf
30 files changed +3856 −124
ROADMAP.md +10 −11
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 56 %** (46 done, 4 partial, 35 missing of 85). Partial counts half.
5 **Parity: 58 %** (47 done, 4 partial, 34 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13 13 | [Reading](#reading) | 71 % | 13 | 1 | 5 |
14 | [Writing](#writing) | 61 % | 8 | 1 | 5 |
14 | [Writing](#writing) | 68 % | 9 | 1 | 4 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
17 17 | [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -24,14 +24,13 @@ Feature parity with the Microsoft Teams desktop client.
24 24
25 25 | # | Feature | Note |
26 26 |---|---|---|
27 | 1 | Attach a file, paste or drag an image | |
28 | 2 | Channel: new post with subject, post cards | |
29 | 3 | Sign in on Linux without Chrome on a debug port | |
30 | 4 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
31 | 5 | Emoji picker in the composer | Reaction picker exists |
32 | 6 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
33 | 7 | Typing indicator | |
34 | 8 | Unsent messages survive a restart | |
27 | 1 | Channel: new post with subject, post cards | |
28 | 2 | Sign in on Linux without Chrome on a debug port | |
29 | 3 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
30 | 4 | Emoji picker in the composer | Reaction picker exists |
31 | 5 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
32 | 6 | Typing indicator | |
33 | 7 | Unsent messages survive a restart | |
35 34
36 35 ## Sign-in and app
37 36
@@ -97,7 +96,7 @@ Feature parity with the Microsoft Teams desktop client.
97 96 | React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
98 97 | Emoji picker | Partial | For reactions; composer still uses colon codes |
99 98 | Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
100 | Attach a file, paste or drag an image | Missing | |
99 | Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
101 100 | GIFs and stickers | Missing | |
102 101 | Schedule send | Missing | |
103 102 | Unsent messages survive a restart | Missing | Pending sends live in memory only |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 56 %** (46 done, 4 partial, 35 missing of 85). Partial counts half.
5**Parity: 58 %** (47 done, 4 partial, 34 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
12| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13| [Reading](#reading) | 71 % | 13 | 1 | 5 |
13| [Reading](#reading) | 71 % | 13 | 1 | 5 |
14| [Writing](#writing) | 61 % | 8 | 1 | 5 |
14| [Writing](#writing) | 68 % | 9 | 1 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -24,14 +24,13 @@ Feature parity with the Microsoft Teams desktop client.
24
24
25| # | Feature | Note |
25| # | Feature | Note |
26|---|---|---|
26|---|---|---|
27| 1 | Attach a file, paste or drag an image | |
27| 1 | Channel: new post with subject, post cards | |
28| 2 | Channel: new post with subject, post cards | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
29| 3 | Sign in on Linux without Chrome on a debug port | |
29| 3 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
30| 4 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
30| 4 | Emoji picker in the composer | Reaction picker exists |
31| 5 | Emoji picker in the composer | Reaction picker exists |
31| 5 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
32| 6 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
32| 6 | Typing indicator | |
33| 7 | Typing indicator | |
33| 7 | Unsent messages survive a restart | |
34| 8 | Unsent messages survive a restart | |
35
34
36## Sign-in and app
35## Sign-in and app
37
36
@@ -97,7 +96,7 @@ Feature parity with the Microsoft Teams desktop client.
97| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
96| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
98| Emoji picker | Partial | For reactions; composer still uses colon codes |
97| Emoji picker | Partial | For reactions; composer still uses colon codes |
99| Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
98| Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
100| Attach a file, paste or drag an image | Missing | |
99| Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
101| GIFs and stickers | Missing | |
100| GIFs and stickers | Missing | |
102| Schedule send | Missing | |
101| Schedule send | Missing | |
103| Unsent messages survive a restart | Missing | Pending sends live in memory only |
102| Unsent messages survive a restart | Missing | Pending sends live in memory only |
crates/app/Cargo.toml +1 −1
@@ -28,7 +28,7 @@ session.workspace = true
28 28 store.workspace = true
29 29 teams-core.workspace = true
30 30 tokio.workspace = true
31 image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
31 image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }
32 32
33 33 [target.'cfg(windows)'.dependencies]
34 34 webview.workspace = true
@@ -28,7 +28,7 @@ session.workspace = true
28store.workspace = true
28store.workspace = true
29teams-core.workspace = true
29teams-core.workspace = true
30tokio.workspace = true
30tokio.workspace = true
31image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
31image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }
32
32
33[target.'cfg(windows)'.dependencies]
33[target.'cfg(windows)'.dependencies]
34webview.workspace = true
34webview.workspace = true
crates/app/assets/symbols/attach_file.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
crates/app/assets/symbols/upload.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/></svg>
crates/app/src/assets.rs +3 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 13] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 15] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -22,6 +22,8 @@ const SYMBOLS: [(&str, &[u8]); 13] = symbols![
22 22 "error",
23 23 "notifications",
24 24 "content_copy",
25 "attach_file",
26 "upload",
25 27 ];
26 28
27 29 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 13] = symbols![
11const SYMBOLS: [(&str, &[u8]); 15] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -22,6 +22,8 @@ const SYMBOLS: [(&str, &[u8]); 13] = symbols![
22 "error",
22 "error",
23 "notifications",
23 "notifications",
24 "content_copy",
24 "content_copy",
25 "attach_file",
26 "upload",
25];
27];
26
28
27pub struct AppAssets;
29pub struct AppAssets;
crates/app/src/rows.rs +11 −0
@@ -1,7 +1,9 @@
1 1 use std::collections::BTreeMap;
2 2 use std::ops::Range;
3 use std::sync::Arc;
3 4
4 5 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 use gpui_kit::Image;
5 7 use store::MessageRecord;
6 8 use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
7 9
@@ -89,6 +91,13 @@ pub enum Delivery {
89 91 Failed(String),
90 92 }
91 93
94 /// An image of a message that is still being sent, shown from its local bytes.
95 #[derive(Debug, Clone, PartialEq)]
96 pub struct LocalImage {
97 pub image: Arc<Image>,
98 pub size: Option<(u32, u32)>,
99 }
100
92 101 #[derive(Debug, Clone, PartialEq)]
93 102 pub struct MessageRow {
94 103 pub key: String,
@@ -104,6 +113,7 @@ pub struct MessageRow {
104 113 pub deleted: bool,
105 114 pub reactions: Vec<ReactionChip>,
106 115 pub images: Vec<ImageRef>,
116 pub local_images: Vec<LocalImage>,
107 117 pub files: Vec<FileCard>,
108 118 pub reply_count: Option<usize>,
109 119 pub new_marker: bool,
@@ -367,6 +377,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
367 377 deleted: record.deleted,
368 378 reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()),
369 379 images,
380 local_images: Vec::new(),
370 381 files: files(record),
371 382 reply_count: None,
372 383 new_marker: false,
@@ -1,7 +1,9 @@
1use std::collections::BTreeMap;
1use std::collections::BTreeMap;
2use std::ops::Range;
2use std::ops::Range;
3use std::sync::Arc;
3
4
4use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
5use store::MessageRecord;
7use store::MessageRecord;
6use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
8use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
7
9
@@ -89,6 +91,13 @@ pub enum Delivery {
89 Failed(String),
91 Failed(String),
90}
92}
91
93
94/// An image of a message that is still being sent, shown from its local bytes.
95#[derive(Debug, Clone, PartialEq)]
96pub struct LocalImage {
97 pub image: Arc<Image>,
98 pub size: Option<(u32, u32)>,
99}
100
92#[derive(Debug, Clone, PartialEq)]
101#[derive(Debug, Clone, PartialEq)]
93pub struct MessageRow {
102pub struct MessageRow {
94 pub key: String,
103 pub key: String,
@@ -104,6 +113,7 @@ pub struct MessageRow {
104 pub deleted: bool,
113 pub deleted: bool,
105 pub reactions: Vec<ReactionChip>,
114 pub reactions: Vec<ReactionChip>,
106 pub images: Vec<ImageRef>,
115 pub images: Vec<ImageRef>,
116 pub local_images: Vec<LocalImage>,
107 pub files: Vec<FileCard>,
117 pub files: Vec<FileCard>,
108 pub reply_count: Option<usize>,
118 pub reply_count: Option<usize>,
109 pub new_marker: bool,
119 pub new_marker: bool,
@@ -367,6 +377,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
367 deleted: record.deleted,
377 deleted: record.deleted,
368 reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()),
378 reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()),
369 images,
379 images,
380 local_images: Vec::new(),
370 files: files(record),
381 files: files(record),
371 reply_count: None,
382 reply_count: None,
372 new_marker: false,
383 new_marker: false,
crates/app/src/runtime.rs +11 −0
@@ -31,3 +31,14 @@ pub fn spawn<T: Send + 'static>(
31 31 });
32 32 receiver
33 33 }
34
35 /// Like `spawn`, plus a handle that stops the future at its next await point.
36 pub fn spawn_abortable<T: Send + 'static>(
37 future: impl Future<Output = T> + Send + 'static,
38 ) -> (oneshot::Receiver<T>, tokio::task::AbortHandle) {
39 let (sender, receiver) = oneshot::channel();
40 let task = runtime().spawn(async move {
41 let _ = sender.send(future.await);
42 });
43 (receiver, task.abort_handle())
44 }
@@ -31,3 +31,14 @@ pub fn spawn<T: Send + 'static>(
31 });
31 });
32 receiver
32 receiver
33}
33}
34
35/// Like `spawn`, plus a handle that stops the future at its next await point.
36pub fn spawn_abortable<T: Send + 'static>(
37 future: impl Future<Output = T> + Send + 'static,
38) -> (oneshot::Receiver<T>, tokio::task::AbortHandle) {
39 let (sender, receiver) = oneshot::channel();
40 let task = runtime().spawn(async move {
41 let _ = sender.send(future.await);
42 });
43 (receiver, task.abort_handle())
44}
crates/app/src/views/attachment_tray.rs added +1381 −0
@@ -0,0 +1,1381 @@
1 use std::io::Cursor;
2 use std::path::{Path, PathBuf};
3 use std::sync::Arc;
4
5 use gpui_kit::assets::IconName;
6 use gpui_kit::component::{h_flex, v_flex};
7 use gpui_kit::prelude::FluentBuilder as _;
8 use gpui_kit::*;
9 use teams_core::{FileKind, FileReference, UploadedFile};
10
11 use super::attachments::file_badge;
12 use super::widgets::icon;
13 use crate::format;
14 use crate::theme;
15
16 pub const MAX_ATTACHMENTS: usize = 10;
17 pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
18 pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
19 pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
20 pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
21 const PASTED_IMAGE_STEM: &str = "pasted-image";
22 const THUMB_SIZE: f32 = 72.;
23 const CHIP_WIDTH: f32 = 220.;
24 const CHIP_HEIGHT: f32 = 48.;
25 const CHIP_BADGE_SIZE: f32 = 30.;
26 const REMOVE_SIZE: f32 = 18.;
27 const TRAY_GAP: f32 = 8.;
28 const PROGRESS_HEIGHT: f32 = 2.;
29
30 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 pub enum InlineFormat {
32 Png,
33 Jpeg,
34 Gif,
35 Webp,
36 }
37
38 impl InlineFormat {
39 fn image_format(self) -> ImageFormat {
40 match self {
41 InlineFormat::Png => ImageFormat::Png,
42 InlineFormat::Jpeg => ImageFormat::Jpeg,
43 InlineFormat::Gif => ImageFormat::Gif,
44 InlineFormat::Webp => ImageFormat::Webp,
45 }
46 }
47
48 fn decoder_format(self) -> Option<image::ImageFormat> {
49 match self {
50 InlineFormat::Png => Some(image::ImageFormat::Png),
51 InlineFormat::Jpeg => Some(image::ImageFormat::Jpeg),
52 InlineFormat::Webp => Some(image::ImageFormat::WebP),
53 InlineFormat::Gif => None,
54 }
55 }
56 }
57
58 pub fn sniff_inline_format(bytes: &[u8]) -> Option<InlineFormat> {
59 match bytes {
60 [0x89, b'P', b'N', b'G', ..] => Some(InlineFormat::Png),
61 [0xFF, 0xD8, 0xFF, ..] => Some(InlineFormat::Jpeg),
62 [b'G', b'I', b'F', b'8', ..] => Some(InlineFormat::Gif),
63 [
64 b'R',
65 b'I',
66 b'F',
67 b'F',
68 _,
69 _,
70 _,
71 _,
72 b'W',
73 b'E',
74 b'B',
75 b'P',
76 ..,
77 ] => Some(InlineFormat::Webp),
78 _ => None,
79 }
80 }
81
82 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
83 pub enum Classification {
84 Inline(InlineFormat),
85 File { sent_as_file: bool },
86 }
87
88 /// `inline_used` is the raw bytes of the images already inline in the tray.
89 pub fn classify(name: &str, bytes: &[u8], inline_used: u64) -> Classification {
90 let size = bytes.len() as u64;
91 match sniff_inline_format(bytes) {
92 Some(format)
93 if size <= INLINE_IMAGE_MAX_BYTES && inline_used + size <= INLINE_TOTAL_MAX_BYTES =>
94 {
95 Classification::Inline(format)
96 }
97 Some(_) => Classification::File { sent_as_file: true },
98 None => Classification::File {
99 sent_as_file: FileKind::from_name(name) == FileKind::Image,
100 },
101 }
102 }
103
104 fn image_dimensions(format: InlineFormat, bytes: &[u8]) -> Option<(u32, u32)> {
105 match format.decoder_format() {
106 Some(decoder) => image::ImageReader::with_format(Cursor::new(bytes), decoder)
107 .into_dimensions()
108 .ok(),
109 None => {
110 let header = bytes.get(6..10)?;
111 Some((
112 u32::from(u16::from_le_bytes([header[0], header[1]])),
113 u32::from(u16::from_le_bytes([header[2], header[3]])),
114 ))
115 }
116 }
117 }
118
119 pub fn limit_notice(dropped: usize) -> String {
120 let files = if dropped == 1 {
121 "1 file was".to_owned()
122 } else {
123 format!("{dropped} files were")
124 };
125 format!("Up to {MAX_ATTACHMENTS} attachments per message. {files} not added.")
126 }
127
128 #[derive(Debug, Clone, PartialEq, Eq)]
129 pub enum UploadState {
130 Uploading(u8),
131 Done(DoneFile),
132 Failed,
133 Sharing(UploadedFile),
134 ShareFailed(UploadedFile),
135 }
136
137 /// `uploaded` is known for files the app uploaded, so an unsent one can be deleted again.
138 #[derive(Debug, Clone, PartialEq, Eq)]
139 pub struct DoneFile {
140 pub reference: FileReference,
141 pub uploaded: Option<UploadedFile>,
142 }
143
144 #[derive(Debug, Clone, PartialEq, Eq)]
145 pub enum UploadResult {
146 Done(DoneFile),
147 ShareFailed(UploadedFile),
148 Failed,
149 }
150
151 impl UploadState {
152 fn uploaded(&self) -> Option<UploadedFile> {
153 match self {
154 UploadState::Done(done) => done.uploaded.clone(),
155 UploadState::Sharing(uploaded) | UploadState::ShareFailed(uploaded) => {
156 Some(uploaded.clone())
157 }
158 _ => None,
159 }
160 }
161 }
162
163 #[derive(Debug, Clone)]
164 #[allow(clippy::large_enum_variant)]
165 pub enum ItemKind {
166 Reading,
167 Image {
168 image: Arc<Image>,
169 dimensions: Option<(u32, u32)>,
170 },
171 File {
172 bytes: Arc<Vec<u8>>,
173 upload: UploadState,
174 sent_as_file: bool,
175 },
176 }
177
178 #[derive(Debug, Clone)]
179 pub struct TrayItem {
180 pub id: u64,
181 pub name: String,
182 pub size: u64,
183 pub kind: ItemKind,
184 }
185
186 impl TrayItem {
187 fn blocks_send(&self) -> bool {
188 match &self.kind {
189 ItemKind::Reading => true,
190 ItemKind::Image { .. } => false,
191 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
192 }
193 }
194 }
195
196 #[derive(Debug, Clone, PartialEq, Eq)]
197 pub struct OutgoingImage {
198 pub name: String,
199 pub image: Arc<Image>,
200 pub dimensions: Option<(u32, u32)>,
201 }
202
203 #[derive(Debug, Clone, PartialEq, Eq)]
204 pub struct OutgoingFile {
205 pub name: String,
206 pub size: u64,
207 pub kind: FileKind,
208 pub reference: FileReference,
209 pub uploaded: Option<UploadedFile>,
210 }
211
212 #[derive(Debug, Clone)]
213 pub enum JobKind {
214 Upload,
215 Share(UploadedFile),
216 }
217
218 #[derive(Debug, Clone)]
219 pub struct UploadJob {
220 pub id: u64,
221 pub name: String,
222 pub bytes: Arc<Vec<u8>>,
223 pub kind: JobKind,
224 }
225
226 #[derive(Debug, Clone, PartialEq, Eq)]
227 pub struct LoadedFile {
228 pub bytes: Vec<u8>,
229 pub dimensions: Option<(u32, u32)>,
230 pub file_name: Option<String>,
231 }
232
233 impl LoadedFile {
234 pub fn new(bytes: Vec<u8>) -> Self {
235 let dimensions =
236 sniff_inline_format(&bytes).and_then(|format| image_dimensions(format, &bytes));
237 LoadedFile {
238 bytes,
239 dimensions,
240 file_name: None,
241 }
242 }
243 }
244
245 #[derive(Debug, Clone, Default)]
246 pub struct AttachmentTray {
247 items: Vec<TrayItem>,
248 next_id: u64,
249 notice: Option<String>,
250 }
251
252 impl AttachmentTray {
253 pub fn items(&self) -> &[TrayItem] {
254 &self.items
255 }
256
257 pub fn is_empty(&self) -> bool {
258 self.items.is_empty()
259 }
260
261 pub fn notice(&self) -> Option<&str> {
262 self.notice.as_deref()
263 }
264
265 pub fn blocks_send(&self) -> bool {
266 self.items.iter().any(TrayItem::blocks_send)
267 }
268
269 fn push(&mut self, name: String, size: u64, kind: ItemKind) -> u64 {
270 self.next_id += 1;
271 self.items.push(TrayItem {
272 id: self.next_id,
273 name,
274 size,
275 kind,
276 });
277 self.next_id
278 }
279
280 /// Items beyond the limit are dropped; the ids returned belong to the first names.
281 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
282 self.notice = None;
283 let accepted = names
284 .len()
285 .min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
286 let ids = names[..accepted]
287 .iter()
288 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
289 .collect();
290 if accepted < names.len() {
291 self.notice = Some(limit_notice(names.len() - accepted));
292 }
293 ids
294 }
295
296 /// Returns the upload to start when the item turned out to be a file.
297 pub fn finish_reading(
298 &mut self,
299 id: u64,
300 loaded: LoadedFile,
301 files_allowed: bool,
302 ) -> Option<UploadJob> {
303 let position = self
304 .items
305 .iter()
306 .position(|item| item.id == id && matches!(item.kind, ItemKind::Reading))?;
307 let name = loaded
308 .file_name
309 .clone()
310 .unwrap_or_else(|| self.items[position].name.clone());
311 let size = loaded.bytes.len() as u64;
312 match classify(&name, &loaded.bytes, self.inline_bytes()) {
313 Classification::Inline(format) => {
314 let item = &mut self.items[position];
315 item.name = name;
316 item.size = size;
317 item.kind = ItemKind::Image {
318 image: Arc::new(Image::from_bytes(format.image_format(), loaded.bytes)),
319 dimensions: loaded.dimensions,
320 };
321 None
322 }
323 Classification::File { .. } if !files_allowed => {
324 self.items.remove(position);
325 self.notice = Some(FILES_LATER_NOTICE.to_owned());
326 None
327 }
328 Classification::File { sent_as_file } => {
329 let bytes = Arc::new(loaded.bytes);
330 let item = &mut self.items[position];
331 item.name = name.clone();
332 item.size = size;
333 item.kind = ItemKind::File {
334 bytes: bytes.clone(),
335 upload: UploadState::Uploading(0),
336 sent_as_file,
337 };
338 Some(UploadJob {
339 id,
340 name,
341 bytes,
342 kind: JobKind::Upload,
343 })
344 }
345 }
346 }
347
348 pub fn fail_reading(&mut self, id: u64, message: String) {
349 let before = self.items.len();
350 self.items.retain(|item| item.id != id);
351 if self.items.len() != before {
352 self.notice = Some(message);
353 }
354 }
355
356 pub fn set_progress(&mut self, id: u64, percent: u8) {
357 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
358 && matches!(upload, UploadState::Uploading(_))
359 {
360 *upload = UploadState::Uploading(percent.min(100));
361 }
362 }
363
364 /// The bytes are on the server; from here a remove or switch must delete the item.
365 /// Returns the file back when its item is gone, so the caller can delete it.
366 pub fn mark_uploaded(&mut self, id: u64, uploaded: UploadedFile) -> Option<UploadedFile> {
367 if !self.items.iter().any(|item| item.id == id) {
368 return Some(uploaded);
369 }
370 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
371 && matches!(upload, UploadState::Uploading(_))
372 {
373 *upload = UploadState::Sharing(uploaded);
374 }
375 None
376 }
377
378 /// Returns the uploaded file of a result whose item is gone, so the caller can delete it.
379 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
380 if !self.items.iter().any(|item| item.id == id) {
381 return match result {
382 UploadResult::Done(done) => done.uploaded,
383 UploadResult::ShareFailed(uploaded) => Some(uploaded),
384 UploadResult::Failed => None,
385 };
386 }
387 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
388 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
389 {
390 *upload = match result {
391 UploadResult::Done(done) => UploadState::Done(done),
392 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
393 UploadResult::Failed => UploadState::Failed,
394 };
395 }
396 None
397 }
398
399 pub fn retry(&mut self, id: u64) -> Option<UploadJob> {
400 self.notice = None;
401 let item = self.items.iter_mut().find(|item| item.id == id)?;
402 let ItemKind::File { bytes, upload, .. } = &mut item.kind else {
403 return None;
404 };
405 match upload.clone() {
406 UploadState::Failed => *upload = UploadState::Uploading(0),
407 UploadState::ShareFailed(uploaded) => *upload = UploadState::Sharing(uploaded),
408 _ => return None,
409 }
410 let kind = match upload {
411 UploadState::Sharing(uploaded) => JobKind::Share(uploaded.clone()),
412 _ => JobKind::Upload,
413 };
414 Some(UploadJob {
415 id,
416 name: item.name.clone(),
417 bytes: bytes.clone(),
418 kind,
419 })
420 }
421
422 /// Returns the uploaded file of the removed item, which was never sent.
423 pub fn remove(&mut self, id: u64) -> Option<UploadedFile> {
424 self.notice = None;
425 let position = self.items.iter().position(|item| item.id == id)?;
426 match self.items.remove(position).kind {
427 ItemKind::File { upload, .. } => upload.uploaded(),
428 _ => None,
429 }
430 }
431
432 /// Returns the uploaded files that were dropped unsent.
433 pub fn clear(&mut self) -> Vec<UploadedFile> {
434 self.notice = None;
435 self.items
436 .drain(..)
437 .filter_map(|item| match item.kind {
438 ItemKind::File { upload, .. } => upload.uploaded(),
439 _ => None,
440 })
441 .collect()
442 }
443
444 pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {
445 self.notice = None;
446 let (images, others): (Vec<_>, Vec<_>) = self
447 .items
448 .drain(..)
449 .partition(|item| matches!(item.kind, ItemKind::Image { .. }));
450 self.items = images;
451 others
452 .into_iter()
453 .filter_map(|item| match item.kind {
454 ItemKind::File { upload, .. } => upload.uploaded(),
455 _ => None,
456 })
457 .collect()
458 }
459
460 fn inline_bytes(&self) -> u64 {
461 self.items
462 .iter()
463 .filter(|item| matches!(item.kind, ItemKind::Image { .. }))
464 .map(|item| item.size)
465 .sum()
466 }
467
468 pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) {
469 self.clear();
470 for image in images {
471 self.push(
472 image.name.clone(),
473 image.image.bytes.len() as u64,
474 ItemKind::Image {
475 image: image.image.clone(),
476 dimensions: image.dimensions,
477 },
478 );
479 }
480 for file in files {
481 self.push(
482 file.name.clone(),
483 file.size,
484 ItemKind::File {
485 bytes: Arc::new(Vec::new()),
486 upload: UploadState::Done(DoneFile {
487 reference: file.reference.clone(),
488 uploaded: file.uploaded.clone(),
489 }),
490 sent_as_file: false,
491 },
492 );
493 }
494 }
495
496 pub fn outgoing_images(&self) -> Vec<OutgoingImage> {
497 self.items
498 .iter()
499 .filter_map(|item| match &item.kind {
500 ItemKind::Image { image, dimensions } => Some(OutgoingImage {
501 name: item.name.clone(),
502 image: image.clone(),
503 dimensions: *dimensions,
504 }),
505 _ => None,
506 })
507 .collect()
508 }
509
510 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
511 self.items
512 .iter()
513 .filter_map(|item| match &item.kind {
514 ItemKind::File {
515 upload: UploadState::Done(done),
516 ..
517 } => Some(OutgoingFile {
518 name: item.name.clone(),
519 size: item.size,
520 kind: FileKind::from_name(&item.name),
521 reference: done.reference.clone(),
522 uploaded: done.uploaded.clone(),
523 }),
524 _ => None,
525 })
526 .collect()
527 }
528
529 fn kind_of_mut(&mut self, id: u64) -> Option<&mut ItemKind> {
530 self.items
531 .iter_mut()
532 .find(|item| item.id == id)
533 .map(|item| &mut item.kind)
534 }
535 }
536
537 fn display_name(path: &Path) -> String {
538 path.file_name()
539 .map(|name| name.to_string_lossy().into_owned())
540 .unwrap_or_else(|| path.to_string_lossy().into_owned())
541 }
542
543 pub fn discard_uploaded(engine: Option<Arc<crate::backend::Engine>>, files: Vec<UploadedFile>) {
544 let Some(engine) = engine else {
545 return;
546 };
547 for file in files {
548 let engine = engine.clone();
549 drop(crate::runtime::spawn(async move {
550 let _ = engine.discard_attachment(&file).await;
551 }));
552 }
553 }
554
555 pub fn names_of(paths: &[PathBuf]) -> Vec<String> {
556 paths.iter().map(|path| display_name(path)).collect()
557 }
558
559 pub fn read_attachment(path: &Path) -> Result<LoadedFile, String> {
560 let name = display_name(path);
561 let unreadable = || format!("Could not read {name}.");
562 let metadata = std::fs::metadata(path).map_err(|_| unreadable())?;
563 if !metadata.is_file() {
564 return Err(unreadable());
565 }
566 if metadata.len() > MAX_FILE_BYTES {
567 return Err(format!(
568 "{name} is larger than {} MB.",
569 MAX_FILE_BYTES / (1024 * 1024)
570 ));
571 }
572 let bytes = std::fs::read(path).map_err(|_| unreadable())?;
573 if bytes.is_empty() {
574 return Err(format!("{name} is empty."));
575 }
576 Ok(LoadedFile::new(bytes))
577 }
578
579 pub fn pasted_image_name() -> String {
580 format!("{PASTED_IMAGE_STEM}.png")
581 }
582
583 /// Formats the app cannot send inline (bitmaps from the Windows clipboard) become PNG.
584 pub fn prepare_pasted_image(pasted: Image) -> Result<LoadedFile, String> {
585 let unreadable = || format!("Could not read {}.", pasted_image_name());
586 let extension = match pasted.format {
587 ImageFormat::Png => "png",
588 ImageFormat::Jpeg => "jpg",
589 ImageFormat::Gif => "gif",
590 ImageFormat::Webp => "webp",
591 ImageFormat::Bmp => {
592 let decoded =
593 image::load_from_memory_with_format(&pasted.bytes, image::ImageFormat::Bmp)
594 .map_err(|_| unreadable())?;
595 let mut png = Vec::new();
596 decoded
597 .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
598 .map_err(|_| unreadable())?;
599 return Ok(LoadedFile {
600 file_name: Some(pasted_image_name()),
601 ..LoadedFile::new(png)
602 });
603 }
604 _ => return Err(unreadable()),
605 };
606 Ok(LoadedFile {
607 file_name: Some(format!("{PASTED_IMAGE_STEM}.{extension}")),
608 ..LoadedFile::new(pasted.bytes)
609 })
610 }
611
612 #[derive(Debug, Clone, PartialEq)]
613 pub enum PasteAction {
614 Text,
615 Files(Vec<PathBuf>),
616 Image(Image),
617 }
618
619 /// Office and browser copies carry text next to a bitmap; the text is what was meant.
620 pub fn paste_action(item: &ClipboardItem) -> PasteAction {
621 let mut pasted = None;
622 for entry in item.entries() {
623 match entry {
624 ClipboardEntry::ExternalPaths(paths) if !paths.paths().is_empty() => {
625 return PasteAction::Files(paths.paths().to_vec());
626 }
627 ClipboardEntry::Image(found)
628 if pasted.is_none() && found.format != ImageFormat::Svg =>
629 {
630 pasted = Some(found.clone());
631 }
632 _ => {}
633 }
634 }
635 let has_text = item.text().is_some_and(|text| !text.trim().is_empty());
636 match pasted {
637 Some(image) if !has_text => PasteAction::Image(image),
638 _ => PasteAction::Text,
639 }
640 }
641
642 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
643 pub enum Tone {
644 Muted,
645 Danger,
646 }
647
648 #[derive(Debug, Clone, PartialEq, Eq)]
649 pub struct ChipState {
650 pub subtitle: String,
651 pub tone: Tone,
652 pub progress: Option<u8>,
653 pub failed: bool,
654 }
655
656 pub fn chip_state(item: &TrayItem) -> ChipState {
657 let size = format::file_size_label(item.size);
658 let muted = |subtitle: String| ChipState {
659 subtitle,
660 tone: Tone::Muted,
661 progress: None,
662 failed: false,
663 };
664 match &item.kind {
665 ItemKind::Reading => muted("Reading ...".to_owned()),
666 ItemKind::Image { .. } => muted(size),
667 ItemKind::File {
668 upload,
669 sent_as_file,
670 ..
671 } => match upload {
672 UploadState::Uploading(percent) => ChipState {
673 progress: Some(*percent),
674 ..muted(format!("Uploading {percent} %"))
675 },
676 UploadState::Sharing(_) => ChipState {
677 progress: Some(100),
678 ..muted("Uploading 100 %".to_owned())
679 },
680 UploadState::Done(_) if *sent_as_file => muted(format!("{size}, sent as file")),
681 UploadState::Done(_) => muted(size),
682 UploadState::Failed => ChipState {
683 tone: Tone::Danger,
684 failed: true,
685 ..muted("Upload failed.".to_owned())
686 },
687 UploadState::ShareFailed(_) => ChipState {
688 tone: Tone::Danger,
689 failed: true,
690 ..muted("Sharing failed.".to_owned())
691 },
692 },
693 }
694 }
695
696 type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
697
698 fn remove_button<T: 'static>(
699 id: u64,
700 over_image: bool,
701 remove: ItemAction<T>,
702 cx: &mut Context<T>,
703 ) -> Stateful<Div> {
704 let button = div()
705 .id(ElementId::Name(format!("attachment-remove-{id}").into()))
706 .size(px(REMOVE_SIZE))
707 .flex_none()
708 .flex()
709 .items_center()
710 .justify_center()
711 .rounded_full()
712 .cursor_pointer();
713 let button = if over_image {
714 button
715 .bg(black().opacity(0.6))
716 .hover(|button| button.bg(black().opacity(0.85)))
717 .child(icon(IconName::Close, 10., white()))
718 } else {
719 button
720 .hover(|button| button.bg(theme::row_hover()))
721 .child(icon(IconName::Close, 10., theme::text_muted()))
722 };
723 button.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
724 }
725
726 fn thumbnail<T: 'static>(
727 item: &TrayItem,
728 image: &Arc<Image>,
729 remove: ItemAction<T>,
730 cx: &mut Context<T>,
731 ) -> AnyElement {
732 div()
733 .id(ElementId::Name(format!("attachment-{}", item.id).into()))
734 .relative()
735 .size(px(THUMB_SIZE))
736 .flex_none()
737 .rounded(px(8.))
738 .overflow_hidden()
739 .border_1()
740 .border_color(theme::border_strong())
741 .child(img(image.clone()).size_full().object_fit(ObjectFit::Cover))
742 .child(
743 div()
744 .absolute()
745 .top(px(4.))
746 .right(px(4.))
747 .child(remove_button(item.id, true, remove, cx)),
748 )
749 .into_any_element()
750 }
751
752 fn chip<T: 'static>(
753 item: &TrayItem,
754 remove: ItemAction<T>,
755 retry: ItemAction<T>,
756 cx: &mut Context<T>,
757 ) -> AnyElement {
758 let state = chip_state(item);
759 let id = item.id;
760 let subtitle_color = match state.tone {
761 Tone::Muted => theme::text_muted(),
762 Tone::Danger => theme::red(),
763 };
764 h_flex()
765 .id(ElementId::Name(format!("attachment-{id}").into()))
766 .relative()
767 .w(px(CHIP_WIDTH))
768 .h(px(CHIP_HEIGHT))
769 .flex_none()
770 .gap(px(9.))
771 .px(px(9.))
772 .items_center()
773 .rounded(px(8.))
774 .overflow_hidden()
775 .bg(theme::surface_raised())
776 .border_1()
777 .border_color(if state.failed {
778 theme::red()
779 } else {
780 theme::border_strong()
781 })
782 .child(file_badge(FileKind::from_name(&item.name), CHIP_BADGE_SIZE))
783 .child(
784 v_flex()
785 .flex_1()
786 .min_w_0()
787 .child(
788 div()
789 .truncate()
790 .text_size(px(12.5))
791 .text_color(theme::text())
792 .child(item.name.clone()),
793 )
794 .child(
795 div()
796 .truncate()
797 .text_size(px(11.))
798 .text_color(subtitle_color)
799 .child(state.subtitle),
800 ),
801 )
802 .when(state.failed, |chip| {
803 chip.child(
804 div()
805 .id(ElementId::Name(format!("attachment-retry-{id}").into()))
806 .flex_none()
807 .text_size(px(12.))
808 .font_weight(FontWeight::SEMIBOLD)
809 .text_color(theme::accent_text())
810 .cursor_pointer()
811 .hover(|button| button.underline())
812 .child("Retry")
813 .on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),
814 )
815 })
816 .child(remove_button(id, false, remove, cx))
817 .when_some(state.progress, |chip, percent| {
818 chip.child(
819 div()
820 .absolute()
821 .left_0()
822 .bottom_0()
823 .h(px(PROGRESS_HEIGHT))
824 .w(relative(f32::from(percent) / 100.))
825 .bg(theme::accent()),
826 )
827 })
828 .into_any_element()
829 }
830
831 pub fn render_tray<T: 'static>(
832 tray: &AttachmentTray,
833 remove: ItemAction<T>,
834 retry: ItemAction<T>,
835 cx: &mut Context<T>,
836 ) -> Option<Div> {
837 if tray.is_empty() {
838 return None;
839 }
840 let elements: Vec<AnyElement> = tray
841 .items()
842 .iter()
843 .map(|item| match &item.kind {
844 ItemKind::Image { image, .. } => thumbnail(item, image, remove, cx),
845 _ => chip(item, remove, retry, cx),
846 })
847 .collect();
848 Some(
849 h_flex()
850 .w_full()
851 .flex_wrap()
852 .gap(px(TRAY_GAP))
853 .px(px(12.))
854 .pt(px(10.))
855 .pb(px(2.))
856 .children(elements),
857 )
858 }
859
860 #[cfg(test)]
861 mod tests {
862 use std::io::Cursor;
863 use std::path::PathBuf;
864
865 use super::JobKind;
866 use gpui_kit::{ClipboardEntry, ClipboardItem, ExternalPaths, Image, ImageFormat};
867 use teams_core::{FileKind, FileReference, UploadedFile};
868
869 use super::{
870 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
871 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,
872 Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
873 prepare_pasted_image, read_attachment, sniff_inline_format,
874 };
875
876 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
877
878 fn png(width: u32, height: u32) -> Vec<u8> {
879 let mut bytes = Vec::new();
880 image::RgbaImage::new(width, height)
881 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
882 .unwrap();
883 bytes
884 }
885
886 fn padded(mut bytes: Vec<u8>, length: u64) -> Vec<u8> {
887 bytes.resize(length as usize, 0);
888 bytes
889 }
890
891 fn reference(name: &str) -> FileReference {
892 FileReference {
893 attachment_id: format!("id-{name}"),
894 content_url: format!("https://files.example/{name}"),
895 name: name.to_owned(),
896 }
897 }
898
899 fn done(name: &str) -> UploadResult {
900 UploadResult::Done(DoneFile {
901 reference: reference(name),
902 uploaded: None,
903 })
904 }
905
906 fn sample_upload() -> UploadedFile {
907 UploadedFile {
908 drive_id: "d".into(),
909 item_id: "i".into(),
910 name: "plan.pdf".into(),
911 web_url: "https://x".into(),
912 web_dav_url: None,
913 etag: "\"{G},1\"".into(),
914 }
915 }
916
917 fn names(count: usize) -> Vec<String> {
918 (0..count)
919 .map(|index| format!("file-{index}.pdf"))
920 .collect()
921 }
922
923 fn loaded_file(name: &str) -> LoadedFile {
924 LoadedFile {
925 file_name: Some(name.to_owned()),
926 ..LoadedFile::new(b"%PDF-1.7".to_vec())
927 }
928 }
929
930 fn tray_with_file() -> (AttachmentTray, u64) {
931 let mut tray = AttachmentTray::default();
932 let id = tray.add_pending(&["plan.pdf".to_owned()])[0];
933 tray.finish_reading(id, LoadedFile::new(b"%PDF-1.7".to_vec()), true);
934 (tray, id)
935 }
936
937 #[test]
938 fn magic_bytes_decide_the_inline_format() {
939 assert_eq!(sniff_inline_format(&png(1, 1)), Some(InlineFormat::Png));
940 assert_eq!(
941 sniff_inline_format(&[0xFF, 0xD8, 0xFF, 0xE0, 0]),
942 Some(InlineFormat::Jpeg)
943 );
944 assert_eq!(sniff_inline_format(b"GIF89a...."), Some(InlineFormat::Gif));
945 assert_eq!(
946 sniff_inline_format(b"RIFF\x10\0\0\0WEBPVP8 "),
947 Some(InlineFormat::Webp)
948 );
949 assert_eq!(sniff_inline_format(b"BM......"), None);
950 assert_eq!(sniff_inline_format(b"%PDF-1.7"), None);
951 assert_eq!(sniff_inline_format(&[]), None);
952 }
953
954 #[test]
955 fn small_supported_images_are_inline() {
956 assert_eq!(
957 classify("shot.png", &png(2, 2), 0),
958 Classification::Inline(InlineFormat::Png)
959 );
960 }
961
962 #[test]
963 fn images_over_one_megabyte_become_files() {
964 let at_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
965 let over_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES + 1);
966 assert_eq!(
967 classify("a.png", &at_limit, 0),
968 Classification::Inline(InlineFormat::Png)
969 );
970 assert_eq!(
971 classify("a.png", &over_limit, 0),
972 Classification::File { sent_as_file: true }
973 );
974 }
975
976 #[test]
977 fn the_inline_total_is_capped_and_later_images_become_files() {
978 let image = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
979 assert_eq!(
980 classify(
981 "a.png",
982 &image,
983 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES
984 ),
985 Classification::Inline(InlineFormat::Png)
986 );
987 assert_eq!(
988 classify(
989 "a.png",
990 &image,
991 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES + 1
992 ),
993 Classification::File { sent_as_file: true }
994 );
995 }
996
997 #[test]
998 fn removing_an_inline_image_does_not_reclassify_the_others() {
999 let big = || LoadedFile::new(padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES));
1000 let mut tray = AttachmentTray::default();
1001 let ids = tray.add_pending(&names(4));
1002 for id in &ids[..3] {
1003 tray.finish_reading(*id, big(), true);
1004 }
1005 let job = tray.finish_reading(ids[3], big(), true);
1006 assert!(
1007 job.is_some(),
1008 "the fourth 1 MiB image exceeds 2.5 MiB inline"
1009 );
1010 tray.remove(ids[0]);
1011 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1012 }
1013
1014 #[test]
1015 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1016 let (mut tray, id) = tray_with_file();
1017 let uploaded = sample_upload();
1018 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1019 let state = chip_state(&tray.items()[0]);
1020 assert_eq!(state.subtitle, "Sharing failed.");
1021 assert!(state.failed);
1022 assert!(tray.blocks_send());
1023 let job = tray.retry(id).unwrap();
1024 assert!(matches!(job.kind, JobKind::Share(ref file) if *file == uploaded));
1025 assert_eq!(tray.clear(), vec![uploaded.clone()]);
1026 let (mut tray, id) = tray_with_file();
1027 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1028 tray.retry(id);
1029 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1030 assert_eq!(tray.remove(id), Some(uploaded));
1031 }
1032
1033 #[test]
1034 fn an_item_being_shared_can_be_deleted_by_remove_or_clear() {
1035 let (mut tray, id) = tray_with_file();
1036 tray.mark_uploaded(id, sample_upload());
1037 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 100 %");
1038 assert!(tray.blocks_send());
1039 tray.set_progress(id, 10);
1040 assert_eq!(chip_state(&tray.items()[0]).progress, Some(100));
1041 assert_eq!(tray.remove(id), Some(sample_upload()));
1042
1043 let (mut tray, id) = tray_with_file();
1044 tray.mark_uploaded(id, sample_upload());
1045 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload()));
1046 assert!(chip_state(&tray.items()[0]).failed);
1047 assert_eq!(tray.keep_images_only(), vec![sample_upload()]);
1048 }
1049
1050 #[test]
1051 fn events_for_a_removed_item_hand_the_upload_back_for_deletion() {
1052 let (mut tray, id) = tray_with_file();
1053 tray.remove(id);
1054 assert_eq!(
1055 tray.mark_uploaded(id, sample_upload()),
1056 Some(sample_upload())
1057 );
1058 let done = UploadResult::Done(DoneFile {
1059 reference: reference("plan.pdf"),
1060 uploaded: Some(sample_upload()),
1061 });
1062 assert_eq!(tray.finish_upload(id, done), Some(sample_upload()));
1063 assert_eq!(
1064 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload())),
1065 Some(sample_upload())
1066 );
1067 assert_eq!(tray.finish_upload(id, UploadResult::Failed), None);
1068 }
1069
1070 #[test]
1071 fn events_for_a_live_item_are_never_handed_back() {
1072 let (mut tray, id) = tray_with_file();
1073 assert_eq!(tray.mark_uploaded(id, sample_upload()), None);
1074 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1075 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1076 }
1077
1078 #[test]
1079 fn removing_or_clearing_reports_the_uploads_that_were_never_sent() {
1080 let (mut tray, id) = tray_with_file();
1081 tray.finish_upload(
1082 id,
1083 UploadResult::Done(DoneFile {
1084 reference: reference("plan.pdf"),
1085 uploaded: Some(sample_upload()),
1086 }),
1087 );
1088 assert_eq!(tray.clear(), vec![sample_upload()]);
1089 let (mut other, other_id) = tray_with_file();
1090 assert_eq!(other.remove(other_id), None);
1091 }
1092
1093 #[test]
1094 fn other_image_formats_become_files_with_the_note() {
1095 assert_eq!(
1096 classify("scan.bmp", b"BM......", 0),
1097 Classification::File { sent_as_file: true }
1098 );
1099 assert_eq!(
1100 classify("photo.HEIC", b"....ftypheic", 0),
1101 Classification::File { sent_as_file: true }
1102 );
1103 assert_eq!(
1104 classify("plan.pdf", b"%PDF-1.7", 0),
1105 Classification::File {
1106 sent_as_file: false
1107 }
1108 );
1109 }
1110
1111 #[test]
1112 fn dimensions_come_from_the_headers() {
1113 assert_eq!(LoadedFile::new(png(7, 3)).dimensions, Some((7, 3)));
1114 let mut gif = b"GIF89a".to_vec();
1115 gif.extend_from_slice(&[10, 0, 20, 0]);
1116 assert_eq!(LoadedFile::new(gif).dimensions, Some((10, 20)));
1117 assert_eq!(LoadedFile::new(b"%PDF".to_vec()).dimensions, None);
1118 }
1119
1120 #[test]
1121 fn the_tenth_attachment_fits_and_the_rest_are_dropped() {
1122 let mut tray = AttachmentTray::default();
1123 assert_eq!(tray.add_pending(&names(4)).len(), 4);
1124 let ids = tray.add_pending(&names(9));
1125 assert_eq!(ids.len(), 6);
1126 assert_eq!(tray.items().len(), MAX_ATTACHMENTS);
1127 assert_eq!(
1128 tray.notice(),
1129 Some("Up to 10 attachments per message. 3 files were not added.")
1130 );
1131 }
1132
1133 #[test]
1134 fn one_dropped_file_reads_in_the_singular() {
1135 assert_eq!(
1136 limit_notice(1),
1137 "Up to 10 attachments per message. 1 file was not added."
1138 );
1139 }
1140
1141 #[test]
1142 fn the_limit_notice_clears_on_the_next_change() {
1143 let mut tray = AttachmentTray::default();
1144 let ids = tray.add_pending(&names(12));
1145 assert!(tray.notice().is_some());
1146 tray.remove(ids[0]);
1147 assert_eq!(tray.notice(), None);
1148 tray.add_pending(&names(3));
1149 assert!(tray.notice().is_some());
1150 tray.clear();
1151 assert_eq!(tray.notice(), None);
1152 }
1153
1154 #[test]
1155 fn a_file_starts_uploading_and_an_image_does_not() {
1156 let mut tray = AttachmentTray::default();
1157 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1158 let job = tray.finish_reading(ids[0], LoadedFile::new(b"%PDF".to_vec()), true);
1159 assert_eq!(job.as_ref().map(|job| job.name.as_str()), Some("a.pdf"));
1160 assert!(
1161 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), true)
1162 .is_none()
1163 );
1164 assert!(matches!(tray.items()[1].kind, ItemKind::Image { .. }));
1165 assert!(tray.blocks_send());
1166 }
1167
1168 #[test]
1169 fn a_pasted_name_replaces_the_placeholder() {
1170 let mut tray = AttachmentTray::default();
1171 let id = tray.add_pending(&[pasted_image_name()])[0];
1172 let loaded = LoadedFile {
1173 file_name: Some("pasted-image.jpg".into()),
1174 ..LoadedFile::new(vec![0xFF, 0xD8, 0xFF, 0xE0])
1175 };
1176 tray.finish_reading(id, loaded, true);
1177 assert_eq!(tray.items()[0].name, "pasted-image.jpg");
1178 }
1179
1180 #[test]
1181 fn files_are_refused_while_the_chat_does_not_exist() {
1182 let mut tray = AttachmentTray::default();
1183 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1184 assert!(
1185 tray.finish_reading(ids[0], loaded_file("a.pdf"), false)
1186 .is_none()
1187 );
1188 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), false);
1189 assert_eq!(tray.items().len(), 1);
1190 assert_eq!(tray.notice(), Some(FILES_LATER_NOTICE));
1191 assert!(!tray.blocks_send());
1192 }
1193
1194 #[test]
1195 fn upload_progress_then_done_unblocks_sending() {
1196 let (mut tray, id) = tray_with_file();
1197 tray.set_progress(id, 42);
1198 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 42 %");
1199 assert_eq!(chip_state(&tray.items()[0]).progress, Some(42));
1200 assert!(tray.blocks_send());
1201 tray.finish_upload(id, done("plan.pdf"));
1202 assert!(!tray.blocks_send());
1203 assert_eq!(tray.outgoing_files().len(), 1);
1204 assert_eq!(
1205 tray.outgoing_files()[0].kind,
1206 FileKind::from_name("plan.pdf")
1207 );
1208 }
1209
1210 #[test]
1211 fn progress_after_the_upload_ended_is_ignored() {
1212 let (mut tray, id) = tray_with_file();
1213 tray.finish_upload(id, done("plan.pdf"));
1214 tray.set_progress(id, 10);
1215 tray.finish_upload(id, UploadResult::Failed);
1216 assert!(!tray.blocks_send());
1217 }
1218
1219 #[test]
1220 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1221 let (mut tray, id) = tray_with_file();
1222 tray.finish_upload(id, UploadResult::Failed);
1223 let state = chip_state(&tray.items()[0]);
1224 assert_eq!(state.subtitle, "Upload failed.");
1225 assert_eq!(state.tone, Tone::Danger);
1226 assert!(state.failed);
1227 assert!(tray.blocks_send());
1228 assert!(tray.outgoing_files().is_empty());
1229
1230 let job = tray.retry(id).expect("failed uploads can be retried");
1231 assert_eq!(job.name, "plan.pdf");
1232 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 0 %");
1233 assert!(tray.retry(id).is_none());
1234
1235 tray.finish_upload(id, UploadResult::Failed);
1236 tray.remove(id);
1237 assert!(!tray.blocks_send());
1238 }
1239
1240 #[test]
1241 fn a_result_for_a_removed_item_is_dropped() {
1242 let (mut tray, id) = tray_with_file();
1243 tray.remove(id);
1244 tray.finish_upload(id, done("plan.pdf"));
1245 assert!(tray.is_empty());
1246 }
1247
1248 #[test]
1249 fn done_chips_show_the_size_and_the_file_note() {
1250 let mut tray = AttachmentTray::default();
1251 let id = tray.add_pending(&["scan.bmp".to_owned()])[0];
1252 tray.finish_reading(id, LoadedFile::new(b"BM....".to_vec()), true);
1253 tray.finish_upload(id, done("scan.bmp"));
1254 assert_eq!(chip_state(&tray.items()[0]).subtitle, "6 B, sent as file");
1255 let (mut other, other_id) = tray_with_file();
1256 other.finish_upload(other_id, done("plan.pdf"));
1257 assert_eq!(chip_state(&other.items()[0]).subtitle, "8 B");
1258 }
1259
1260 #[test]
1261 fn restore_brings_back_images_and_uploaded_files() {
1262 let mut source = AttachmentTray::default();
1263 let ids = source.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1264 source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);
1265 source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1266 source.finish_upload(ids[1], done("b.pdf"));
1267 let (images, files) = (source.outgoing_images(), source.outgoing_files());
1268
1269 let mut restored = AttachmentTray::default();
1270 restored.restore(&images, &files);
1271 assert_eq!(restored.outgoing_images(), images);
1272 assert_eq!(restored.outgoing_files(), files);
1273 assert!(!restored.blocks_send());
1274 }
1275
1276 #[test]
1277 fn switching_chats_for_a_draft_keeps_only_images() {
1278 let mut tray = AttachmentTray::default();
1279 let ids = tray.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1280 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1281 tray.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1282 tray.keep_images_only();
1283 assert_eq!(tray.items().len(), 1);
1284 assert!(matches!(tray.items()[0].kind, ItemKind::Image { .. }));
1285 }
1286
1287 #[test]
1288 fn a_failed_read_removes_the_item_and_says_why() {
1289 let mut tray = AttachmentTray::default();
1290 let id = tray.add_pending(&["gone.txt".to_owned()])[0];
1291 tray.fail_reading(id, "Could not read gone.txt.".to_owned());
1292 assert!(tray.is_empty());
1293 assert_eq!(tray.notice(), Some("Could not read gone.txt."));
1294 }
1295
1296 #[test]
1297 fn reading_items_block_sending() {
1298 let mut tray = AttachmentTray::default();
1299 tray.add_pending(&["a.pdf".to_owned()]);
1300 assert!(tray.blocks_send());
1301 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Reading ...");
1302 }
1303
1304 #[test]
1305 fn files_are_read_from_disk_with_their_limits() {
1306 let directory = tempfile::tempdir().unwrap();
1307 let file = directory.path().join("note.txt");
1308 std::fs::write(&file, b"hello").unwrap();
1309 let empty = directory.path().join("empty.txt");
1310 std::fs::write(&empty, b"").unwrap();
1311
1312 assert_eq!(read_attachment(&file).unwrap().bytes, b"hello");
1313 assert_eq!(read_attachment(&empty).unwrap_err(), "empty.txt is empty.");
1314 assert!(
1315 read_attachment(directory.path())
1316 .unwrap_err()
1317 .ends_with('.')
1318 );
1319 assert_eq!(
1320 read_attachment(&directory.path().join("missing.txt")).unwrap_err(),
1321 "Could not read missing.txt."
1322 );
1323 }
1324
1325 fn clipboard(entries: Vec<ClipboardEntry>) -> ClipboardItem {
1326 ClipboardItem { entries }
1327 }
1328
1329 fn pasted_png() -> Image {
1330 Image::from_bytes(ImageFormat::Png, png(2, 2))
1331 }
1332
1333 #[test]
1334 fn pasting_an_image_alone_adds_an_image() {
1335 let item = clipboard(vec![ClipboardEntry::Image(pasted_png())]);
1336 assert_eq!(paste_action(&item), PasteAction::Image(pasted_png()));
1337 }
1338
1339 #[test]
1340 fn pasting_copied_files_adds_those_files() {
1341 let paths = ExternalPaths(vec![PathBuf::from("/a/b.pdf")].into_iter().collect());
1342 let item = clipboard(vec![ClipboardEntry::ExternalPaths(paths)]);
1343 assert_eq!(
1344 paste_action(&item),
1345 PasteAction::Files(vec![PathBuf::from("/a/b.pdf")])
1346 );
1347 }
1348
1349 #[test]
1350 fn pasting_text_or_text_with_a_bitmap_stays_text() {
1351 assert_eq!(
1352 paste_action(&ClipboardItem::new_string("hi".into())),
1353 PasteAction::Text
1354 );
1355 let both = clipboard(vec![
1356 ClipboardEntry::from("cells".to_owned()),
1357 ClipboardEntry::Image(pasted_png()),
1358 ]);
1359 assert_eq!(paste_action(&both), PasteAction::Text);
1360 assert_eq!(paste_action(&clipboard(Vec::new())), PasteAction::Text);
1361 }
1362
1363 #[test]
1364 fn a_pasted_bitmap_becomes_a_png() {
1365 let mut bmp = Vec::new();
1366 image::RgbaImage::new(3, 2)
1367 .write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp)
1368 .unwrap();
1369 let loaded = prepare_pasted_image(Image::from_bytes(ImageFormat::Bmp, bmp)).unwrap();
1370 assert_eq!(sniff_inline_format(&loaded.bytes), Some(InlineFormat::Png));
1371 assert_eq!(loaded.dimensions, Some((3, 2)));
1372 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1373 }
1374
1375 #[test]
1376 fn a_pasted_png_keeps_its_bytes() {
1377 let loaded = prepare_pasted_image(pasted_png()).unwrap();
1378 assert_eq!(loaded.bytes, png(2, 2));
1379 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1380 }
1381 }
@@ -0,0 +1,1381 @@
1use std::io::Cursor;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{FileKind, FileReference, UploadedFile};
10
11use super::attachments::file_badge;
12use super::widgets::icon;
13use crate::format;
14use crate::theme;
15
16pub const MAX_ATTACHMENTS: usize = 10;
17pub const INLINE_IMAGE_MAX_BYTES: u64 = 1024 * 1024;
18pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
19pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
20pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
21const PASTED_IMAGE_STEM: &str = "pasted-image";
22const THUMB_SIZE: f32 = 72.;
23const CHIP_WIDTH: f32 = 220.;
24const CHIP_HEIGHT: f32 = 48.;
25const CHIP_BADGE_SIZE: f32 = 30.;
26const REMOVE_SIZE: f32 = 18.;
27const TRAY_GAP: f32 = 8.;
28const PROGRESS_HEIGHT: f32 = 2.;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum InlineFormat {
32 Png,
33 Jpeg,
34 Gif,
35 Webp,
36}
37
38impl InlineFormat {
39 fn image_format(self) -> ImageFormat {
40 match self {
41 InlineFormat::Png => ImageFormat::Png,
42 InlineFormat::Jpeg => ImageFormat::Jpeg,
43 InlineFormat::Gif => ImageFormat::Gif,
44 InlineFormat::Webp => ImageFormat::Webp,
45 }
46 }
47
48 fn decoder_format(self) -> Option<image::ImageFormat> {
49 match self {
50 InlineFormat::Png => Some(image::ImageFormat::Png),
51 InlineFormat::Jpeg => Some(image::ImageFormat::Jpeg),
52 InlineFormat::Webp => Some(image::ImageFormat::WebP),
53 InlineFormat::Gif => None,
54 }
55 }
56}
57
58pub fn sniff_inline_format(bytes: &[u8]) -> Option<InlineFormat> {
59 match bytes {
60 [0x89, b'P', b'N', b'G', ..] => Some(InlineFormat::Png),
61 [0xFF, 0xD8, 0xFF, ..] => Some(InlineFormat::Jpeg),
62 [b'G', b'I', b'F', b'8', ..] => Some(InlineFormat::Gif),
63 [
64 b'R',
65 b'I',
66 b'F',
67 b'F',
68 _,
69 _,
70 _,
71 _,
72 b'W',
73 b'E',
74 b'B',
75 b'P',
76 ..,
77 ] => Some(InlineFormat::Webp),
78 _ => None,
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Classification {
84 Inline(InlineFormat),
85 File { sent_as_file: bool },
86}
87
88/// `inline_used` is the raw bytes of the images already inline in the tray.
89pub fn classify(name: &str, bytes: &[u8], inline_used: u64) -> Classification {
90 let size = bytes.len() as u64;
91 match sniff_inline_format(bytes) {
92 Some(format)
93 if size <= INLINE_IMAGE_MAX_BYTES && inline_used + size <= INLINE_TOTAL_MAX_BYTES =>
94 {
95 Classification::Inline(format)
96 }
97 Some(_) => Classification::File { sent_as_file: true },
98 None => Classification::File {
99 sent_as_file: FileKind::from_name(name) == FileKind::Image,
100 },
101 }
102}
103
104fn image_dimensions(format: InlineFormat, bytes: &[u8]) -> Option<(u32, u32)> {
105 match format.decoder_format() {
106 Some(decoder) => image::ImageReader::with_format(Cursor::new(bytes), decoder)
107 .into_dimensions()
108 .ok(),
109 None => {
110 let header = bytes.get(6..10)?;
111 Some((
112 u32::from(u16::from_le_bytes([header[0], header[1]])),
113 u32::from(u16::from_le_bytes([header[2], header[3]])),
114 ))
115 }
116 }
117}
118
119pub fn limit_notice(dropped: usize) -> String {
120 let files = if dropped == 1 {
121 "1 file was".to_owned()
122 } else {
123 format!("{dropped} files were")
124 };
125 format!("Up to {MAX_ATTACHMENTS} attachments per message. {files} not added.")
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum UploadState {
130 Uploading(u8),
131 Done(DoneFile),
132 Failed,
133 Sharing(UploadedFile),
134 ShareFailed(UploadedFile),
135}
136
137/// `uploaded` is known for files the app uploaded, so an unsent one can be deleted again.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct DoneFile {
140 pub reference: FileReference,
141 pub uploaded: Option<UploadedFile>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum UploadResult {
146 Done(DoneFile),
147 ShareFailed(UploadedFile),
148 Failed,
149}
150
151impl UploadState {
152 fn uploaded(&self) -> Option<UploadedFile> {
153 match self {
154 UploadState::Done(done) => done.uploaded.clone(),
155 UploadState::Sharing(uploaded) | UploadState::ShareFailed(uploaded) => {
156 Some(uploaded.clone())
157 }
158 _ => None,
159 }
160 }
161}
162
163#[derive(Debug, Clone)]
164#[allow(clippy::large_enum_variant)]
165pub enum ItemKind {
166 Reading,
167 Image {
168 image: Arc<Image>,
169 dimensions: Option<(u32, u32)>,
170 },
171 File {
172 bytes: Arc<Vec<u8>>,
173 upload: UploadState,
174 sent_as_file: bool,
175 },
176}
177
178#[derive(Debug, Clone)]
179pub struct TrayItem {
180 pub id: u64,
181 pub name: String,
182 pub size: u64,
183 pub kind: ItemKind,
184}
185
186impl TrayItem {
187 fn blocks_send(&self) -> bool {
188 match &self.kind {
189 ItemKind::Reading => true,
190 ItemKind::Image { .. } => false,
191 ItemKind::File { upload, .. } => !matches!(upload, UploadState::Done(_)),
192 }
193 }
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct OutgoingImage {
198 pub name: String,
199 pub image: Arc<Image>,
200 pub dimensions: Option<(u32, u32)>,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct OutgoingFile {
205 pub name: String,
206 pub size: u64,
207 pub kind: FileKind,
208 pub reference: FileReference,
209 pub uploaded: Option<UploadedFile>,
210}
211
212#[derive(Debug, Clone)]
213pub enum JobKind {
214 Upload,
215 Share(UploadedFile),
216}
217
218#[derive(Debug, Clone)]
219pub struct UploadJob {
220 pub id: u64,
221 pub name: String,
222 pub bytes: Arc<Vec<u8>>,
223 pub kind: JobKind,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct LoadedFile {
228 pub bytes: Vec<u8>,
229 pub dimensions: Option<(u32, u32)>,
230 pub file_name: Option<String>,
231}
232
233impl LoadedFile {
234 pub fn new(bytes: Vec<u8>) -> Self {
235 let dimensions =
236 sniff_inline_format(&bytes).and_then(|format| image_dimensions(format, &bytes));
237 LoadedFile {
238 bytes,
239 dimensions,
240 file_name: None,
241 }
242 }
243}
244
245#[derive(Debug, Clone, Default)]
246pub struct AttachmentTray {
247 items: Vec<TrayItem>,
248 next_id: u64,
249 notice: Option<String>,
250}
251
252impl AttachmentTray {
253 pub fn items(&self) -> &[TrayItem] {
254 &self.items
255 }
256
257 pub fn is_empty(&self) -> bool {
258 self.items.is_empty()
259 }
260
261 pub fn notice(&self) -> Option<&str> {
262 self.notice.as_deref()
263 }
264
265 pub fn blocks_send(&self) -> bool {
266 self.items.iter().any(TrayItem::blocks_send)
267 }
268
269 fn push(&mut self, name: String, size: u64, kind: ItemKind) -> u64 {
270 self.next_id += 1;
271 self.items.push(TrayItem {
272 id: self.next_id,
273 name,
274 size,
275 kind,
276 });
277 self.next_id
278 }
279
280 /// Items beyond the limit are dropped; the ids returned belong to the first names.
281 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
282 self.notice = None;
283 let accepted = names
284 .len()
285 .min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
286 let ids = names[..accepted]
287 .iter()
288 .map(|name| self.push(name.clone(), 0, ItemKind::Reading))
289 .collect();
290 if accepted < names.len() {
291 self.notice = Some(limit_notice(names.len() - accepted));
292 }
293 ids
294 }
295
296 /// Returns the upload to start when the item turned out to be a file.
297 pub fn finish_reading(
298 &mut self,
299 id: u64,
300 loaded: LoadedFile,
301 files_allowed: bool,
302 ) -> Option<UploadJob> {
303 let position = self
304 .items
305 .iter()
306 .position(|item| item.id == id && matches!(item.kind, ItemKind::Reading))?;
307 let name = loaded
308 .file_name
309 .clone()
310 .unwrap_or_else(|| self.items[position].name.clone());
311 let size = loaded.bytes.len() as u64;
312 match classify(&name, &loaded.bytes, self.inline_bytes()) {
313 Classification::Inline(format) => {
314 let item = &mut self.items[position];
315 item.name = name;
316 item.size = size;
317 item.kind = ItemKind::Image {
318 image: Arc::new(Image::from_bytes(format.image_format(), loaded.bytes)),
319 dimensions: loaded.dimensions,
320 };
321 None
322 }
323 Classification::File { .. } if !files_allowed => {
324 self.items.remove(position);
325 self.notice = Some(FILES_LATER_NOTICE.to_owned());
326 None
327 }
328 Classification::File { sent_as_file } => {
329 let bytes = Arc::new(loaded.bytes);
330 let item = &mut self.items[position];
331 item.name = name.clone();
332 item.size = size;
333 item.kind = ItemKind::File {
334 bytes: bytes.clone(),
335 upload: UploadState::Uploading(0),
336 sent_as_file,
337 };
338 Some(UploadJob {
339 id,
340 name,
341 bytes,
342 kind: JobKind::Upload,
343 })
344 }
345 }
346 }
347
348 pub fn fail_reading(&mut self, id: u64, message: String) {
349 let before = self.items.len();
350 self.items.retain(|item| item.id != id);
351 if self.items.len() != before {
352 self.notice = Some(message);
353 }
354 }
355
356 pub fn set_progress(&mut self, id: u64, percent: u8) {
357 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
358 && matches!(upload, UploadState::Uploading(_))
359 {
360 *upload = UploadState::Uploading(percent.min(100));
361 }
362 }
363
364 /// The bytes are on the server; from here a remove or switch must delete the item.
365 /// Returns the file back when its item is gone, so the caller can delete it.
366 pub fn mark_uploaded(&mut self, id: u64, uploaded: UploadedFile) -> Option<UploadedFile> {
367 if !self.items.iter().any(|item| item.id == id) {
368 return Some(uploaded);
369 }
370 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
371 && matches!(upload, UploadState::Uploading(_))
372 {
373 *upload = UploadState::Sharing(uploaded);
374 }
375 None
376 }
377
378 /// Returns the uploaded file of a result whose item is gone, so the caller can delete it.
379 pub fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
380 if !self.items.iter().any(|item| item.id == id) {
381 return match result {
382 UploadResult::Done(done) => done.uploaded,
383 UploadResult::ShareFailed(uploaded) => Some(uploaded),
384 UploadResult::Failed => None,
385 };
386 }
387 if let Some(ItemKind::File { upload, .. }) = self.kind_of_mut(id)
388 && matches!(upload, UploadState::Uploading(_) | UploadState::Sharing(_))
389 {
390 *upload = match result {
391 UploadResult::Done(done) => UploadState::Done(done),
392 UploadResult::ShareFailed(uploaded) => UploadState::ShareFailed(uploaded),
393 UploadResult::Failed => UploadState::Failed,
394 };
395 }
396 None
397 }
398
399 pub fn retry(&mut self, id: u64) -> Option<UploadJob> {
400 self.notice = None;
401 let item = self.items.iter_mut().find(|item| item.id == id)?;
402 let ItemKind::File { bytes, upload, .. } = &mut item.kind else {
403 return None;
404 };
405 match upload.clone() {
406 UploadState::Failed => *upload = UploadState::Uploading(0),
407 UploadState::ShareFailed(uploaded) => *upload = UploadState::Sharing(uploaded),
408 _ => return None,
409 }
410 let kind = match upload {
411 UploadState::Sharing(uploaded) => JobKind::Share(uploaded.clone()),
412 _ => JobKind::Upload,
413 };
414 Some(UploadJob {
415 id,
416 name: item.name.clone(),
417 bytes: bytes.clone(),
418 kind,
419 })
420 }
421
422 /// Returns the uploaded file of the removed item, which was never sent.
423 pub fn remove(&mut self, id: u64) -> Option<UploadedFile> {
424 self.notice = None;
425 let position = self.items.iter().position(|item| item.id == id)?;
426 match self.items.remove(position).kind {
427 ItemKind::File { upload, .. } => upload.uploaded(),
428 _ => None,
429 }
430 }
431
432 /// Returns the uploaded files that were dropped unsent.
433 pub fn clear(&mut self) -> Vec<UploadedFile> {
434 self.notice = None;
435 self.items
436 .drain(..)
437 .filter_map(|item| match item.kind {
438 ItemKind::File { upload, .. } => upload.uploaded(),
439 _ => None,
440 })
441 .collect()
442 }
443
444 pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {
445 self.notice = None;
446 let (images, others): (Vec<_>, Vec<_>) = self
447 .items
448 .drain(..)
449 .partition(|item| matches!(item.kind, ItemKind::Image { .. }));
450 self.items = images;
451 others
452 .into_iter()
453 .filter_map(|item| match item.kind {
454 ItemKind::File { upload, .. } => upload.uploaded(),
455 _ => None,
456 })
457 .collect()
458 }
459
460 fn inline_bytes(&self) -> u64 {
461 self.items
462 .iter()
463 .filter(|item| matches!(item.kind, ItemKind::Image { .. }))
464 .map(|item| item.size)
465 .sum()
466 }
467
468 pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) {
469 self.clear();
470 for image in images {
471 self.push(
472 image.name.clone(),
473 image.image.bytes.len() as u64,
474 ItemKind::Image {
475 image: image.image.clone(),
476 dimensions: image.dimensions,
477 },
478 );
479 }
480 for file in files {
481 self.push(
482 file.name.clone(),
483 file.size,
484 ItemKind::File {
485 bytes: Arc::new(Vec::new()),
486 upload: UploadState::Done(DoneFile {
487 reference: file.reference.clone(),
488 uploaded: file.uploaded.clone(),
489 }),
490 sent_as_file: false,
491 },
492 );
493 }
494 }
495
496 pub fn outgoing_images(&self) -> Vec<OutgoingImage> {
497 self.items
498 .iter()
499 .filter_map(|item| match &item.kind {
500 ItemKind::Image { image, dimensions } => Some(OutgoingImage {
501 name: item.name.clone(),
502 image: image.clone(),
503 dimensions: *dimensions,
504 }),
505 _ => None,
506 })
507 .collect()
508 }
509
510 pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
511 self.items
512 .iter()
513 .filter_map(|item| match &item.kind {
514 ItemKind::File {
515 upload: UploadState::Done(done),
516 ..
517 } => Some(OutgoingFile {
518 name: item.name.clone(),
519 size: item.size,
520 kind: FileKind::from_name(&item.name),
521 reference: done.reference.clone(),
522 uploaded: done.uploaded.clone(),
523 }),
524 _ => None,
525 })
526 .collect()
527 }
528
529 fn kind_of_mut(&mut self, id: u64) -> Option<&mut ItemKind> {
530 self.items
531 .iter_mut()
532 .find(|item| item.id == id)
533 .map(|item| &mut item.kind)
534 }
535}
536
537fn display_name(path: &Path) -> String {
538 path.file_name()
539 .map(|name| name.to_string_lossy().into_owned())
540 .unwrap_or_else(|| path.to_string_lossy().into_owned())
541}
542
543pub fn discard_uploaded(engine: Option<Arc<crate::backend::Engine>>, files: Vec<UploadedFile>) {
544 let Some(engine) = engine else {
545 return;
546 };
547 for file in files {
548 let engine = engine.clone();
549 drop(crate::runtime::spawn(async move {
550 let _ = engine.discard_attachment(&file).await;
551 }));
552 }
553}
554
555pub fn names_of(paths: &[PathBuf]) -> Vec<String> {
556 paths.iter().map(|path| display_name(path)).collect()
557}
558
559pub fn read_attachment(path: &Path) -> Result<LoadedFile, String> {
560 let name = display_name(path);
561 let unreadable = || format!("Could not read {name}.");
562 let metadata = std::fs::metadata(path).map_err(|_| unreadable())?;
563 if !metadata.is_file() {
564 return Err(unreadable());
565 }
566 if metadata.len() > MAX_FILE_BYTES {
567 return Err(format!(
568 "{name} is larger than {} MB.",
569 MAX_FILE_BYTES / (1024 * 1024)
570 ));
571 }
572 let bytes = std::fs::read(path).map_err(|_| unreadable())?;
573 if bytes.is_empty() {
574 return Err(format!("{name} is empty."));
575 }
576 Ok(LoadedFile::new(bytes))
577}
578
579pub fn pasted_image_name() -> String {
580 format!("{PASTED_IMAGE_STEM}.png")
581}
582
583/// Formats the app cannot send inline (bitmaps from the Windows clipboard) become PNG.
584pub fn prepare_pasted_image(pasted: Image) -> Result<LoadedFile, String> {
585 let unreadable = || format!("Could not read {}.", pasted_image_name());
586 let extension = match pasted.format {
587 ImageFormat::Png => "png",
588 ImageFormat::Jpeg => "jpg",
589 ImageFormat::Gif => "gif",
590 ImageFormat::Webp => "webp",
591 ImageFormat::Bmp => {
592 let decoded =
593 image::load_from_memory_with_format(&pasted.bytes, image::ImageFormat::Bmp)
594 .map_err(|_| unreadable())?;
595 let mut png = Vec::new();
596 decoded
597 .write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png)
598 .map_err(|_| unreadable())?;
599 return Ok(LoadedFile {
600 file_name: Some(pasted_image_name()),
601 ..LoadedFile::new(png)
602 });
603 }
604 _ => return Err(unreadable()),
605 };
606 Ok(LoadedFile {
607 file_name: Some(format!("{PASTED_IMAGE_STEM}.{extension}")),
608 ..LoadedFile::new(pasted.bytes)
609 })
610}
611
612#[derive(Debug, Clone, PartialEq)]
613pub enum PasteAction {
614 Text,
615 Files(Vec<PathBuf>),
616 Image(Image),
617}
618
619/// Office and browser copies carry text next to a bitmap; the text is what was meant.
620pub fn paste_action(item: &ClipboardItem) -> PasteAction {
621 let mut pasted = None;
622 for entry in item.entries() {
623 match entry {
624 ClipboardEntry::ExternalPaths(paths) if !paths.paths().is_empty() => {
625 return PasteAction::Files(paths.paths().to_vec());
626 }
627 ClipboardEntry::Image(found)
628 if pasted.is_none() && found.format != ImageFormat::Svg =>
629 {
630 pasted = Some(found.clone());
631 }
632 _ => {}
633 }
634 }
635 let has_text = item.text().is_some_and(|text| !text.trim().is_empty());
636 match pasted {
637 Some(image) if !has_text => PasteAction::Image(image),
638 _ => PasteAction::Text,
639 }
640}
641
642#[derive(Debug, Clone, Copy, PartialEq, Eq)]
643pub enum Tone {
644 Muted,
645 Danger,
646}
647
648#[derive(Debug, Clone, PartialEq, Eq)]
649pub struct ChipState {
650 pub subtitle: String,
651 pub tone: Tone,
652 pub progress: Option<u8>,
653 pub failed: bool,
654}
655
656pub fn chip_state(item: &TrayItem) -> ChipState {
657 let size = format::file_size_label(item.size);
658 let muted = |subtitle: String| ChipState {
659 subtitle,
660 tone: Tone::Muted,
661 progress: None,
662 failed: false,
663 };
664 match &item.kind {
665 ItemKind::Reading => muted("Reading ...".to_owned()),
666 ItemKind::Image { .. } => muted(size),
667 ItemKind::File {
668 upload,
669 sent_as_file,
670 ..
671 } => match upload {
672 UploadState::Uploading(percent) => ChipState {
673 progress: Some(*percent),
674 ..muted(format!("Uploading {percent} %"))
675 },
676 UploadState::Sharing(_) => ChipState {
677 progress: Some(100),
678 ..muted("Uploading 100 %".to_owned())
679 },
680 UploadState::Done(_) if *sent_as_file => muted(format!("{size}, sent as file")),
681 UploadState::Done(_) => muted(size),
682 UploadState::Failed => ChipState {
683 tone: Tone::Danger,
684 failed: true,
685 ..muted("Upload failed.".to_owned())
686 },
687 UploadState::ShareFailed(_) => ChipState {
688 tone: Tone::Danger,
689 failed: true,
690 ..muted("Sharing failed.".to_owned())
691 },
692 },
693 }
694}
695
696type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
697
698fn remove_button<T: 'static>(
699 id: u64,
700 over_image: bool,
701 remove: ItemAction<T>,
702 cx: &mut Context<T>,
703) -> Stateful<Div> {
704 let button = div()
705 .id(ElementId::Name(format!("attachment-remove-{id}").into()))
706 .size(px(REMOVE_SIZE))
707 .flex_none()
708 .flex()
709 .items_center()
710 .justify_center()
711 .rounded_full()
712 .cursor_pointer();
713 let button = if over_image {
714 button
715 .bg(black().opacity(0.6))
716 .hover(|button| button.bg(black().opacity(0.85)))
717 .child(icon(IconName::Close, 10., white()))
718 } else {
719 button
720 .hover(|button| button.bg(theme::row_hover()))
721 .child(icon(IconName::Close, 10., theme::text_muted()))
722 };
723 button.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
724}
725
726fn thumbnail<T: 'static>(
727 item: &TrayItem,
728 image: &Arc<Image>,
729 remove: ItemAction<T>,
730 cx: &mut Context<T>,
731) -> AnyElement {
732 div()
733 .id(ElementId::Name(format!("attachment-{}", item.id).into()))
734 .relative()
735 .size(px(THUMB_SIZE))
736 .flex_none()
737 .rounded(px(8.))
738 .overflow_hidden()
739 .border_1()
740 .border_color(theme::border_strong())
741 .child(img(image.clone()).size_full().object_fit(ObjectFit::Cover))
742 .child(
743 div()
744 .absolute()
745 .top(px(4.))
746 .right(px(4.))
747 .child(remove_button(item.id, true, remove, cx)),
748 )
749 .into_any_element()
750}
751
752fn chip<T: 'static>(
753 item: &TrayItem,
754 remove: ItemAction<T>,
755 retry: ItemAction<T>,
756 cx: &mut Context<T>,
757) -> AnyElement {
758 let state = chip_state(item);
759 let id = item.id;
760 let subtitle_color = match state.tone {
761 Tone::Muted => theme::text_muted(),
762 Tone::Danger => theme::red(),
763 };
764 h_flex()
765 .id(ElementId::Name(format!("attachment-{id}").into()))
766 .relative()
767 .w(px(CHIP_WIDTH))
768 .h(px(CHIP_HEIGHT))
769 .flex_none()
770 .gap(px(9.))
771 .px(px(9.))
772 .items_center()
773 .rounded(px(8.))
774 .overflow_hidden()
775 .bg(theme::surface_raised())
776 .border_1()
777 .border_color(if state.failed {
778 theme::red()
779 } else {
780 theme::border_strong()
781 })
782 .child(file_badge(FileKind::from_name(&item.name), CHIP_BADGE_SIZE))
783 .child(
784 v_flex()
785 .flex_1()
786 .min_w_0()
787 .child(
788 div()
789 .truncate()
790 .text_size(px(12.5))
791 .text_color(theme::text())
792 .child(item.name.clone()),
793 )
794 .child(
795 div()
796 .truncate()
797 .text_size(px(11.))
798 .text_color(subtitle_color)
799 .child(state.subtitle),
800 ),
801 )
802 .when(state.failed, |chip| {
803 chip.child(
804 div()
805 .id(ElementId::Name(format!("attachment-retry-{id}").into()))
806 .flex_none()
807 .text_size(px(12.))
808 .font_weight(FontWeight::SEMIBOLD)
809 .text_color(theme::accent_text())
810 .cursor_pointer()
811 .hover(|button| button.underline())
812 .child("Retry")
813 .on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),
814 )
815 })
816 .child(remove_button(id, false, remove, cx))
817 .when_some(state.progress, |chip, percent| {
818 chip.child(
819 div()
820 .absolute()
821 .left_0()
822 .bottom_0()
823 .h(px(PROGRESS_HEIGHT))
824 .w(relative(f32::from(percent) / 100.))
825 .bg(theme::accent()),
826 )
827 })
828 .into_any_element()
829}
830
831pub fn render_tray<T: 'static>(
832 tray: &AttachmentTray,
833 remove: ItemAction<T>,
834 retry: ItemAction<T>,
835 cx: &mut Context<T>,
836) -> Option<Div> {
837 if tray.is_empty() {
838 return None;
839 }
840 let elements: Vec<AnyElement> = tray
841 .items()
842 .iter()
843 .map(|item| match &item.kind {
844 ItemKind::Image { image, .. } => thumbnail(item, image, remove, cx),
845 _ => chip(item, remove, retry, cx),
846 })
847 .collect();
848 Some(
849 h_flex()
850 .w_full()
851 .flex_wrap()
852 .gap(px(TRAY_GAP))
853 .px(px(12.))
854 .pt(px(10.))
855 .pb(px(2.))
856 .children(elements),
857 )
858}
859
860#[cfg(test)]
861mod tests {
862 use std::io::Cursor;
863 use std::path::PathBuf;
864
865 use super::JobKind;
866 use gpui_kit::{ClipboardEntry, ClipboardItem, ExternalPaths, Image, ImageFormat};
867 use teams_core::{FileKind, FileReference, UploadedFile};
868
869 use super::{
870 AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
871 INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,
872 Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
873 prepare_pasted_image, read_attachment, sniff_inline_format,
874 };
875
876 const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
877
878 fn png(width: u32, height: u32) -> Vec<u8> {
879 let mut bytes = Vec::new();
880 image::RgbaImage::new(width, height)
881 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
882 .unwrap();
883 bytes
884 }
885
886 fn padded(mut bytes: Vec<u8>, length: u64) -> Vec<u8> {
887 bytes.resize(length as usize, 0);
888 bytes
889 }
890
891 fn reference(name: &str) -> FileReference {
892 FileReference {
893 attachment_id: format!("id-{name}"),
894 content_url: format!("https://files.example/{name}"),
895 name: name.to_owned(),
896 }
897 }
898
899 fn done(name: &str) -> UploadResult {
900 UploadResult::Done(DoneFile {
901 reference: reference(name),
902 uploaded: None,
903 })
904 }
905
906 fn sample_upload() -> UploadedFile {
907 UploadedFile {
908 drive_id: "d".into(),
909 item_id: "i".into(),
910 name: "plan.pdf".into(),
911 web_url: "https://x".into(),
912 web_dav_url: None,
913 etag: "\"{G},1\"".into(),
914 }
915 }
916
917 fn names(count: usize) -> Vec<String> {
918 (0..count)
919 .map(|index| format!("file-{index}.pdf"))
920 .collect()
921 }
922
923 fn loaded_file(name: &str) -> LoadedFile {
924 LoadedFile {
925 file_name: Some(name.to_owned()),
926 ..LoadedFile::new(b"%PDF-1.7".to_vec())
927 }
928 }
929
930 fn tray_with_file() -> (AttachmentTray, u64) {
931 let mut tray = AttachmentTray::default();
932 let id = tray.add_pending(&["plan.pdf".to_owned()])[0];
933 tray.finish_reading(id, LoadedFile::new(b"%PDF-1.7".to_vec()), true);
934 (tray, id)
935 }
936
937 #[test]
938 fn magic_bytes_decide_the_inline_format() {
939 assert_eq!(sniff_inline_format(&png(1, 1)), Some(InlineFormat::Png));
940 assert_eq!(
941 sniff_inline_format(&[0xFF, 0xD8, 0xFF, 0xE0, 0]),
942 Some(InlineFormat::Jpeg)
943 );
944 assert_eq!(sniff_inline_format(b"GIF89a...."), Some(InlineFormat::Gif));
945 assert_eq!(
946 sniff_inline_format(b"RIFF\x10\0\0\0WEBPVP8 "),
947 Some(InlineFormat::Webp)
948 );
949 assert_eq!(sniff_inline_format(b"BM......"), None);
950 assert_eq!(sniff_inline_format(b"%PDF-1.7"), None);
951 assert_eq!(sniff_inline_format(&[]), None);
952 }
953
954 #[test]
955 fn small_supported_images_are_inline() {
956 assert_eq!(
957 classify("shot.png", &png(2, 2), 0),
958 Classification::Inline(InlineFormat::Png)
959 );
960 }
961
962 #[test]
963 fn images_over_one_megabyte_become_files() {
964 let at_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
965 let over_limit = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES + 1);
966 assert_eq!(
967 classify("a.png", &at_limit, 0),
968 Classification::Inline(InlineFormat::Png)
969 );
970 assert_eq!(
971 classify("a.png", &over_limit, 0),
972 Classification::File { sent_as_file: true }
973 );
974 }
975
976 #[test]
977 fn the_inline_total_is_capped_and_later_images_become_files() {
978 let image = padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES);
979 assert_eq!(
980 classify(
981 "a.png",
982 &image,
983 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES
984 ),
985 Classification::Inline(InlineFormat::Png)
986 );
987 assert_eq!(
988 classify(
989 "a.png",
990 &image,
991 INLINE_TOTAL_MAX_BYTES - INLINE_IMAGE_MAX_BYTES + 1
992 ),
993 Classification::File { sent_as_file: true }
994 );
995 }
996
997 #[test]
998 fn removing_an_inline_image_does_not_reclassify_the_others() {
999 let big = || LoadedFile::new(padded(PNG_HEADER.to_vec(), INLINE_IMAGE_MAX_BYTES));
1000 let mut tray = AttachmentTray::default();
1001 let ids = tray.add_pending(&names(4));
1002 for id in &ids[..3] {
1003 tray.finish_reading(*id, big(), true);
1004 }
1005 let job = tray.finish_reading(ids[3], big(), true);
1006 assert!(
1007 job.is_some(),
1008 "the fourth 1 MiB image exceeds 2.5 MiB inline"
1009 );
1010 tray.remove(ids[0]);
1011 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1012 }
1013
1014 #[test]
1015 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1016 let (mut tray, id) = tray_with_file();
1017 let uploaded = sample_upload();
1018 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1019 let state = chip_state(&tray.items()[0]);
1020 assert_eq!(state.subtitle, "Sharing failed.");
1021 assert!(state.failed);
1022 assert!(tray.blocks_send());
1023 let job = tray.retry(id).unwrap();
1024 assert!(matches!(job.kind, JobKind::Share(ref file) if *file == uploaded));
1025 assert_eq!(tray.clear(), vec![uploaded.clone()]);
1026 let (mut tray, id) = tray_with_file();
1027 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1028 tray.retry(id);
1029 tray.finish_upload(id, UploadResult::ShareFailed(uploaded.clone()));
1030 assert_eq!(tray.remove(id), Some(uploaded));
1031 }
1032
1033 #[test]
1034 fn an_item_being_shared_can_be_deleted_by_remove_or_clear() {
1035 let (mut tray, id) = tray_with_file();
1036 tray.mark_uploaded(id, sample_upload());
1037 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 100 %");
1038 assert!(tray.blocks_send());
1039 tray.set_progress(id, 10);
1040 assert_eq!(chip_state(&tray.items()[0]).progress, Some(100));
1041 assert_eq!(tray.remove(id), Some(sample_upload()));
1042
1043 let (mut tray, id) = tray_with_file();
1044 tray.mark_uploaded(id, sample_upload());
1045 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload()));
1046 assert!(chip_state(&tray.items()[0]).failed);
1047 assert_eq!(tray.keep_images_only(), vec![sample_upload()]);
1048 }
1049
1050 #[test]
1051 fn events_for_a_removed_item_hand_the_upload_back_for_deletion() {
1052 let (mut tray, id) = tray_with_file();
1053 tray.remove(id);
1054 assert_eq!(
1055 tray.mark_uploaded(id, sample_upload()),
1056 Some(sample_upload())
1057 );
1058 let done = UploadResult::Done(DoneFile {
1059 reference: reference("plan.pdf"),
1060 uploaded: Some(sample_upload()),
1061 });
1062 assert_eq!(tray.finish_upload(id, done), Some(sample_upload()));
1063 assert_eq!(
1064 tray.finish_upload(id, UploadResult::ShareFailed(sample_upload())),
1065 Some(sample_upload())
1066 );
1067 assert_eq!(tray.finish_upload(id, UploadResult::Failed), None);
1068 }
1069
1070 #[test]
1071 fn events_for_a_live_item_are_never_handed_back() {
1072 let (mut tray, id) = tray_with_file();
1073 assert_eq!(tray.mark_uploaded(id, sample_upload()), None);
1074 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1075 assert_eq!(tray.finish_upload(id, done("plan.pdf")), None);
1076 }
1077
1078 #[test]
1079 fn removing_or_clearing_reports_the_uploads_that_were_never_sent() {
1080 let (mut tray, id) = tray_with_file();
1081 tray.finish_upload(
1082 id,
1083 UploadResult::Done(DoneFile {
1084 reference: reference("plan.pdf"),
1085 uploaded: Some(sample_upload()),
1086 }),
1087 );
1088 assert_eq!(tray.clear(), vec![sample_upload()]);
1089 let (mut other, other_id) = tray_with_file();
1090 assert_eq!(other.remove(other_id), None);
1091 }
1092
1093 #[test]
1094 fn other_image_formats_become_files_with_the_note() {
1095 assert_eq!(
1096 classify("scan.bmp", b"BM......", 0),
1097 Classification::File { sent_as_file: true }
1098 );
1099 assert_eq!(
1100 classify("photo.HEIC", b"....ftypheic", 0),
1101 Classification::File { sent_as_file: true }
1102 );
1103 assert_eq!(
1104 classify("plan.pdf", b"%PDF-1.7", 0),
1105 Classification::File {
1106 sent_as_file: false
1107 }
1108 );
1109 }
1110
1111 #[test]
1112 fn dimensions_come_from_the_headers() {
1113 assert_eq!(LoadedFile::new(png(7, 3)).dimensions, Some((7, 3)));
1114 let mut gif = b"GIF89a".to_vec();
1115 gif.extend_from_slice(&[10, 0, 20, 0]);
1116 assert_eq!(LoadedFile::new(gif).dimensions, Some((10, 20)));
1117 assert_eq!(LoadedFile::new(b"%PDF".to_vec()).dimensions, None);
1118 }
1119
1120 #[test]
1121 fn the_tenth_attachment_fits_and_the_rest_are_dropped() {
1122 let mut tray = AttachmentTray::default();
1123 assert_eq!(tray.add_pending(&names(4)).len(), 4);
1124 let ids = tray.add_pending(&names(9));
1125 assert_eq!(ids.len(), 6);
1126 assert_eq!(tray.items().len(), MAX_ATTACHMENTS);
1127 assert_eq!(
1128 tray.notice(),
1129 Some("Up to 10 attachments per message. 3 files were not added.")
1130 );
1131 }
1132
1133 #[test]
1134 fn one_dropped_file_reads_in_the_singular() {
1135 assert_eq!(
1136 limit_notice(1),
1137 "Up to 10 attachments per message. 1 file was not added."
1138 );
1139 }
1140
1141 #[test]
1142 fn the_limit_notice_clears_on_the_next_change() {
1143 let mut tray = AttachmentTray::default();
1144 let ids = tray.add_pending(&names(12));
1145 assert!(tray.notice().is_some());
1146 tray.remove(ids[0]);
1147 assert_eq!(tray.notice(), None);
1148 tray.add_pending(&names(3));
1149 assert!(tray.notice().is_some());
1150 tray.clear();
1151 assert_eq!(tray.notice(), None);
1152 }
1153
1154 #[test]
1155 fn a_file_starts_uploading_and_an_image_does_not() {
1156 let mut tray = AttachmentTray::default();
1157 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1158 let job = tray.finish_reading(ids[0], LoadedFile::new(b"%PDF".to_vec()), true);
1159 assert_eq!(job.as_ref().map(|job| job.name.as_str()), Some("a.pdf"));
1160 assert!(
1161 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), true)
1162 .is_none()
1163 );
1164 assert!(matches!(tray.items()[1].kind, ItemKind::Image { .. }));
1165 assert!(tray.blocks_send());
1166 }
1167
1168 #[test]
1169 fn a_pasted_name_replaces_the_placeholder() {
1170 let mut tray = AttachmentTray::default();
1171 let id = tray.add_pending(&[pasted_image_name()])[0];
1172 let loaded = LoadedFile {
1173 file_name: Some("pasted-image.jpg".into()),
1174 ..LoadedFile::new(vec![0xFF, 0xD8, 0xFF, 0xE0])
1175 };
1176 tray.finish_reading(id, loaded, true);
1177 assert_eq!(tray.items()[0].name, "pasted-image.jpg");
1178 }
1179
1180 #[test]
1181 fn files_are_refused_while_the_chat_does_not_exist() {
1182 let mut tray = AttachmentTray::default();
1183 let ids = tray.add_pending(&["a.pdf".to_owned(), "b.png".to_owned()]);
1184 assert!(
1185 tray.finish_reading(ids[0], loaded_file("a.pdf"), false)
1186 .is_none()
1187 );
1188 tray.finish_reading(ids[1], LoadedFile::new(png(2, 2)), false);
1189 assert_eq!(tray.items().len(), 1);
1190 assert_eq!(tray.notice(), Some(FILES_LATER_NOTICE));
1191 assert!(!tray.blocks_send());
1192 }
1193
1194 #[test]
1195 fn upload_progress_then_done_unblocks_sending() {
1196 let (mut tray, id) = tray_with_file();
1197 tray.set_progress(id, 42);
1198 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 42 %");
1199 assert_eq!(chip_state(&tray.items()[0]).progress, Some(42));
1200 assert!(tray.blocks_send());
1201 tray.finish_upload(id, done("plan.pdf"));
1202 assert!(!tray.blocks_send());
1203 assert_eq!(tray.outgoing_files().len(), 1);
1204 assert_eq!(
1205 tray.outgoing_files()[0].kind,
1206 FileKind::from_name("plan.pdf")
1207 );
1208 }
1209
1210 #[test]
1211 fn progress_after_the_upload_ended_is_ignored() {
1212 let (mut tray, id) = tray_with_file();
1213 tray.finish_upload(id, done("plan.pdf"));
1214 tray.set_progress(id, 10);
1215 tray.finish_upload(id, UploadResult::Failed);
1216 assert!(!tray.blocks_send());
1217 }
1218
1219 #[test]
1220 fn a_failed_upload_blocks_sending_until_it_is_retried_or_removed() {
1221 let (mut tray, id) = tray_with_file();
1222 tray.finish_upload(id, UploadResult::Failed);
1223 let state = chip_state(&tray.items()[0]);
1224 assert_eq!(state.subtitle, "Upload failed.");
1225 assert_eq!(state.tone, Tone::Danger);
1226 assert!(state.failed);
1227 assert!(tray.blocks_send());
1228 assert!(tray.outgoing_files().is_empty());
1229
1230 let job = tray.retry(id).expect("failed uploads can be retried");
1231 assert_eq!(job.name, "plan.pdf");
1232 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Uploading 0 %");
1233 assert!(tray.retry(id).is_none());
1234
1235 tray.finish_upload(id, UploadResult::Failed);
1236 tray.remove(id);
1237 assert!(!tray.blocks_send());
1238 }
1239
1240 #[test]
1241 fn a_result_for_a_removed_item_is_dropped() {
1242 let (mut tray, id) = tray_with_file();
1243 tray.remove(id);
1244 tray.finish_upload(id, done("plan.pdf"));
1245 assert!(tray.is_empty());
1246 }
1247
1248 #[test]
1249 fn done_chips_show_the_size_and_the_file_note() {
1250 let mut tray = AttachmentTray::default();
1251 let id = tray.add_pending(&["scan.bmp".to_owned()])[0];
1252 tray.finish_reading(id, LoadedFile::new(b"BM....".to_vec()), true);
1253 tray.finish_upload(id, done("scan.bmp"));
1254 assert_eq!(chip_state(&tray.items()[0]).subtitle, "6 B, sent as file");
1255 let (mut other, other_id) = tray_with_file();
1256 other.finish_upload(other_id, done("plan.pdf"));
1257 assert_eq!(chip_state(&other.items()[0]).subtitle, "8 B");
1258 }
1259
1260 #[test]
1261 fn restore_brings_back_images_and_uploaded_files() {
1262 let mut source = AttachmentTray::default();
1263 let ids = source.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1264 source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);
1265 source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1266 source.finish_upload(ids[1], done("b.pdf"));
1267 let (images, files) = (source.outgoing_images(), source.outgoing_files());
1268
1269 let mut restored = AttachmentTray::default();
1270 restored.restore(&images, &files);
1271 assert_eq!(restored.outgoing_images(), images);
1272 assert_eq!(restored.outgoing_files(), files);
1273 assert!(!restored.blocks_send());
1274 }
1275
1276 #[test]
1277 fn switching_chats_for_a_draft_keeps_only_images() {
1278 let mut tray = AttachmentTray::default();
1279 let ids = tray.add_pending(&["a.png".to_owned(), "b.pdf".to_owned()]);
1280 tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1281 tray.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1282 tray.keep_images_only();
1283 assert_eq!(tray.items().len(), 1);
1284 assert!(matches!(tray.items()[0].kind, ItemKind::Image { .. }));
1285 }
1286
1287 #[test]
1288 fn a_failed_read_removes_the_item_and_says_why() {
1289 let mut tray = AttachmentTray::default();
1290 let id = tray.add_pending(&["gone.txt".to_owned()])[0];
1291 tray.fail_reading(id, "Could not read gone.txt.".to_owned());
1292 assert!(tray.is_empty());
1293 assert_eq!(tray.notice(), Some("Could not read gone.txt."));
1294 }
1295
1296 #[test]
1297 fn reading_items_block_sending() {
1298 let mut tray = AttachmentTray::default();
1299 tray.add_pending(&["a.pdf".to_owned()]);
1300 assert!(tray.blocks_send());
1301 assert_eq!(chip_state(&tray.items()[0]).subtitle, "Reading ...");
1302 }
1303
1304 #[test]
1305 fn files_are_read_from_disk_with_their_limits() {
1306 let directory = tempfile::tempdir().unwrap();
1307 let file = directory.path().join("note.txt");
1308 std::fs::write(&file, b"hello").unwrap();
1309 let empty = directory.path().join("empty.txt");
1310 std::fs::write(&empty, b"").unwrap();
1311
1312 assert_eq!(read_attachment(&file).unwrap().bytes, b"hello");
1313 assert_eq!(read_attachment(&empty).unwrap_err(), "empty.txt is empty.");
1314 assert!(
1315 read_attachment(directory.path())
1316 .unwrap_err()
1317 .ends_with('.')
1318 );
1319 assert_eq!(
1320 read_attachment(&directory.path().join("missing.txt")).unwrap_err(),
1321 "Could not read missing.txt."
1322 );
1323 }
1324
1325 fn clipboard(entries: Vec<ClipboardEntry>) -> ClipboardItem {
1326 ClipboardItem { entries }
1327 }
1328
1329 fn pasted_png() -> Image {
1330 Image::from_bytes(ImageFormat::Png, png(2, 2))
1331 }
1332
1333 #[test]
1334 fn pasting_an_image_alone_adds_an_image() {
1335 let item = clipboard(vec![ClipboardEntry::Image(pasted_png())]);
1336 assert_eq!(paste_action(&item), PasteAction::Image(pasted_png()));
1337 }
1338
1339 #[test]
1340 fn pasting_copied_files_adds_those_files() {
1341 let paths = ExternalPaths(vec![PathBuf::from("/a/b.pdf")].into_iter().collect());
1342 let item = clipboard(vec![ClipboardEntry::ExternalPaths(paths)]);
1343 assert_eq!(
1344 paste_action(&item),
1345 PasteAction::Files(vec![PathBuf::from("/a/b.pdf")])
1346 );
1347 }
1348
1349 #[test]
1350 fn pasting_text_or_text_with_a_bitmap_stays_text() {
1351 assert_eq!(
1352 paste_action(&ClipboardItem::new_string("hi".into())),
1353 PasteAction::Text
1354 );
1355 let both = clipboard(vec![
1356 ClipboardEntry::from("cells".to_owned()),
1357 ClipboardEntry::Image(pasted_png()),
1358 ]);
1359 assert_eq!(paste_action(&both), PasteAction::Text);
1360 assert_eq!(paste_action(&clipboard(Vec::new())), PasteAction::Text);
1361 }
1362
1363 #[test]
1364 fn a_pasted_bitmap_becomes_a_png() {
1365 let mut bmp = Vec::new();
1366 image::RgbaImage::new(3, 2)
1367 .write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp)
1368 .unwrap();
1369 let loaded = prepare_pasted_image(Image::from_bytes(ImageFormat::Bmp, bmp)).unwrap();
1370 assert_eq!(sniff_inline_format(&loaded.bytes), Some(InlineFormat::Png));
1371 assert_eq!(loaded.dimensions, Some((3, 2)));
1372 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1373 }
1374
1375 #[test]
1376 fn a_pasted_png_keeps_its_bytes() {
1377 let loaded = prepare_pasted_image(pasted_png()).unwrap();
1378 assert_eq!(loaded.bytes, png(2, 2));
1379 assert_eq!(loaded.file_name.as_deref(), Some("pasted-image.png"));
1380 }
1381}
crates/app/src/views/attachments.rs +38 −6
@@ -7,6 +7,7 @@ use teams_core::{FileCard, FileKind, ImageRef};
7 7 use super::widgets::icon;
8 8 use crate::data::Directory;
9 9 use crate::format;
10 use crate::rows::LocalImage;
10 11 use crate::theme;
11 12
12 13 pub const IMAGE_MAX_WIDTH: f32 = 360.;
@@ -117,10 +118,10 @@ pub fn file_subtitle(card: &FileCard) -> String {
117 118 }
118 119 }
119 120
120 fn file_view(card: &FileCard, id: String) -> AnyElement {
121 let style = kind_style(card.kind);
122 let badge = div()
123 .size(px(FILE_BADGE_SIZE))
121 pub fn file_badge(kind: FileKind, size: f32) -> Div {
122 let style = kind_style(kind);
123 div()
124 .size(px(size))
124 125 .flex_none()
125 126 .flex()
126 127 .items_center()
@@ -133,7 +134,32 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
133 134 .when(style.label.is_empty(), |badge| {
134 135 badge.child(icon(IconName::File, 16., gpui_kit::white()))
135 136 })
136 .when(!style.label.is_empty(), |badge| badge.child(style.label));
137 .when(!style.label.is_empty(), |badge| badge.child(style.label))
138 }
139
140 fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
141 let (width, height) = fit_image(image.size);
142 div()
143 .id(ElementId::Name(id.into()))
144 .w(px(width))
145 .h(px(height))
146 .max_w(relative(1.))
147 .flex_none()
148 .rounded(px(IMAGE_RADIUS))
149 .overflow_hidden()
150 .border_1()
151 .border_color(theme::border())
152 .child(
153 img(image.image.clone())
154 .size_full()
155 .rounded(px(IMAGE_RADIUS))
156 .object_fit(ObjectFit::Cover),
157 )
158 .into_any_element()
159 }
160
161 fn file_view(card: &FileCard, id: String) -> AnyElement {
162 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
137 163 let url = card.open_url.clone();
138 164 h_flex()
139 165 .id(ElementId::Name(id.into()))
@@ -176,11 +202,12 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
176 202
177 203 pub fn attachments_view(
178 204 images: &[ImageRef],
205 local_images: &[LocalImage],
179 206 files: &[FileCard],
180 207 id: &str,
181 208 directory: &Directory,
182 209 ) -> Option<Div> {
183 if images.is_empty() && files.is_empty() {
210 if images.is_empty() && local_images.is_empty() && files.is_empty() {
184 211 return None;
185 212 }
186 213 Some(
@@ -192,6 +219,11 @@ pub fn attachments_view(
192 219 image_view(image, format!("{id}-image-{index}"), directory)
193 220 }),
194 221 )
222 .children(
223 local_images.iter().enumerate().map(|(index, image)| {
224 local_image_view(image, format!("{id}-local-image-{index}"))
225 }),
226 )
195 227 .children(
196 228 files
197 229 .iter()
@@ -7,6 +7,7 @@ use teams_core::{FileCard, FileKind, ImageRef};
7use super::widgets::icon;
7use super::widgets::icon;
8use crate::data::Directory;
8use crate::data::Directory;
9use crate::format;
9use crate::format;
10use crate::rows::LocalImage;
10use crate::theme;
11use crate::theme;
11
12
12pub const IMAGE_MAX_WIDTH: f32 = 360.;
13pub const IMAGE_MAX_WIDTH: f32 = 360.;
@@ -117,10 +118,10 @@ pub fn file_subtitle(card: &FileCard) -> String {
117 }
118 }
118}
119}
119
120
120fn file_view(card: &FileCard, id: String) -> AnyElement {
121pub fn file_badge(kind: FileKind, size: f32) -> Div {
121 let style = kind_style(card.kind);
122 let style = kind_style(kind);
122 let badge = div()
123 div()
123 .size(px(FILE_BADGE_SIZE))
124 .size(px(size))
124 .flex_none()
125 .flex_none()
125 .flex()
126 .flex()
126 .items_center()
127 .items_center()
@@ -133,7 +134,32 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
133 .when(style.label.is_empty(), |badge| {
134 .when(style.label.is_empty(), |badge| {
134 badge.child(icon(IconName::File, 16., gpui_kit::white()))
135 badge.child(icon(IconName::File, 16., gpui_kit::white()))
135 })
136 })
136 .when(!style.label.is_empty(), |badge| badge.child(style.label));
137 .when(!style.label.is_empty(), |badge| badge.child(style.label))
138}
139
140fn local_image_view(image: &LocalImage, id: String) -> AnyElement {
141 let (width, height) = fit_image(image.size);
142 div()
143 .id(ElementId::Name(id.into()))
144 .w(px(width))
145 .h(px(height))
146 .max_w(relative(1.))
147 .flex_none()
148 .rounded(px(IMAGE_RADIUS))
149 .overflow_hidden()
150 .border_1()
151 .border_color(theme::border())
152 .child(
153 img(image.image.clone())
154 .size_full()
155 .rounded(px(IMAGE_RADIUS))
156 .object_fit(ObjectFit::Cover),
157 )
158 .into_any_element()
159}
160
161fn file_view(card: &FileCard, id: String) -> AnyElement {
162 let badge = file_badge(card.kind, FILE_BADGE_SIZE);
137 let url = card.open_url.clone();
163 let url = card.open_url.clone();
138 h_flex()
164 h_flex()
139 .id(ElementId::Name(id.into()))
165 .id(ElementId::Name(id.into()))
@@ -176,11 +202,12 @@ fn file_view(card: &FileCard, id: String) -> AnyElement {
176
202
177pub fn attachments_view(
203pub fn attachments_view(
178 images: &[ImageRef],
204 images: &[ImageRef],
205 local_images: &[LocalImage],
179 files: &[FileCard],
206 files: &[FileCard],
180 id: &str,
207 id: &str,
181 directory: &Directory,
208 directory: &Directory,
182) -> Option<Div> {
209) -> Option<Div> {
183 if images.is_empty() && files.is_empty() {
210 if images.is_empty() && local_images.is_empty() && files.is_empty() {
184 return None;
211 return None;
185 }
212 }
186 Some(
213 Some(
@@ -192,6 +219,11 @@ pub fn attachments_view(
192 image_view(image, format!("{id}-image-{index}"), directory)
219 image_view(image, format!("{id}-image-{index}"), directory)
193 }),
220 }),
194 )
221 )
222 .children(
223 local_images.iter().enumerate().map(|(index, image)| {
224 local_image_view(image, format!("{id}-local-image-{index}"))
225 }),
226 )
195 .children(
227 .children(
196 files
228 files
197 .iter()
229 .iter()
crates/app/src/views/composer.rs +705 −18
@@ -1,5 +1,7 @@
1 use std::collections::HashMap;
1 use std::collections::{HashMap, HashSet};
2 2 use std::ops::Range;
3 use std::path::PathBuf;
4 use std::sync::Arc;
3 5 use std::time::Duration;
4 6
5 7 use gpui_kit::assets::IconName;
@@ -9,12 +11,20 @@ use gpui_kit::component::{
9 11 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
10 12 MoveUp, Textarea, TextareaState,
11 13 },
14 tooltip::Tooltip,
12 15 v_flex,
13 16 };
14 17 use gpui_kit::prelude::FluentBuilder as _;
15 18 use gpui_kit::*;
16 use teams_core::{MentionCandidate, MentionInput};
19 use teams_core::{
20 FileReference, HostedImage, MentionCandidate, MentionInput, MessageExtras, UploadedFile,
21 };
17 22
23 use super::attachment_tray::{
24 AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,
25 UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,
26 prepare_pasted_image, read_attachment, render_tray,
27 };
18 28 use super::avatar::{person_avatar, square_avatar};
19 29 use super::emoji_popup::{self, EmojiPopup};
20 30 use super::widgets::{icon, symbol};
@@ -31,6 +41,9 @@ const MENTION_QUERY_MAX_CHARS: usize = 32;
31 41 const MENTION_QUERY_MAX_WORDS: usize = 3;
32 42 const POPUP_WIDTH: f32 = 380.;
33 43 const POPUP_ROW_HEIGHT: f32 = 44.;
44 const DEMO_UPLOAD_STEPS: u8 = 10;
45 const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
46 const DEMO_FAILURE_STEP: u8 = 6;
34 47
35 48 #[derive(Debug, Clone, PartialEq, Eq)]
36 49 pub struct ReplyPreview {
@@ -51,10 +64,57 @@ pub struct Outgoing {
51 64 pub mentions: Vec<MentionInput>,
52 65 pub reply: Option<ReplyPreview>,
53 66 pub edit: Option<EditPreview>,
67 pub images: Vec<OutgoingImage>,
68 pub files: Vec<OutgoingFile>,
69 }
70
71 impl Outgoing {
72 pub fn has_attachments(&self) -> bool {
73 !self.images.is_empty() || !self.files.is_empty()
74 }
75
76 pub fn extras(&self) -> MessageExtras {
77 MessageExtras {
78 kept: Vec::new(),
79 images: self
80 .images
81 .iter()
82 .map(|outgoing| HostedImage {
83 content_type: outgoing.image.format.mime_type().to_owned(),
84 bytes: Arc::new(outgoing.image.bytes.clone()),
85 })
86 .collect(),
87 files: self
88 .files
89 .iter()
90 .map(|file| file.reference.clone())
91 .collect(),
92 }
93 }
94 }
95
96 enum UploadEvent {
97 Progress(u8),
98 Uploaded(UploadedFile),
99 Finished(UploadResult),
100 }
101
102 enum UploadHandle {
103 Network(tokio::task::AbortHandle),
104 Demo(Task<()>),
105 }
106
107 impl UploadHandle {
108 fn cancel(self) {
109 match self {
110 UploadHandle::Network(handle) => handle.abort(),
111 UploadHandle::Demo(task) => drop(task),
112 }
113 }
54 114 }
55 115
56 116 pub enum ComposerEvent {
57 Submit(Outgoing),
117 Submit(Box<Outgoing>),
58 118 EditLast,
59 119 }
60 120
@@ -88,11 +148,19 @@ pub struct Composer {
88 148 conversion: Option<Conversion>,
89 149 undone_value: Option<String>,
90 150 previous_value: String,
151 tray: AttachmentTray,
152 uploads: HashMap<u64, UploadHandle>,
153 demo_failed: HashSet<u64>,
154 carry_images_into: Option<String>,
91 155 _subscription: Subscription,
92 156 }
93 157
94 158 impl EventEmitter<ComposerEvent> for Composer {}
95 159
160 pub fn is_plain_enter(event: &InputEvent) -> bool {
161 matches!(event, InputEvent::PressEnter { shift: false, .. })
162 }
163
96 164 /// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
97 165 pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
98 166 match event {
@@ -180,6 +248,10 @@ impl Composer {
180 248 conversion: None,
181 249 undone_value: None,
182 250 previous_value: String::new(),
251 tray: AttachmentTray::default(),
252 uploads: HashMap::new(),
253 demo_failed: HashSet::new(),
254 carry_images_into: None,
183 255 _subscription: subscription,
184 256 }
185 257 }
@@ -198,7 +270,9 @@ impl Composer {
198 270 self.update_mention(cx);
199 271 }
200 272 let value = input.read(cx).value();
201 if submitted_text(event, &value).is_some() {
273 if submitted_text(event, &value).is_some()
274 || (is_plain_enter(event) && !self.tray.is_empty())
275 {
202 276 self.submit_current(window, cx);
203 277 }
204 278 }
@@ -458,7 +532,15 @@ impl Composer {
458 532 ) {
459 533 self.set_placeholder(&format!("Message {name}"), window, cx);
460 534 if self.conversation_id.as_deref() != Some(conversation_id) {
535 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
461 536 self.conversation_id = Some(conversation_id.to_owned());
537 self.cancel_uploads();
538 let dropped = if carry {
539 self.tray.keep_images_only()
540 } else {
541 self.tray.clear()
542 };
543 self.discard_uploaded(dropped, cx);
462 544 self.reply = None;
463 545 if self.editing.take().is_some() {
464 546 self.input
@@ -470,6 +552,15 @@ impl Composer {
470 552 }
471 553 }
472 554
555 /// The draft's images follow the user into this chat; any other switch clears the tray.
556 pub fn carry_images_into(&mut self, conversation_id: String) {
557 self.carry_images_into = Some(conversation_id);
558 }
559
560 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
561 discard_uploaded(self.app.read(cx).engine.clone(), files);
562 }
563
473 564 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
474 565 self.reply = reply;
475 566 if self.reply.is_some() {
@@ -491,9 +582,10 @@ impl Composer {
491 582 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
492 583 let state = self.input.read(cx);
493 584 let mut text = state.value().trim().to_owned();
494 if text.is_empty() {
585 if !self.can_send(cx) {
495 586 return None;
496 587 }
588 let attachments_apply = self.editing.is_none();
497 589 if self.undone_value.as_deref() != Some(state.value().as_ref())
498 590 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
499 591 {
@@ -510,7 +602,276 @@ impl Composer {
510 602 mentions,
511 603 reply: self.reply.clone(),
512 604 edit: self.editing.clone(),
605 images: if attachments_apply {
606 self.tray.outgoing_images()
607 } else {
608 Vec::new()
609 },
610 files: if attachments_apply {
611 self.tray.outgoing_files()
612 } else {
613 Vec::new()
614 },
615 })
616 }
617
618 fn can_send(&self, cx: &App) -> bool {
619 let has_text = !self.input.read(cx).value().trim().is_empty();
620 if self.editing.is_some() {
621 return has_text;
622 }
623 (has_text || !self.tray.is_empty()) && !self.tray.blocks_send()
624 }
625
626 pub fn is_editing(&self) -> bool {
627 self.editing.is_some()
628 }
629
630 fn files_allowed(&self) -> bool {
631 self.conversation_id
632 .as_deref()
633 .is_some_and(|conversation_id| !conversation_id.is_empty())
634 }
635
636 fn cancel_uploads(&mut self) {
637 for (_, handle) in self.uploads.drain() {
638 handle.cancel();
639 }
640 }
641
642 pub fn open_picker(&mut self, cx: &mut Context<Self>) {
643 if self.editing.is_some() {
644 return;
645 }
646 let receiver = cx.prompt_for_paths(PathPromptOptions {
647 files: true,
648 directories: false,
649 multiple: true,
650 prompt: None,
651 });
652 cx.spawn(async move |this, cx| {
653 if let Ok(Ok(Some(paths))) = receiver.await {
654 this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();
655 }
656 })
657 .detach();
658 }
659
660 pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
661 if self.editing.is_some() || paths.is_empty() {
662 return;
663 }
664 let ids = self.tray.add_pending(&names_of(&paths));
665 for (id, path) in ids.into_iter().zip(paths) {
666 cx.spawn(async move |this, cx| {
667 let loaded = cx
668 .background_executor()
669 .spawn(async move { read_attachment(&path) })
670 .await;
671 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
672 .ok();
673 })
674 .detach();
675 }
676 cx.notify();
677 }
678
679 fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {
680 let ids = self.tray.add_pending(&[pasted_image_name()]);
681 cx.notify();
682 let Some(&id) = ids.first() else {
683 return;
684 };
685 cx.spawn(async move |this, cx| {
686 let loaded = cx
687 .background_executor()
688 .spawn(async move { prepare_pasted_image(pasted) })
689 .await;
690 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
691 .ok();
513 692 })
693 .detach();
694 }
695
696 fn paste(&mut self, item: &ClipboardItem, cx: &mut Context<Self>) -> bool {
697 if self.editing.is_some() {
698 return false;
699 }
700 match paste_action(item) {
701 PasteAction::Text => false,
702 PasteAction::Files(paths) => {
703 self.add_paths(paths, cx);
704 true
705 }
706 PasteAction::Image(pasted) => {
707 self.add_pasted_image(pasted, cx);
708 true
709 }
710 }
711 }
712
713 fn finish_reading(
714 &mut self,
715 id: u64,
716 loaded: Result<LoadedFile, String>,
717 cx: &mut Context<Self>,
718 ) {
719 match loaded {
720 Ok(loaded) => {
721 let files_allowed = self.files_allowed();
722 if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {
723 self.start_upload(job, cx);
724 }
725 }
726 Err(message) => self.tray.fail_reading(id, message),
727 }
728 cx.notify();
729 }
730
731 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
732 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
733 self.tray.finish_upload(job.id, UploadResult::Failed);
734 return;
735 };
736 let state = self.app.read(cx);
737 let (demo, engine) = (state.mode.demo, state.engine.clone());
738 if demo {
739 self.simulate_upload(job, cx);
740 return;
741 }
742 let Some(engine) = engine else {
743 self.tray.finish_upload(job.id, UploadResult::Failed);
744 return;
745 };
746 let id = job.id;
747 let (event_sender, mut event_receiver) =
748 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
749 let finished_sender = event_sender.clone();
750 let (_, handle) = runtime::spawn_abortable(async move {
751 let result = async {
752 let uploaded = match job.kind {
753 JobKind::Upload => {
754 let progress_sender = event_sender.clone();
755 let uploaded = engine
756 .upload_attachment_file(
757 &conversation_id,
758 &job.name,
759 &job.bytes,
760 move |percent| {
761 let _ = progress_sender.send(UploadEvent::Progress(percent));
762 },
763 )
764 .await;
765 match uploaded {
766 Ok(uploaded) => {
767 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
768 uploaded
769 }
770 Err(_) => return UploadResult::Failed,
771 }
772 }
773 JobKind::Share(uploaded) => uploaded,
774 };
775 let Some(reference) = uploaded.reference() else {
776 return UploadResult::Failed;
777 };
778 match engine.share_attachment(&conversation_id, &uploaded).await {
779 Ok(()) => UploadResult::Done(DoneFile {
780 reference,
781 uploaded: Some(uploaded),
782 }),
783 Err(_) => UploadResult::ShareFailed(uploaded),
784 }
785 }
786 .await;
787 let _ = finished_sender.send(UploadEvent::Finished(result));
788 });
789 self.uploads.insert(id, UploadHandle::Network(handle));
790 cx.spawn(async move |this, cx| {
791 while let Some(event) = event_receiver.recv().await {
792 let updated = this.update(cx, |this, cx| {
793 let orphan = match event {
794 UploadEvent::Progress(percent) => {
795 this.tray.set_progress(id, percent);
796 None
797 }
798 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
799 UploadEvent::Finished(result) => this.finish_upload(id, result),
800 };
801 this.discard_uploaded(orphan.into_iter().collect(), cx);
802 cx.notify();
803 });
804 if updated.is_err() {
805 break;
806 }
807 }
808 })
809 .detach();
810 }
811
812 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
813 let id = job.id;
814 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
815 let task = cx.spawn(async move |this, cx| {
816 for step in 1..=DEMO_UPLOAD_STEPS {
817 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
818 if fails && step == DEMO_FAILURE_STEP {
819 this.update(cx, |this, cx| {
820 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
821 })
822 .ok();
823 return;
824 }
825 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
826 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
827 .ok();
828 }
829 let reference = FileReference {
830 attachment_id: format!("demo-attachment-{id}"),
831 content_url: format!("https://demo.invalid/files/{}", job.name),
832 name: job.name,
833 };
834 let done = DoneFile {
835 reference,
836 uploaded: None,
837 };
838 this.update(cx, |this, cx| {
839 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
840 })
841 .ok();
842 });
843 self.uploads.insert(id, UploadHandle::Demo(task));
844 }
845
846 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
847 self.tray.set_progress(id, percent);
848 cx.notify();
849 }
850
851 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
852 self.uploads.remove(&id);
853 self.tray.finish_upload(id, result)
854 }
855
856 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
857 self.finish_upload(id, result);
858 cx.notify();
859 }
860
861 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
862 if let Some(handle) = self.uploads.remove(&id) {
863 handle.cancel();
864 }
865 let uploaded = self.tray.remove(id);
866 self.discard_uploaded(uploaded.into_iter().collect(), cx);
867 cx.notify();
868 }
869
870 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
871 if let Some(job) = self.tray.retry(id) {
872 self.start_upload(job, cx);
873 }
874 cx.notify();
514 875 }
515 876
516 877 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -520,10 +881,13 @@ impl Composer {
520 881 self.input
521 882 .update(cx, |state, cx| state.set_value("", window, cx));
522 883 self.mention_inputs.clear();
884 if self.editing.is_none() {
885 self.tray.clear();
886 }
523 887 self.reply = None;
524 888 self.editing = None;
525 889 self.close_popup();
526 cx.emit(ComposerEvent::Submit(outgoing));
890 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
527 891 cx.notify();
528 892 }
529 893
@@ -553,6 +917,10 @@ impl Composer {
553 917 });
554 918 self.reply = outgoing.reply.clone();
555 919 self.editing = outgoing.edit.clone();
920 if outgoing.edit.is_none() {
921 self.cancel_uploads();
922 self.tray.restore(&outgoing.images, &outgoing.files);
923 }
556 924 self.close_popup();
557 925 cx.notify();
558 926 }
@@ -571,7 +939,7 @@ impl Composer {
571 939 }
572 940
573 941 pub fn is_empty(&self, cx: &App) -> bool {
574 self.input.read(cx).value().trim().is_empty()
942 self.input.read(cx).value().trim().is_empty() && self.tray.is_empty()
575 943 }
576 944
577 945 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -799,7 +1167,8 @@ impl Composer {
799 1167 impl Render for Composer {
800 1168 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
801 1169 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
802 let empty = self.is_empty(cx);
1170 let can_send = self.can_send(cx);
1171 let can_attach = self.editing.is_none();
803 1172 let send = div()
804 1173 .id("composer-send")
805 1174 .size(px(32.))
@@ -809,16 +1178,37 @@ impl Render for Composer {
809 1178 .justify_center()
810 1179 .rounded(px(8.))
811 1180 .child(symbol("keyboard_return", 20., white()))
812 .when(empty, |button| button.opacity(0.4))
813 .when(!empty, |button| {
1181 .when(!can_send, |button| button.opacity(0.4))
1182 .when(can_send, |button| {
814 1183 button
815 1184 .cursor_pointer()
816 1185 .hover(|button| button.bg(white().opacity(0.1)))
817 1186 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
818 1187 });
1188 let attach = can_attach.then(|| {
1189 div()
1190 .id("composer-attach")
1191 .size(px(32.))
1192 .flex_none()
1193 .flex()
1194 .items_center()
1195 .justify_center()
1196 .rounded(px(8.))
1197 .cursor_pointer()
1198 .hover(|button| button.bg(theme::row_hover()))
1199 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
1200 .child(symbol("attach_file", 20., theme::text_muted()))
1201 .on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))
1202 });
1203 let composer = cx.weak_entity();
819 1204 let input = Textarea::new(&self.input)
820 1205 .appearance(false)
821 1206 .bordered(false)
1207 .on_paste(move |item, _, cx| {
1208 composer
1209 .update(cx, |this, cx| this.paste(item, cx))
1210 .unwrap_or(false)
1211 })
822 1212 .token(|context, _, _| {
823 1213 div()
824 1214 .h(context.line_height())
@@ -833,6 +1223,24 @@ impl Render for Composer {
833 1223 .font_weight(FontWeight::SEMIBOLD)
834 1224 .child(context.token().label().clone())
835 1225 });
1226 let tray = can_attach
1227 .then(|| {
1228 render_tray(
1229 &self.tray,
1230 Self::remove_attachment,
1231 Self::retry_attachment,
1232 cx,
1233 )
1234 })
1235 .flatten();
1236 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
1237 div()
1238 .w_full()
1239 .mb(px(6.))
1240 .text_size(px(12.))
1241 .text_color(theme::amber())
1242 .child(notice.to_owned())
1243 });
836 1244 v_flex()
837 1245 .w_full()
838 1246 .flex_none()
@@ -884,6 +1292,7 @@ impl Render for Composer {
884 1292 cx.stop_propagation();
885 1293 }
886 1294 }))
1295 .children(notice)
887 1296 .children(self.render_reply_strip(cx))
888 1297 .children(self.render_edit_strip(cx))
889 1298 .child(
@@ -893,13 +1302,8 @@ impl Render for Composer {
893 1302 .children(self.render_popup(cx))
894 1303 .children(self.render_emoji_popup(window, cx))
895 1304 .child(
896 h_flex()
1305 v_flex()
897 1306 .w_full()
898 .items_end()
899 .gap(px(6.))
900 .py(px(6.))
901 .pl(px(12.))
902 .pr(px(6.))
903 1307 .rounded(px(10.))
904 1308 .bg(theme::surface())
905 1309 .border_1()
@@ -908,8 +1312,19 @@ impl Render for Composer {
908 1312 } else {
909 1313 theme::border_strong()
910 1314 })
911 .child(div().flex_1().min_w_0().child(input))
912 .child(send),
1315 .children(tray)
1316 .child(
1317 h_flex()
1318 .w_full()
1319 .items_end()
1320 .gap(px(6.))
1321 .py(px(6.))
1322 .pl(px(if can_attach { 6. } else { 12. }))
1323 .pr(px(6.))
1324 .children(attach)
1325 .child(div().flex_1().min_w_0().child(input))
1326 .child(send),
1327 ),
913 1328 ),
914 1329 )
915 1330 }
@@ -985,6 +1400,51 @@ mod tests {
985 1400 );
986 1401 }
987 1402
1403 #[test]
1404 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
1405 use std::sync::Arc;
1406
1407 use gpui_kit::{Image, ImageFormat};
1408 use teams_core::FileKind;
1409
1410 use super::{Outgoing, OutgoingFile, OutgoingImage};
1411
1412 let outgoing = Outgoing {
1413 text: String::new(),
1414 mentions: Vec::new(),
1415 reply: None,
1416 edit: None,
1417 images: vec![OutgoingImage {
1418 name: "pasted-image.png".into(),
1419 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
1420 dimensions: Some((1, 1)),
1421 }],
1422 files: vec![OutgoingFile {
1423 name: "plan.pdf".into(),
1424 size: 9,
1425 kind: FileKind::Pdf,
1426 uploaded: None,
1427 reference: teams_core::FileReference {
1428 attachment_id: "guid".into(),
1429 content_url: "https://files.example/plan.pdf".into(),
1430 name: "plan.pdf".into(),
1431 },
1432 }],
1433 };
1434 let extras = outgoing.extras();
1435 assert_eq!(extras.images[0].content_type, "image/png");
1436 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
1437 assert_eq!(extras.files[0].attachment_id, "guid");
1438 assert!(outgoing.has_attachments());
1439 }
1440
1441 #[test]
1442 fn enter_sends_attachments_even_without_text() {
1443 assert!(super::is_plain_enter(&press(false)));
1444 assert!(!super::is_plain_enter(&press(true)));
1445 assert!(!super::is_plain_enter(&InputEvent::Change));
1446 }
1447
988 1448 mod keys {
989 1449 use std::sync::Arc;
990 1450
@@ -1025,5 +1485,232 @@ mod tests {
1025 1485 .unwrap();
1026 1486 assert_eq!(value, "X");
1027 1487 }
1488
1489 #[gpui_kit::test]
1490 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
1491 cx.update(gpui_kit::init);
1492 let store = Arc::new(Store::open_in_memory().unwrap());
1493 let mode = Mode {
1494 demo: true,
1495 read_only: false,
1496 demo_sync: None,
1497 };
1498 let (handle, composer) = cx.update(|cx| {
1499 let app = cx.new(|_| AppState::new(store, mode));
1500 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1501 cx.new(|cx| Composer::new(app, window, cx))
1502 })
1503 .unwrap()
1504 });
1505 let directory = tempfile::tempdir().unwrap();
1506 let path = directory.path().join("plan.pdf");
1507 std::fs::write(&path, b"%PDF-1.7").unwrap();
1508 cx.update_window(handle, |_, window, cx| {
1509 composer.update(cx, |composer, cx| {
1510 composer.set_conversation("demo-chat", "Demo", window, cx);
1511 composer.add_paths(vec![path], cx);
1512 });
1513 })
1514 .unwrap();
1515 cx.run_until_parked();
1516 cx.update(|cx| {
1517 let composer = composer.read(cx);
1518 assert!(composer.tray.blocks_send());
1519 assert!(!composer.can_send(cx));
1520 });
1521 cx.executor()
1522 .advance_clock(std::time::Duration::from_secs(3));
1523 cx.run_until_parked();
1524 cx.update(|cx| {
1525 let composer = composer.read(cx);
1526 assert!(composer.can_send(cx));
1527 let outgoing = composer
1528 .outgoing(cx)
1529 .expect("an attachment alone is a message");
1530 assert_eq!(outgoing.text, "");
1531 assert_eq!(outgoing.files.len(), 1);
1532 assert_eq!(outgoing.files[0].name, "plan.pdf");
1533 });
1534 }
1535
1536 #[gpui_kit::test]
1537 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
1538 cx.update(gpui_kit::init);
1539 let store = Arc::new(Store::open_in_memory().unwrap());
1540 let mode = Mode {
1541 demo: true,
1542 read_only: false,
1543 demo_sync: None,
1544 };
1545 let (handle, composer) = cx.update(|cx| {
1546 let app = cx.new(|_| AppState::new(store, mode));
1547 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1548 cx.new(|cx| Composer::new(app, window, cx))
1549 })
1550 .unwrap()
1551 });
1552 let directory = tempfile::tempdir().unwrap();
1553 let path = directory.path().join("plan.pdf");
1554 std::fs::write(&path, b"%PDF-1.7").unwrap();
1555 cx.update_window(handle, |_, window, cx| {
1556 composer.update(cx, |composer, cx| {
1557 composer.set_conversation("demo-chat", "Demo", window, cx);
1558 composer.add_paths(vec![path], cx);
1559 });
1560 })
1561 .unwrap();
1562 cx.run_until_parked();
1563 cx.update_window(handle, |_, window, cx| {
1564 composer.update(cx, |composer, cx| {
1565 composer.set_conversation("other-chat", "Other", window, cx)
1566 });
1567 })
1568 .unwrap();
1569 cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));
1570 }
1571
1572 fn demo_composer(
1573 cx: &mut TestAppContext,
1574 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
1575 cx.update(gpui_kit::init);
1576 let store = Arc::new(Store::open_in_memory().unwrap());
1577 let mode = Mode {
1578 demo: true,
1579 read_only: false,
1580 demo_sync: None,
1581 };
1582 let (handle, composer) = cx.update(|cx| {
1583 let app = cx.new(|_| AppState::new(store, mode));
1584 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1585 cx.new(|cx| Composer::new(app, window, cx))
1586 })
1587 .unwrap()
1588 });
1589 (handle, composer)
1590 }
1591
1592 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
1593 let path = directory.join("dot.png");
1594 image::RgbaImage::new(2, 2).save(&path).unwrap();
1595 path
1596 }
1597
1598 #[gpui_kit::test]
1599 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
1600 use super::super::{EditPreview, Outgoing};
1601
1602 let (handle, composer) = demo_composer(cx);
1603 let directory = tempfile::tempdir().unwrap();
1604 let path = directory.path().join("plan.pdf");
1605 std::fs::write(&path, b"%PDF-1.7").unwrap();
1606 cx.update_window(handle, |_, window, cx| {
1607 composer.update(cx, |composer, cx| {
1608 composer.set_conversation("demo-chat", "Demo", window, cx);
1609 composer.add_paths(vec![path], cx);
1610 });
1611 })
1612 .unwrap();
1613 cx.run_until_parked();
1614 cx.executor()
1615 .advance_clock(std::time::Duration::from_secs(3));
1616 cx.run_until_parked();
1617 cx.update_window(handle, |_, window, cx| {
1618 composer.update(cx, |composer, cx| {
1619 let draft = Outgoing {
1620 text: "old".into(),
1621 mentions: Vec::new(),
1622 reply: None,
1623 edit: Some(EditPreview {
1624 message_id: "m1".into(),
1625 excerpt: "old".into(),
1626 }),
1627 images: Vec::new(),
1628 files: Vec::new(),
1629 };
1630 composer.begin_edit(draft, window, cx);
1631 });
1632 })
1633 .unwrap();
1634 cx.update(|cx| {
1635 let composer = composer.read(cx);
1636 assert_eq!(composer.tray.items().len(), 1);
1637 let outgoing = composer.outgoing(cx).unwrap();
1638 assert!(outgoing.files.is_empty());
1639 assert_eq!(outgoing.text, "old");
1640 });
1641 cx.update_window(handle, |_, window, cx| {
1642 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
1643 })
1644 .unwrap();
1645 cx.update(|cx| {
1646 let composer = composer.read(cx);
1647 assert_eq!(composer.tray.items().len(), 1);
1648 assert!(composer.can_send(cx));
1649 });
1650 }
1651
1652 #[gpui_kit::test]
1653 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
1654 let (handle, composer) = demo_composer(cx);
1655 let directory = tempfile::tempdir().unwrap();
1656 let path = small_png(directory.path());
1657 for (carry, chosen, expected) in [
1658 (Some("chat-a"), "chat-a", 1),
1659 (None, "chat-b", 0),
1660 (Some("chat-a"), "chat-b", 0),
1661 ] {
1662 cx.update_window(handle, |_, window, cx| {
1663 composer.update(cx, |composer, cx| {
1664 composer.set_conversation("", "", window, cx);
1665 composer.add_paths(vec![path.clone()], cx);
1666 });
1667 })
1668 .unwrap();
1669 cx.run_until_parked();
1670 cx.update_window(handle, |_, window, cx| {
1671 composer.update(cx, |composer, cx| {
1672 if let Some(chat) = carry {
1673 composer.carry_images_into(chat.to_owned());
1674 }
1675 composer.set_conversation(chosen, "Chat", window, cx);
1676 });
1677 })
1678 .unwrap();
1679 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
1680 }
1681 }
1682
1683 #[gpui_kit::test]
1684 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
1685 cx: &mut TestAppContext,
1686 ) {
1687 let (handle, composer) = demo_composer(cx);
1688 let directory = tempfile::tempdir().unwrap();
1689 let png = small_png(directory.path());
1690 let pdf = directory.path().join("plan.pdf");
1691 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
1692 cx.update_window(handle, |_, window, cx| {
1693 composer.update(cx, |composer, cx| {
1694 composer.set_conversation("bob-chat", "Bob", window, cx);
1695 composer.add_paths(vec![png, pdf], cx);
1696 });
1697 })
1698 .unwrap();
1699 cx.run_until_parked();
1700 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
1701 cx.update_window(handle, |_, window, cx| {
1702 composer.update(cx, |composer, cx| {
1703 composer.carry_images_into(String::new());
1704 composer.set_conversation("", "", window, cx);
1705 });
1706 })
1707 .unwrap();
1708 cx.update(|cx| {
1709 let composer = composer.read(cx);
1710 assert_eq!(composer.tray.items().len(), 1);
1711 assert_eq!(composer.tray.items()[0].name, "dot.png");
1712 assert!(!composer.files_allowed());
1713 });
1714 }
1028 1715 }
1029 1716 }
@@ -1,5 +1,7 @@
1use std::collections::HashMap;
1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::sync::Arc;
3use std::time::Duration;
5use std::time::Duration;
4
6
5use gpui_kit::assets::IconName;
7use gpui_kit::assets::IconName;
@@ -9,12 +11,20 @@ use gpui_kit::component::{
9 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
11 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
10 MoveUp, Textarea, TextareaState,
12 MoveUp, Textarea, TextareaState,
11 },
13 },
14 tooltip::Tooltip,
12 v_flex,
15 v_flex,
13};
16};
14use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::*;
18use gpui_kit::*;
16use teams_core::{MentionCandidate, MentionInput};
19use teams_core::{
20 FileReference, HostedImage, MentionCandidate, MentionInput, MessageExtras, UploadedFile,
21};
17
22
23use super::attachment_tray::{
24 AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,
25 UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,
26 prepare_pasted_image, read_attachment, render_tray,
27};
18use super::avatar::{person_avatar, square_avatar};
28use super::avatar::{person_avatar, square_avatar};
19use super::emoji_popup::{self, EmojiPopup};
29use super::emoji_popup::{self, EmojiPopup};
20use super::widgets::{icon, symbol};
30use super::widgets::{icon, symbol};
@@ -31,6 +41,9 @@ const MENTION_QUERY_MAX_CHARS: usize = 32;
31const MENTION_QUERY_MAX_WORDS: usize = 3;
41const MENTION_QUERY_MAX_WORDS: usize = 3;
32const POPUP_WIDTH: f32 = 380.;
42const POPUP_WIDTH: f32 = 380.;
33const POPUP_ROW_HEIGHT: f32 = 44.;
43const POPUP_ROW_HEIGHT: f32 = 44.;
44const DEMO_UPLOAD_STEPS: u8 = 10;
45const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
46const DEMO_FAILURE_STEP: u8 = 6;
34
47
35#[derive(Debug, Clone, PartialEq, Eq)]
48#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ReplyPreview {
49pub struct ReplyPreview {
@@ -51,10 +64,57 @@ pub struct Outgoing {
51 pub mentions: Vec<MentionInput>,
64 pub mentions: Vec<MentionInput>,
52 pub reply: Option<ReplyPreview>,
65 pub reply: Option<ReplyPreview>,
53 pub edit: Option<EditPreview>,
66 pub edit: Option<EditPreview>,
67 pub images: Vec<OutgoingImage>,
68 pub files: Vec<OutgoingFile>,
69}
70
71impl Outgoing {
72 pub fn has_attachments(&self) -> bool {
73 !self.images.is_empty() || !self.files.is_empty()
74 }
75
76 pub fn extras(&self) -> MessageExtras {
77 MessageExtras {
78 kept: Vec::new(),
79 images: self
80 .images
81 .iter()
82 .map(|outgoing| HostedImage {
83 content_type: outgoing.image.format.mime_type().to_owned(),
84 bytes: Arc::new(outgoing.image.bytes.clone()),
85 })
86 .collect(),
87 files: self
88 .files
89 .iter()
90 .map(|file| file.reference.clone())
91 .collect(),
92 }
93 }
94}
95
96enum UploadEvent {
97 Progress(u8),
98 Uploaded(UploadedFile),
99 Finished(UploadResult),
100}
101
102enum UploadHandle {
103 Network(tokio::task::AbortHandle),
104 Demo(Task<()>),
105}
106
107impl UploadHandle {
108 fn cancel(self) {
109 match self {
110 UploadHandle::Network(handle) => handle.abort(),
111 UploadHandle::Demo(task) => drop(task),
112 }
113 }
54}
114}
55
115
56pub enum ComposerEvent {
116pub enum ComposerEvent {
57 Submit(Outgoing),
117 Submit(Box<Outgoing>),
58 EditLast,
118 EditLast,
59}
119}
60
120
@@ -88,11 +148,19 @@ pub struct Composer {
88 conversion: Option<Conversion>,
148 conversion: Option<Conversion>,
89 undone_value: Option<String>,
149 undone_value: Option<String>,
90 previous_value: String,
150 previous_value: String,
151 tray: AttachmentTray,
152 uploads: HashMap<u64, UploadHandle>,
153 demo_failed: HashSet<u64>,
154 carry_images_into: Option<String>,
91 _subscription: Subscription,
155 _subscription: Subscription,
92}
156}
93
157
94impl EventEmitter<ComposerEvent> for Composer {}
158impl EventEmitter<ComposerEvent> for Composer {}
95
159
160pub fn is_plain_enter(event: &InputEvent) -> bool {
161 matches!(event, InputEvent::PressEnter { shift: false, .. })
162}
163
96/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
164/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
97pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
165pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
98 match event {
166 match event {
@@ -180,6 +248,10 @@ impl Composer {
180 conversion: None,
248 conversion: None,
181 undone_value: None,
249 undone_value: None,
182 previous_value: String::new(),
250 previous_value: String::new(),
251 tray: AttachmentTray::default(),
252 uploads: HashMap::new(),
253 demo_failed: HashSet::new(),
254 carry_images_into: None,
183 _subscription: subscription,
255 _subscription: subscription,
184 }
256 }
185 }
257 }
@@ -198,7 +270,9 @@ impl Composer {
198 self.update_mention(cx);
270 self.update_mention(cx);
199 }
271 }
200 let value = input.read(cx).value();
272 let value = input.read(cx).value();
201 if submitted_text(event, &value).is_some() {
273 if submitted_text(event, &value).is_some()
274 || (is_plain_enter(event) && !self.tray.is_empty())
275 {
202 self.submit_current(window, cx);
276 self.submit_current(window, cx);
203 }
277 }
204 }
278 }
@@ -458,7 +532,15 @@ impl Composer {
458 ) {
532 ) {
459 self.set_placeholder(&format!("Message {name}"), window, cx);
533 self.set_placeholder(&format!("Message {name}"), window, cx);
460 if self.conversation_id.as_deref() != Some(conversation_id) {
534 if self.conversation_id.as_deref() != Some(conversation_id) {
535 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
461 self.conversation_id = Some(conversation_id.to_owned());
536 self.conversation_id = Some(conversation_id.to_owned());
537 self.cancel_uploads();
538 let dropped = if carry {
539 self.tray.keep_images_only()
540 } else {
541 self.tray.clear()
542 };
543 self.discard_uploaded(dropped, cx);
462 self.reply = None;
544 self.reply = None;
463 if self.editing.take().is_some() {
545 if self.editing.take().is_some() {
464 self.input
546 self.input
@@ -470,6 +552,15 @@ impl Composer {
470 }
552 }
471 }
553 }
472
554
555 /// The draft's images follow the user into this chat; any other switch clears the tray.
556 pub fn carry_images_into(&mut self, conversation_id: String) {
557 self.carry_images_into = Some(conversation_id);
558 }
559
560 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
561 discard_uploaded(self.app.read(cx).engine.clone(), files);
562 }
563
473 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
564 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
474 self.reply = reply;
565 self.reply = reply;
475 if self.reply.is_some() {
566 if self.reply.is_some() {
@@ -491,9 +582,10 @@ impl Composer {
491 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
582 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
492 let state = self.input.read(cx);
583 let state = self.input.read(cx);
493 let mut text = state.value().trim().to_owned();
584 let mut text = state.value().trim().to_owned();
494 if text.is_empty() {
585 if !self.can_send(cx) {
495 return None;
586 return None;
496 }
587 }
588 let attachments_apply = self.editing.is_none();
497 if self.undone_value.as_deref() != Some(state.value().as_ref())
589 if self.undone_value.as_deref() != Some(state.value().as_ref())
498 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
590 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
499 {
591 {
@@ -510,7 +602,276 @@ impl Composer {
510 mentions,
602 mentions,
511 reply: self.reply.clone(),
603 reply: self.reply.clone(),
512 edit: self.editing.clone(),
604 edit: self.editing.clone(),
605 images: if attachments_apply {
606 self.tray.outgoing_images()
607 } else {
608 Vec::new()
609 },
610 files: if attachments_apply {
611 self.tray.outgoing_files()
612 } else {
613 Vec::new()
614 },
615 })
616 }
617
618 fn can_send(&self, cx: &App) -> bool {
619 let has_text = !self.input.read(cx).value().trim().is_empty();
620 if self.editing.is_some() {
621 return has_text;
622 }
623 (has_text || !self.tray.is_empty()) && !self.tray.blocks_send()
624 }
625
626 pub fn is_editing(&self) -> bool {
627 self.editing.is_some()
628 }
629
630 fn files_allowed(&self) -> bool {
631 self.conversation_id
632 .as_deref()
633 .is_some_and(|conversation_id| !conversation_id.is_empty())
634 }
635
636 fn cancel_uploads(&mut self) {
637 for (_, handle) in self.uploads.drain() {
638 handle.cancel();
639 }
640 }
641
642 pub fn open_picker(&mut self, cx: &mut Context<Self>) {
643 if self.editing.is_some() {
644 return;
645 }
646 let receiver = cx.prompt_for_paths(PathPromptOptions {
647 files: true,
648 directories: false,
649 multiple: true,
650 prompt: None,
651 });
652 cx.spawn(async move |this, cx| {
653 if let Ok(Ok(Some(paths))) = receiver.await {
654 this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();
655 }
656 })
657 .detach();
658 }
659
660 pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
661 if self.editing.is_some() || paths.is_empty() {
662 return;
663 }
664 let ids = self.tray.add_pending(&names_of(&paths));
665 for (id, path) in ids.into_iter().zip(paths) {
666 cx.spawn(async move |this, cx| {
667 let loaded = cx
668 .background_executor()
669 .spawn(async move { read_attachment(&path) })
670 .await;
671 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
672 .ok();
673 })
674 .detach();
675 }
676 cx.notify();
677 }
678
679 fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {
680 let ids = self.tray.add_pending(&[pasted_image_name()]);
681 cx.notify();
682 let Some(&id) = ids.first() else {
683 return;
684 };
685 cx.spawn(async move |this, cx| {
686 let loaded = cx
687 .background_executor()
688 .spawn(async move { prepare_pasted_image(pasted) })
689 .await;
690 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
691 .ok();
513 })
692 })
693 .detach();
694 }
695
696 fn paste(&mut self, item: &ClipboardItem, cx: &mut Context<Self>) -> bool {
697 if self.editing.is_some() {
698 return false;
699 }
700 match paste_action(item) {
701 PasteAction::Text => false,
702 PasteAction::Files(paths) => {
703 self.add_paths(paths, cx);
704 true
705 }
706 PasteAction::Image(pasted) => {
707 self.add_pasted_image(pasted, cx);
708 true
709 }
710 }
711 }
712
713 fn finish_reading(
714 &mut self,
715 id: u64,
716 loaded: Result<LoadedFile, String>,
717 cx: &mut Context<Self>,
718 ) {
719 match loaded {
720 Ok(loaded) => {
721 let files_allowed = self.files_allowed();
722 if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {
723 self.start_upload(job, cx);
724 }
725 }
726 Err(message) => self.tray.fail_reading(id, message),
727 }
728 cx.notify();
729 }
730
731 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
732 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
733 self.tray.finish_upload(job.id, UploadResult::Failed);
734 return;
735 };
736 let state = self.app.read(cx);
737 let (demo, engine) = (state.mode.demo, state.engine.clone());
738 if demo {
739 self.simulate_upload(job, cx);
740 return;
741 }
742 let Some(engine) = engine else {
743 self.tray.finish_upload(job.id, UploadResult::Failed);
744 return;
745 };
746 let id = job.id;
747 let (event_sender, mut event_receiver) =
748 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
749 let finished_sender = event_sender.clone();
750 let (_, handle) = runtime::spawn_abortable(async move {
751 let result = async {
752 let uploaded = match job.kind {
753 JobKind::Upload => {
754 let progress_sender = event_sender.clone();
755 let uploaded = engine
756 .upload_attachment_file(
757 &conversation_id,
758 &job.name,
759 &job.bytes,
760 move |percent| {
761 let _ = progress_sender.send(UploadEvent::Progress(percent));
762 },
763 )
764 .await;
765 match uploaded {
766 Ok(uploaded) => {
767 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
768 uploaded
769 }
770 Err(_) => return UploadResult::Failed,
771 }
772 }
773 JobKind::Share(uploaded) => uploaded,
774 };
775 let Some(reference) = uploaded.reference() else {
776 return UploadResult::Failed;
777 };
778 match engine.share_attachment(&conversation_id, &uploaded).await {
779 Ok(()) => UploadResult::Done(DoneFile {
780 reference,
781 uploaded: Some(uploaded),
782 }),
783 Err(_) => UploadResult::ShareFailed(uploaded),
784 }
785 }
786 .await;
787 let _ = finished_sender.send(UploadEvent::Finished(result));
788 });
789 self.uploads.insert(id, UploadHandle::Network(handle));
790 cx.spawn(async move |this, cx| {
791 while let Some(event) = event_receiver.recv().await {
792 let updated = this.update(cx, |this, cx| {
793 let orphan = match event {
794 UploadEvent::Progress(percent) => {
795 this.tray.set_progress(id, percent);
796 None
797 }
798 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
799 UploadEvent::Finished(result) => this.finish_upload(id, result),
800 };
801 this.discard_uploaded(orphan.into_iter().collect(), cx);
802 cx.notify();
803 });
804 if updated.is_err() {
805 break;
806 }
807 }
808 })
809 .detach();
810 }
811
812 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
813 let id = job.id;
814 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
815 let task = cx.spawn(async move |this, cx| {
816 for step in 1..=DEMO_UPLOAD_STEPS {
817 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
818 if fails && step == DEMO_FAILURE_STEP {
819 this.update(cx, |this, cx| {
820 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
821 })
822 .ok();
823 return;
824 }
825 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
826 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
827 .ok();
828 }
829 let reference = FileReference {
830 attachment_id: format!("demo-attachment-{id}"),
831 content_url: format!("https://demo.invalid/files/{}", job.name),
832 name: job.name,
833 };
834 let done = DoneFile {
835 reference,
836 uploaded: None,
837 };
838 this.update(cx, |this, cx| {
839 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
840 })
841 .ok();
842 });
843 self.uploads.insert(id, UploadHandle::Demo(task));
844 }
845
846 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
847 self.tray.set_progress(id, percent);
848 cx.notify();
849 }
850
851 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
852 self.uploads.remove(&id);
853 self.tray.finish_upload(id, result)
854 }
855
856 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
857 self.finish_upload(id, result);
858 cx.notify();
859 }
860
861 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
862 if let Some(handle) = self.uploads.remove(&id) {
863 handle.cancel();
864 }
865 let uploaded = self.tray.remove(id);
866 self.discard_uploaded(uploaded.into_iter().collect(), cx);
867 cx.notify();
868 }
869
870 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
871 if let Some(job) = self.tray.retry(id) {
872 self.start_upload(job, cx);
873 }
874 cx.notify();
514 }
875 }
515
876
516 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
877 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -520,10 +881,13 @@ impl Composer {
520 self.input
881 self.input
521 .update(cx, |state, cx| state.set_value("", window, cx));
882 .update(cx, |state, cx| state.set_value("", window, cx));
522 self.mention_inputs.clear();
883 self.mention_inputs.clear();
884 if self.editing.is_none() {
885 self.tray.clear();
886 }
523 self.reply = None;
887 self.reply = None;
524 self.editing = None;
888 self.editing = None;
525 self.close_popup();
889 self.close_popup();
526 cx.emit(ComposerEvent::Submit(outgoing));
890 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
527 cx.notify();
891 cx.notify();
528 }
892 }
529
893
@@ -553,6 +917,10 @@ impl Composer {
553 });
917 });
554 self.reply = outgoing.reply.clone();
918 self.reply = outgoing.reply.clone();
555 self.editing = outgoing.edit.clone();
919 self.editing = outgoing.edit.clone();
920 if outgoing.edit.is_none() {
921 self.cancel_uploads();
922 self.tray.restore(&outgoing.images, &outgoing.files);
923 }
556 self.close_popup();
924 self.close_popup();
557 cx.notify();
925 cx.notify();
558 }
926 }
@@ -571,7 +939,7 @@ impl Composer {
571 }
939 }
572
940
573 pub fn is_empty(&self, cx: &App) -> bool {
941 pub fn is_empty(&self, cx: &App) -> bool {
574 self.input.read(cx).value().trim().is_empty()
942 self.input.read(cx).value().trim().is_empty() && self.tray.is_empty()
575 }
943 }
576
944
577 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
945 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -799,7 +1167,8 @@ impl Composer {
799impl Render for Composer {
1167impl Render for Composer {
800 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1168 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
801 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
1169 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
802 let empty = self.is_empty(cx);
1170 let can_send = self.can_send(cx);
1171 let can_attach = self.editing.is_none();
803 let send = div()
1172 let send = div()
804 .id("composer-send")
1173 .id("composer-send")
805 .size(px(32.))
1174 .size(px(32.))
@@ -809,16 +1178,37 @@ impl Render for Composer {
809 .justify_center()
1178 .justify_center()
810 .rounded(px(8.))
1179 .rounded(px(8.))
811 .child(symbol("keyboard_return", 20., white()))
1180 .child(symbol("keyboard_return", 20., white()))
812 .when(empty, |button| button.opacity(0.4))
1181 .when(!can_send, |button| button.opacity(0.4))
813 .when(!empty, |button| {
1182 .when(can_send, |button| {
814 button
1183 button
815 .cursor_pointer()
1184 .cursor_pointer()
816 .hover(|button| button.bg(white().opacity(0.1)))
1185 .hover(|button| button.bg(white().opacity(0.1)))
817 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
1186 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
818 });
1187 });
1188 let attach = can_attach.then(|| {
1189 div()
1190 .id("composer-attach")
1191 .size(px(32.))
1192 .flex_none()
1193 .flex()
1194 .items_center()
1195 .justify_center()
1196 .rounded(px(8.))
1197 .cursor_pointer()
1198 .hover(|button| button.bg(theme::row_hover()))
1199 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
1200 .child(symbol("attach_file", 20., theme::text_muted()))
1201 .on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))
1202 });
1203 let composer = cx.weak_entity();
819 let input = Textarea::new(&self.input)
1204 let input = Textarea::new(&self.input)
820 .appearance(false)
1205 .appearance(false)
821 .bordered(false)
1206 .bordered(false)
1207 .on_paste(move |item, _, cx| {
1208 composer
1209 .update(cx, |this, cx| this.paste(item, cx))
1210 .unwrap_or(false)
1211 })
822 .token(|context, _, _| {
1212 .token(|context, _, _| {
823 div()
1213 div()
824 .h(context.line_height())
1214 .h(context.line_height())
@@ -833,6 +1223,24 @@ impl Render for Composer {
833 .font_weight(FontWeight::SEMIBOLD)
1223 .font_weight(FontWeight::SEMIBOLD)
834 .child(context.token().label().clone())
1224 .child(context.token().label().clone())
835 });
1225 });
1226 let tray = can_attach
1227 .then(|| {
1228 render_tray(
1229 &self.tray,
1230 Self::remove_attachment,
1231 Self::retry_attachment,
1232 cx,
1233 )
1234 })
1235 .flatten();
1236 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
1237 div()
1238 .w_full()
1239 .mb(px(6.))
1240 .text_size(px(12.))
1241 .text_color(theme::amber())
1242 .child(notice.to_owned())
1243 });
836 v_flex()
1244 v_flex()
837 .w_full()
1245 .w_full()
838 .flex_none()
1246 .flex_none()
@@ -884,6 +1292,7 @@ impl Render for Composer {
884 cx.stop_propagation();
1292 cx.stop_propagation();
885 }
1293 }
886 }))
1294 }))
1295 .children(notice)
887 .children(self.render_reply_strip(cx))
1296 .children(self.render_reply_strip(cx))
888 .children(self.render_edit_strip(cx))
1297 .children(self.render_edit_strip(cx))
889 .child(
1298 .child(
@@ -893,13 +1302,8 @@ impl Render for Composer {
893 .children(self.render_popup(cx))
1302 .children(self.render_popup(cx))
894 .children(self.render_emoji_popup(window, cx))
1303 .children(self.render_emoji_popup(window, cx))
895 .child(
1304 .child(
896 h_flex()
1305 v_flex()
897 .w_full()
1306 .w_full()
898 .items_end()
899 .gap(px(6.))
900 .py(px(6.))
901 .pl(px(12.))
902 .pr(px(6.))
903 .rounded(px(10.))
1307 .rounded(px(10.))
904 .bg(theme::surface())
1308 .bg(theme::surface())
905 .border_1()
1309 .border_1()
@@ -908,8 +1312,19 @@ impl Render for Composer {
908 } else {
1312 } else {
909 theme::border_strong()
1313 theme::border_strong()
910 })
1314 })
911 .child(div().flex_1().min_w_0().child(input))
1315 .children(tray)
912 .child(send),
1316 .child(
1317 h_flex()
1318 .w_full()
1319 .items_end()
1320 .gap(px(6.))
1321 .py(px(6.))
1322 .pl(px(if can_attach { 6. } else { 12. }))
1323 .pr(px(6.))
1324 .children(attach)
1325 .child(div().flex_1().min_w_0().child(input))
1326 .child(send),
1327 ),
913 ),
1328 ),
914 )
1329 )
915 }
1330 }
@@ -985,6 +1400,51 @@ mod tests {
985 );
1400 );
986 }
1401 }
987
1402
1403 #[test]
1404 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
1405 use std::sync::Arc;
1406
1407 use gpui_kit::{Image, ImageFormat};
1408 use teams_core::FileKind;
1409
1410 use super::{Outgoing, OutgoingFile, OutgoingImage};
1411
1412 let outgoing = Outgoing {
1413 text: String::new(),
1414 mentions: Vec::new(),
1415 reply: None,
1416 edit: None,
1417 images: vec![OutgoingImage {
1418 name: "pasted-image.png".into(),
1419 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
1420 dimensions: Some((1, 1)),
1421 }],
1422 files: vec![OutgoingFile {
1423 name: "plan.pdf".into(),
1424 size: 9,
1425 kind: FileKind::Pdf,
1426 uploaded: None,
1427 reference: teams_core::FileReference {
1428 attachment_id: "guid".into(),
1429 content_url: "https://files.example/plan.pdf".into(),
1430 name: "plan.pdf".into(),
1431 },
1432 }],
1433 };
1434 let extras = outgoing.extras();
1435 assert_eq!(extras.images[0].content_type, "image/png");
1436 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
1437 assert_eq!(extras.files[0].attachment_id, "guid");
1438 assert!(outgoing.has_attachments());
1439 }
1440
1441 #[test]
1442 fn enter_sends_attachments_even_without_text() {
1443 assert!(super::is_plain_enter(&press(false)));
1444 assert!(!super::is_plain_enter(&press(true)));
1445 assert!(!super::is_plain_enter(&InputEvent::Change));
1446 }
1447
988 mod keys {
1448 mod keys {
989 use std::sync::Arc;
1449 use std::sync::Arc;
990
1450
@@ -1025,5 +1485,232 @@ mod tests {
1025 .unwrap();
1485 .unwrap();
1026 assert_eq!(value, "X");
1486 assert_eq!(value, "X");
1027 }
1487 }
1488
1489 #[gpui_kit::test]
1490 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
1491 cx.update(gpui_kit::init);
1492 let store = Arc::new(Store::open_in_memory().unwrap());
1493 let mode = Mode {
1494 demo: true,
1495 read_only: false,
1496 demo_sync: None,
1497 };
1498 let (handle, composer) = cx.update(|cx| {
1499 let app = cx.new(|_| AppState::new(store, mode));
1500 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1501 cx.new(|cx| Composer::new(app, window, cx))
1502 })
1503 .unwrap()
1504 });
1505 let directory = tempfile::tempdir().unwrap();
1506 let path = directory.path().join("plan.pdf");
1507 std::fs::write(&path, b"%PDF-1.7").unwrap();
1508 cx.update_window(handle, |_, window, cx| {
1509 composer.update(cx, |composer, cx| {
1510 composer.set_conversation("demo-chat", "Demo", window, cx);
1511 composer.add_paths(vec![path], cx);
1512 });
1513 })
1514 .unwrap();
1515 cx.run_until_parked();
1516 cx.update(|cx| {
1517 let composer = composer.read(cx);
1518 assert!(composer.tray.blocks_send());
1519 assert!(!composer.can_send(cx));
1520 });
1521 cx.executor()
1522 .advance_clock(std::time::Duration::from_secs(3));
1523 cx.run_until_parked();
1524 cx.update(|cx| {
1525 let composer = composer.read(cx);
1526 assert!(composer.can_send(cx));
1527 let outgoing = composer
1528 .outgoing(cx)
1529 .expect("an attachment alone is a message");
1530 assert_eq!(outgoing.text, "");
1531 assert_eq!(outgoing.files.len(), 1);
1532 assert_eq!(outgoing.files[0].name, "plan.pdf");
1533 });
1534 }
1535
1536 #[gpui_kit::test]
1537 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
1538 cx.update(gpui_kit::init);
1539 let store = Arc::new(Store::open_in_memory().unwrap());
1540 let mode = Mode {
1541 demo: true,
1542 read_only: false,
1543 demo_sync: None,
1544 };
1545 let (handle, composer) = cx.update(|cx| {
1546 let app = cx.new(|_| AppState::new(store, mode));
1547 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1548 cx.new(|cx| Composer::new(app, window, cx))
1549 })
1550 .unwrap()
1551 });
1552 let directory = tempfile::tempdir().unwrap();
1553 let path = directory.path().join("plan.pdf");
1554 std::fs::write(&path, b"%PDF-1.7").unwrap();
1555 cx.update_window(handle, |_, window, cx| {
1556 composer.update(cx, |composer, cx| {
1557 composer.set_conversation("demo-chat", "Demo", window, cx);
1558 composer.add_paths(vec![path], cx);
1559 });
1560 })
1561 .unwrap();
1562 cx.run_until_parked();
1563 cx.update_window(handle, |_, window, cx| {
1564 composer.update(cx, |composer, cx| {
1565 composer.set_conversation("other-chat", "Other", window, cx)
1566 });
1567 })
1568 .unwrap();
1569 cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));
1570 }
1571
1572 fn demo_composer(
1573 cx: &mut TestAppContext,
1574 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
1575 cx.update(gpui_kit::init);
1576 let store = Arc::new(Store::open_in_memory().unwrap());
1577 let mode = Mode {
1578 demo: true,
1579 read_only: false,
1580 demo_sync: None,
1581 };
1582 let (handle, composer) = cx.update(|cx| {
1583 let app = cx.new(|_| AppState::new(store, mode));
1584 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1585 cx.new(|cx| Composer::new(app, window, cx))
1586 })
1587 .unwrap()
1588 });
1589 (handle, composer)
1590 }
1591
1592 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
1593 let path = directory.join("dot.png");
1594 image::RgbaImage::new(2, 2).save(&path).unwrap();
1595 path
1596 }
1597
1598 #[gpui_kit::test]
1599 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
1600 use super::super::{EditPreview, Outgoing};
1601
1602 let (handle, composer) = demo_composer(cx);
1603 let directory = tempfile::tempdir().unwrap();
1604 let path = directory.path().join("plan.pdf");
1605 std::fs::write(&path, b"%PDF-1.7").unwrap();
1606 cx.update_window(handle, |_, window, cx| {
1607 composer.update(cx, |composer, cx| {
1608 composer.set_conversation("demo-chat", "Demo", window, cx);
1609 composer.add_paths(vec![path], cx);
1610 });
1611 })
1612 .unwrap();
1613 cx.run_until_parked();
1614 cx.executor()
1615 .advance_clock(std::time::Duration::from_secs(3));
1616 cx.run_until_parked();
1617 cx.update_window(handle, |_, window, cx| {
1618 composer.update(cx, |composer, cx| {
1619 let draft = Outgoing {
1620 text: "old".into(),
1621 mentions: Vec::new(),
1622 reply: None,
1623 edit: Some(EditPreview {
1624 message_id: "m1".into(),
1625 excerpt: "old".into(),
1626 }),
1627 images: Vec::new(),
1628 files: Vec::new(),
1629 };
1630 composer.begin_edit(draft, window, cx);
1631 });
1632 })
1633 .unwrap();
1634 cx.update(|cx| {
1635 let composer = composer.read(cx);
1636 assert_eq!(composer.tray.items().len(), 1);
1637 let outgoing = composer.outgoing(cx).unwrap();
1638 assert!(outgoing.files.is_empty());
1639 assert_eq!(outgoing.text, "old");
1640 });
1641 cx.update_window(handle, |_, window, cx| {
1642 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
1643 })
1644 .unwrap();
1645 cx.update(|cx| {
1646 let composer = composer.read(cx);
1647 assert_eq!(composer.tray.items().len(), 1);
1648 assert!(composer.can_send(cx));
1649 });
1650 }
1651
1652 #[gpui_kit::test]
1653 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
1654 let (handle, composer) = demo_composer(cx);
1655 let directory = tempfile::tempdir().unwrap();
1656 let path = small_png(directory.path());
1657 for (carry, chosen, expected) in [
1658 (Some("chat-a"), "chat-a", 1),
1659 (None, "chat-b", 0),
1660 (Some("chat-a"), "chat-b", 0),
1661 ] {
1662 cx.update_window(handle, |_, window, cx| {
1663 composer.update(cx, |composer, cx| {
1664 composer.set_conversation("", "", window, cx);
1665 composer.add_paths(vec![path.clone()], cx);
1666 });
1667 })
1668 .unwrap();
1669 cx.run_until_parked();
1670 cx.update_window(handle, |_, window, cx| {
1671 composer.update(cx, |composer, cx| {
1672 if let Some(chat) = carry {
1673 composer.carry_images_into(chat.to_owned());
1674 }
1675 composer.set_conversation(chosen, "Chat", window, cx);
1676 });
1677 })
1678 .unwrap();
1679 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
1680 }
1681 }
1682
1683 #[gpui_kit::test]
1684 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
1685 cx: &mut TestAppContext,
1686 ) {
1687 let (handle, composer) = demo_composer(cx);
1688 let directory = tempfile::tempdir().unwrap();
1689 let png = small_png(directory.path());
1690 let pdf = directory.path().join("plan.pdf");
1691 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
1692 cx.update_window(handle, |_, window, cx| {
1693 composer.update(cx, |composer, cx| {
1694 composer.set_conversation("bob-chat", "Bob", window, cx);
1695 composer.add_paths(vec![png, pdf], cx);
1696 });
1697 })
1698 .unwrap();
1699 cx.run_until_parked();
1700 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
1701 cx.update_window(handle, |_, window, cx| {
1702 composer.update(cx, |composer, cx| {
1703 composer.carry_images_into(String::new());
1704 composer.set_conversation("", "", window, cx);
1705 });
1706 })
1707 .unwrap();
1708 cx.update(|cx| {
1709 let composer = composer.read(cx);
1710 assert_eq!(composer.tray.items().len(), 1);
1711 assert_eq!(composer.tray.items()[0].name, "dot.png");
1712 assert!(!composer.files_allowed());
1713 });
1714 }
1028 }
1715 }
1029}
1716}
crates/app/src/views/conversation.rs +268 −48
@@ -15,7 +15,7 @@ use gpui_kit::component::{
15 15 use gpui_kit::prelude::FluentBuilder as _;
16 16 use gpui_kit::*;
17 17 use store::MessageRecord;
18 use teams_core::{ImageRef, MentionInput};
18 use teams_core::{FileCard, ImageRef, MentionInput};
19 19
20 20 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
21 21 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
@@ -23,14 +23,14 @@ use super::message_actions::{Action, MessageMenu};
23 23 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
24 24 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
25 25 use super::reaction_picker::{PickHandler, ReactionPicker};
26 use super::widgets::icon;
26 use super::widgets::{icon, symbol};
27 27 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
28 28 use crate::data::{is_one_on_one, others};
29 29 use crate::read_state::{ReadTrigger, plan_read};
30 30 use crate::render::Block;
31 31 use crate::render::blocks::Inline;
32 32 use crate::rows::{
33 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
33 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
34 34 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
35 35 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
36 36 };
@@ -120,6 +120,7 @@ pub struct ConversationView {
120 120 picker: Entity<ReactionPicker>,
121 121 highlighted_message: Option<String>,
122 122 notice: Option<String>,
123 drag_file_count: usize,
123 124 sync_generation: u64,
124 125 window_active: bool,
125 126 _subscriptions: Vec<Subscription>,
@@ -132,6 +133,37 @@ fn open_limit(selection: &Selection) -> usize {
132 133 }
133 134 }
134 135
136 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
137 enum DropTarget {
138 Chat,
139 Channel,
140 NewChat,
141 }
142
143 fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
144 let files = if count == 1 {
145 "1 file".to_owned()
146 } else {
147 format!("{count} files")
148 };
149 match target {
150 DropTarget::Chat => (
151 format!("Drop to attach to {title}"),
152 format!("{files}. Images go into the message, other files to your OneDrive."),
153 ),
154 DropTarget::Channel => (
155 format!("Drop to attach to {title}"),
156 format!("{files}. Images go into the message, other files to the channel's Files."),
157 ),
158 DropTarget::NewChat => (
159 "Drop to attach to the new chat".to_owned(),
160 format!(
161 "{files}. Images go into the message. Files can be added once the chat exists."
162 ),
163 ),
164 }
165 }
166
135 167 fn short_error(error: &dyn std::fmt::Display) -> String {
136 168 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
137 169 }
@@ -167,6 +199,7 @@ impl ConversationView {
167 199 picker,
168 200 highlighted_message: None,
169 201 notice: None,
202 drag_file_count: 0,
170 203 sync_generation: 0,
171 204 window_active: window.is_window_active(),
172 205 _subscriptions: subscriptions,
@@ -212,6 +245,14 @@ impl ConversationView {
212 245 return;
213 246 }
214 247 if self.draft_active {
248 let created = self
249 .draft_created
250 .as_ref()
251 .map(|(_, chat_id)| chat_id.clone());
252 if let Some(chat_id) = created {
253 self.composer
254 .update(cx, |composer, _| composer.carry_images_into(chat_id));
255 }
215 256 self.leave_draft(window, cx);
216 257 }
217 258 match selection {
@@ -271,12 +312,12 @@ impl ConversationView {
271 312 ) {
272 313 match event {
273 314 ComposerEvent::Submit(outgoing) if self.draft_active => {
274 self.send_new_chat(outgoing.clone(), window, cx)
315 self.send_new_chat((**outgoing).clone(), window, cx)
275 316 }
276 317 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
277 self.send_edit(outgoing.clone(), window, cx)
318 self.send_edit((**outgoing).clone(), window, cx)
278 319 }
279 ComposerEvent::Submit(outgoing) => self.send(outgoing.clone(), window, cx),
320 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
280 321 ComposerEvent::EditLast => self.edit_last_own(window, cx),
281 322 }
282 323 }
@@ -304,7 +345,7 @@ impl ConversationView {
304 345 sync: SyncProgress::default(),
305 346 });
306 347 self.sync_generation += 1;
307 self.pending.clear();
348 self.clear_pending();
308 349 self.notice = None;
309 350 self.rebuild(true, cx);
310 351 self.start_fetch(cx);
@@ -334,8 +375,7 @@ impl ConversationView {
334 375 if !self.draft_active {
335 376 self.draft_active = true;
336 377 self.current = None;
337 self.pending.clear();
338 self.pending_outgoing.clear();
378 self.clear_pending();
339 379 self.notice = None;
340 380 self.draft_created = None;
341 381 self.draft_error = None;
@@ -359,8 +399,7 @@ impl ConversationView {
359 399 self.draft_active = false;
360 400 self.draft_created = None;
361 401 self.draft_error = None;
362 self.pending.clear();
363 self.pending_outgoing.clear();
402 self.clear_pending();
364 403 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
365 404 }
366 405
@@ -401,8 +440,17 @@ impl ConversationView {
401 440 let target = self.draft_target_chat(cx);
402 441 if target != self.conversation_id() {
403 442 match target {
404 Some(chat_id) => self.open(Selection::Chat(chat_id), window, cx),
443 Some(chat_id) => {
444 self.composer.update(cx, |composer, _| {
445 composer.carry_images_into(chat_id.clone())
446 });
447 self.open(Selection::Chat(chat_id), window, cx)
448 }
405 449 None => {
450 self.composer.update(cx, |composer, cx| {
451 composer.carry_images_into(String::new());
452 composer.set_conversation("", "", window, cx);
453 });
406 454 self.current = None;
407 455 self.sync_generation += 1;
408 456 self.rebuild(true, cx);
@@ -504,7 +552,7 @@ impl ConversationView {
504 552 } else {
505 553 row_key
506 554 };
507 self.pending.clear();
555 self.clear_pending();
508 556 self.rebuild(true, cx);
509 557 let index = self
510 558 .rows
@@ -1131,11 +1179,16 @@ impl ConversationView {
1131 1179 self.rebuild(false, cx);
1132 1180 }
1133 1181
1182 fn clear_pending(&mut self) {
1183 self.pending.clear();
1184 self.pending_outgoing.clear();
1185 }
1186
1134 1187 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1135 1188 if let Some(current) = self.current.as_mut() {
1136 1189 current.mode = ViewMode::Thread(root_id);
1137 1190 }
1138 self.pending.clear();
1191 self.clear_pending();
1139 1192 self.rebuild(true, cx);
1140 1193 }
1141 1194
@@ -1143,7 +1196,7 @@ impl ConversationView {
1143 1196 if let Some(current) = self.current.as_mut() {
1144 1197 current.mode = ViewMode::ThreadList;
1145 1198 }
1146 self.pending.clear();
1199 self.clear_pending();
1147 1200 self.rebuild(true, cx);
1148 1201 }
1149 1202
@@ -1171,6 +1224,7 @@ impl ConversationView {
1171 1224
1172 1225 let sent = outgoing.clone();
1173 1226 let receiver = runtime::spawn(async move {
1227 let extras = sent.extras();
1174 1228 let Outgoing {
1175 1229 text,
1176 1230 mentions,
@@ -1180,22 +1234,40 @@ impl ConversationView {
1180 1234 match (&view_mode, reply) {
1181 1235 (_, Some(reply)) => {
1182 1236 engine
1183 .reply_to_with_mentions(&conversation_id, &reply.message_id, text, mentions)
1237 .reply_to_with_extras(
1238 &conversation_id,
1239 &reply.message_id,
1240 text,
1241 mentions,
1242 &extras,
1243 )
1184 1244 .await
1185 1245 }
1186 1246 (ViewMode::Flat, None) => {
1187 1247 engine
1188 .send_message_with_mentions(&conversation_id, text, None, mentions)
1248 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1189 1249 .await
1190 1250 }
1191 1251 (ViewMode::ThreadList, None) => {
1192 1252 engine
1193 .post_to_channel_with_mentions(&conversation_id, text, None, mentions)
1253 .post_to_channel_with_extras(
1254 &conversation_id,
1255 text,
1256 None,
1257 mentions,
1258 &extras,
1259 )
1194 1260 .await
1195 1261 }
1196 1262 (ViewMode::Thread(root_id), None) => {
1197 1263 engine
1198 .send_message_with_mentions(&conversation_id, text, Some(root_id), mentions)
1264 .send_message_with_extras(
1265 &conversation_id,
1266 text,
1267 Some(root_id),
1268 mentions,
1269 &extras,
1270 )
1199 1271 .await
1200 1272 }
1201 1273 }
@@ -1203,10 +1275,8 @@ impl ConversationView {
1203 1275 });
1204 1276 cx.spawn_in(window, async move |this, cx| {
1205 1277 let result = receiver.await;
1206 this.update_in(cx, |this, window, cx| {
1207 this.finish_send(&key, result, window, cx)
1208 })
1209 .ok();
1278 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1279 .ok();
1210 1280 })
1211 1281 .detach();
1212 1282 }
@@ -1238,12 +1308,34 @@ impl ConversationView {
1238 1308 card: false,
1239 1309 time: chrono::Local::now().format("%H:%M").to_string(),
1240 1310 day_header: None,
1241 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1311 blocks: if outgoing.text.is_empty() {
1312 Vec::new()
1313 } else {
1314 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1315 },
1242 1316 edited: false,
1243 1317 deleted: false,
1244 1318 reactions: Vec::new(),
1245 1319 images: Vec::new(),
1246 files: Vec::new(),
1320 local_images: outgoing
1321 .images
1322 .iter()
1323 .map(|image| LocalImage {
1324 image: image.image.clone(),
1325 size: image.dimensions,
1326 })
1327 .collect(),
1328 files: outgoing
1329 .files
1330 .iter()
1331 .map(|file| FileCard {
1332 name: file.name.clone(),
1333 kind: file.kind,
1334 content_type: None,
1335 size: Some(file.size),
1336 open_url: file.reference.content_url.clone(),
1337 })
1338 .collect(),
1247 1339 reply_count: None,
1248 1340 new_marker: false,
1249 1341 reply_faces: Vec::new(),
@@ -1283,6 +1375,10 @@ impl ConversationView {
1283 1375 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1284 1376 return;
1285 1377 }
1378 if mode.demo && outgoing.has_attachments() {
1379 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1380 return;
1381 }
1286 1382 if mode.demo {
1287 1383 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1288 1384 return;
@@ -1320,7 +1416,13 @@ impl ConversationView {
1320 1416 }
1321 1417 };
1322 1418 let sent = engine
1323 .send_message_with_mentions(&chat_id, &outgoing.text, None, &outgoing.mentions)
1419 .send_message_with_extras(
1420 &chat_id,
1421 &outgoing.text,
1422 None,
1423 &outgoing.mentions,
1424 &outgoing.extras(),
1425 )
1324 1426 .await;
1325 1427 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1326 1428 });
@@ -1536,6 +1638,8 @@ impl ConversationView {
1536 1638 mentions,
1537 1639 reply: None,
1538 1640 edit: Some(edit),
1641 images: Vec::new(),
1642 files: Vec::new(),
1539 1643 };
1540 1644 self.composer
1541 1645 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
@@ -1600,9 +1704,14 @@ impl ConversationView {
1600 1704 let failed = !matches!(receiver.await, Ok(Ok(())));
1601 1705 this.update_in(cx, |this, window, cx| {
1602 1706 if failed {
1603 this.notice = Some("Edit failed: your text is back in the composer".to_owned());
1604 this.composer
1605 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1707 if this.composer.read(cx).is_empty(cx) {
1708 this.notice =
1709 Some("Edit failed: your text is back in the composer".to_owned());
1710 this.composer
1711 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1712 } else {
1713 this.notice = Some("Edit failed".to_owned());
1714 }
1606 1715 cx.notify();
1607 1716 }
1608 1717 })
@@ -1738,7 +1847,6 @@ impl ConversationView {
1738 1847 &mut self,
1739 1848 key: &str,
1740 1849 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
1741 window: &mut Window,
1742 1850 cx: &mut Context<Self>,
1743 1851 ) {
1744 1852 let failure = match result {
@@ -1754,19 +1862,92 @@ impl ConversationView {
1754 1862 Some(error) => {
1755 1863 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1756 1864 row.delivery = Delivery::Failed(error.clone());
1757 }
1758 self.notice = Some(format!("Not sent: {error}"));
1759 if self.composer.read(cx).is_empty(cx)
1760 && let Some(outgoing) = self.pending_outgoing.get(key).cloned()
1761 {
1762 self.composer
1763 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1865 self.notice = Some(format!("Not sent: {error}"));
1764 1866 }
1765 1867 }
1766 1868 }
1767 1869 self.rebuild(false, cx);
1768 1870 }
1769 1871
1872 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
1873 let target = match self.current.as_ref().map(|current| &current.selection) {
1874 Some(Selection::Chat(_)) => DropTarget::Chat,
1875 Some(Selection::Channel(_)) => DropTarget::Channel,
1876 None => DropTarget::NewChat,
1877 };
1878 let title = self
1879 .current
1880 .as_ref()
1881 .map(|current| current.title.as_str())
1882 .unwrap_or_default();
1883 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
1884 let composer = self.composer.clone();
1885 div()
1886 .id("drop-overlay")
1887 .absolute()
1888 .top_0()
1889 .left_0()
1890 .size_full()
1891 .opacity(0.)
1892 .bg(theme::drop_background())
1893 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
1894 if composer.read(cx).is_editing() {
1895 style
1896 } else {
1897 style.opacity(1.)
1898 }
1899 })
1900 .on_drag_move(
1901 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
1902 let count = event.drag(cx).paths().len();
1903 if this.drag_file_count != count {
1904 this.drag_file_count = count;
1905 cx.notify();
1906 }
1907 }),
1908 )
1909 .on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {
1910 let paths = dropped.paths().to_vec();
1911 this.composer
1912 .update(cx, |composer, cx| composer.add_paths(paths, cx));
1913 }))
1914 .child(
1915 div()
1916 .absolute()
1917 .inset(px(12.))
1918 .rounded(px(12.))
1919 .border_2()
1920 .border_dashed()
1921 .border_color(theme::accent())
1922 .flex()
1923 .items_center()
1924 .justify_center()
1925 .child(
1926 v_flex()
1927 .items_center()
1928 .gap(px(6.))
1929 .px(px(28.))
1930 .py(px(18.))
1931 .rounded(px(12.))
1932 .bg(black().opacity(0.55))
1933 .child(symbol("upload", 28., theme::accent_text()))
1934 .child(
1935 div()
1936 .text_size(px(15.))
1937 .font_weight(FontWeight::SEMIBOLD)
1938 .text_color(theme::text_strong())
1939 .child(heading),
1940 )
1941 .child(
1942 div()
1943 .text_size(px(12.))
1944 .text_color(theme::text_muted())
1945 .child(detail),
1946 ),
1947 ),
1948 )
1949 }
1950
1770 1951 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1771 1952 let message = self.draft_error.clone()?;
1772 1953 let failed_key = self
@@ -2149,17 +2330,24 @@ impl Render for ConversationView {
2149 2330 } else {
2150 2331 scroller.into_any_element()
2151 2332 };
2152 root.child(div().flex_1().min_h_0().child(body))
2153 .children(self.render_draft_error(cx))
2154 .child(self.composer.clone())
2155 .when(drafting, |root| {
2156 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2157 if this.draft.read(cx).has_focus(window, cx) {
2158 this.draft.update(cx, |draft, cx| draft.escape(cx));
2159 }
2160 }))
2161 })
2162 .into_any_element()
2333 root.child(
2334 v_flex()
2335 .relative()
2336 .flex_1()
2337 .min_h_0()
2338 .child(div().flex_1().min_h_0().child(body))
2339 .children(self.render_draft_error(cx))
2340 .child(self.composer.clone())
2341 .child(self.render_drop_overlay(cx)),
2342 )
2343 .when(drafting, |root| {
2344 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2345 if this.draft.read(cx).has_focus(window, cx) {
2346 this.draft.update(cx, |draft, cx| draft.escape(cx));
2347 }
2348 }))
2349 })
2350 .into_any_element()
2163 2351 }
2164 2352 }
2165 2353
@@ -2197,6 +2385,8 @@ fn progress_bar() -> impl IntoElement {
2197 2385 mod tests {
2198 2386 use std::sync::Arc;
2199 2387
2388 use super::{DropTarget, drop_overlay_text};
2389
2200 2390 use gpui_kit::test::TestWindowExt as _;
2201 2391 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2202 2392 use store::Store;
@@ -2204,6 +2394,36 @@ mod tests {
2204 2394 use super::ConversationView;
2205 2395 use crate::app_state::{AppState, Mode, Selection};
2206 2396
2397 #[test]
2398 fn chat_overlay_names_the_chat_and_the_onedrive() {
2399 assert_eq!(
2400 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
2401 (
2402 "Drop to attach to Mara Lin".to_owned(),
2403 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
2404 )
2405 );
2406 }
2407
2408 #[test]
2409 fn channel_overlay_points_to_the_channel_files() {
2410 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
2411 assert_eq!(
2412 detail,
2413 "1 file. Images go into the message, other files to the channel's Files."
2414 );
2415 }
2416
2417 #[test]
2418 fn new_chat_overlay_says_files_wait_for_the_chat() {
2419 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
2420 assert_eq!(heading, "Drop to attach to the new chat");
2421 assert_eq!(
2422 detail,
2423 "2 files. Images go into the message. Files can be added once the chat exists."
2424 );
2425 }
2426
2207 2427 #[gpui_kit::test]
2208 2428 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2209 2429 cx.update(gpui_kit::init);
@@ -15,7 +15,7 @@ use gpui_kit::component::{
15use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::*;
16use gpui_kit::*;
17use store::MessageRecord;
17use store::MessageRecord;
18use teams_core::{ImageRef, MentionInput};
18use teams_core::{FileCard, ImageRef, MentionInput};
19
19
20use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
20use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
21use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
@@ -23,14 +23,14 @@ use super::message_actions::{Action, MessageMenu};
23use super::message_row::{RowActions, render_message_row, render_skeleton_row};
23use super::message_row::{RowActions, render_message_row, render_skeleton_row};
24use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
24use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
25use super::reaction_picker::{PickHandler, ReactionPicker};
25use super::reaction_picker::{PickHandler, ReactionPicker};
26use super::widgets::icon;
26use super::widgets::{icon, symbol};
27use crate::app_state::{AppEvent, AppState, Selection, selection_title};
27use crate::app_state::{AppEvent, AppState, Selection, selection_title};
28use crate::data::{is_one_on_one, others};
28use crate::data::{is_one_on_one, others};
29use crate::read_state::{ReadTrigger, plan_read};
29use crate::read_state::{ReadTrigger, plan_read};
30use crate::render::Block;
30use crate::render::Block;
31use crate::render::blocks::Inline;
31use crate::render::blocks::Inline;
32use crate::rows::{
32use crate::rows::{
33 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
33 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
34 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
34 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
35 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
35 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
36};
36};
@@ -120,6 +120,7 @@ pub struct ConversationView {
120 picker: Entity<ReactionPicker>,
120 picker: Entity<ReactionPicker>,
121 highlighted_message: Option<String>,
121 highlighted_message: Option<String>,
122 notice: Option<String>,
122 notice: Option<String>,
123 drag_file_count: usize,
123 sync_generation: u64,
124 sync_generation: u64,
124 window_active: bool,
125 window_active: bool,
125 _subscriptions: Vec<Subscription>,
126 _subscriptions: Vec<Subscription>,
@@ -132,6 +133,37 @@ fn open_limit(selection: &Selection) -> usize {
132 }
133 }
133}
134}
134
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137enum DropTarget {
138 Chat,
139 Channel,
140 NewChat,
141}
142
143fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
144 let files = if count == 1 {
145 "1 file".to_owned()
146 } else {
147 format!("{count} files")
148 };
149 match target {
150 DropTarget::Chat => (
151 format!("Drop to attach to {title}"),
152 format!("{files}. Images go into the message, other files to your OneDrive."),
153 ),
154 DropTarget::Channel => (
155 format!("Drop to attach to {title}"),
156 format!("{files}. Images go into the message, other files to the channel's Files."),
157 ),
158 DropTarget::NewChat => (
159 "Drop to attach to the new chat".to_owned(),
160 format!(
161 "{files}. Images go into the message. Files can be added once the chat exists."
162 ),
163 ),
164 }
165}
166
135fn short_error(error: &dyn std::fmt::Display) -> String {
167fn short_error(error: &dyn std::fmt::Display) -> String {
136 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
168 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
137}
169}
@@ -167,6 +199,7 @@ impl ConversationView {
167 picker,
199 picker,
168 highlighted_message: None,
200 highlighted_message: None,
169 notice: None,
201 notice: None,
202 drag_file_count: 0,
170 sync_generation: 0,
203 sync_generation: 0,
171 window_active: window.is_window_active(),
204 window_active: window.is_window_active(),
172 _subscriptions: subscriptions,
205 _subscriptions: subscriptions,
@@ -212,6 +245,14 @@ impl ConversationView {
212 return;
245 return;
213 }
246 }
214 if self.draft_active {
247 if self.draft_active {
248 let created = self
249 .draft_created
250 .as_ref()
251 .map(|(_, chat_id)| chat_id.clone());
252 if let Some(chat_id) = created {
253 self.composer
254 .update(cx, |composer, _| composer.carry_images_into(chat_id));
255 }
215 self.leave_draft(window, cx);
256 self.leave_draft(window, cx);
216 }
257 }
217 match selection {
258 match selection {
@@ -271,12 +312,12 @@ impl ConversationView {
271 ) {
312 ) {
272 match event {
313 match event {
273 ComposerEvent::Submit(outgoing) if self.draft_active => {
314 ComposerEvent::Submit(outgoing) if self.draft_active => {
274 self.send_new_chat(outgoing.clone(), window, cx)
315 self.send_new_chat((**outgoing).clone(), window, cx)
275 }
316 }
276 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
317 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
277 self.send_edit(outgoing.clone(), window, cx)
318 self.send_edit((**outgoing).clone(), window, cx)
278 }
319 }
279 ComposerEvent::Submit(outgoing) => self.send(outgoing.clone(), window, cx),
320 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
280 ComposerEvent::EditLast => self.edit_last_own(window, cx),
321 ComposerEvent::EditLast => self.edit_last_own(window, cx),
281 }
322 }
282 }
323 }
@@ -304,7 +345,7 @@ impl ConversationView {
304 sync: SyncProgress::default(),
345 sync: SyncProgress::default(),
305 });
346 });
306 self.sync_generation += 1;
347 self.sync_generation += 1;
307 self.pending.clear();
348 self.clear_pending();
308 self.notice = None;
349 self.notice = None;
309 self.rebuild(true, cx);
350 self.rebuild(true, cx);
310 self.start_fetch(cx);
351 self.start_fetch(cx);
@@ -334,8 +375,7 @@ impl ConversationView {
334 if !self.draft_active {
375 if !self.draft_active {
335 self.draft_active = true;
376 self.draft_active = true;
336 self.current = None;
377 self.current = None;
337 self.pending.clear();
378 self.clear_pending();
338 self.pending_outgoing.clear();
339 self.notice = None;
379 self.notice = None;
340 self.draft_created = None;
380 self.draft_created = None;
341 self.draft_error = None;
381 self.draft_error = None;
@@ -359,8 +399,7 @@ impl ConversationView {
359 self.draft_active = false;
399 self.draft_active = false;
360 self.draft_created = None;
400 self.draft_created = None;
361 self.draft_error = None;
401 self.draft_error = None;
362 self.pending.clear();
402 self.clear_pending();
363 self.pending_outgoing.clear();
364 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
403 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
365 }
404 }
366
405
@@ -401,8 +440,17 @@ impl ConversationView {
401 let target = self.draft_target_chat(cx);
440 let target = self.draft_target_chat(cx);
402 if target != self.conversation_id() {
441 if target != self.conversation_id() {
403 match target {
442 match target {
404 Some(chat_id) => self.open(Selection::Chat(chat_id), window, cx),
443 Some(chat_id) => {
444 self.composer.update(cx, |composer, _| {
445 composer.carry_images_into(chat_id.clone())
446 });
447 self.open(Selection::Chat(chat_id), window, cx)
448 }
405 None => {
449 None => {
450 self.composer.update(cx, |composer, cx| {
451 composer.carry_images_into(String::new());
452 composer.set_conversation("", "", window, cx);
453 });
406 self.current = None;
454 self.current = None;
407 self.sync_generation += 1;
455 self.sync_generation += 1;
408 self.rebuild(true, cx);
456 self.rebuild(true, cx);
@@ -504,7 +552,7 @@ impl ConversationView {
504 } else {
552 } else {
505 row_key
553 row_key
506 };
554 };
507 self.pending.clear();
555 self.clear_pending();
508 self.rebuild(true, cx);
556 self.rebuild(true, cx);
509 let index = self
557 let index = self
510 .rows
558 .rows
@@ -1131,11 +1179,16 @@ impl ConversationView {
1131 self.rebuild(false, cx);
1179 self.rebuild(false, cx);
1132 }
1180 }
1133
1181
1182 fn clear_pending(&mut self) {
1183 self.pending.clear();
1184 self.pending_outgoing.clear();
1185 }
1186
1134 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1187 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1135 if let Some(current) = self.current.as_mut() {
1188 if let Some(current) = self.current.as_mut() {
1136 current.mode = ViewMode::Thread(root_id);
1189 current.mode = ViewMode::Thread(root_id);
1137 }
1190 }
1138 self.pending.clear();
1191 self.clear_pending();
1139 self.rebuild(true, cx);
1192 self.rebuild(true, cx);
1140 }
1193 }
1141
1194
@@ -1143,7 +1196,7 @@ impl ConversationView {
1143 if let Some(current) = self.current.as_mut() {
1196 if let Some(current) = self.current.as_mut() {
1144 current.mode = ViewMode::ThreadList;
1197 current.mode = ViewMode::ThreadList;
1145 }
1198 }
1146 self.pending.clear();
1199 self.clear_pending();
1147 self.rebuild(true, cx);
1200 self.rebuild(true, cx);
1148 }
1201 }
1149
1202
@@ -1171,6 +1224,7 @@ impl ConversationView {
1171
1224
1172 let sent = outgoing.clone();
1225 let sent = outgoing.clone();
1173 let receiver = runtime::spawn(async move {
1226 let receiver = runtime::spawn(async move {
1227 let extras = sent.extras();
1174 let Outgoing {
1228 let Outgoing {
1175 text,
1229 text,
1176 mentions,
1230 mentions,
@@ -1180,22 +1234,40 @@ impl ConversationView {
1180 match (&view_mode, reply) {
1234 match (&view_mode, reply) {
1181 (_, Some(reply)) => {
1235 (_, Some(reply)) => {
1182 engine
1236 engine
1183 .reply_to_with_mentions(&conversation_id, &reply.message_id, text, mentions)
1237 .reply_to_with_extras(
1238 &conversation_id,
1239 &reply.message_id,
1240 text,
1241 mentions,
1242 &extras,
1243 )
1184 .await
1244 .await
1185 }
1245 }
1186 (ViewMode::Flat, None) => {
1246 (ViewMode::Flat, None) => {
1187 engine
1247 engine
1188 .send_message_with_mentions(&conversation_id, text, None, mentions)
1248 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1189 .await
1249 .await
1190 }
1250 }
1191 (ViewMode::ThreadList, None) => {
1251 (ViewMode::ThreadList, None) => {
1192 engine
1252 engine
1193 .post_to_channel_with_mentions(&conversation_id, text, None, mentions)
1253 .post_to_channel_with_extras(
1254 &conversation_id,
1255 text,
1256 None,
1257 mentions,
1258 &extras,
1259 )
1194 .await
1260 .await
1195 }
1261 }
1196 (ViewMode::Thread(root_id), None) => {
1262 (ViewMode::Thread(root_id), None) => {
1197 engine
1263 engine
1198 .send_message_with_mentions(&conversation_id, text, Some(root_id), mentions)
1264 .send_message_with_extras(
1265 &conversation_id,
1266 text,
1267 Some(root_id),
1268 mentions,
1269 &extras,
1270 )
1199 .await
1271 .await
1200 }
1272 }
1201 }
1273 }
@@ -1203,10 +1275,8 @@ impl ConversationView {
1203 });
1275 });
1204 cx.spawn_in(window, async move |this, cx| {
1276 cx.spawn_in(window, async move |this, cx| {
1205 let result = receiver.await;
1277 let result = receiver.await;
1206 this.update_in(cx, |this, window, cx| {
1278 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1207 this.finish_send(&key, result, window, cx)
1279 .ok();
1208 })
1209 .ok();
1210 })
1280 })
1211 .detach();
1281 .detach();
1212 }
1282 }
@@ -1238,12 +1308,34 @@ impl ConversationView {
1238 card: false,
1308 card: false,
1239 time: chrono::Local::now().format("%H:%M").to_string(),
1309 time: chrono::Local::now().format("%H:%M").to_string(),
1240 day_header: None,
1310 day_header: None,
1241 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1311 blocks: if outgoing.text.is_empty() {
1312 Vec::new()
1313 } else {
1314 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1315 },
1242 edited: false,
1316 edited: false,
1243 deleted: false,
1317 deleted: false,
1244 reactions: Vec::new(),
1318 reactions: Vec::new(),
1245 images: Vec::new(),
1319 images: Vec::new(),
1246 files: Vec::new(),
1320 local_images: outgoing
1321 .images
1322 .iter()
1323 .map(|image| LocalImage {
1324 image: image.image.clone(),
1325 size: image.dimensions,
1326 })
1327 .collect(),
1328 files: outgoing
1329 .files
1330 .iter()
1331 .map(|file| FileCard {
1332 name: file.name.clone(),
1333 kind: file.kind,
1334 content_type: None,
1335 size: Some(file.size),
1336 open_url: file.reference.content_url.clone(),
1337 })
1338 .collect(),
1247 reply_count: None,
1339 reply_count: None,
1248 new_marker: false,
1340 new_marker: false,
1249 reply_faces: Vec::new(),
1341 reply_faces: Vec::new(),
@@ -1283,6 +1375,10 @@ impl ConversationView {
1283 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1375 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1284 return;
1376 return;
1285 }
1377 }
1378 if mode.demo && outgoing.has_attachments() {
1379 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1380 return;
1381 }
1286 if mode.demo {
1382 if mode.demo {
1287 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1383 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1288 return;
1384 return;
@@ -1320,7 +1416,13 @@ impl ConversationView {
1320 }
1416 }
1321 };
1417 };
1322 let sent = engine
1418 let sent = engine
1323 .send_message_with_mentions(&chat_id, &outgoing.text, None, &outgoing.mentions)
1419 .send_message_with_extras(
1420 &chat_id,
1421 &outgoing.text,
1422 None,
1423 &outgoing.mentions,
1424 &outgoing.extras(),
1425 )
1324 .await;
1426 .await;
1325 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1427 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1326 });
1428 });
@@ -1536,6 +1638,8 @@ impl ConversationView {
1536 mentions,
1638 mentions,
1537 reply: None,
1639 reply: None,
1538 edit: Some(edit),
1640 edit: Some(edit),
1641 images: Vec::new(),
1642 files: Vec::new(),
1539 };
1643 };
1540 self.composer
1644 self.composer
1541 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
1645 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
@@ -1600,9 +1704,14 @@ impl ConversationView {
1600 let failed = !matches!(receiver.await, Ok(Ok(())));
1704 let failed = !matches!(receiver.await, Ok(Ok(())));
1601 this.update_in(cx, |this, window, cx| {
1705 this.update_in(cx, |this, window, cx| {
1602 if failed {
1706 if failed {
1603 this.notice = Some("Edit failed: your text is back in the composer".to_owned());
1707 if this.composer.read(cx).is_empty(cx) {
1604 this.composer
1708 this.notice =
1605 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1709 Some("Edit failed: your text is back in the composer".to_owned());
1710 this.composer
1711 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1712 } else {
1713 this.notice = Some("Edit failed".to_owned());
1714 }
1606 cx.notify();
1715 cx.notify();
1607 }
1716 }
1608 })
1717 })
@@ -1738,7 +1847,6 @@ impl ConversationView {
1738 &mut self,
1847 &mut self,
1739 key: &str,
1848 key: &str,
1740 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
1849 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
1741 window: &mut Window,
1742 cx: &mut Context<Self>,
1850 cx: &mut Context<Self>,
1743 ) {
1851 ) {
1744 let failure = match result {
1852 let failure = match result {
@@ -1754,19 +1862,92 @@ impl ConversationView {
1754 Some(error) => {
1862 Some(error) => {
1755 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1863 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1756 row.delivery = Delivery::Failed(error.clone());
1864 row.delivery = Delivery::Failed(error.clone());
1757 }
1865 self.notice = Some(format!("Not sent: {error}"));
1758 self.notice = Some(format!("Not sent: {error}"));
1759 if self.composer.read(cx).is_empty(cx)
1760 && let Some(outgoing) = self.pending_outgoing.get(key).cloned()
1761 {
1762 self.composer
1763 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1764 }
1866 }
1765 }
1867 }
1766 }
1868 }
1767 self.rebuild(false, cx);
1869 self.rebuild(false, cx);
1768 }
1870 }
1769
1871
1872 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
1873 let target = match self.current.as_ref().map(|current| &current.selection) {
1874 Some(Selection::Chat(_)) => DropTarget::Chat,
1875 Some(Selection::Channel(_)) => DropTarget::Channel,
1876 None => DropTarget::NewChat,
1877 };
1878 let title = self
1879 .current
1880 .as_ref()
1881 .map(|current| current.title.as_str())
1882 .unwrap_or_default();
1883 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
1884 let composer = self.composer.clone();
1885 div()
1886 .id("drop-overlay")
1887 .absolute()
1888 .top_0()
1889 .left_0()
1890 .size_full()
1891 .opacity(0.)
1892 .bg(theme::drop_background())
1893 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
1894 if composer.read(cx).is_editing() {
1895 style
1896 } else {
1897 style.opacity(1.)
1898 }
1899 })
1900 .on_drag_move(
1901 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
1902 let count = event.drag(cx).paths().len();
1903 if this.drag_file_count != count {
1904 this.drag_file_count = count;
1905 cx.notify();
1906 }
1907 }),
1908 )
1909 .on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {
1910 let paths = dropped.paths().to_vec();
1911 this.composer
1912 .update(cx, |composer, cx| composer.add_paths(paths, cx));
1913 }))
1914 .child(
1915 div()
1916 .absolute()
1917 .inset(px(12.))
1918 .rounded(px(12.))
1919 .border_2()
1920 .border_dashed()
1921 .border_color(theme::accent())
1922 .flex()
1923 .items_center()
1924 .justify_center()
1925 .child(
1926 v_flex()
1927 .items_center()
1928 .gap(px(6.))
1929 .px(px(28.))
1930 .py(px(18.))
1931 .rounded(px(12.))
1932 .bg(black().opacity(0.55))
1933 .child(symbol("upload", 28., theme::accent_text()))
1934 .child(
1935 div()
1936 .text_size(px(15.))
1937 .font_weight(FontWeight::SEMIBOLD)
1938 .text_color(theme::text_strong())
1939 .child(heading),
1940 )
1941 .child(
1942 div()
1943 .text_size(px(12.))
1944 .text_color(theme::text_muted())
1945 .child(detail),
1946 ),
1947 ),
1948 )
1949 }
1950
1770 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1951 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1771 let message = self.draft_error.clone()?;
1952 let message = self.draft_error.clone()?;
1772 let failed_key = self
1953 let failed_key = self
@@ -2149,17 +2330,24 @@ impl Render for ConversationView {
2149 } else {
2330 } else {
2150 scroller.into_any_element()
2331 scroller.into_any_element()
2151 };
2332 };
2152 root.child(div().flex_1().min_h_0().child(body))
2333 root.child(
2153 .children(self.render_draft_error(cx))
2334 v_flex()
2154 .child(self.composer.clone())
2335 .relative()
2155 .when(drafting, |root| {
2336 .flex_1()
2156 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2337 .min_h_0()
2157 if this.draft.read(cx).has_focus(window, cx) {
2338 .child(div().flex_1().min_h_0().child(body))
2158 this.draft.update(cx, |draft, cx| draft.escape(cx));
2339 .children(self.render_draft_error(cx))
2159 }
2340 .child(self.composer.clone())
2160 }))
2341 .child(self.render_drop_overlay(cx)),
2161 })
2342 )
2162 .into_any_element()
2343 .when(drafting, |root| {
2344 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2345 if this.draft.read(cx).has_focus(window, cx) {
2346 this.draft.update(cx, |draft, cx| draft.escape(cx));
2347 }
2348 }))
2349 })
2350 .into_any_element()
2163 }
2351 }
2164}
2352}
2165
2353
@@ -2197,6 +2385,8 @@ fn progress_bar() -> impl IntoElement {
2197mod tests {
2385mod tests {
2198 use std::sync::Arc;
2386 use std::sync::Arc;
2199
2387
2388 use super::{DropTarget, drop_overlay_text};
2389
2200 use gpui_kit::test::TestWindowExt as _;
2390 use gpui_kit::test::TestWindowExt as _;
2201 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2391 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2202 use store::Store;
2392 use store::Store;
@@ -2204,6 +2394,36 @@ mod tests {
2204 use super::ConversationView;
2394 use super::ConversationView;
2205 use crate::app_state::{AppState, Mode, Selection};
2395 use crate::app_state::{AppState, Mode, Selection};
2206
2396
2397 #[test]
2398 fn chat_overlay_names_the_chat_and_the_onedrive() {
2399 assert_eq!(
2400 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
2401 (
2402 "Drop to attach to Mara Lin".to_owned(),
2403 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
2404 )
2405 );
2406 }
2407
2408 #[test]
2409 fn channel_overlay_points_to_the_channel_files() {
2410 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
2411 assert_eq!(
2412 detail,
2413 "1 file. Images go into the message, other files to the channel's Files."
2414 );
2415 }
2416
2417 #[test]
2418 fn new_chat_overlay_says_files_wait_for_the_chat() {
2419 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
2420 assert_eq!(heading, "Drop to attach to the new chat");
2421 assert_eq!(
2422 detail,
2423 "2 files. Images go into the message. Files can be added once the chat exists."
2424 );
2425 }
2426
2207 #[gpui_kit::test]
2427 #[gpui_kit::test]
2208 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2428 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2209 cx.update(gpui_kit::init);
2429 cx.update(gpui_kit::init);
crates/app/src/views/message_row.rs +4 −1
@@ -165,6 +165,7 @@ fn bubble(
165 165 }
166 166 content = content.children(attachments_view(
167 167 &row.images,
168 &row.local_images,
168 169 &row.files,
169 170 &format!("message-{index}"),
170 171 directory,
@@ -323,7 +324,8 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
323 324 }
324 325
325 326 fn has_text(row: &MessageRow) -> bool {
326 !row.blocks.is_empty() || (row.images.is_empty() && row.files.is_empty())
327 !row.blocks.is_empty()
328 || (row.images.is_empty() && row.local_images.is_empty() && row.files.is_empty())
327 329 }
328 330
329 331 fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
@@ -469,6 +471,7 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
469 471 }
470 472 body = body.children(attachments_view(
471 473 &row.images,
474 &row.local_images,
472 475 &row.files,
473 476 &format!("message-{index}"),
474 477 directory,
@@ -165,6 +165,7 @@ fn bubble(
165 }
165 }
166 content = content.children(attachments_view(
166 content = content.children(attachments_view(
167 &row.images,
167 &row.images,
168 &row.local_images,
168 &row.files,
169 &row.files,
169 &format!("message-{index}"),
170 &format!("message-{index}"),
170 directory,
171 directory,
@@ -323,7 +324,8 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
323}
324}
324
325
325fn has_text(row: &MessageRow) -> bool {
326fn has_text(row: &MessageRow) -> bool {
326 !row.blocks.is_empty() || (row.images.is_empty() && row.files.is_empty())
327 !row.blocks.is_empty()
328 || (row.images.is_empty() && row.local_images.is_empty() && row.files.is_empty())
327}
329}
328
330
329fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
331fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
@@ -469,6 +471,7 @@ fn post_card(row: &MessageRow, index: usize, directory: &Directory, cx: &App) ->
469 }
471 }
470 body = body.children(attachments_view(
472 body = body.children(attachments_view(
471 &row.images,
473 &row.images,
474 &row.local_images,
472 &row.files,
475 &row.files,
473 &format!("message-{index}"),
476 &format!("message-{index}"),
474 directory,
477 directory,
crates/app/src/views/mod.rs +1 −0
@@ -1,3 +1,4 @@
1 pub mod attachment_tray;
1 2 pub mod attachments;
2 3 pub mod avatar;
3 4 pub mod composer;
@@ -1,3 +1,4 @@
1pub mod attachment_tray;
1pub mod attachments;
2pub mod attachments;
2pub mod avatar;
3pub mod avatar;
3pub mod composer;
4pub mod composer;
crates/core/src/actions.rs +188 −8
@@ -1,5 +1,7 @@
1 1 use chrono::Utc;
2 use graph::{MessageTarget, OutgoingMention};
2 use graph::{
3 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4 };
3 5 use store::MessageRecord;
4 6
5 7 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
@@ -26,18 +28,43 @@ impl<R: Remote> SyncEngine<R> {
26 28 markdown: &str,
27 29 thread_root_id: Option<&str>,
28 30 mentions: &[MentionInput],
31 ) -> Result<MessageRecord> {
32 self.send_message_with_extras(
33 conversation_id,
34 markdown,
35 thread_root_id,
36 mentions,
37 &MessageExtras::default(),
38 )
39 .await
40 }
41
42 pub async fn send_message_with_extras(
43 &self,
44 conversation_id: &str,
45 markdown: &str,
46 thread_root_id: Option<&str>,
47 mentions: &[MentionInput],
48 extras: &MessageExtras,
29 49 ) -> Result<MessageRecord> {
30 50 let conversation = self.resolve(conversation_id)?;
31 51 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
32 52 let sent = match (conversation, thread_root_id) {
33 53 (Conversation::Chat, None) => {
34 54 self.remote
35 .send_chat_message(conversation_id, &html, &mentions)
55 .send_chat_message(conversation_id, &html, &mentions, extras)
36 56 .await?
37 57 }
38 58 (Conversation::Channel { team_id }, Some(root_id)) => {
39 59 self.remote
40 .reply_to_channel_message(&team_id, conversation_id, root_id, &html, &mentions)
60 .reply_to_channel_message(
61 &team_id,
62 conversation_id,
63 root_id,
64 &html,
65 &mentions,
66 extras,
67 )
41 68 .await?
42 69 }
43 70 (Conversation::Chat, Some(_)) => {
@@ -69,13 +96,31 @@ impl<R: Remote> SyncEngine<R> {
69 96 message_id: &str,
70 97 markdown: &str,
71 98 mentions: &[MentionInput],
99 ) -> Result<MessageRecord> {
100 self.reply_to_with_extras(
101 conversation_id,
102 message_id,
103 markdown,
104 mentions,
105 &MessageExtras::default(),
106 )
107 .await
108 }
109
110 pub async fn reply_to_with_extras(
111 &self,
112 conversation_id: &str,
113 message_id: &str,
114 markdown: &str,
115 mentions: &[MentionInput],
116 extras: &MessageExtras,
72 117 ) -> Result<MessageRecord> {
73 118 let conversation = self.resolve(conversation_id)?;
74 119 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
75 120 let sent = match conversation {
76 121 Conversation::Chat => {
77 122 self.remote
78 .reply_with_quote(conversation_id, message_id, &html, &mentions)
123 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
79 124 .await?
80 125 }
81 126 Conversation::Channel { team_id } => {
@@ -86,7 +131,14 @@ impl<R: Remote> SyncEngine<R> {
86 131 .and_then(|record| record.reply_to_id)
87 132 .unwrap_or_else(|| message_id.to_owned());
88 133 self.remote
89 .reply_to_channel_message(&team_id, conversation_id, &root_id, &html, &mentions)
134 .reply_to_channel_message(
135 &team_id,
136 conversation_id,
137 &root_id,
138 &html,
139 &mentions,
140 extras,
141 )
90 142 .await?
91 143 }
92 144 };
@@ -128,6 +180,24 @@ impl<R: Remote> SyncEngine<R> {
128 180 markdown: &str,
129 181 subject: Option<&str>,
130 182 mentions: &[MentionInput],
183 ) -> Result<MessageRecord> {
184 self.post_to_channel_with_extras(
185 channel_id,
186 markdown,
187 subject,
188 mentions,
189 &MessageExtras::default(),
190 )
191 .await
192 }
193
194 pub async fn post_to_channel_with_extras(
195 &self,
196 channel_id: &str,
197 markdown: &str,
198 subject: Option<&str>,
199 mentions: &[MentionInput],
200 extras: &MessageExtras,
131 201 ) -> Result<MessageRecord> {
132 202 let conversation = self.resolve(channel_id)?;
133 203 let Conversation::Channel { team_id } = &conversation else {
@@ -136,11 +206,104 @@ impl<R: Remote> SyncEngine<R> {
136 206 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
137 207 let sent = self
138 208 .remote
139 .send_channel_message(team_id, channel_id, &html, subject, &mentions)
209 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
140 210 .await?;
141 211 self.cache_sent(channel_id, &sent)
142 212 }
143 213
214 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
215 pub async fn upload_attachment(
216 &self,
217 conversation_id: &str,
218 file_name: &str,
219 bytes: &[u8],
220 progress: impl Fn(u8) + Send + Sync,
221 ) -> Result<FileReference> {
222 let uploaded = self
223 .upload_attachment_file(conversation_id, file_name, bytes, progress)
224 .await?;
225 self.share_attachment(conversation_id, &uploaded).await?;
226 uploaded.reference().ok_or_else(missing_attachment_id)
227 }
228
229 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
230 pub async fn upload_attachment_file(
231 &self,
232 conversation_id: &str,
233 file_name: &str,
234 bytes: &[u8],
235 progress: impl Fn(u8) + Send + Sync,
236 ) -> Result<UploadedFile> {
237 let destination = match self.resolve(conversation_id)? {
238 Conversation::Chat => UploadDestination::ChatFiles,
239 Conversation::Channel { team_id } => {
240 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
241 }
242 };
243 let uploaded = self
244 .remote
245 .upload_file(&destination, file_name, bytes, &progress)
246 .await?;
247 if uploaded.reference().is_none() {
248 let _ = self.remote.delete_file(&uploaded).await;
249 return Err(missing_attachment_id());
250 }
251 Ok(uploaded)
252 }
253
254 /// Read-only for the other chat members; channels need nothing.
255 pub async fn share_attachment(
256 &self,
257 conversation_id: &str,
258 uploaded: &UploadedFile,
259 ) -> Result<()> {
260 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
261 return Ok(());
262 }
263 let other_members = self.other_member_ids(conversation_id).await?;
264 self.remote.share_file(uploaded, &other_members).await
265 }
266
267 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
268 self.remote.delete_file(uploaded).await
269 }
270
271 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
272 let cached = self
273 .channel_folders
274 .lock()
275 .expect("channel folder cache poisoned")
276 .get(channel_id)
277 .cloned();
278 if let Some(folder) = cached {
279 return Ok(folder);
280 }
281 let folder = self
282 .remote
283 .channel_files_folder(team_id, channel_id)
284 .await?;
285 self.channel_folders
286 .lock()
287 .expect("channel folder cache poisoned")
288 .insert(channel_id.to_owned(), folder.clone());
289 Ok(folder)
290 }
291
292 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
293 let my_user_id = self.my_user_id().await?;
294 let members = self
295 .store
296 .chat(chat_id)?
297 .map(|chat| chat.members)
298 .filter(|members| !members.is_empty())
299 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
300 Ok(members
301 .into_iter()
302 .filter_map(|member| member.user_id)
303 .filter(|user_id| *user_id != my_user_id)
304 .collect())
305 }
306
144 307 pub async fn refresh_message(
145 308 &self,
146 309 conversation_id: &str,
@@ -224,9 +387,22 @@ impl<R: Remote> SyncEngine<R> {
224 387 mentions: &[MentionInput],
225 388 ) -> Result<()> {
226 389 let conversation = self.resolve(conversation_id)?;
227 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
390 let (mut html, mentions) = outgoing(&conversation, markdown, mentions)?;
228 391 let target = self.message_target(conversation_id, message_id)?;
229 self.remote.edit_message(&target, &html, &mentions).await?;
392 let mut extras = MessageExtras::default();
393 if let Some(record) = self
394 .store
395 .messages_by_id(conversation_id, &[message_id.to_owned()])?
396 .remove(message_id)
397 {
398 let preserved = crate::stored::edit_preserved(&record);
399 html.push_str(&preserved.images_html);
400 extras.files = preserved.files;
401 extras.kept = preserved.kept;
402 }
403 self.remote
404 .edit_message(&target, &html, &mentions, &extras)
405 .await?;
230 406 self.refresh_message(conversation_id, message_id).await?;
231 407 Ok(())
232 408 }
@@ -330,3 +506,7 @@ fn outgoing(
330 506 }
331 507 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
332 508 }
509
510 fn missing_attachment_id() -> Error {
511 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
512 }
@@ -1,5 +1,7 @@
1use chrono::Utc;
1use chrono::Utc;
2use graph::{MessageTarget, OutgoingMention};
2use graph::{
3 FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
4};
3use store::MessageRecord;
5use store::MessageRecord;
4
6
5use crate::engine::{Conversation, META_USER_ID, SyncEngine};
7use crate::engine::{Conversation, META_USER_ID, SyncEngine};
@@ -26,18 +28,43 @@ impl<R: Remote> SyncEngine<R> {
26 markdown: &str,
28 markdown: &str,
27 thread_root_id: Option<&str>,
29 thread_root_id: Option<&str>,
28 mentions: &[MentionInput],
30 mentions: &[MentionInput],
31 ) -> Result<MessageRecord> {
32 self.send_message_with_extras(
33 conversation_id,
34 markdown,
35 thread_root_id,
36 mentions,
37 &MessageExtras::default(),
38 )
39 .await
40 }
41
42 pub async fn send_message_with_extras(
43 &self,
44 conversation_id: &str,
45 markdown: &str,
46 thread_root_id: Option<&str>,
47 mentions: &[MentionInput],
48 extras: &MessageExtras,
29 ) -> Result<MessageRecord> {
49 ) -> Result<MessageRecord> {
30 let conversation = self.resolve(conversation_id)?;
50 let conversation = self.resolve(conversation_id)?;
31 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
51 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
32 let sent = match (conversation, thread_root_id) {
52 let sent = match (conversation, thread_root_id) {
33 (Conversation::Chat, None) => {
53 (Conversation::Chat, None) => {
34 self.remote
54 self.remote
35 .send_chat_message(conversation_id, &html, &mentions)
55 .send_chat_message(conversation_id, &html, &mentions, extras)
36 .await?
56 .await?
37 }
57 }
38 (Conversation::Channel { team_id }, Some(root_id)) => {
58 (Conversation::Channel { team_id }, Some(root_id)) => {
39 self.remote
59 self.remote
40 .reply_to_channel_message(&team_id, conversation_id, root_id, &html, &mentions)
60 .reply_to_channel_message(
61 &team_id,
62 conversation_id,
63 root_id,
64 &html,
65 &mentions,
66 extras,
67 )
41 .await?
68 .await?
42 }
69 }
43 (Conversation::Chat, Some(_)) => {
70 (Conversation::Chat, Some(_)) => {
@@ -69,13 +96,31 @@ impl<R: Remote> SyncEngine<R> {
69 message_id: &str,
96 message_id: &str,
70 markdown: &str,
97 markdown: &str,
71 mentions: &[MentionInput],
98 mentions: &[MentionInput],
99 ) -> Result<MessageRecord> {
100 self.reply_to_with_extras(
101 conversation_id,
102 message_id,
103 markdown,
104 mentions,
105 &MessageExtras::default(),
106 )
107 .await
108 }
109
110 pub async fn reply_to_with_extras(
111 &self,
112 conversation_id: &str,
113 message_id: &str,
114 markdown: &str,
115 mentions: &[MentionInput],
116 extras: &MessageExtras,
72 ) -> Result<MessageRecord> {
117 ) -> Result<MessageRecord> {
73 let conversation = self.resolve(conversation_id)?;
118 let conversation = self.resolve(conversation_id)?;
74 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
119 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
75 let sent = match conversation {
120 let sent = match conversation {
76 Conversation::Chat => {
121 Conversation::Chat => {
77 self.remote
122 self.remote
78 .reply_with_quote(conversation_id, message_id, &html, &mentions)
123 .reply_with_quote(conversation_id, message_id, &html, &mentions, extras)
79 .await?
124 .await?
80 }
125 }
81 Conversation::Channel { team_id } => {
126 Conversation::Channel { team_id } => {
@@ -86,7 +131,14 @@ impl<R: Remote> SyncEngine<R> {
86 .and_then(|record| record.reply_to_id)
131 .and_then(|record| record.reply_to_id)
87 .unwrap_or_else(|| message_id.to_owned());
132 .unwrap_or_else(|| message_id.to_owned());
88 self.remote
133 self.remote
89 .reply_to_channel_message(&team_id, conversation_id, &root_id, &html, &mentions)
134 .reply_to_channel_message(
135 &team_id,
136 conversation_id,
137 &root_id,
138 &html,
139 &mentions,
140 extras,
141 )
90 .await?
142 .await?
91 }
143 }
92 };
144 };
@@ -128,6 +180,24 @@ impl<R: Remote> SyncEngine<R> {
128 markdown: &str,
180 markdown: &str,
129 subject: Option<&str>,
181 subject: Option<&str>,
130 mentions: &[MentionInput],
182 mentions: &[MentionInput],
183 ) -> Result<MessageRecord> {
184 self.post_to_channel_with_extras(
185 channel_id,
186 markdown,
187 subject,
188 mentions,
189 &MessageExtras::default(),
190 )
191 .await
192 }
193
194 pub async fn post_to_channel_with_extras(
195 &self,
196 channel_id: &str,
197 markdown: &str,
198 subject: Option<&str>,
199 mentions: &[MentionInput],
200 extras: &MessageExtras,
131 ) -> Result<MessageRecord> {
201 ) -> Result<MessageRecord> {
132 let conversation = self.resolve(channel_id)?;
202 let conversation = self.resolve(channel_id)?;
133 let Conversation::Channel { team_id } = &conversation else {
203 let Conversation::Channel { team_id } = &conversation else {
@@ -136,11 +206,104 @@ impl<R: Remote> SyncEngine<R> {
136 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
206 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
137 let sent = self
207 let sent = self
138 .remote
208 .remote
139 .send_channel_message(team_id, channel_id, &html, subject, &mentions)
209 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
140 .await?;
210 .await?;
141 self.cache_sent(channel_id, &sent)
211 self.cache_sent(channel_id, &sent)
142 }
212 }
143
213
214 /// Upload then share; the app uses the two steps apart so a failed share does not upload again.
215 pub async fn upload_attachment(
216 &self,
217 conversation_id: &str,
218 file_name: &str,
219 bytes: &[u8],
220 progress: impl Fn(u8) + Send + Sync,
221 ) -> Result<FileReference> {
222 let uploaded = self
223 .upload_attachment_file(conversation_id, file_name, bytes, progress)
224 .await?;
225 self.share_attachment(conversation_id, &uploaded).await?;
226 uploaded.reference().ok_or_else(missing_attachment_id)
227 }
228
229 /// Chat files go to the sender's "Microsoft Teams Chat Files", channel files to the channel's folder.
230 pub async fn upload_attachment_file(
231 &self,
232 conversation_id: &str,
233 file_name: &str,
234 bytes: &[u8],
235 progress: impl Fn(u8) + Send + Sync,
236 ) -> Result<UploadedFile> {
237 let destination = match self.resolve(conversation_id)? {
238 Conversation::Chat => UploadDestination::ChatFiles,
239 Conversation::Channel { team_id } => {
240 UploadDestination::Folder(self.channel_folder(&team_id, conversation_id).await?)
241 }
242 };
243 let uploaded = self
244 .remote
245 .upload_file(&destination, file_name, bytes, &progress)
246 .await?;
247 if uploaded.reference().is_none() {
248 let _ = self.remote.delete_file(&uploaded).await;
249 return Err(missing_attachment_id());
250 }
251 Ok(uploaded)
252 }
253
254 /// Read-only for the other chat members; channels need nothing.
255 pub async fn share_attachment(
256 &self,
257 conversation_id: &str,
258 uploaded: &UploadedFile,
259 ) -> Result<()> {
260 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
261 return Ok(());
262 }
263 let other_members = self.other_member_ids(conversation_id).await?;
264 self.remote.share_file(uploaded, &other_members).await
265 }
266
267 pub async fn discard_attachment(&self, uploaded: &UploadedFile) -> Result<()> {
268 self.remote.delete_file(uploaded).await
269 }
270
271 async fn channel_folder(&self, team_id: &str, channel_id: &str) -> Result<graph::DriveFolder> {
272 let cached = self
273 .channel_folders
274 .lock()
275 .expect("channel folder cache poisoned")
276 .get(channel_id)
277 .cloned();
278 if let Some(folder) = cached {
279 return Ok(folder);
280 }
281 let folder = self
282 .remote
283 .channel_files_folder(team_id, channel_id)
284 .await?;
285 self.channel_folders
286 .lock()
287 .expect("channel folder cache poisoned")
288 .insert(channel_id.to_owned(), folder.clone());
289 Ok(folder)
290 }
291
292 async fn other_member_ids(&self, chat_id: &str) -> Result<Vec<String>> {
293 let my_user_id = self.my_user_id().await?;
294 let members = self
295 .store
296 .chat(chat_id)?
297 .map(|chat| chat.members)
298 .filter(|members| !members.is_empty())
299 .ok_or_else(|| graph::Error::Upload("Chat members not loaded yet.".into()))?;
300 Ok(members
301 .into_iter()
302 .filter_map(|member| member.user_id)
303 .filter(|user_id| *user_id != my_user_id)
304 .collect())
305 }
306
144 pub async fn refresh_message(
307 pub async fn refresh_message(
145 &self,
308 &self,
146 conversation_id: &str,
309 conversation_id: &str,
@@ -224,9 +387,22 @@ impl<R: Remote> SyncEngine<R> {
224 mentions: &[MentionInput],
387 mentions: &[MentionInput],
225 ) -> Result<()> {
388 ) -> Result<()> {
226 let conversation = self.resolve(conversation_id)?;
389 let conversation = self.resolve(conversation_id)?;
227 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
390 let (mut html, mentions) = outgoing(&conversation, markdown, mentions)?;
228 let target = self.message_target(conversation_id, message_id)?;
391 let target = self.message_target(conversation_id, message_id)?;
229 self.remote.edit_message(&target, &html, &mentions).await?;
392 let mut extras = MessageExtras::default();
393 if let Some(record) = self
394 .store
395 .messages_by_id(conversation_id, &[message_id.to_owned()])?
396 .remove(message_id)
397 {
398 let preserved = crate::stored::edit_preserved(&record);
399 html.push_str(&preserved.images_html);
400 extras.files = preserved.files;
401 extras.kept = preserved.kept;
402 }
403 self.remote
404 .edit_message(&target, &html, &mentions, &extras)
405 .await?;
230 self.refresh_message(conversation_id, message_id).await?;
406 self.refresh_message(conversation_id, message_id).await?;
231 Ok(())
407 Ok(())
232 }
408 }
@@ -330,3 +506,7 @@ fn outgoing(
330 }
506 }
331 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
507 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
332}
508}
509
510fn missing_attachment_id() -> Error {
511 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
512}
crates/core/src/engine.rs +3 −1
@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
3 3 use std::sync::{Arc, Mutex};
4 4
5 5 use chrono::{DateTime, Duration, Utc};
6 use graph::{Graph, MESSAGE_PAGE_SIZE, Message};
6 use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7 7 use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8 8 use tokio::sync::{OnceCell, broadcast};
9 9
@@ -117,6 +117,7 @@ pub struct SyncEngine<R: Remote = Graph> {
117 117 pub(crate) directory_cache: Mutex<DirectoryCache>,
118 118 preview_changed: AtomicBool,
119 119 pub(crate) receipts: ReceiptCache,
120 pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
120 121 }
121 122
122 123 impl<R: Remote> SyncEngine<R> {
@@ -140,6 +141,7 @@ impl<R: Remote> SyncEngine<R> {
140 141 directory_cache: Mutex::new(DirectoryCache::new()),
141 142 preview_changed: AtomicBool::new(false),
142 143 receipts: ReceiptCache::default(),
144 channel_folders: Mutex::new(HashMap::new()),
143 145 }
144 146 }
145 147
@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
3use std::sync::{Arc, Mutex};
4
4
5use chrono::{DateTime, Duration, Utc};
5use chrono::{DateTime, Duration, Utc};
6use graph::{Graph, MESSAGE_PAGE_SIZE, Message};
6use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
7use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8use tokio::sync::{OnceCell, broadcast};
8use tokio::sync::{OnceCell, broadcast};
9
9
@@ -117,6 +117,7 @@ pub struct SyncEngine<R: Remote = Graph> {
117 pub(crate) directory_cache: Mutex<DirectoryCache>,
117 pub(crate) directory_cache: Mutex<DirectoryCache>,
118 preview_changed: AtomicBool,
118 preview_changed: AtomicBool,
119 pub(crate) receipts: ReceiptCache,
119 pub(crate) receipts: ReceiptCache,
120 pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
120}
121}
121
122
122impl<R: Remote> SyncEngine<R> {
123impl<R: Remote> SyncEngine<R> {
@@ -140,6 +141,7 @@ impl<R: Remote> SyncEngine<R> {
140 directory_cache: Mutex::new(DirectoryCache::new()),
141 directory_cache: Mutex::new(DirectoryCache::new()),
141 preview_changed: AtomicBool::new(false),
142 preview_changed: AtomicBool::new(false),
142 receipts: ReceiptCache::default(),
143 receipts: ReceiptCache::default(),
144 channel_folders: Mutex::new(HashMap::new()),
143 }
145 }
144 }
146 }
145
147
crates/core/src/lib.rs +3 −1
@@ -27,7 +27,9 @@ pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
27 27 pub use error::{Error, Result};
28 28 pub use events::CoreEvent;
29 29 pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
30 pub use graph::MentionTarget;
30 pub use graph::{
31 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, UploadedFile,
32 };
31 33 pub use images::StoredImage;
32 34 pub use mapping::{chat_record, message_record};
33 35 pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
@@ -27,7 +27,9 @@ pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
27pub use error::{Error, Result};
27pub use error::{Error, Result};
28pub use events::CoreEvent;
28pub use events::CoreEvent;
29pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
29pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
30pub use graph::MentionTarget;
30pub use graph::{
31 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, UploadedFile,
32};
31pub use images::StoredImage;
33pub use images::StoredImage;
32pub use mapping::{chat_record, message_record};
34pub use mapping::{chat_record, message_record};
33pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
35pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
crates/core/src/mapping.rs +5 −0
@@ -203,6 +203,11 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
203 203 .as_deref()
204 204 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
205 205 .and_then(quote_info),
206 id: attachment.id.clone(),
207 content: attachment
208 .content
209 .clone()
210 .filter(|_| is_card || attachment.content_type.as_deref() == Some("messageReference")),
206 211 }
207 212 }
208 213
@@ -203,6 +203,11 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
203 .as_deref()
203 .as_deref()
204 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
204 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
205 .and_then(quote_info),
205 .and_then(quote_info),
206 id: attachment.id.clone(),
207 content: attachment
208 .content
209 .clone()
210 .filter(|_| is_card || attachment.content_type.as_deref() == Some("messageReference")),
206 }
211 }
207}
212}
208
213
crates/core/src/remote.rs +75 −12
@@ -1,8 +1,8 @@
1 1 use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
2 2 use chrono::{DateTime, Utc};
3 3 use graph::{
4 Channel, Chat, Graph, Member, Message, MessageTarget, OutgoingMention, Photo, Presence, Team,
5 User,
4 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
5 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
6 6 };
7 7
8 8 use crate::error::{Error, Result};
@@ -82,6 +82,7 @@ pub trait Remote {
82 82 chat_id: &str,
83 83 html: &str,
84 84 mentions: &[OutgoingMention],
85 extras: &MessageExtras,
85 86 ) -> Result<Message>;
86 87 async fn send_channel_message(
87 88 &self,
@@ -90,6 +91,7 @@ pub trait Remote {
90 91 html: &str,
91 92 subject: Option<&str>,
92 93 mentions: &[OutgoingMention],
94 extras: &MessageExtras,
93 95 ) -> Result<Message>;
94 96 async fn reply_to_channel_message(
95 97 &self,
@@ -98,6 +100,7 @@ pub trait Remote {
98 100 message_id: &str,
99 101 html: &str,
100 102 mentions: &[OutgoingMention],
103 extras: &MessageExtras,
101 104 ) -> Result<Message>;
102 105 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
103 106 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
@@ -107,6 +110,7 @@ pub trait Remote {
107 110 target: &MessageTarget,
108 111 html: &str,
109 112 mentions: &[OutgoingMention],
113 extras: &MessageExtras,
110 114 ) -> Result<()>;
111 115 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
112 116 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
@@ -124,10 +128,33 @@ pub trait Remote {
124 128 _quoted_message_id: &str,
125 129 _html: &str,
126 130 _mentions: &[OutgoingMention],
131 _extras: &MessageExtras,
127 132 ) -> Result<Message> {
128 133 Err(Error::Unsupported("a quoted reply"))
129 134 }
130 135
136 async fn channel_files_folder(&self, _team_id: &str, _channel_id: &str) -> Result<DriveFolder> {
137 Err(Error::Unsupported("a channel files folder"))
138 }
139
140 async fn upload_file(
141 &self,
142 _destination: &UploadDestination,
143 _file_name: &str,
144 _bytes: &[u8],
145 _progress: &(dyn Fn(u8) + Send + Sync),
146 ) -> Result<UploadedFile> {
147 Err(Error::Unsupported("a file upload"))
148 }
149
150 async fn share_file(&self, _file: &UploadedFile, _user_ids: &[String]) -> Result<()> {
151 Err(Error::Unsupported("sharing a file"))
152 }
153
154 async fn delete_file(&self, _file: &UploadedFile) -> Result<()> {
155 Err(Error::Unsupported("deleting a file"))
156 }
157
131 158 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
132 159 Err(Error::Unsupported("hosted content"))
133 160 }
@@ -262,8 +289,9 @@ impl Remote for Graph {
262 289 chat_id: &str,
263 290 html: &str,
264 291 mentions: &[OutgoingMention],
292 extras: &MessageExtras,
265 293 ) -> Result<Message> {
266 Ok(Graph::send_chat_message(self, chat_id, html, mentions).await?)
294 Ok(Graph::send_chat_message(self, chat_id, html, mentions, extras).await?)
267 295 }
268 296
269 297 async fn send_channel_message(
@@ -273,8 +301,12 @@ impl Remote for Graph {
273 301 html: &str,
274 302 subject: Option<&str>,
275 303 mentions: &[OutgoingMention],
304 extras: &MessageExtras,
276 305 ) -> Result<Message> {
277 Ok(Graph::send_channel_message(self, team_id, channel_id, html, subject, mentions).await?)
306 Ok(
307 Graph::send_channel_message(self, team_id, channel_id, html, subject, mentions, extras)
308 .await?,
309 )
278 310 }
279 311
280 312 async fn reply_to_channel_message(
@@ -284,11 +316,12 @@ impl Remote for Graph {
284 316 message_id: &str,
285 317 html: &str,
286 318 mentions: &[OutgoingMention],
319 extras: &MessageExtras,
287 320 ) -> Result<Message> {
288 Ok(
289 Graph::reply_to_channel_message(self, team_id, channel_id, message_id, html, mentions)
290 .await?,
321 Ok(Graph::reply_to_channel_message(
322 self, team_id, channel_id, message_id, html, mentions, extras,
291 323 )
324 .await?)
292 325 }
293 326
294 327 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
@@ -308,15 +341,19 @@ impl Remote for Graph {
308 341 target: &MessageTarget,
309 342 html: &str,
310 343 mentions: &[OutgoingMention],
344 extras: &MessageExtras,
311 345 ) -> Result<()> {
312 346 match chatsvc_conversation(target) {
313 Some(conversation) if mentions.is_empty() => Ok(Messages::new(self.session())
314 .edit_message(&conversation, target.message_id(), html)
315 .await?),
347 Some(conversation) if mentions.is_empty() => {
348 let html = format!("{}{html}{}", extras.kept_html(), extras.files_html());
349 Ok(Messages::new(self.session())
350 .edit_message(&conversation, target.message_id(), &html)
351 .await?)
352 }
316 353 Some(_) => Err(Error::Unsupported(
317 354 "editing a channel message with mentions",
318 355 )),
319 None => Ok(Graph::edit_message(self, target, html, mentions).await?),
356 None => Ok(Graph::edit_message(self, target, html, mentions, extras).await?),
320 357 }
321 358 }
322 359
@@ -352,8 +389,34 @@ impl Remote for Graph {
352 389 quoted_message_id: &str,
353 390 html: &str,
354 391 mentions: &[OutgoingMention],
392 extras: &MessageExtras,
355 393 ) -> Result<Message> {
356 Ok(Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions).await?)
394 Ok(
395 Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions, extras)
396 .await?,
397 )
398 }
399
400 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
401 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
402 }
403
404 async fn upload_file(
405 &self,
406 destination: &UploadDestination,
407 file_name: &str,
408 bytes: &[u8],
409 progress: &(dyn Fn(u8) + Send + Sync),
410 ) -> Result<UploadedFile> {
411 Ok(Graph::upload_file(self, destination, file_name, bytes, progress).await?)
412 }
413
414 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
415 Ok(Graph::share_item(self, file, user_ids).await?)
416 }
417
418 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
419 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
357 420 }
358 421
359 422 async fn hosted_content(&self, url: &str) -> Result<Photo> {
@@ -1,8 +1,8 @@
1use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
1use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
2use chrono::{DateTime, Utc};
2use chrono::{DateTime, Utc};
3use graph::{
3use graph::{
4 Channel, Chat, Graph, Member, Message, MessageTarget, OutgoingMention, Photo, Presence, Team,
4 Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
5 User,
5 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
6};
6};
7
7
8use crate::error::{Error, Result};
8use crate::error::{Error, Result};
@@ -82,6 +82,7 @@ pub trait Remote {
82 chat_id: &str,
82 chat_id: &str,
83 html: &str,
83 html: &str,
84 mentions: &[OutgoingMention],
84 mentions: &[OutgoingMention],
85 extras: &MessageExtras,
85 ) -> Result<Message>;
86 ) -> Result<Message>;
86 async fn send_channel_message(
87 async fn send_channel_message(
87 &self,
88 &self,
@@ -90,6 +91,7 @@ pub trait Remote {
90 html: &str,
91 html: &str,
91 subject: Option<&str>,
92 subject: Option<&str>,
92 mentions: &[OutgoingMention],
93 mentions: &[OutgoingMention],
94 extras: &MessageExtras,
93 ) -> Result<Message>;
95 ) -> Result<Message>;
94 async fn reply_to_channel_message(
96 async fn reply_to_channel_message(
95 &self,
97 &self,
@@ -98,6 +100,7 @@ pub trait Remote {
98 message_id: &str,
100 message_id: &str,
99 html: &str,
101 html: &str,
100 mentions: &[OutgoingMention],
102 mentions: &[OutgoingMention],
103 extras: &MessageExtras,
101 ) -> Result<Message>;
104 ) -> Result<Message>;
102 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
105 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
103 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
106 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()>;
@@ -107,6 +110,7 @@ pub trait Remote {
107 target: &MessageTarget,
110 target: &MessageTarget,
108 html: &str,
111 html: &str,
109 mentions: &[OutgoingMention],
112 mentions: &[OutgoingMention],
113 extras: &MessageExtras,
110 ) -> Result<()>;
114 ) -> Result<()>;
111 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
115 async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()>;
112 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
116 async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat>;
@@ -124,10 +128,33 @@ pub trait Remote {
124 _quoted_message_id: &str,
128 _quoted_message_id: &str,
125 _html: &str,
129 _html: &str,
126 _mentions: &[OutgoingMention],
130 _mentions: &[OutgoingMention],
131 _extras: &MessageExtras,
127 ) -> Result<Message> {
132 ) -> Result<Message> {
128 Err(Error::Unsupported("a quoted reply"))
133 Err(Error::Unsupported("a quoted reply"))
129 }
134 }
130
135
136 async fn channel_files_folder(&self, _team_id: &str, _channel_id: &str) -> Result<DriveFolder> {
137 Err(Error::Unsupported("a channel files folder"))
138 }
139
140 async fn upload_file(
141 &self,
142 _destination: &UploadDestination,
143 _file_name: &str,
144 _bytes: &[u8],
145 _progress: &(dyn Fn(u8) + Send + Sync),
146 ) -> Result<UploadedFile> {
147 Err(Error::Unsupported("a file upload"))
148 }
149
150 async fn share_file(&self, _file: &UploadedFile, _user_ids: &[String]) -> Result<()> {
151 Err(Error::Unsupported("sharing a file"))
152 }
153
154 async fn delete_file(&self, _file: &UploadedFile) -> Result<()> {
155 Err(Error::Unsupported("deleting a file"))
156 }
157
131 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
158 async fn hosted_content(&self, _url: &str) -> Result<Photo> {
132 Err(Error::Unsupported("hosted content"))
159 Err(Error::Unsupported("hosted content"))
133 }
160 }
@@ -262,8 +289,9 @@ impl Remote for Graph {
262 chat_id: &str,
289 chat_id: &str,
263 html: &str,
290 html: &str,
264 mentions: &[OutgoingMention],
291 mentions: &[OutgoingMention],
292 extras: &MessageExtras,
265 ) -> Result<Message> {
293 ) -> Result<Message> {
266 Ok(Graph::send_chat_message(self, chat_id, html, mentions).await?)
294 Ok(Graph::send_chat_message(self, chat_id, html, mentions, extras).await?)
267 }
295 }
268
296
269 async fn send_channel_message(
297 async fn send_channel_message(
@@ -273,8 +301,12 @@ impl Remote for Graph {
273 html: &str,
301 html: &str,
274 subject: Option<&str>,
302 subject: Option<&str>,
275 mentions: &[OutgoingMention],
303 mentions: &[OutgoingMention],
304 extras: &MessageExtras,
276 ) -> Result<Message> {
305 ) -> Result<Message> {
277 Ok(Graph::send_channel_message(self, team_id, channel_id, html, subject, mentions).await?)
306 Ok(
307 Graph::send_channel_message(self, team_id, channel_id, html, subject, mentions, extras)
308 .await?,
309 )
278 }
310 }
279
311
280 async fn reply_to_channel_message(
312 async fn reply_to_channel_message(
@@ -284,11 +316,12 @@ impl Remote for Graph {
284 message_id: &str,
316 message_id: &str,
285 html: &str,
317 html: &str,
286 mentions: &[OutgoingMention],
318 mentions: &[OutgoingMention],
319 extras: &MessageExtras,
287 ) -> Result<Message> {
320 ) -> Result<Message> {
288 Ok(
321 Ok(Graph::reply_to_channel_message(
289 Graph::reply_to_channel_message(self, team_id, channel_id, message_id, html, mentions)
322 self, team_id, channel_id, message_id, html, mentions, extras,
290 .await?,
291 )
323 )
324 .await?)
292 }
325 }
293
326
294 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
327 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
@@ -308,15 +341,19 @@ impl Remote for Graph {
308 target: &MessageTarget,
341 target: &MessageTarget,
309 html: &str,
342 html: &str,
310 mentions: &[OutgoingMention],
343 mentions: &[OutgoingMention],
344 extras: &MessageExtras,
311 ) -> Result<()> {
345 ) -> Result<()> {
312 match chatsvc_conversation(target) {
346 match chatsvc_conversation(target) {
313 Some(conversation) if mentions.is_empty() => Ok(Messages::new(self.session())
347 Some(conversation) if mentions.is_empty() => {
314 .edit_message(&conversation, target.message_id(), html)
348 let html = format!("{}{html}{}", extras.kept_html(), extras.files_html());
315 .await?),
349 Ok(Messages::new(self.session())
350 .edit_message(&conversation, target.message_id(), &html)
351 .await?)
352 }
316 Some(_) => Err(Error::Unsupported(
353 Some(_) => Err(Error::Unsupported(
317 "editing a channel message with mentions",
354 "editing a channel message with mentions",
318 )),
355 )),
319 None => Ok(Graph::edit_message(self, target, html, mentions).await?),
356 None => Ok(Graph::edit_message(self, target, html, mentions, extras).await?),
320 }
357 }
321 }
358 }
322
359
@@ -352,8 +389,34 @@ impl Remote for Graph {
352 quoted_message_id: &str,
389 quoted_message_id: &str,
353 html: &str,
390 html: &str,
354 mentions: &[OutgoingMention],
391 mentions: &[OutgoingMention],
392 extras: &MessageExtras,
355 ) -> Result<Message> {
393 ) -> Result<Message> {
356 Ok(Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions).await?)
394 Ok(
395 Graph::reply_with_quote(self, chat_id, quoted_message_id, html, mentions, extras)
396 .await?,
397 )
398 }
399
400 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
401 Ok(Graph::channel_files_folder(self, team_id, channel_id).await?)
402 }
403
404 async fn upload_file(
405 &self,
406 destination: &UploadDestination,
407 file_name: &str,
408 bytes: &[u8],
409 progress: &(dyn Fn(u8) + Send + Sync),
410 ) -> Result<UploadedFile> {
411 Ok(Graph::upload_file(self, destination, file_name, bytes, progress).await?)
412 }
413
414 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
415 Ok(Graph::share_item(self, file, user_ids).await?)
416 }
417
418 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
419 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
357 }
420 }
358
421
359 async fn hosted_content(&self, url: &str) -> Result<Photo> {
422 async fn hosted_content(&self, url: &str) -> Result<Photo> {
crates/core/src/stored.rs +143 −0
@@ -16,6 +16,11 @@ pub struct AttachmentInfo {
16 16 pub size: Option<u64>,
17 17 #[serde(default)]
18 18 pub quote: Option<QuoteInfo>,
19 #[serde(default)]
20 pub id: Option<String>,
21 /// Raw content, kept only for quotes and cards so an edit can send them back unchanged.
22 #[serde(default)]
23 pub content: Option<String>,
19 24 }
20 25
21 26 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -163,6 +168,86 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
163 168 found
164 169 }
165 170
171 #[derive(Debug, Clone, Default, PartialEq, Eq)]
172 pub struct EditPreserved {
173 pub images_html: String,
174 pub files: Vec<graph::FileReference>,
175 pub kept: Vec<graph::KeptAttachment>,
176 }
177
178 /// What an edit must carry over: the `<img>` elements, the file attachments and the quote or card attachments, each matched to its `<attachment id>` tag.
179 pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
180 let fragment = Html::parse_fragment(&record.body_html);
181 let mut preserved = EditPreserved::default();
182 let mut tag_ids: Vec<&str> = Vec::new();
183 for element in fragment
184 .root_element()
185 .descendants()
186 .filter_map(ElementRef::wrap)
187 {
188 let value = element.value();
189 let is_emoji = value
190 .attr("itemtype")
191 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
192 match value.name() {
193 "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
194 preserved
195 .images_html
196 .push_str(&format!("<p>{}</p>", element.html()));
197 }
198 "attachment" => tag_ids.extend(value.attr("id")),
199 _ => {}
200 }
201 }
202 let stored = attachments(record);
203 let attachment_id = |attachment: &AttachmentInfo| {
204 attachment.id.clone().or_else(|| {
205 attachment
206 .quote
207 .as_ref()
208 .map(|quote| quote.message_id.clone())
209 })
210 };
211 let mut unclaimed: Vec<&str> = tag_ids
212 .iter()
213 .copied()
214 .filter(|id| {
215 !stored.iter().any(|attachment| {
216 !attachment.is_file() && attachment_id(attachment).as_deref() == Some(*id)
217 })
218 })
219 .collect();
220 for attachment in stored {
221 if attachment.is_file() {
222 let id = match attachment_id(&attachment) {
223 Some(id) if tag_ids.contains(&id.as_str()) => id,
224 Some(_) => continue,
225 None if unclaimed.is_empty() => continue,
226 None => unclaimed.remove(0).to_owned(),
227 };
228 if let Some(content_url) = attachment.url {
229 preserved.files.push(graph::FileReference {
230 attachment_id: id,
231 content_url,
232 name: attachment.name.unwrap_or_default(),
233 });
234 }
235 } else if let Some(id) = attachment_id(&attachment)
236 && tag_ids.contains(&id.as_str())
237 && attachment.content.is_some()
238 {
239 preserved.kept.push(graph::KeptAttachment {
240 id,
241 content_type: attachment.content_type,
242 content: attachment.content,
243 content_url: attachment.url,
244 name: attachment.name,
245 });
246 }
247 }
248 preserved
249 }
250
166 251 #[derive(Debug, Clone, PartialEq, Eq)]
167 252 pub struct FileCard {
168 253 pub name: String,
@@ -366,6 +451,62 @@ mod tests {
366 451 assert!(images(&deleted).is_empty());
367 452 }
368 453
454 #[test]
455 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
456 let html = "<p>text</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>";
457 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
458 let preserved = edit_preserved(&record(html, attachments));
459 assert!(
460 preserved
461 .images_html
462 .starts_with("<p><img src=\"https://graph.microsoft.com/")
463 );
464 assert!(!preserved.images_html.contains("text"));
465 assert_eq!(preserved.files.len(), 1);
466 assert_eq!(preserved.files[0].attachment_id, "G1");
467 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
468 assert_eq!(preserved.files[0].name, "a.pdf");
469 assert!(preserved.kept.is_empty());
470 }
471
472 const QUOTED_HTML: &str =
473 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
474
475 #[test]
476 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
477 let attachments = r#"[
478 {"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","content":"{\"messageId\":\"Q1\",\"messagePreview\":\"hi\"}","quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
479 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
480 ]"#;
481 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
482 assert_eq!(preserved.files.len(), 1);
483 assert_eq!(preserved.files[0].attachment_id, "F1");
484 assert_eq!(preserved.kept.len(), 1);
485 assert_eq!(preserved.kept[0].id, "Q1");
486 assert_eq!(
487 preserved.kept[0].content_type.as_deref(),
488 Some("messageReference")
489 );
490 assert!(
491 preserved.kept[0]
492 .content
493 .as_deref()
494 .unwrap()
495 .contains("messagePreview")
496 );
497 }
498
499 #[test]
500 fn records_cached_before_content_was_stored_leave_the_quote_out() {
501 let attachments = r#"[
502 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
503 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
504 ]"#;
505 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
506 assert_eq!(preserved.files[0].attachment_id, "F1");
507 assert!(preserved.kept.is_empty());
508 }
509
369 510 #[test]
370 511 fn file_kind_follows_the_extension_then_the_content_type() {
371 512 let kind = |name: Option<&str>, content_type: &str| {
@@ -376,6 +517,8 @@ mod tests {
376 517 text: None,
377 518 size: None,
378 519 quote: None,
520 id: None,
521 content: None,
379 522 }
380 523 .file_kind()
381 524 };
@@ -16,6 +16,11 @@ pub struct AttachmentInfo {
16 pub size: Option<u64>,
16 pub size: Option<u64>,
17 #[serde(default)]
17 #[serde(default)]
18 pub quote: Option<QuoteInfo>,
18 pub quote: Option<QuoteInfo>,
19 #[serde(default)]
20 pub id: Option<String>,
21 /// Raw content, kept only for quotes and cards so an edit can send them back unchanged.
22 #[serde(default)]
23 pub content: Option<String>,
19}
24}
20
25
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -163,6 +168,86 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
163 found
168 found
164}
169}
165
170
171#[derive(Debug, Clone, Default, PartialEq, Eq)]
172pub struct EditPreserved {
173 pub images_html: String,
174 pub files: Vec<graph::FileReference>,
175 pub kept: Vec<graph::KeptAttachment>,
176}
177
178/// What an edit must carry over: the `<img>` elements, the file attachments and the quote or card attachments, each matched to its `<attachment id>` tag.
179pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
180 let fragment = Html::parse_fragment(&record.body_html);
181 let mut preserved = EditPreserved::default();
182 let mut tag_ids: Vec<&str> = Vec::new();
183 for element in fragment
184 .root_element()
185 .descendants()
186 .filter_map(ElementRef::wrap)
187 {
188 let value = element.value();
189 let is_emoji = value
190 .attr("itemtype")
191 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
192 match value.name() {
193 "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
194 preserved
195 .images_html
196 .push_str(&format!("<p>{}</p>", element.html()));
197 }
198 "attachment" => tag_ids.extend(value.attr("id")),
199 _ => {}
200 }
201 }
202 let stored = attachments(record);
203 let attachment_id = |attachment: &AttachmentInfo| {
204 attachment.id.clone().or_else(|| {
205 attachment
206 .quote
207 .as_ref()
208 .map(|quote| quote.message_id.clone())
209 })
210 };
211 let mut unclaimed: Vec<&str> = tag_ids
212 .iter()
213 .copied()
214 .filter(|id| {
215 !stored.iter().any(|attachment| {
216 !attachment.is_file() && attachment_id(attachment).as_deref() == Some(*id)
217 })
218 })
219 .collect();
220 for attachment in stored {
221 if attachment.is_file() {
222 let id = match attachment_id(&attachment) {
223 Some(id) if tag_ids.contains(&id.as_str()) => id,
224 Some(_) => continue,
225 None if unclaimed.is_empty() => continue,
226 None => unclaimed.remove(0).to_owned(),
227 };
228 if let Some(content_url) = attachment.url {
229 preserved.files.push(graph::FileReference {
230 attachment_id: id,
231 content_url,
232 name: attachment.name.unwrap_or_default(),
233 });
234 }
235 } else if let Some(id) = attachment_id(&attachment)
236 && tag_ids.contains(&id.as_str())
237 && attachment.content.is_some()
238 {
239 preserved.kept.push(graph::KeptAttachment {
240 id,
241 content_type: attachment.content_type,
242 content: attachment.content,
243 content_url: attachment.url,
244 name: attachment.name,
245 });
246 }
247 }
248 preserved
249}
250
166#[derive(Debug, Clone, PartialEq, Eq)]
251#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct FileCard {
252pub struct FileCard {
168 pub name: String,
253 pub name: String,
@@ -366,6 +451,62 @@ mod tests {
366 assert!(images(&deleted).is_empty());
451 assert!(images(&deleted).is_empty());
367 }
452 }
368
453
454 #[test]
455 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
456 let html = "<p>text</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>";
457 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
458 let preserved = edit_preserved(&record(html, attachments));
459 assert!(
460 preserved
461 .images_html
462 .starts_with("<p><img src=\"https://graph.microsoft.com/")
463 );
464 assert!(!preserved.images_html.contains("text"));
465 assert_eq!(preserved.files.len(), 1);
466 assert_eq!(preserved.files[0].attachment_id, "G1");
467 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
468 assert_eq!(preserved.files[0].name, "a.pdf");
469 assert!(preserved.kept.is_empty());
470 }
471
472 const QUOTED_HTML: &str =
473 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
474
475 #[test]
476 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
477 let attachments = r#"[
478 {"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","content":"{\"messageId\":\"Q1\",\"messagePreview\":\"hi\"}","quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
479 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
480 ]"#;
481 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
482 assert_eq!(preserved.files.len(), 1);
483 assert_eq!(preserved.files[0].attachment_id, "F1");
484 assert_eq!(preserved.kept.len(), 1);
485 assert_eq!(preserved.kept[0].id, "Q1");
486 assert_eq!(
487 preserved.kept[0].content_type.as_deref(),
488 Some("messageReference")
489 );
490 assert!(
491 preserved.kept[0]
492 .content
493 .as_deref()
494 .unwrap()
495 .contains("messagePreview")
496 );
497 }
498
499 #[test]
500 fn records_cached_before_content_was_stored_leave_the_quote_out() {
501 let attachments = r#"[
502 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
503 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
504 ]"#;
505 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
506 assert_eq!(preserved.files[0].attachment_id, "F1");
507 assert!(preserved.kept.is_empty());
508 }
509
369 #[test]
510 #[test]
370 fn file_kind_follows_the_extension_then_the_content_type() {
511 fn file_kind_follows_the_extension_then_the_content_type() {
371 let kind = |name: Option<&str>, content_type: &str| {
512 let kind = |name: Option<&str>, content_type: &str| {
@@ -376,6 +517,8 @@ mod tests {
376 text: None,
517 text: None,
377 size: None,
518 size: None,
378 quote: None,
519 quote: None,
520 id: None,
521 content: None,
379 }
522 }
380 .file_kind()
523 .file_kind()
381 };
524 };
crates/core/tests/engine.rs +217 −1
@@ -3,7 +3,8 @@ use std::sync::{Arc, Mutex};
3 3
4 4 use chrono::{DateTime, Duration, TimeZone, Utc};
5 5 use graph::{
6 Channel, Chat, Member, Message, MessageTarget, OutgoingMention, Photo, Presence, Team, User,
6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
7 8 };
8 9 use serde_json::json;
9 10 use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
@@ -80,6 +81,8 @@ struct Fake {
80 81 presence_answers: Mutex<Vec<Presence>>,
81 82 hosted_requests: Mutex<Vec<String>>,
82 83 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
84 extras_sent: Mutex<Vec<MessageExtras>>,
85 folder_requests: Mutex<usize>,
83 86 directory_users: Mutex<Vec<User>>,
84 87 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
85 88 horizon_calls: Mutex<usize>,
@@ -331,9 +334,11 @@ impl Remote for Handle {
331 334 _chat_id: &str,
332 335 html: &str,
333 336 mentions: &[OutgoingMention],
337 extras: &MessageExtras,
334 338 ) -> Result<Message> {
335 339 self.sent.lock().unwrap().push(html.to_owned());
336 340 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
341 self.extras_sent.lock().unwrap().push(extras.clone());
337 342 Ok(message(9000, 500, html))
338 343 }
339 344
@@ -344,9 +349,11 @@ impl Remote for Handle {
344 349 html: &str,
345 350 subject: Option<&str>,
346 351 mentions: &[OutgoingMention],
352 extras: &MessageExtras,
347 353 ) -> Result<Message> {
348 354 self.record(format!("post subject={subject:?}"));
349 355 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
356 self.extras_sent.lock().unwrap().push(extras.clone());
350 357 Ok(message(9001, 501, html))
351 358 }
352 359
@@ -357,9 +364,11 @@ impl Remote for Handle {
357 364 message_id: &str,
358 365 html: &str,
359 366 mentions: &[OutgoingMention],
367 extras: &MessageExtras,
360 368 ) -> Result<Message> {
361 369 self.record(format!("reply to {message_id}"));
362 370 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
371 self.extras_sent.lock().unwrap().push(extras.clone());
363 372 Ok(message(9002, 502, html))
364 373 }
365 374
@@ -386,9 +395,16 @@ impl Remote for Handle {
386 395 target: &MessageTarget,
387 396 html: &str,
388 397 mentions: &[OutgoingMention],
398 extras: &MessageExtras,
389 399 ) -> Result<()> {
390 400 self.record(format!("edit {} {html}", describe(target)));
391 401 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
402 self.extras_sent.lock().unwrap().push(extras.clone());
403 Ok(())
404 }
405
406 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
407 self.record(format!("delete_file {}", file.item_id));
392 408 Ok(())
393 409 }
394 410
@@ -421,12 +437,52 @@ impl Remote for Handle {
421 437 quoted_message_id: &str,
422 438 html: &str,
423 439 mentions: &[OutgoingMention],
440 extras: &MessageExtras,
424 441 ) -> Result<Message> {
425 442 self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}"));
426 443 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
444 self.extras_sent.lock().unwrap().push(extras.clone());
427 445 Ok(message(9003, 503, html))
428 446 }
429 447
448 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
449 *self.folder_requests.lock().unwrap() += 1;
450 self.record(format!("files_folder {team_id} {channel_id}"));
451 Ok(DriveFolder {
452 drive_id: "drive-1".into(),
453 item_id: "folder-1".into(),
454 })
455 }
456
457 async fn upload_file(
458 &self,
459 destination: &UploadDestination,
460 file_name: &str,
461 bytes: &[u8],
462 progress: &(dyn Fn(u8) + Send + Sync),
463 ) -> Result<UploadedFile> {
464 let target = match destination {
465 UploadDestination::ChatFiles => "chat-files".to_owned(),
466 UploadDestination::Folder(folder) => format!("{}/{}", folder.drive_id, folder.item_id),
467 };
468 self.record(format!("upload {target} {file_name} {}", bytes.len()));
469 progress(50);
470 progress(100);
471 Ok(UploadedFile {
472 drive_id: "drive-1".into(),
473 item_id: "item-1".into(),
474 name: file_name.to_owned(),
475 web_url: "https://files.example/web".into(),
476 web_dav_url: Some("https://files.example/dav".into()),
477 etag: "\"{GUID-1},2\"".into(),
478 })
479 }
480
481 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
482 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
483 Ok(())
484 }
485
430 486 async fn hosted_content(&self, url: &str) -> Result<Photo> {
431 487 self.hosted_requests.lock().unwrap().push(url.to_owned());
432 488 if url.contains("broken") {
@@ -989,6 +1045,166 @@ async fn channel_sends_post_and_reply_through_graph() {
989 1045 assert!(engine.post_to_channel(CHAT, "x", None).await.is_err());
990 1046 }
991 1047
1048 #[tokio::test]
1049 async fn chat_upload_goes_to_chat_files_and_is_shared_with_the_other_members() {
1050 let fake = Arc::new(Fake::default());
1051 let engine = chat_engine(&fake, small_pages()).await;
1052 let steps = Arc::new(Mutex::new(Vec::new()));
1053 let seen = steps.clone();
1054
1055 let reference = engine
1056 .upload_attachment(CHAT, "plan.pdf", &[1, 2, 3], move |percent| {
1057 seen.lock().unwrap().push(percent)
1058 })
1059 .await
1060 .unwrap();
1061
1062 assert_eq!(
1063 fake.calls(),
1064 ["upload chat-files plan.pdf 3", "share item-1 user-ada"]
1065 );
1066 assert_eq!(*steps.lock().unwrap(), [50, 100]);
1067 assert_eq!(reference.attachment_id, "GUID-1");
1068 assert_eq!(reference.content_url, "https://files.example/dav");
1069 assert_eq!(reference.name, "plan.pdf");
1070 }
1071
1072 #[tokio::test]
1073 async fn channel_upload_uses_the_cached_files_folder_and_shares_nothing() {
1074 let fake = Arc::new(Fake::default());
1075 let engine = channel_engine(&fake).await;
1076
1077 engine
1078 .upload_attachment(CHANNEL, "a.pdf", &[1], |_| {})
1079 .await
1080 .unwrap();
1081 engine
1082 .upload_attachment(CHANNEL, "b.pdf", &[1, 2], |_| {})
1083 .await
1084 .unwrap();
1085
1086 assert_eq!(*fake.folder_requests.lock().unwrap(), 1);
1087 let uploads: Vec<String> = fake
1088 .calls()
1089 .into_iter()
1090 .filter(|call| call.starts_with("upload") || call.starts_with("share"))
1091 .collect();
1092 assert_eq!(
1093 uploads,
1094 [
1095 "upload drive-1/folder-1 a.pdf 1",
1096 "upload drive-1/folder-1 b.pdf 2"
1097 ]
1098 );
1099 }
1100
1101 fn uploaded() -> UploadedFile {
1102 UploadedFile {
1103 drive_id: "drive-1".into(),
1104 item_id: "item-1".into(),
1105 name: "a.pdf".into(),
1106 web_url: "https://files.example/web".into(),
1107 web_dav_url: None,
1108 etag: "\"{GUID-1},2\"".into(),
1109 }
1110 }
1111
1112 #[tokio::test]
1113 async fn sharing_fails_loudly_when_the_chat_members_are_unknown() {
1114 let fake = Arc::new(Fake::default());
1115 let engine = chat_engine(&fake, small_pages()).await;
1116 engine
1117 .store()
1118 .upsert_chats(&[store::ChatRecord {
1119 id: "19:bare@thread.v2".into(),
1120 ..Default::default()
1121 }])
1122 .unwrap();
1123
1124 let error = engine
1125 .share_attachment("19:bare@thread.v2", &uploaded())
1126 .await
1127 .unwrap_err();
1128 assert!(error.to_string().contains("Chat members not loaded yet."));
1129 engine.share_attachment(CHAT, &uploaded()).await.unwrap();
1130 assert!(fake.calls().contains(&"share item-1 user-ada".to_owned()));
1131 }
1132
1133 #[tokio::test]
1134 async fn discarding_an_upload_deletes_the_drive_item() {
1135 let fake = Arc::new(Fake::default());
1136 let engine = chat_engine(&fake, small_pages()).await;
1137 engine.discard_attachment(&uploaded()).await.unwrap();
1138 assert_eq!(fake.calls(), ["delete_file item-1"]);
1139 }
1140
1141 #[tokio::test]
1142 async fn an_edit_keeps_the_images_and_files_of_the_original() {
1143 let fake = Arc::new(Fake::default());
1144 let engine = chat_engine(&fake, small_pages()).await;
1145 engine
1146 .store()
1147 .upsert_messages(&[store::MessageRecord {
1148 conversation_id: CHAT.into(),
1149 message_id: "m-edit".into(),
1150 created_at: base(),
1151 body_html: "<p>old</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>".into(),
1152 attachments_json: r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}]"#.into(),
1153 reactions_json: "[]".into(),
1154 mentions_json: "[]".into(),
1155 ..Default::default()
1156 }])
1157 .unwrap();
1158
1159 let _ = engine.edit_message(CHAT, "m-edit", "new").await;
1160
1161 let call = fake
1162 .calls()
1163 .into_iter()
1164 .find(|call| call.starts_with("edit"))
1165 .unwrap();
1166 assert!(call.contains("new<p><img src=\"https://graph.microsoft.com/"));
1167 let extras = fake.extras_sent.lock().unwrap();
1168 assert_eq!(extras[0].files[0].attachment_id, "G1");
1169 assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf");
1170 }
1171
1172 #[tokio::test]
1173 async fn upload_to_an_unknown_conversation_fails() {
1174 let fake = Arc::new(Fake::default());
1175 let engine = chat_engine(&fake, small_pages()).await;
1176 assert!(
1177 engine
1178 .upload_attachment("unknown", "a.pdf", &[1], |_| {})
1179 .await
1180 .is_err()
1181 );
1182 }
1183
1184 #[tokio::test]
1185 async fn send_with_extras_hands_images_and_files_to_the_remote() {
1186 let fake = Arc::new(Fake::default());
1187 let engine = chat_engine(&fake, small_pages()).await;
1188 let extras = MessageExtras {
1189 kept: Vec::new(),
1190 images: vec![HostedImage {
1191 content_type: "image/png".into(),
1192 bytes: Arc::new(vec![9]),
1193 }],
1194 files: Vec::new(),
1195 };
1196
1197 engine
1198 .send_message_with_extras(CHAT, "look", None, &[], &extras)
1199 .await
1200 .unwrap();
1201 engine.send_message(CHAT, "plain", None).await.unwrap();
1202
1203 let sent = fake.extras_sent.lock().unwrap();
1204 assert_eq!(sent[0], extras);
1205 assert!(sent[1].is_empty());
1206 }
1207
992 1208 #[tokio::test]
993 1209 async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
994 1210 let fake = Arc::new(Fake::default());
@@ -3,7 +3,8 @@ use std::sync::{Arc, Mutex};
3
3
4use chrono::{DateTime, Duration, TimeZone, Utc};
4use chrono::{DateTime, Duration, TimeZone, Utc};
5use graph::{
5use graph::{
6 Channel, Chat, Member, Message, MessageTarget, OutgoingMention, Photo, Presence, Team, User,
6 Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget,
7 OutgoingMention, Photo, Presence, Team, UploadDestination, UploadedFile, User,
7};
8};
8use serde_json::json;
9use serde_json::json;
9use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
10use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
@@ -80,6 +81,8 @@ struct Fake {
80 presence_answers: Mutex<Vec<Presence>>,
81 presence_answers: Mutex<Vec<Presence>>,
81 hosted_requests: Mutex<Vec<String>>,
82 hosted_requests: Mutex<Vec<String>>,
82 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
83 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
84 extras_sent: Mutex<Vec<MessageExtras>>,
85 folder_requests: Mutex<usize>,
83 directory_users: Mutex<Vec<User>>,
86 directory_users: Mutex<Vec<User>>,
84 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
87 horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
85 horizon_calls: Mutex<usize>,
88 horizon_calls: Mutex<usize>,
@@ -331,9 +334,11 @@ impl Remote for Handle {
331 _chat_id: &str,
334 _chat_id: &str,
332 html: &str,
335 html: &str,
333 mentions: &[OutgoingMention],
336 mentions: &[OutgoingMention],
337 extras: &MessageExtras,
334 ) -> Result<Message> {
338 ) -> Result<Message> {
335 self.sent.lock().unwrap().push(html.to_owned());
339 self.sent.lock().unwrap().push(html.to_owned());
336 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
340 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
341 self.extras_sent.lock().unwrap().push(extras.clone());
337 Ok(message(9000, 500, html))
342 Ok(message(9000, 500, html))
338 }
343 }
339
344
@@ -344,9 +349,11 @@ impl Remote for Handle {
344 html: &str,
349 html: &str,
345 subject: Option<&str>,
350 subject: Option<&str>,
346 mentions: &[OutgoingMention],
351 mentions: &[OutgoingMention],
352 extras: &MessageExtras,
347 ) -> Result<Message> {
353 ) -> Result<Message> {
348 self.record(format!("post subject={subject:?}"));
354 self.record(format!("post subject={subject:?}"));
349 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
355 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
356 self.extras_sent.lock().unwrap().push(extras.clone());
350 Ok(message(9001, 501, html))
357 Ok(message(9001, 501, html))
351 }
358 }
352
359
@@ -357,9 +364,11 @@ impl Remote for Handle {
357 message_id: &str,
364 message_id: &str,
358 html: &str,
365 html: &str,
359 mentions: &[OutgoingMention],
366 mentions: &[OutgoingMention],
367 extras: &MessageExtras,
360 ) -> Result<Message> {
368 ) -> Result<Message> {
361 self.record(format!("reply to {message_id}"));
369 self.record(format!("reply to {message_id}"));
362 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
370 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
371 self.extras_sent.lock().unwrap().push(extras.clone());
363 Ok(message(9002, 502, html))
372 Ok(message(9002, 502, html))
364 }
373 }
365
374
@@ -386,9 +395,16 @@ impl Remote for Handle {
386 target: &MessageTarget,
395 target: &MessageTarget,
387 html: &str,
396 html: &str,
388 mentions: &[OutgoingMention],
397 mentions: &[OutgoingMention],
398 extras: &MessageExtras,
389 ) -> Result<()> {
399 ) -> Result<()> {
390 self.record(format!("edit {} {html}", describe(target)));
400 self.record(format!("edit {} {html}", describe(target)));
391 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
401 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
402 self.extras_sent.lock().unwrap().push(extras.clone());
403 Ok(())
404 }
405
406 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
407 self.record(format!("delete_file {}", file.item_id));
392 Ok(())
408 Ok(())
393 }
409 }
394
410
@@ -421,12 +437,52 @@ impl Remote for Handle {
421 quoted_message_id: &str,
437 quoted_message_id: &str,
422 html: &str,
438 html: &str,
423 mentions: &[OutgoingMention],
439 mentions: &[OutgoingMention],
440 extras: &MessageExtras,
424 ) -> Result<Message> {
441 ) -> Result<Message> {
425 self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}"));
442 self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}"));
426 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
443 self.mentions_sent.lock().unwrap().push(mentions.to_vec());
444 self.extras_sent.lock().unwrap().push(extras.clone());
427 Ok(message(9003, 503, html))
445 Ok(message(9003, 503, html))
428 }
446 }
429
447
448 async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> {
449 *self.folder_requests.lock().unwrap() += 1;
450 self.record(format!("files_folder {team_id} {channel_id}"));
451 Ok(DriveFolder {
452 drive_id: "drive-1".into(),
453 item_id: "folder-1".into(),
454 })
455 }
456
457 async fn upload_file(
458 &self,
459 destination: &UploadDestination,
460 file_name: &str,
461 bytes: &[u8],
462 progress: &(dyn Fn(u8) + Send + Sync),
463 ) -> Result<UploadedFile> {
464 let target = match destination {
465 UploadDestination::ChatFiles => "chat-files".to_owned(),
466 UploadDestination::Folder(folder) => format!("{}/{}", folder.drive_id, folder.item_id),
467 };
468 self.record(format!("upload {target} {file_name} {}", bytes.len()));
469 progress(50);
470 progress(100);
471 Ok(UploadedFile {
472 drive_id: "drive-1".into(),
473 item_id: "item-1".into(),
474 name: file_name.to_owned(),
475 web_url: "https://files.example/web".into(),
476 web_dav_url: Some("https://files.example/dav".into()),
477 etag: "\"{GUID-1},2\"".into(),
478 })
479 }
480
481 async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
482 self.record(format!("share {} {}", file.item_id, user_ids.join(",")));
483 Ok(())
484 }
485
430 async fn hosted_content(&self, url: &str) -> Result<Photo> {
486 async fn hosted_content(&self, url: &str) -> Result<Photo> {
431 self.hosted_requests.lock().unwrap().push(url.to_owned());
487 self.hosted_requests.lock().unwrap().push(url.to_owned());
432 if url.contains("broken") {
488 if url.contains("broken") {
@@ -989,6 +1045,166 @@ async fn channel_sends_post_and_reply_through_graph() {
989 assert!(engine.post_to_channel(CHAT, "x", None).await.is_err());
1045 assert!(engine.post_to_channel(CHAT, "x", None).await.is_err());
990}
1046}
991
1047
1048#[tokio::test]
1049async fn chat_upload_goes_to_chat_files_and_is_shared_with_the_other_members() {
1050 let fake = Arc::new(Fake::default());
1051 let engine = chat_engine(&fake, small_pages()).await;
1052 let steps = Arc::new(Mutex::new(Vec::new()));
1053 let seen = steps.clone();
1054
1055 let reference = engine
1056 .upload_attachment(CHAT, "plan.pdf", &[1, 2, 3], move |percent| {
1057 seen.lock().unwrap().push(percent)
1058 })
1059 .await
1060 .unwrap();
1061
1062 assert_eq!(
1063 fake.calls(),
1064 ["upload chat-files plan.pdf 3", "share item-1 user-ada"]
1065 );
1066 assert_eq!(*steps.lock().unwrap(), [50, 100]);
1067 assert_eq!(reference.attachment_id, "GUID-1");
1068 assert_eq!(reference.content_url, "https://files.example/dav");
1069 assert_eq!(reference.name, "plan.pdf");
1070}
1071
1072#[tokio::test]
1073async fn channel_upload_uses_the_cached_files_folder_and_shares_nothing() {
1074 let fake = Arc::new(Fake::default());
1075 let engine = channel_engine(&fake).await;
1076
1077 engine
1078 .upload_attachment(CHANNEL, "a.pdf", &[1], |_| {})
1079 .await
1080 .unwrap();
1081 engine
1082 .upload_attachment(CHANNEL, "b.pdf", &[1, 2], |_| {})
1083 .await
1084 .unwrap();
1085
1086 assert_eq!(*fake.folder_requests.lock().unwrap(), 1);
1087 let uploads: Vec<String> = fake
1088 .calls()
1089 .into_iter()
1090 .filter(|call| call.starts_with("upload") || call.starts_with("share"))
1091 .collect();
1092 assert_eq!(
1093 uploads,
1094 [
1095 "upload drive-1/folder-1 a.pdf 1",
1096 "upload drive-1/folder-1 b.pdf 2"
1097 ]
1098 );
1099}
1100
1101fn uploaded() -> UploadedFile {
1102 UploadedFile {
1103 drive_id: "drive-1".into(),
1104 item_id: "item-1".into(),
1105 name: "a.pdf".into(),
1106 web_url: "https://files.example/web".into(),
1107 web_dav_url: None,
1108 etag: "\"{GUID-1},2\"".into(),
1109 }
1110}
1111
1112#[tokio::test]
1113async fn sharing_fails_loudly_when_the_chat_members_are_unknown() {
1114 let fake = Arc::new(Fake::default());
1115 let engine = chat_engine(&fake, small_pages()).await;
1116 engine
1117 .store()
1118 .upsert_chats(&[store::ChatRecord {
1119 id: "19:bare@thread.v2".into(),
1120 ..Default::default()
1121 }])
1122 .unwrap();
1123
1124 let error = engine
1125 .share_attachment("19:bare@thread.v2", &uploaded())
1126 .await
1127 .unwrap_err();
1128 assert!(error.to_string().contains("Chat members not loaded yet."));
1129 engine.share_attachment(CHAT, &uploaded()).await.unwrap();
1130 assert!(fake.calls().contains(&"share item-1 user-ada".to_owned()));
1131}
1132
1133#[tokio::test]
1134async fn discarding_an_upload_deletes_the_drive_item() {
1135 let fake = Arc::new(Fake::default());
1136 let engine = chat_engine(&fake, small_pages()).await;
1137 engine.discard_attachment(&uploaded()).await.unwrap();
1138 assert_eq!(fake.calls(), ["delete_file item-1"]);
1139}
1140
1141#[tokio::test]
1142async fn an_edit_keeps_the_images_and_files_of_the_original() {
1143 let fake = Arc::new(Fake::default());
1144 let engine = chat_engine(&fake, small_pages()).await;
1145 engine
1146 .store()
1147 .upsert_messages(&[store::MessageRecord {
1148 conversation_id: CHAT.into(),
1149 message_id: "m-edit".into(),
1150 created_at: base(),
1151 body_html: "<p>old</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>".into(),
1152 attachments_json: r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}]"#.into(),
1153 reactions_json: "[]".into(),
1154 mentions_json: "[]".into(),
1155 ..Default::default()
1156 }])
1157 .unwrap();
1158
1159 let _ = engine.edit_message(CHAT, "m-edit", "new").await;
1160
1161 let call = fake
1162 .calls()
1163 .into_iter()
1164 .find(|call| call.starts_with("edit"))
1165 .unwrap();
1166 assert!(call.contains("new<p><img src=\"https://graph.microsoft.com/"));
1167 let extras = fake.extras_sent.lock().unwrap();
1168 assert_eq!(extras[0].files[0].attachment_id, "G1");
1169 assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf");
1170}
1171
1172#[tokio::test]
1173async fn upload_to_an_unknown_conversation_fails() {
1174 let fake = Arc::new(Fake::default());
1175 let engine = chat_engine(&fake, small_pages()).await;
1176 assert!(
1177 engine
1178 .upload_attachment("unknown", "a.pdf", &[1], |_| {})
1179 .await
1180 .is_err()
1181 );
1182}
1183
1184#[tokio::test]
1185async fn send_with_extras_hands_images_and_files_to_the_remote() {
1186 let fake = Arc::new(Fake::default());
1187 let engine = chat_engine(&fake, small_pages()).await;
1188 let extras = MessageExtras {
1189 kept: Vec::new(),
1190 images: vec![HostedImage {
1191 content_type: "image/png".into(),
1192 bytes: Arc::new(vec![9]),
1193 }],
1194 files: Vec::new(),
1195 };
1196
1197 engine
1198 .send_message_with_extras(CHAT, "look", None, &[], &extras)
1199 .await
1200 .unwrap();
1201 engine.send_message(CHAT, "plain", None).await.unwrap();
1202
1203 let sent = fake.extras_sent.lock().unwrap();
1204 assert_eq!(sent[0], extras);
1205 assert!(sent[1].is_empty());
1206}
1207
992#[tokio::test]
1208#[tokio::test]
993async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
1209async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
994 let fake = Arc::new(Fake::default());
1210 let fake = Arc::new(Fake::default());
crates/graph/Cargo.toml +1 −0
@@ -13,6 +13,7 @@ serde.workspace = true
13 13 serde_json.workspace = true
14 14 session.workspace = true
15 15 thiserror.workspace = true
16 tokio.workspace = true
16 17
17 18 [dev-dependencies]
18 19 tokio.workspace = true
@@ -13,6 +13,7 @@ serde.workspace = true
13serde_json.workspace = true
13serde_json.workspace = true
14session.workspace = true
14session.workspace = true
15thiserror.workspace = true
15thiserror.workspace = true
16tokio.workspace = true
16
17
17[dev-dependencies]
18[dev-dependencies]
18tokio.workspace = true
19tokio.workspace = true
crates/graph/src/error.rs +4 −0
@@ -10,4 +10,8 @@ pub enum Error {
10 10 ForeignNextLink,
11 11 #[error("cannot decode a binary answer: {0}")]
12 12 Decode(String),
13 #[error("cannot upload an empty file")]
14 EmptyUpload,
15 #[error("upload failed: {0}")]
16 Upload(String),
13 17 }
@@ -10,4 +10,8 @@ pub enum Error {
10 ForeignNextLink,
10 ForeignNextLink,
11 #[error("cannot decode a binary answer: {0}")]
11 #[error("cannot decode a binary answer: {0}")]
12 Decode(String),
12 Decode(String),
13 #[error("cannot upload an empty file")]
14 EmptyUpload,
15 #[error("upload failed: {0}")]
16 Upload(String),
13}
17}
crates/graph/src/files.rs added +436 −0
@@ -0,0 +1,436 @@
1 use base64::Engine as _;
2 use base64::engine::general_purpose::STANDARD;
3 use serde::Deserialize;
4 use serde_json::{Value, json};
5 use session::{Method, Request, Scope, Session};
6
7 use crate::client::Graph;
8 use crate::error::{Error, Result};
9 use crate::outgoing::FileReference;
10 use crate::urls;
11
12 const FILES_SCOPE: &str = "Files.ReadWrite";
13 const CHUNK_UNIT_BYTES: u64 = 327_680;
14 pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
15 const MAX_CHUNK_RETRIES: usize = 3;
16
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct DriveFolder {
19 pub drive_id: String,
20 pub item_id: String,
21 }
22
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub enum UploadDestination {
25 ChatFiles,
26 Folder(DriveFolder),
27 }
28
29 #[derive(Debug, Clone, PartialEq, Eq)]
30 pub struct UploadedFile {
31 pub drive_id: String,
32 pub item_id: String,
33 pub name: String,
34 pub web_url: String,
35 pub web_dav_url: Option<String>,
36 pub etag: String,
37 }
38
39 impl UploadedFile {
40 pub fn reference(&self) -> Option<FileReference> {
41 Some(FileReference {
42 attachment_id: etag_guid(&self.etag)?,
43 content_url: self
44 .web_dav_url
45 .clone()
46 .unwrap_or_else(|| self.web_url.clone()),
47 name: self.name.clone(),
48 })
49 }
50 }
51
52 #[derive(Debug, Deserialize)]
53 #[serde(rename_all = "camelCase")]
54 struct DriveItem {
55 id: String,
56 name: String,
57 #[serde(default)]
58 web_url: String,
59 web_dav_url: Option<String>,
60 #[serde(default)]
61 e_tag: String,
62 parent_reference: Option<ParentReference>,
63 }
64
65 #[derive(Debug, Deserialize)]
66 #[serde(rename_all = "camelCase")]
67 struct ParentReference {
68 drive_id: Option<String>,
69 }
70
71 impl DriveItem {
72 fn drive_id(&self) -> Option<String> {
73 self.parent_reference.as_ref()?.drive_id.clone()
74 }
75 }
76
77 /// `"{GUID},3"` becomes `GUID`.
78 pub fn etag_guid(etag: &str) -> Option<String> {
79 let start = etag.find('{')? + 1;
80 let length = etag[start..].find('}')?;
81 let guid = &etag[start..start + length];
82 (!guid.is_empty()).then(|| guid.to_owned())
83 }
84
85 /// Inclusive range of the chunk that starts at `start`; a multiple of 320 KiB long except at the end.
86 pub fn chunk_range_at(start: u64, total: u64) -> (u64, u64) {
87 (start, (start + UPLOAD_CHUNK_BYTES).min(total) - 1)
88 }
89
90 pub fn chunk_ranges(total: u64) -> Vec<(u64, u64)> {
91 let mut ranges = Vec::new();
92 let mut start = 0;
93 while start < total {
94 let range = chunk_range_at(start, total);
95 start = range.1 + 1;
96 ranges.push(range);
97 }
98 ranges
99 }
100
101 /// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`).
102 pub fn next_expected_start(body: &Value) -> Option<u64> {
103 let range = body
104 .get("nextExpectedRanges")?
105 .as_array()?
106 .first()?
107 .as_str()?;
108 range.split('-').next()?.parse().ok()
109 }
110
111 struct SessionGuard {
112 session: Session,
113 url: String,
114 armed: bool,
115 }
116
117 impl SessionGuard {
118 fn disarm(&mut self) {
119 self.armed = false;
120 }
121 }
122
123 impl Drop for SessionGuard {
124 fn drop(&mut self) {
125 if !self.armed {
126 return;
127 }
128 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
129 return;
130 };
131 let session = self.session.clone();
132 let request = Request {
133 method: Method::Delete,
134 anonymous: true,
135 ..Request::get(std::mem::take(&mut self.url))
136 };
137 runtime.spawn(async move {
138 let _ = session.send(request, &Scope::graph(FILES_SCOPE)).await;
139 });
140 }
141 }
142
143 pub fn content_range(start: u64, end: u64, total: u64) -> String {
144 format!("bytes {start}-{end}/{total}")
145 }
146
147 pub fn percent_done(sent: u64, total: u64) -> u8 {
148 if total == 0 {
149 return 100;
150 }
151 (sent.min(total) * 100 / total) as u8
152 }
153
154 impl Graph {
155 pub async fn channel_files_folder(
156 &self,
157 team_id: &str,
158 channel_id: &str,
159 ) -> Result<DriveFolder> {
160 let answer = self
161 .session()
162 .request(
163 Method::Get,
164 &urls::channel_files_folder(team_id, channel_id),
165 &Scope::graph(FILES_SCOPE),
166 None,
167 )
168 .await?;
169 let item: DriveItem = serde_json::from_value(answer.body)?;
170 let drive_id = item
171 .drive_id()
172 .ok_or_else(|| Error::Upload("the channel folder has no drive".into()))?;
173 Ok(DriveFolder {
174 drive_id,
175 item_id: item.id,
176 })
177 }
178
179 pub async fn upload_file(
180 &self,
181 destination: &UploadDestination,
182 file_name: &str,
183 bytes: &[u8],
184 progress: &(dyn Fn(u8) + Send + Sync),
185 ) -> Result<UploadedFile> {
186 if bytes.is_empty() {
187 return Err(Error::EmptyUpload);
188 }
189 let scope = Scope::graph(FILES_SCOPE);
190 let session_url = match destination {
191 UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name),
192 UploadDestination::Folder(folder) => {
193 urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name)
194 }
195 };
196 let created = self
197 .session()
198 .request(
199 Method::Post,
200 &session_url,
201 &scope,
202 Some(json!({"item": {"@microsoft.graph.conflictBehavior": "rename"}})),
203 )
204 .await?;
205 let upload_url = created
206 .body
207 .get("uploadUrl")
208 .and_then(Value::as_str)
209 .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))?
210 .to_owned();
211 let mut guard = SessionGuard {
212 session: self.session().clone(),
213 url: upload_url.clone(),
214 armed: true,
215 };
216 let total = bytes.len() as u64;
217 progress(0);
218 let mut offset = 0;
219 let mut failures = 0;
220 while offset < total {
221 let (start, end) = chunk_range_at(offset, total);
222 let request = Request::anonymous_bytes(
223 Method::Put,
224 upload_url.clone(),
225 vec![("Content-Range".to_owned(), content_range(start, end, total))],
226 STANDARD.encode(&bytes[start as usize..=end as usize]),
227 );
228 match self.session().send(request, &scope).await {
229 Ok(answer) if matches!(answer.status, 200 | 201) => {
230 guard.disarm();
231 progress(100);
232 return finished_item(answer.body);
233 }
234 Ok(_) => {
235 failures = 0;
236 offset = end + 1;
237 progress(percent_done(offset, total).min(99));
238 }
239 Err(error) => {
240 failures += 1;
241 if failures > MAX_CHUNK_RETRIES {
242 return Err(error.into());
243 }
244 if let Some(next) = self.resume_offset(&upload_url, &scope).await {
245 offset = next.min(total);
246 }
247 }
248 }
249 }
250 Err(Error::Upload(
251 "the last chunk did not finish the upload".into(),
252 ))
253 }
254
255 async fn resume_offset(&self, upload_url: &str, scope: &Scope) -> Option<u64> {
256 let request = Request {
257 anonymous: true,
258 ..Request::get(upload_url)
259 };
260 let answer = self.session().send(request, scope).await.ok()?;
261 next_expected_start(&answer.body)
262 }
263
264 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
265 self.session()
266 .request(
267 Method::Delete,
268 &urls::drive_item(drive_id, item_id),
269 &Scope::graph(FILES_SCOPE),
270 None,
271 )
272 .await?;
273 Ok(())
274 }
275
276 pub async fn share_item(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
277 if user_ids.is_empty() {
278 return Ok(());
279 }
280 let recipients: Vec<Value> = user_ids
281 .iter()
282 .map(|user_id| json!({"objectId": user_id}))
283 .collect();
284 self.session()
285 .request(
286 Method::Post,
287 &urls::drive_item_invite(&file.drive_id, &file.item_id),
288 &Scope::graph(FILES_SCOPE),
289 Some(json!({
290 "recipients": recipients,
291 "roles": ["read"],
292 "requireSignIn": true,
293 "sendInvitation": false,
294 })),
295 )
296 .await?;
297 Ok(())
298 }
299 }
300
301 fn finished_item(body: Value) -> Result<UploadedFile> {
302 let item: DriveItem = serde_json::from_value(body)?;
303 let drive_id = item
304 .drive_id()
305 .ok_or_else(|| Error::Upload("the uploaded file has no drive".into()))?;
306 Ok(UploadedFile {
307 drive_id,
308 item_id: item.id,
309 name: item.name,
310 web_url: item.web_url,
311 web_dav_url: item.web_dav_url,
312 etag: item.e_tag,
313 })
314 }
315
316 #[cfg(test)]
317 mod tests {
318 use super::*;
319
320 #[test]
321 fn etag_guid_is_the_part_between_braces() {
322 assert_eq!(
323 etag_guid("\"{4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F},3\""),
324 Some("4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F".to_owned())
325 );
326 assert_eq!(etag_guid("\"abc,3\""), None);
327 assert_eq!(etag_guid("{}"), None);
328 assert_eq!(etag_guid(""), None);
329 }
330
331 #[test]
332 fn small_files_are_one_chunk() {
333 assert_eq!(chunk_ranges(1), vec![(0, 0)]);
334 assert_eq!(
335 chunk_ranges(UPLOAD_CHUNK_BYTES),
336 vec![(0, UPLOAD_CHUNK_BYTES - 1)]
337 );
338 assert!(chunk_ranges(0).is_empty());
339 }
340
341 #[test]
342 fn chunks_are_multiples_of_320_kib_except_the_last() {
343 let total = 2 * UPLOAD_CHUNK_BYTES + 12_345;
344 let ranges = chunk_ranges(total);
345 assert_eq!(ranges.len(), 3);
346 for (start, end) in &ranges[..2] {
347 assert_eq!((end + 1 - start) % CHUNK_UNIT_BYTES, 0);
348 assert_eq!(end + 1 - start, UPLOAD_CHUNK_BYTES);
349 }
350 let (last_start, last_end) = ranges[2];
351 assert_eq!(last_end + 1 - last_start, 12_345);
352 assert_eq!(last_end + 1, total);
353 }
354
355 #[test]
356 fn chunks_are_contiguous_and_cover_the_file() {
357 let total = 3 * UPLOAD_CHUNK_BYTES - 7;
358 let ranges = chunk_ranges(total);
359 assert_eq!(ranges[0].0, 0);
360 for pair in ranges.windows(2) {
361 assert_eq!(pair[0].1 + 1, pair[1].0);
362 }
363 assert_eq!(ranges.last().unwrap().1 + 1, total);
364 }
365
366 #[test]
367 fn resume_offset_comes_from_the_next_expected_range() {
368 assert_eq!(
369 next_expected_start(&json!({"nextExpectedRanges": ["1310720-"]})),
370 Some(1_310_720)
371 );
372 assert_eq!(
373 next_expected_start(&json!({"nextExpectedRanges": ["26-100", "200-"]})),
374 Some(26)
375 );
376 assert_eq!(
377 next_expected_start(&json!({"nextExpectedRanges": []})),
378 None
379 );
380 assert_eq!(next_expected_start(&json!({})), None);
381 }
382
383 #[test]
384 fn chunk_size_stays_well_under_the_evaluate_timeout() {
385 assert_eq!(UPLOAD_CHUNK_BYTES, 1_310_720);
386 assert_eq!(chunk_range_at(1_310_720, 2_000_000), (1_310_720, 1_999_999));
387 }
388
389 #[test]
390 fn content_range_header_matches_graph() {
391 assert_eq!(
392 content_range(0, 5_242_879, 6_000_000),
393 "bytes 0-5242879/6000000"
394 );
395 }
396
397 #[test]
398 fn progress_is_a_percentage() {
399 assert_eq!(percent_done(0, 200), 0);
400 assert_eq!(percent_done(50, 200), 25);
401 assert_eq!(percent_done(200, 200), 100);
402 assert_eq!(percent_done(5, 0), 100);
403 }
404
405 #[test]
406 fn uploaded_file_reference_prefers_the_webdav_url() {
407 let mut file = UploadedFile {
408 drive_id: "d".into(),
409 item_id: "i".into(),
410 name: "a.pdf".into(),
411 web_url: "https://x/web".into(),
412 web_dav_url: Some("https://x/dav".into()),
413 etag: "\"{AAAA},1\"".into(),
414 };
415 let reference = file.reference().unwrap();
416 assert_eq!(reference.attachment_id, "AAAA");
417 assert_eq!(reference.content_url, "https://x/dav");
418 file.web_dav_url = None;
419 assert_eq!(file.reference().unwrap().content_url, "https://x/web");
420 file.etag = "nope".into();
421 assert!(file.reference().is_none());
422 }
423
424 #[test]
425 fn drive_item_answer_parses() {
426 let item = finished_item(json!({
427 "id": "01F", "name": "a.pdf", "webUrl": "https://x/web",
428 "webDavUrl": "https://x/dav", "eTag": "\"{AAAA},2\"",
429 "parentReference": {"driveId": "b!d"}
430 }))
431 .unwrap();
432 assert_eq!(item.drive_id, "b!d");
433 assert_eq!(item.item_id, "01F");
434 assert_eq!(item.web_dav_url.as_deref(), Some("https://x/dav"));
435 }
436 }
@@ -0,0 +1,436 @@
1use base64::Engine as _;
2use base64::engine::general_purpose::STANDARD;
3use serde::Deserialize;
4use serde_json::{Value, json};
5use session::{Method, Request, Scope, Session};
6
7use crate::client::Graph;
8use crate::error::{Error, Result};
9use crate::outgoing::FileReference;
10use crate::urls;
11
12const FILES_SCOPE: &str = "Files.ReadWrite";
13const CHUNK_UNIT_BYTES: u64 = 327_680;
14pub const UPLOAD_CHUNK_BYTES: u64 = 4 * CHUNK_UNIT_BYTES;
15const MAX_CHUNK_RETRIES: usize = 3;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DriveFolder {
19 pub drive_id: String,
20 pub item_id: String,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum UploadDestination {
25 ChatFiles,
26 Folder(DriveFolder),
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct UploadedFile {
31 pub drive_id: String,
32 pub item_id: String,
33 pub name: String,
34 pub web_url: String,
35 pub web_dav_url: Option<String>,
36 pub etag: String,
37}
38
39impl UploadedFile {
40 pub fn reference(&self) -> Option<FileReference> {
41 Some(FileReference {
42 attachment_id: etag_guid(&self.etag)?,
43 content_url: self
44 .web_dav_url
45 .clone()
46 .unwrap_or_else(|| self.web_url.clone()),
47 name: self.name.clone(),
48 })
49 }
50}
51
52#[derive(Debug, Deserialize)]
53#[serde(rename_all = "camelCase")]
54struct DriveItem {
55 id: String,
56 name: String,
57 #[serde(default)]
58 web_url: String,
59 web_dav_url: Option<String>,
60 #[serde(default)]
61 e_tag: String,
62 parent_reference: Option<ParentReference>,
63}
64
65#[derive(Debug, Deserialize)]
66#[serde(rename_all = "camelCase")]
67struct ParentReference {
68 drive_id: Option<String>,
69}
70
71impl DriveItem {
72 fn drive_id(&self) -> Option<String> {
73 self.parent_reference.as_ref()?.drive_id.clone()
74 }
75}
76
77/// `"{GUID},3"` becomes `GUID`.
78pub fn etag_guid(etag: &str) -> Option<String> {
79 let start = etag.find('{')? + 1;
80 let length = etag[start..].find('}')?;
81 let guid = &etag[start..start + length];
82 (!guid.is_empty()).then(|| guid.to_owned())
83}
84
85/// Inclusive range of the chunk that starts at `start`; a multiple of 320 KiB long except at the end.
86pub fn chunk_range_at(start: u64, total: u64) -> (u64, u64) {
87 (start, (start + UPLOAD_CHUNK_BYTES).min(total) - 1)
88}
89
90pub fn chunk_ranges(total: u64) -> Vec<(u64, u64)> {
91 let mut ranges = Vec::new();
92 let mut start = 0;
93 while start < total {
94 let range = chunk_range_at(start, total);
95 start = range.1 + 1;
96 ranges.push(range);
97 }
98 ranges
99}
100
101/// First byte the server still wants, from `nextExpectedRanges` (`["1310720-"]`).
102pub fn next_expected_start(body: &Value) -> Option<u64> {
103 let range = body
104 .get("nextExpectedRanges")?
105 .as_array()?
106 .first()?
107 .as_str()?;
108 range.split('-').next()?.parse().ok()
109}
110
111struct SessionGuard {
112 session: Session,
113 url: String,
114 armed: bool,
115}
116
117impl SessionGuard {
118 fn disarm(&mut self) {
119 self.armed = false;
120 }
121}
122
123impl Drop for SessionGuard {
124 fn drop(&mut self) {
125 if !self.armed {
126 return;
127 }
128 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
129 return;
130 };
131 let session = self.session.clone();
132 let request = Request {
133 method: Method::Delete,
134 anonymous: true,
135 ..Request::get(std::mem::take(&mut self.url))
136 };
137 runtime.spawn(async move {
138 let _ = session.send(request, &Scope::graph(FILES_SCOPE)).await;
139 });
140 }
141}
142
143pub fn content_range(start: u64, end: u64, total: u64) -> String {
144 format!("bytes {start}-{end}/{total}")
145}
146
147pub fn percent_done(sent: u64, total: u64) -> u8 {
148 if total == 0 {
149 return 100;
150 }
151 (sent.min(total) * 100 / total) as u8
152}
153
154impl Graph {
155 pub async fn channel_files_folder(
156 &self,
157 team_id: &str,
158 channel_id: &str,
159 ) -> Result<DriveFolder> {
160 let answer = self
161 .session()
162 .request(
163 Method::Get,
164 &urls::channel_files_folder(team_id, channel_id),
165 &Scope::graph(FILES_SCOPE),
166 None,
167 )
168 .await?;
169 let item: DriveItem = serde_json::from_value(answer.body)?;
170 let drive_id = item
171 .drive_id()
172 .ok_or_else(|| Error::Upload("the channel folder has no drive".into()))?;
173 Ok(DriveFolder {
174 drive_id,
175 item_id: item.id,
176 })
177 }
178
179 pub async fn upload_file(
180 &self,
181 destination: &UploadDestination,
182 file_name: &str,
183 bytes: &[u8],
184 progress: &(dyn Fn(u8) + Send + Sync),
185 ) -> Result<UploadedFile> {
186 if bytes.is_empty() {
187 return Err(Error::EmptyUpload);
188 }
189 let scope = Scope::graph(FILES_SCOPE);
190 let session_url = match destination {
191 UploadDestination::ChatFiles => urls::chat_files_upload_session(file_name),
192 UploadDestination::Folder(folder) => {
193 urls::folder_upload_session(&folder.drive_id, &folder.item_id, file_name)
194 }
195 };
196 let created = self
197 .session()
198 .request(
199 Method::Post,
200 &session_url,
201 &scope,
202 Some(json!({"item": {"@microsoft.graph.conflictBehavior": "rename"}})),
203 )
204 .await?;
205 let upload_url = created
206 .body
207 .get("uploadUrl")
208 .and_then(Value::as_str)
209 .ok_or_else(|| Error::Upload("no upload URL in the answer".into()))?
210 .to_owned();
211 let mut guard = SessionGuard {
212 session: self.session().clone(),
213 url: upload_url.clone(),
214 armed: true,
215 };
216 let total = bytes.len() as u64;
217 progress(0);
218 let mut offset = 0;
219 let mut failures = 0;
220 while offset < total {
221 let (start, end) = chunk_range_at(offset, total);
222 let request = Request::anonymous_bytes(
223 Method::Put,
224 upload_url.clone(),
225 vec![("Content-Range".to_owned(), content_range(start, end, total))],
226 STANDARD.encode(&bytes[start as usize..=end as usize]),
227 );
228 match self.session().send(request, &scope).await {
229 Ok(answer) if matches!(answer.status, 200 | 201) => {
230 guard.disarm();
231 progress(100);
232 return finished_item(answer.body);
233 }
234 Ok(_) => {
235 failures = 0;
236 offset = end + 1;
237 progress(percent_done(offset, total).min(99));
238 }
239 Err(error) => {
240 failures += 1;
241 if failures > MAX_CHUNK_RETRIES {
242 return Err(error.into());
243 }
244 if let Some(next) = self.resume_offset(&upload_url, &scope).await {
245 offset = next.min(total);
246 }
247 }
248 }
249 }
250 Err(Error::Upload(
251 "the last chunk did not finish the upload".into(),
252 ))
253 }
254
255 async fn resume_offset(&self, upload_url: &str, scope: &Scope) -> Option<u64> {
256 let request = Request {
257 anonymous: true,
258 ..Request::get(upload_url)
259 };
260 let answer = self.session().send(request, scope).await.ok()?;
261 next_expected_start(&answer.body)
262 }
263
264 pub async fn delete_drive_item(&self, drive_id: &str, item_id: &str) -> Result<()> {
265 self.session()
266 .request(
267 Method::Delete,
268 &urls::drive_item(drive_id, item_id),
269 &Scope::graph(FILES_SCOPE),
270 None,
271 )
272 .await?;
273 Ok(())
274 }
275
276 pub async fn share_item(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> {
277 if user_ids.is_empty() {
278 return Ok(());
279 }
280 let recipients: Vec<Value> = user_ids
281 .iter()
282 .map(|user_id| json!({"objectId": user_id}))
283 .collect();
284 self.session()
285 .request(
286 Method::Post,
287 &urls::drive_item_invite(&file.drive_id, &file.item_id),
288 &Scope::graph(FILES_SCOPE),
289 Some(json!({
290 "recipients": recipients,
291 "roles": ["read"],
292 "requireSignIn": true,
293 "sendInvitation": false,
294 })),
295 )
296 .await?;
297 Ok(())
298 }
299}
300
301fn finished_item(body: Value) -> Result<UploadedFile> {
302 let item: DriveItem = serde_json::from_value(body)?;
303 let drive_id = item
304 .drive_id()
305 .ok_or_else(|| Error::Upload("the uploaded file has no drive".into()))?;
306 Ok(UploadedFile {
307 drive_id,
308 item_id: item.id,
309 name: item.name,
310 web_url: item.web_url,
311 web_dav_url: item.web_dav_url,
312 etag: item.e_tag,
313 })
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 #[test]
321 fn etag_guid_is_the_part_between_braces() {
322 assert_eq!(
323 etag_guid("\"{4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F},3\""),
324 Some("4F2A9C1E-0B7D-4C3A-9E55-1A2B3C4D5E6F".to_owned())
325 );
326 assert_eq!(etag_guid("\"abc,3\""), None);
327 assert_eq!(etag_guid("{}"), None);
328 assert_eq!(etag_guid(""), None);
329 }
330
331 #[test]
332 fn small_files_are_one_chunk() {
333 assert_eq!(chunk_ranges(1), vec![(0, 0)]);
334 assert_eq!(
335 chunk_ranges(UPLOAD_CHUNK_BYTES),
336 vec![(0, UPLOAD_CHUNK_BYTES - 1)]
337 );
338 assert!(chunk_ranges(0).is_empty());
339 }
340
341 #[test]
342 fn chunks_are_multiples_of_320_kib_except_the_last() {
343 let total = 2 * UPLOAD_CHUNK_BYTES + 12_345;
344 let ranges = chunk_ranges(total);
345 assert_eq!(ranges.len(), 3);
346 for (start, end) in &ranges[..2] {
347 assert_eq!((end + 1 - start) % CHUNK_UNIT_BYTES, 0);
348 assert_eq!(end + 1 - start, UPLOAD_CHUNK_BYTES);
349 }
350 let (last_start, last_end) = ranges[2];
351 assert_eq!(last_end + 1 - last_start, 12_345);
352 assert_eq!(last_end + 1, total);
353 }
354
355 #[test]
356 fn chunks_are_contiguous_and_cover_the_file() {
357 let total = 3 * UPLOAD_CHUNK_BYTES - 7;
358 let ranges = chunk_ranges(total);
359 assert_eq!(ranges[0].0, 0);
360 for pair in ranges.windows(2) {
361 assert_eq!(pair[0].1 + 1, pair[1].0);
362 }
363 assert_eq!(ranges.last().unwrap().1 + 1, total);
364 }
365
366 #[test]
367 fn resume_offset_comes_from_the_next_expected_range() {
368 assert_eq!(
369 next_expected_start(&json!({"nextExpectedRanges": ["1310720-"]})),
370 Some(1_310_720)
371 );
372 assert_eq!(
373 next_expected_start(&json!({"nextExpectedRanges": ["26-100", "200-"]})),
374 Some(26)
375 );
376 assert_eq!(
377 next_expected_start(&json!({"nextExpectedRanges": []})),
378 None
379 );
380 assert_eq!(next_expected_start(&json!({})), None);
381 }
382
383 #[test]
384 fn chunk_size_stays_well_under_the_evaluate_timeout() {
385 assert_eq!(UPLOAD_CHUNK_BYTES, 1_310_720);
386 assert_eq!(chunk_range_at(1_310_720, 2_000_000), (1_310_720, 1_999_999));
387 }
388
389 #[test]
390 fn content_range_header_matches_graph() {
391 assert_eq!(
392 content_range(0, 5_242_879, 6_000_000),
393 "bytes 0-5242879/6000000"
394 );
395 }
396
397 #[test]
398 fn progress_is_a_percentage() {
399 assert_eq!(percent_done(0, 200), 0);
400 assert_eq!(percent_done(50, 200), 25);
401 assert_eq!(percent_done(200, 200), 100);
402 assert_eq!(percent_done(5, 0), 100);
403 }
404
405 #[test]
406 fn uploaded_file_reference_prefers_the_webdav_url() {
407 let mut file = UploadedFile {
408 drive_id: "d".into(),
409 item_id: "i".into(),
410 name: "a.pdf".into(),
411 web_url: "https://x/web".into(),
412 web_dav_url: Some("https://x/dav".into()),
413 etag: "\"{AAAA},1\"".into(),
414 };
415 let reference = file.reference().unwrap();
416 assert_eq!(reference.attachment_id, "AAAA");
417 assert_eq!(reference.content_url, "https://x/dav");
418 file.web_dav_url = None;
419 assert_eq!(file.reference().unwrap().content_url, "https://x/web");
420 file.etag = "nope".into();
421 assert!(file.reference().is_none());
422 }
423
424 #[test]
425 fn drive_item_answer_parses() {
426 let item = finished_item(json!({
427 "id": "01F", "name": "a.pdf", "webUrl": "https://x/web",
428 "webDavUrl": "https://x/dav", "eTag": "\"{AAAA},2\"",
429 "parentReference": {"driveId": "b!d"}
430 }))
431 .unwrap();
432 assert_eq!(item.drive_id, "b!d");
433 assert_eq!(item.item_id, "01F");
434 assert_eq!(item.web_dav_url.as_deref(), Some("https://x/dav"));
435 }
436}
crates/graph/src/lib.rs +8 −1
@@ -1,6 +1,7 @@
1 1 mod client;
2 2 mod content;
3 3 mod error;
4 mod files;
4 5 mod models;
5 6 mod outgoing;
6 7 mod page;
@@ -11,11 +12,17 @@ mod writes;
11 12
12 13 pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
13 14 pub use error::{Error, Result};
15 pub use files::{
16 DriveFolder, UPLOAD_CHUNK_BYTES, UploadDestination, UploadedFile, chunk_range_at, chunk_ranges,
17 etag_guid, next_expected_start,
18 };
14 19 pub use models::{
15 20 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
16 21 Presence, Reaction, Sender, Team, User,
17 22 };
18 pub use outgoing::{MentionTarget, OutgoingMention};
23 pub use outgoing::{
24 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
25 };
19 26 pub use page::Page;
20 27 pub use people::MAX_PRESENCE_IDS;
21 28 pub use target::MessageTarget;
@@ -1,6 +1,7 @@
1mod client;
1mod client;
2mod content;
2mod content;
3mod error;
3mod error;
4mod files;
4mod models;
5mod models;
5mod outgoing;
6mod outgoing;
6mod page;
7mod page;
@@ -11,11 +12,17 @@ mod writes;
11
12
12pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
13pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
13pub use error::{Error, Result};
14pub use error::{Error, Result};
15pub use files::{
16 DriveFolder, UPLOAD_CHUNK_BYTES, UploadDestination, UploadedFile, chunk_range_at, chunk_ranges,
17 etag_guid, next_expected_start,
18};
14pub use models::{
19pub use models::{
15 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
20 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
16 Presence, Reaction, Sender, Team, User,
21 Presence, Reaction, Sender, Team, User,
17};
22};
18pub use outgoing::{MentionTarget, OutgoingMention};
23pub use outgoing::{
24 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
25};
19pub use page::Page;
26pub use page::Page;
20pub use people::MAX_PRESENCE_IDS;
27pub use people::MAX_PRESENCE_IDS;
21pub use target::MessageTarget;
28pub use target::MessageTarget;
crates/graph/src/outgoing.rs +225 −3
@@ -1,3 +1,7 @@
1 use std::sync::Arc;
2
3 use base64::Engine as _;
4 use base64::engine::general_purpose::STANDARD;
1 5 use serde_json::{Value, json};
2 6
3 7 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -32,11 +36,114 @@ impl OutgoingMention {
32 36 }
33 37 }
34 38
35 pub(crate) fn message_body(html: &str, mentions: &[OutgoingMention]) -> Value {
36 let mut body = json!({"body": {"contentType": "html", "content": html}});
39 #[derive(Debug, Clone, PartialEq, Eq)]
40 pub struct HostedImage {
41 pub content_type: String,
42 pub bytes: Arc<Vec<u8>>,
43 }
44
45 /// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
46 #[derive(Debug, Clone, PartialEq, Eq)]
47 pub struct FileReference {
48 pub attachment_id: String,
49 pub content_url: String,
50 pub name: String,
51 }
52
53 /// A quote or card attachment of an edited message, sent back unchanged.
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub struct KeptAttachment {
56 pub id: String,
57 pub content_type: Option<String>,
58 pub content: Option<String>,
59 pub content_url: Option<String>,
60 pub name: Option<String>,
61 }
62
63 #[derive(Debug, Clone, Default, PartialEq, Eq)]
64 pub struct MessageExtras {
65 pub images: Vec<HostedImage>,
66 pub files: Vec<FileReference>,
67 pub kept: Vec<KeptAttachment>,
68 }
69
70 impl MessageExtras {
71 pub fn is_empty(&self) -> bool {
72 self.images.is_empty() && self.files.is_empty() && self.kept.is_empty()
73 }
74
75 pub fn kept_html(&self) -> String {
76 self.kept
77 .iter()
78 .map(|kept| format!("<attachment id=\"{}\"></attachment>", kept.id))
79 .collect()
80 }
81
82 pub fn files_html(&self) -> String {
83 self.files
84 .iter()
85 .map(|file| format!("<attachment id=\"{}\"></attachment>", file.attachment_id))
86 .collect()
87 }
88 }
89
90 fn extras_html(html: &str, extras: &MessageExtras) -> String {
91 let mut content = extras.kept_html();
92 content.push_str(html);
93 for index in 1..=extras.images.len() {
94 content.push_str(&format!(
95 "<p><img src=\"../hostedContents/{index}/$value\"></p>"
96 ));
97 }
98 content.push_str(&extras.files_html());
99 content
100 }
101
102 pub(crate) fn message_body(
103 html: &str,
104 mentions: &[OutgoingMention],
105 extras: &MessageExtras,
106 ) -> Value {
107 let mut body = json!({"body": {"contentType": "html", "content": extras_html(html, extras)}});
37 108 if !mentions.is_empty() {
38 109 body["mentions"] = Value::Array(mentions.iter().map(OutgoingMention::to_json).collect());
39 110 }
111 if !extras.images.is_empty() {
112 body["hostedContents"] = Value::Array(
113 extras
114 .images
115 .iter()
116 .enumerate()
117 .map(|(index, image)| {
118 json!({
119 "@microsoft.graph.temporaryId": (index + 1).to_string(),
120 "contentBytes": STANDARD.encode(image.bytes.as_slice()),
121 "contentType": image.content_type,
122 })
123 })
124 .collect(),
125 );
126 }
127 if !extras.files.is_empty() || !extras.kept.is_empty() {
128 let kept = extras.kept.iter().map(|kept| {
129 json!({
130 "id": kept.id,
131 "contentType": kept.content_type,
132 "content": kept.content,
133 "contentUrl": kept.content_url,
134 "name": kept.name,
135 })
136 });
137 let files = extras.files.iter().map(|file| {
138 json!({
139 "id": file.attachment_id,
140 "contentType": "reference",
141 "contentUrl": file.content_url,
142 "name": file.name,
143 })
144 });
145 body["attachments"] = Value::Array(kept.chain(files).collect());
146 }
40 147 body
41 148 }
42 149
@@ -99,7 +206,12 @@ mod tests {
99 206
100 207 #[test]
101 208 fn body_without_mentions_has_no_mentions_key() {
102 assert!(message_body("<p>x</p>", &[]).get("mentions").is_none());
209 let none = MessageExtras::default();
210 assert!(
211 message_body("<p>x</p>", &[], &none)
212 .get("mentions")
213 .is_none()
214 );
103 215 let with = message_body(
104 216 "<at id=\"0\">A</at>",
105 217 &[mention(
@@ -109,7 +221,117 @@ mod tests {
109 221 user_id: "u".into(),
110 222 },
111 223 )],
224 &none,
112 225 );
113 226 assert_eq!(with["mentions"].as_array().unwrap().len(), 1);
114 227 }
228
229 fn image(content_type: &str, bytes: &[u8]) -> HostedImage {
230 HostedImage {
231 content_type: content_type.to_owned(),
232 bytes: Arc::new(bytes.to_vec()),
233 }
234 }
235
236 #[test]
237 fn plain_body_has_no_hosted_contents_or_attachments() {
238 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
239 assert_eq!(
240 body,
241 json!({"body": {"contentType": "html", "content": "<p>x</p>"}})
242 );
243 }
244
245 #[test]
246 fn images_go_after_the_text_with_matching_temporary_ids() {
247 let extras = MessageExtras {
248 kept: Vec::new(),
249 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
250 files: Vec::new(),
251 };
252 let body = message_body("<p>hi</p>", &[], &extras);
253 assert_eq!(
254 body["body"]["content"],
255 "<p>hi</p><p><img src=\"../hostedContents/1/$value\"></p><p><img src=\"../hostedContents/2/$value\"></p>"
256 );
257 assert_eq!(
258 body["hostedContents"],
259 json!([
260 {"@microsoft.graph.temporaryId": "1", "contentBytes": "AQID", "contentType": "image/png"},
261 {"@microsoft.graph.temporaryId": "2", "contentBytes": "BA==", "contentType": "image/jpeg"},
262 ])
263 );
264 assert!(body.get("attachments").is_none());
265 }
266
267 #[test]
268 fn an_edit_keeps_the_original_files_and_image_elements() {
269 let extras = MessageExtras {
270 kept: Vec::new(),
271 images: Vec::new(),
272 files: vec![FileReference {
273 attachment_id: "G1".into(),
274 content_url: "https://x/a.pdf".into(),
275 name: "a.pdf".into(),
276 }],
277 };
278 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
279 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
280 assert_eq!(
281 body["body"]["content"],
282 format!("<p>new</p>{original_image}<attachment id=\"G1\"></attachment>")
283 );
284 assert_eq!(body["attachments"][0]["id"], "G1");
285 assert!(body.get("hostedContents").is_none());
286 }
287
288 #[test]
289 fn an_edit_sends_the_quote_back_unchanged_before_the_text() {
290 let extras = MessageExtras {
291 images: Vec::new(),
292 files: Vec::new(),
293 kept: vec![KeptAttachment {
294 id: "Q1".into(),
295 content_type: Some("messageReference".into()),
296 content: Some("{\"messageId\":\"Q1\"}".into()),
297 content_url: None,
298 name: None,
299 }],
300 };
301 let body = message_body("<p>new</p>", &[], &extras);
302 assert_eq!(
303 body["body"]["content"],
304 "<attachment id=\"Q1\"></attachment><p>new</p>"
305 );
306 assert_eq!(body["attachments"][0]["contentType"], "messageReference");
307 assert_eq!(body["attachments"][0]["content"], "{\"messageId\":\"Q1\"}");
308 }
309
310 #[test]
311 fn files_become_reference_attachments_with_a_tag_in_the_html() {
312 let extras = MessageExtras {
313 kept: Vec::new(),
314 images: Vec::new(),
315 files: vec![FileReference {
316 attachment_id: "AAAA-1111".into(),
317 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
318 name: "Plan.docx".into(),
319 }],
320 };
321 let body = message_body("", &[], &extras);
322 assert_eq!(
323 body["body"]["content"],
324 "<attachment id=\"AAAA-1111\"></attachment>"
325 );
326 assert_eq!(
327 body["attachments"],
328 json!([{
329 "id": "AAAA-1111",
330 "contentType": "reference",
331 "contentUrl": "https://contoso.sharepoint.com/Plan.docx",
332 "name": "Plan.docx",
333 }])
334 );
335 assert!(body.get("hostedContents").is_none());
336 }
115 337 }
@@ -1,3 +1,7 @@
1use std::sync::Arc;
2
3use base64::Engine as _;
4use base64::engine::general_purpose::STANDARD;
1use serde_json::{Value, json};
5use serde_json::{Value, json};
2
6
3#[derive(Debug, Clone, PartialEq, Eq)]
7#[derive(Debug, Clone, PartialEq, Eq)]
@@ -32,11 +36,114 @@ impl OutgoingMention {
32 }
36 }
33}
37}
34
38
35pub(crate) fn message_body(html: &str, mentions: &[OutgoingMention]) -> Value {
39#[derive(Debug, Clone, PartialEq, Eq)]
36 let mut body = json!({"body": {"contentType": "html", "content": html}});
40pub struct HostedImage {
41 pub content_type: String,
42 pub bytes: Arc<Vec<u8>>,
43}
44
45/// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct FileReference {
48 pub attachment_id: String,
49 pub content_url: String,
50 pub name: String,
51}
52
53/// A quote or card attachment of an edited message, sent back unchanged.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct KeptAttachment {
56 pub id: String,
57 pub content_type: Option<String>,
58 pub content: Option<String>,
59 pub content_url: Option<String>,
60 pub name: Option<String>,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct MessageExtras {
65 pub images: Vec<HostedImage>,
66 pub files: Vec<FileReference>,
67 pub kept: Vec<KeptAttachment>,
68}
69
70impl MessageExtras {
71 pub fn is_empty(&self) -> bool {
72 self.images.is_empty() && self.files.is_empty() && self.kept.is_empty()
73 }
74
75 pub fn kept_html(&self) -> String {
76 self.kept
77 .iter()
78 .map(|kept| format!("<attachment id=\"{}\"></attachment>", kept.id))
79 .collect()
80 }
81
82 pub fn files_html(&self) -> String {
83 self.files
84 .iter()
85 .map(|file| format!("<attachment id=\"{}\"></attachment>", file.attachment_id))
86 .collect()
87 }
88}
89
90fn extras_html(html: &str, extras: &MessageExtras) -> String {
91 let mut content = extras.kept_html();
92 content.push_str(html);
93 for index in 1..=extras.images.len() {
94 content.push_str(&format!(
95 "<p><img src=\"../hostedContents/{index}/$value\"></p>"
96 ));
97 }
98 content.push_str(&extras.files_html());
99 content
100}
101
102pub(crate) fn message_body(
103 html: &str,
104 mentions: &[OutgoingMention],
105 extras: &MessageExtras,
106) -> Value {
107 let mut body = json!({"body": {"contentType": "html", "content": extras_html(html, extras)}});
37 if !mentions.is_empty() {
108 if !mentions.is_empty() {
38 body["mentions"] = Value::Array(mentions.iter().map(OutgoingMention::to_json).collect());
109 body["mentions"] = Value::Array(mentions.iter().map(OutgoingMention::to_json).collect());
39 }
110 }
111 if !extras.images.is_empty() {
112 body["hostedContents"] = Value::Array(
113 extras
114 .images
115 .iter()
116 .enumerate()
117 .map(|(index, image)| {
118 json!({
119 "@microsoft.graph.temporaryId": (index + 1).to_string(),
120 "contentBytes": STANDARD.encode(image.bytes.as_slice()),
121 "contentType": image.content_type,
122 })
123 })
124 .collect(),
125 );
126 }
127 if !extras.files.is_empty() || !extras.kept.is_empty() {
128 let kept = extras.kept.iter().map(|kept| {
129 json!({
130 "id": kept.id,
131 "contentType": kept.content_type,
132 "content": kept.content,
133 "contentUrl": kept.content_url,
134 "name": kept.name,
135 })
136 });
137 let files = extras.files.iter().map(|file| {
138 json!({
139 "id": file.attachment_id,
140 "contentType": "reference",
141 "contentUrl": file.content_url,
142 "name": file.name,
143 })
144 });
145 body["attachments"] = Value::Array(kept.chain(files).collect());
146 }
40 body
147 body
41}
148}
42
149
@@ -99,7 +206,12 @@ mod tests {
99
206
100 #[test]
207 #[test]
101 fn body_without_mentions_has_no_mentions_key() {
208 fn body_without_mentions_has_no_mentions_key() {
102 assert!(message_body("<p>x</p>", &[]).get("mentions").is_none());
209 let none = MessageExtras::default();
210 assert!(
211 message_body("<p>x</p>", &[], &none)
212 .get("mentions")
213 .is_none()
214 );
103 let with = message_body(
215 let with = message_body(
104 "<at id=\"0\">A</at>",
216 "<at id=\"0\">A</at>",
105 &[mention(
217 &[mention(
@@ -109,7 +221,117 @@ mod tests {
109 user_id: "u".into(),
221 user_id: "u".into(),
110 },
222 },
111 )],
223 )],
224 &none,
112 );
225 );
113 assert_eq!(with["mentions"].as_array().unwrap().len(), 1);
226 assert_eq!(with["mentions"].as_array().unwrap().len(), 1);
114 }
227 }
228
229 fn image(content_type: &str, bytes: &[u8]) -> HostedImage {
230 HostedImage {
231 content_type: content_type.to_owned(),
232 bytes: Arc::new(bytes.to_vec()),
233 }
234 }
235
236 #[test]
237 fn plain_body_has_no_hosted_contents_or_attachments() {
238 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
239 assert_eq!(
240 body,
241 json!({"body": {"contentType": "html", "content": "<p>x</p>"}})
242 );
243 }
244
245 #[test]
246 fn images_go_after_the_text_with_matching_temporary_ids() {
247 let extras = MessageExtras {
248 kept: Vec::new(),
249 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
250 files: Vec::new(),
251 };
252 let body = message_body("<p>hi</p>", &[], &extras);
253 assert_eq!(
254 body["body"]["content"],
255 "<p>hi</p><p><img src=\"../hostedContents/1/$value\"></p><p><img src=\"../hostedContents/2/$value\"></p>"
256 );
257 assert_eq!(
258 body["hostedContents"],
259 json!([
260 {"@microsoft.graph.temporaryId": "1", "contentBytes": "AQID", "contentType": "image/png"},
261 {"@microsoft.graph.temporaryId": "2", "contentBytes": "BA==", "contentType": "image/jpeg"},
262 ])
263 );
264 assert!(body.get("attachments").is_none());
265 }
266
267 #[test]
268 fn an_edit_keeps_the_original_files_and_image_elements() {
269 let extras = MessageExtras {
270 kept: Vec::new(),
271 images: Vec::new(),
272 files: vec![FileReference {
273 attachment_id: "G1".into(),
274 content_url: "https://x/a.pdf".into(),
275 name: "a.pdf".into(),
276 }],
277 };
278 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
279 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
280 assert_eq!(
281 body["body"]["content"],
282 format!("<p>new</p>{original_image}<attachment id=\"G1\"></attachment>")
283 );
284 assert_eq!(body["attachments"][0]["id"], "G1");
285 assert!(body.get("hostedContents").is_none());
286 }
287
288 #[test]
289 fn an_edit_sends_the_quote_back_unchanged_before_the_text() {
290 let extras = MessageExtras {
291 images: Vec::new(),
292 files: Vec::new(),
293 kept: vec![KeptAttachment {
294 id: "Q1".into(),
295 content_type: Some("messageReference".into()),
296 content: Some("{\"messageId\":\"Q1\"}".into()),
297 content_url: None,
298 name: None,
299 }],
300 };
301 let body = message_body("<p>new</p>", &[], &extras);
302 assert_eq!(
303 body["body"]["content"],
304 "<attachment id=\"Q1\"></attachment><p>new</p>"
305 );
306 assert_eq!(body["attachments"][0]["contentType"], "messageReference");
307 assert_eq!(body["attachments"][0]["content"], "{\"messageId\":\"Q1\"}");
308 }
309
310 #[test]
311 fn files_become_reference_attachments_with_a_tag_in_the_html() {
312 let extras = MessageExtras {
313 kept: Vec::new(),
314 images: Vec::new(),
315 files: vec![FileReference {
316 attachment_id: "AAAA-1111".into(),
317 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
318 name: "Plan.docx".into(),
319 }],
320 };
321 let body = message_body("", &[], &extras);
322 assert_eq!(
323 body["body"]["content"],
324 "<attachment id=\"AAAA-1111\"></attachment>"
325 );
326 assert_eq!(
327 body["attachments"],
328 json!([{
329 "id": "AAAA-1111",
330 "contentType": "reference",
331 "contentUrl": "https://contoso.sharepoint.com/Plan.docx",
332 "name": "Plan.docx",
333 }])
334 );
335 assert!(body.get("hostedContents").is_none());
336 }
115}
337}
crates/graph/src/urls.rs +55 −0
@@ -88,6 +88,49 @@ pub fn reply_with_quote(chat_id: &str) -> String {
88 88 )
89 89 }
90 90
91 pub const CHAT_FILES_FOLDER: &str = "Microsoft Teams Chat Files";
92
93 pub fn chat_files_upload_session(file_name: &str) -> String {
94 format!(
95 "{GRAPH}/v1.0/me/drive/root:/{}/{}:/createUploadSession",
96 segment(CHAT_FILES_FOLDER),
97 segment(file_name)
98 )
99 }
100
101 pub fn folder_upload_session(drive_id: &str, folder_id: &str, file_name: &str) -> String {
102 format!(
103 "{GRAPH}/v1.0/drives/{}/items/{}:/{}:/createUploadSession",
104 segment(drive_id),
105 segment(folder_id),
106 segment(file_name)
107 )
108 }
109
110 pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {
111 format!(
112 "{GRAPH}/v1.0/teams/{}/channels/{}/filesFolder",
113 segment(team_id),
114 segment(channel_id)
115 )
116 }
117
118 pub fn drive_item(drive_id: &str, item_id: &str) -> String {
119 format!(
120 "{GRAPH}/v1.0/drives/{}/items/{}",
121 segment(drive_id),
122 segment(item_id)
123 )
124 }
125
126 pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
127 format!(
128 "{GRAPH}/v1.0/drives/{}/items/{}/invite",
129 segment(drive_id),
130 segment(item_id)
131 )
132 }
133
91 134 pub fn mark_chat_read(chat_id: &str) -> String {
92 135 format!(
93 136 "{GRAPH}/v1.0/chats/{}/markChatReadForUser",
@@ -205,6 +248,18 @@ mod tests {
205 248 );
206 249 }
207 250
251 #[test]
252 fn upload_session_urls_encode_the_file_name() {
253 assert_eq!(
254 chat_files_upload_session("Q3 plan (1).docx"),
255 "https://graph.microsoft.com/v1.0/me/drive/root:/Microsoft%20Teams%20Chat%20Files/Q3%20plan%20%281%29.docx:/createUploadSession"
256 );
257 assert_eq!(
258 folder_upload_session("b!d", "01F", "a.pdf"),
259 "https://graph.microsoft.com/v1.0/drives/b%21d/items/01F:/a.pdf:/createUploadSession"
260 );
261 }
262
208 263 #[test]
209 264 fn chats_url_orders_newest_first() {
210 265 let url = chats(50);
@@ -88,6 +88,49 @@ pub fn reply_with_quote(chat_id: &str) -> String {
88 )
88 )
89}
89}
90
90
91pub const CHAT_FILES_FOLDER: &str = "Microsoft Teams Chat Files";
92
93pub fn chat_files_upload_session(file_name: &str) -> String {
94 format!(
95 "{GRAPH}/v1.0/me/drive/root:/{}/{}:/createUploadSession",
96 segment(CHAT_FILES_FOLDER),
97 segment(file_name)
98 )
99}
100
101pub fn folder_upload_session(drive_id: &str, folder_id: &str, file_name: &str) -> String {
102 format!(
103 "{GRAPH}/v1.0/drives/{}/items/{}:/{}:/createUploadSession",
104 segment(drive_id),
105 segment(folder_id),
106 segment(file_name)
107 )
108}
109
110pub fn channel_files_folder(team_id: &str, channel_id: &str) -> String {
111 format!(
112 "{GRAPH}/v1.0/teams/{}/channels/{}/filesFolder",
113 segment(team_id),
114 segment(channel_id)
115 )
116}
117
118pub fn drive_item(drive_id: &str, item_id: &str) -> String {
119 format!(
120 "{GRAPH}/v1.0/drives/{}/items/{}",
121 segment(drive_id),
122 segment(item_id)
123 )
124}
125
126pub fn drive_item_invite(drive_id: &str, item_id: &str) -> String {
127 format!(
128 "{GRAPH}/v1.0/drives/{}/items/{}/invite",
129 segment(drive_id),
130 segment(item_id)
131 )
132}
133
91pub fn mark_chat_read(chat_id: &str) -> String {
134pub fn mark_chat_read(chat_id: &str) -> String {
92 format!(
135 format!(
93 "{GRAPH}/v1.0/chats/{}/markChatReadForUser",
136 "{GRAPH}/v1.0/chats/{}/markChatReadForUser",
@@ -205,6 +248,18 @@ mod tests {
205 );
248 );
206 }
249 }
207
250
251 #[test]
252 fn upload_session_urls_encode_the_file_name() {
253 assert_eq!(
254 chat_files_upload_session("Q3 plan (1).docx"),
255 "https://graph.microsoft.com/v1.0/me/drive/root:/Microsoft%20Teams%20Chat%20Files/Q3%20plan%20%281%29.docx:/createUploadSession"
256 );
257 assert_eq!(
258 folder_upload_session("b!d", "01F", "a.pdf"),
259 "https://graph.microsoft.com/v1.0/drives/b%21d/items/01F:/a.pdf:/createUploadSession"
260 );
261 }
262
208 #[test]
263 #[test]
209 fn chats_url_orders_newest_first() {
264 fn chats_url_orders_newest_first() {
210 let url = chats(50);
265 let url = chats(50);
crates/graph/src/writes.rs +11 −6
@@ -4,7 +4,7 @@ use session::{GRAPH, Method, Scope};
4 4 use crate::client::Graph;
5 5 use crate::error::Result;
6 6 use crate::models::{Chat, Message};
7 use crate::outgoing::{OutgoingMention, message_body};
7 use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
8 8 use crate::target::MessageTarget;
9 9 use crate::urls;
10 10
@@ -22,12 +22,13 @@ impl Graph {
22 22 chat_id: &str,
23 23 html: &str,
24 24 mentions: &[OutgoingMention],
25 extras: &MessageExtras,
25 26 ) -> Result<Message> {
26 27 self.write_for_message(
27 28 Method::Post,
28 29 &urls::chat_message_collection(chat_id),
29 30 "Chat.ReadWrite",
30 Some(message_body(html, mentions)),
31 Some(message_body(html, mentions, extras)),
31 32 )
32 33 .await
33 34 }
@@ -39,8 +40,9 @@ impl Graph {
39 40 html: &str,
40 41 subject: Option<&str>,
41 42 mentions: &[OutgoingMention],
43 extras: &MessageExtras,
42 44 ) -> Result<Message> {
43 let mut body = message_body(html, mentions);
45 let mut body = message_body(html, mentions, extras);
44 46 if let Some(subject) = subject.filter(|subject| !subject.is_empty()) {
45 47 body["subject"] = json!(subject);
46 48 }
@@ -60,12 +62,13 @@ impl Graph {
60 62 message_id: &str,
61 63 html: &str,
62 64 mentions: &[OutgoingMention],
65 extras: &MessageExtras,
63 66 ) -> Result<Message> {
64 67 self.write_for_message(
65 68 Method::Post,
66 69 &urls::channel_reply_post(team_id, channel_id, message_id),
67 70 "ChannelMessage.Send",
68 Some(message_body(html, mentions)),
71 Some(message_body(html, mentions, extras)),
69 72 )
70 73 .await
71 74 }
@@ -77,10 +80,11 @@ impl Graph {
77 80 quoted_message_id: &str,
78 81 html: &str,
79 82 mentions: &[OutgoingMention],
83 extras: &MessageExtras,
80 84 ) -> Result<Message> {
81 85 let body = json!({
82 86 "messageIds": [quoted_message_id],
83 "replyMessage": message_body(html, mentions),
87 "replyMessage": message_body(html, mentions, extras),
84 88 });
85 89 self.write_for_message(
86 90 Method::Post,
@@ -132,12 +136,13 @@ impl Graph {
132 136 target: &MessageTarget,
133 137 html: &str,
134 138 mentions: &[OutgoingMention],
139 extras: &MessageExtras,
135 140 ) -> Result<()> {
136 141 self.write(
137 142 Method::Patch,
138 143 &target.url(),
139 144 target.write_scope(),
140 Some(message_body(html, mentions)),
145 Some(message_body(html, mentions, extras)),
141 146 )
142 147 .await
143 148 }
@@ -4,7 +4,7 @@ use session::{GRAPH, Method, Scope};
4use crate::client::Graph;
4use crate::client::Graph;
5use crate::error::Result;
5use crate::error::Result;
6use crate::models::{Chat, Message};
6use crate::models::{Chat, Message};
7use crate::outgoing::{OutgoingMention, message_body};
7use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
8use crate::target::MessageTarget;
8use crate::target::MessageTarget;
9use crate::urls;
9use crate::urls;
10
10
@@ -22,12 +22,13 @@ impl Graph {
22 chat_id: &str,
22 chat_id: &str,
23 html: &str,
23 html: &str,
24 mentions: &[OutgoingMention],
24 mentions: &[OutgoingMention],
25 extras: &MessageExtras,
25 ) -> Result<Message> {
26 ) -> Result<Message> {
26 self.write_for_message(
27 self.write_for_message(
27 Method::Post,
28 Method::Post,
28 &urls::chat_message_collection(chat_id),
29 &urls::chat_message_collection(chat_id),
29 "Chat.ReadWrite",
30 "Chat.ReadWrite",
30 Some(message_body(html, mentions)),
31 Some(message_body(html, mentions, extras)),
31 )
32 )
32 .await
33 .await
33 }
34 }
@@ -39,8 +40,9 @@ impl Graph {
39 html: &str,
40 html: &str,
40 subject: Option<&str>,
41 subject: Option<&str>,
41 mentions: &[OutgoingMention],
42 mentions: &[OutgoingMention],
43 extras: &MessageExtras,
42 ) -> Result<Message> {
44 ) -> Result<Message> {
43 let mut body = message_body(html, mentions);
45 let mut body = message_body(html, mentions, extras);
44 if let Some(subject) = subject.filter(|subject| !subject.is_empty()) {
46 if let Some(subject) = subject.filter(|subject| !subject.is_empty()) {
45 body["subject"] = json!(subject);
47 body["subject"] = json!(subject);
46 }
48 }
@@ -60,12 +62,13 @@ impl Graph {
60 message_id: &str,
62 message_id: &str,
61 html: &str,
63 html: &str,
62 mentions: &[OutgoingMention],
64 mentions: &[OutgoingMention],
65 extras: &MessageExtras,
63 ) -> Result<Message> {
66 ) -> Result<Message> {
64 self.write_for_message(
67 self.write_for_message(
65 Method::Post,
68 Method::Post,
66 &urls::channel_reply_post(team_id, channel_id, message_id),
69 &urls::channel_reply_post(team_id, channel_id, message_id),
67 "ChannelMessage.Send",
70 "ChannelMessage.Send",
68 Some(message_body(html, mentions)),
71 Some(message_body(html, mentions, extras)),
69 )
72 )
70 .await
73 .await
71 }
74 }
@@ -77,10 +80,11 @@ impl Graph {
77 quoted_message_id: &str,
80 quoted_message_id: &str,
78 html: &str,
81 html: &str,
79 mentions: &[OutgoingMention],
82 mentions: &[OutgoingMention],
83 extras: &MessageExtras,
80 ) -> Result<Message> {
84 ) -> Result<Message> {
81 let body = json!({
85 let body = json!({
82 "messageIds": [quoted_message_id],
86 "messageIds": [quoted_message_id],
83 "replyMessage": message_body(html, mentions),
87 "replyMessage": message_body(html, mentions, extras),
84 });
88 });
85 self.write_for_message(
89 self.write_for_message(
86 Method::Post,
90 Method::Post,
@@ -132,12 +136,13 @@ impl Graph {
132 target: &MessageTarget,
136 target: &MessageTarget,
133 html: &str,
137 html: &str,
134 mentions: &[OutgoingMention],
138 mentions: &[OutgoingMention],
139 extras: &MessageExtras,
135 ) -> Result<()> {
140 ) -> Result<()> {
136 self.write(
141 self.write(
137 Method::Patch,
142 Method::Patch,
138 &target.url(),
143 &target.url(),
139 target.write_scope(),
144 target.write_scope(),
140 Some(message_body(html, mentions)),
145 Some(message_body(html, mentions, extras)),
141 )
146 )
142 .await
147 .await
143 }
148 }
crates/session/assets/fetch.js +1 −1
@@ -59,7 +59,7 @@
59 59 try {
60 60 const response = await fetch(request.url, {
61 61 method: request.method,
62 headers: {Authorization: 'Bearer ' + token, ...request.headers},
62 headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},
63 63 body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : request.body,
64 64 });
65 65 if (request.binary && response.ok) {
@@ -59,7 +59,7 @@
59 try {
59 try {
60 const response = await fetch(request.url, {
60 const response = await fetch(request.url, {
61 method: request.method,
61 method: request.method,
62 headers: {Authorization: 'Bearer ' + token, ...request.headers},
62 headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},
63 body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : request.body,
63 body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : request.body,
64 });
64 });
65 if (request.binary && response.ok) {
65 if (request.binary && response.ok) {
crates/session/src/request.rs +39 −0
@@ -29,6 +29,8 @@ pub struct Request {
29 29 pub headers: Vec<(String, String)>,
30 30 pub body: Option<Value>,
31 31 pub binary: bool,
32 pub anonymous: bool,
33 pub body_base64: Option<String>,
32 34 }
33 35
34 36 impl Request {
@@ -47,6 +49,19 @@ impl Request {
47 49 headers: Vec::new(),
48 50 body: None,
49 51 binary: false,
52 anonymous: false,
53 body_base64: None,
54 }
55 }
56
57 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
58 pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
59 Request {
60 method,
61 headers,
62 anonymous: true,
63 body_base64: Some(body_base64),
64 ..Request::get(url)
50 65 }
51 66 }
52 67
@@ -64,6 +79,8 @@ impl Request {
64 79 headers: Vec::new(),
65 80 body: Some(body),
66 81 binary: false,
82 anonymous: false,
83 body_base64: None,
67 84 }
68 85 }
69 86 }
@@ -87,7 +104,10 @@ pub(crate) struct WireRequest<'a> {
87 104 pub url: &'a str,
88 105 pub headers: serde_json::Map<String, Value>,
89 106 pub body: Option<String>,
107 #[serde(rename = "bodyBase64")]
108 pub body_base64: Option<&'a str>,
90 109 pub binary: bool,
110 pub anonymous: bool,
91 111 }
92 112
93 113 impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -105,7 +125,9 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
105 125 url: &request.url,
106 126 headers,
107 127 body: request.body.as_ref().map(Value::to_string),
128 body_base64: request.body_base64.as_deref(),
108 129 binary: request.binary,
130 anonymous: request.anonymous,
109 131 }
110 132 }
111 133 }
@@ -166,6 +188,23 @@ mod tests {
166 188 assert!(!WireRequest::from(&Request::get("u")).binary);
167 189 }
168 190
191 #[test]
192 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
193 let request = Request::anonymous_bytes(
194 Method::Put,
195 "https://upload.example/session",
196 vec![("Content-Range".into(), "bytes 0-2/3".into())],
197 "AQID".into(),
198 );
199 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
200 assert_eq!(wire["method"], "PUT");
201 assert_eq!(wire["anonymous"], true);
202 assert_eq!(wire["bodyBase64"], "AQID");
203 assert_eq!(wire["body"], Value::Null);
204 assert!(wire["headers"].get("Content-Type").is_none());
205 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
206 }
207
169 208 #[test]
170 209 fn get_has_no_body() {
171 210 let request = Request::get("u");
@@ -29,6 +29,8 @@ pub struct Request {
29 pub headers: Vec<(String, String)>,
29 pub headers: Vec<(String, String)>,
30 pub body: Option<Value>,
30 pub body: Option<Value>,
31 pub binary: bool,
31 pub binary: bool,
32 pub anonymous: bool,
33 pub body_base64: Option<String>,
32}
34}
33
35
34impl Request {
36impl Request {
@@ -47,6 +49,19 @@ impl Request {
47 headers: Vec::new(),
49 headers: Vec::new(),
48 body: None,
50 body: None,
49 binary: false,
51 binary: false,
52 anonymous: false,
53 body_base64: None,
54 }
55 }
56
57 /// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
58 pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
59 Request {
60 method,
61 headers,
62 anonymous: true,
63 body_base64: Some(body_base64),
64 ..Request::get(url)
50 }
65 }
51 }
66 }
52
67
@@ -64,6 +79,8 @@ impl Request {
64 headers: Vec::new(),
79 headers: Vec::new(),
65 body: Some(body),
80 body: Some(body),
66 binary: false,
81 binary: false,
82 anonymous: false,
83 body_base64: None,
67 }
84 }
68 }
85 }
69}
86}
@@ -87,7 +104,10 @@ pub(crate) struct WireRequest<'a> {
87 pub url: &'a str,
104 pub url: &'a str,
88 pub headers: serde_json::Map<String, Value>,
105 pub headers: serde_json::Map<String, Value>,
89 pub body: Option<String>,
106 pub body: Option<String>,
107 #[serde(rename = "bodyBase64")]
108 pub body_base64: Option<&'a str>,
90 pub binary: bool,
109 pub binary: bool,
110 pub anonymous: bool,
91}
111}
92
112
93impl<'a> From<&'a Request> for WireRequest<'a> {
113impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -105,7 +125,9 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
105 url: &request.url,
125 url: &request.url,
106 headers,
126 headers,
107 body: request.body.as_ref().map(Value::to_string),
127 body: request.body.as_ref().map(Value::to_string),
128 body_base64: request.body_base64.as_deref(),
108 binary: request.binary,
129 binary: request.binary,
130 anonymous: request.anonymous,
109 }
131 }
110 }
132 }
111}
133}
@@ -166,6 +188,23 @@ mod tests {
166 assert!(!WireRequest::from(&Request::get("u")).binary);
188 assert!(!WireRequest::from(&Request::get("u")).binary);
167 }
189 }
168
190
191 #[test]
192 fn anonymous_bytes_travel_as_base64_without_a_content_type() {
193 let request = Request::anonymous_bytes(
194 Method::Put,
195 "https://upload.example/session",
196 vec![("Content-Range".into(), "bytes 0-2/3".into())],
197 "AQID".into(),
198 );
199 let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
200 assert_eq!(wire["method"], "PUT");
201 assert_eq!(wire["anonymous"], true);
202 assert_eq!(wire["bodyBase64"], "AQID");
203 assert_eq!(wire["body"], Value::Null);
204 assert!(wire["headers"].get("Content-Type").is_none());
205 assert_eq!(wire["headers"]["Content-Range"], "bytes 0-2/3");
206 }
207
169 #[test]
208 #[test]
170 fn get_has_no_body() {
209 fn get_has_no_body() {
171 let request = Request::get("u");
210 let request = Request::get("u");
crates/session/src/session.rs +7 −4
@@ -83,14 +83,17 @@ impl Session {
83 83 pub async fn request(&self, method: Method, url: &str, scope: &Scope, body: Option<Value>) -> Result<ApiResponse> {
84 84 let request = Request {
85 85 method,
86 url: url.to_owned(),
87 headers: Vec::new(),
88 86 body,
89 binary: false,
87 ..Request::get(url)
90 88 };
89 self.send(request, scope).await
90 }
91
92 pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> {
93 let url = request.url.clone();
91 94 let response = self.batch(&[request], scope).await?.remove(0);
92 95 if response.status >= 400 || response.status == 0 {
93 return Err(Error::api(response.status, url, response.body));
96 return Err(Error::api(response.status, &url, response.body));
94 97 }
95 98 Ok(response)
96 99 }
@@ -83,14 +83,17 @@ impl Session {
83 pub async fn request(&self, method: Method, url: &str, scope: &Scope, body: Option<Value>) -> Result<ApiResponse> {
83 pub async fn request(&self, method: Method, url: &str, scope: &Scope, body: Option<Value>) -> Result<ApiResponse> {
84 let request = Request {
84 let request = Request {
85 method,
85 method,
86 url: url.to_owned(),
87 headers: Vec::new(),
88 body,
86 body,
89 binary: false,
87 ..Request::get(url)
90 };
88 };
89 self.send(request, scope).await
90 }
91
92 pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> {
93 let url = request.url.clone();
91 let response = self.batch(&[request], scope).await?.remove(0);
94 let response = self.batch(&[request], scope).await?.remove(0);
92 if response.status >= 400 || response.status == 0 {
95 if response.status >= 400 || response.status == 0 {
93 return Err(Error::api(response.status, url, response.body));
96 return Err(Error::api(response.status, &url, response.body));
94 }
97 }
95 Ok(response)
98 Ok(response)
96 }
99 }