BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / shared.rs

shared.rs

3e25d31a History
shared.rs 22.5 KiB Download Raw
1use std::path::PathBuf;
2use std::rc::Rc;
3use std::time::Instant;
4
5use gpui_kit::component::input::{InputEvent, InputState};
6use gpui_kit::*;
7use store::ChannelTabRecord;
8use teams_core::{DriveEntry, DriveFolder};
9
10use super::ConversationView;
11use crate::app_state::Selection;
12use crate::channel_files::{
13 Crumb, DownloadSource, LibraryPath, MessageFilter, SharedContent, SharedItem, file_card,
14 library_file, shared_items, sorted_entries,
15};
16use crate::downloads::DownloadKey;
17use crate::notice::short_error;
18use crate::runtime;
19use crate::views::attachment_tray::{display_name, read_attachment};
20use crate::views::channel_tabs::{
21 ChannelPane, TabAction, TabBarActions, fallback_tab_link, render_tab_bar, tab_action,
22};
23use crate::views::shared_tab::{
24 LibraryView, Listing, MessagesView, SharedCommand, SharedRun, SharedScope, render_library,
25 render_messages,
26};
27use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
28
29const LIBRARY_KEY: &str = "library";
30const NEW_FOLDER_PLACEHOLDER: &str = "Folder name";
31const ITEM_SCAN_LIMIT: usize = 5000;
32
33pub(super) struct SharedState {
34 scope: SharedScope,
35 filter: MessageFilter,
36 path: Option<LibraryPath>,
37 listing: Listing,
38 generation: u64,
39 new_folder_open: bool,
40 uploads_running: usize,
41 pub(super) items: Vec<SharedItem>,
42 listed_at: Option<Instant>,
43}
44
45impl Default for SharedState {
46 fn default() -> Self {
47 SharedState {
48 scope: SharedScope::Library,
49 filter: MessageFilter::All,
50 path: None,
51 listing: Listing::Loading,
52 generation: 0,
53 new_folder_open: false,
54 uploads_running: 0,
55 items: Vec::new(),
56 listed_at: None,
57 }
58 }
59}
60
61impl ConversationView {
62 fn channel_id(&self) -> Option<String> {
63 match &self.current.as_ref()?.selection {
64 Selection::Channel(channel_id) => Some(channel_id.clone()),
65 Selection::Chat(_) => None,
66 }
67 }
68
69 pub(super) fn shared_active(&self) -> bool {
70 self.pane == ChannelPane::Shared && self.in_feed()
71 }
72
73 pub(super) fn reset_channel_tabs(&mut self, cx: &mut Context<Self>) {
74 self.pane = ChannelPane::Posts;
75 self.tab_links.clear();
76 self.shared = SharedState {
77 generation: self.shared.generation + 1,
78 ..SharedState::default()
79 };
80 self.reload_channel_tabs(cx);
81 }
82
83 pub(super) fn reload_channel_tabs(&mut self, cx: &mut Context<Self>) {
84 let store = self.app.read(cx).store.clone();
85 let tabs = self
86 .channel_id()
87 .and_then(|channel_id| store.channel_tabs(&channel_id).ok())
88 .unwrap_or_default();
89 if tabs != self.channel_tabs {
90 self.channel_tabs = tabs;
91 cx.notify();
92 }
93 }
94
95 pub(super) fn render_tab_bar(
96 &self,
97 window: &Window,
98 cx: &mut Context<Self>,
99 ) -> Option<AnyElement> {
100 self.channel_id().filter(|_| self.in_feed())?;
101 let available =
102 f32::from(window.viewport_size().width) - RAIL_WIDTH - SIDEBAR_WIDTH - 2. * ISLAND_GAP;
103 let view = cx.weak_entity();
104 let select = Rc::new(move |pane, cx: &mut App| {
105 view.update(cx, |this, cx| this.select_pane(pane, cx)).ok();
106 });
107 let open = {
108 let view = cx.weak_entity();
109 Rc::new(move |index: usize, _: &mut Window, cx: &mut App| {
110 view.update(cx, |this, cx| this.open_channel_tab(index, cx))
111 .ok();
112 })
113 };
114 Some(render_tab_bar(
115 &self.channel_tabs,
116 self.pane,
117 available,
118 &TabBarActions { select, open },
119 ))
120 }
121
122 fn open_channel_tab(&mut self, index: usize, cx: &mut Context<Self>) {
123 let (Some(tab), Some(channel_id)) =
124 (self.channel_tabs.get(index).cloned(), self.channel_id())
125 else {
126 return;
127 };
128 let resolved = self.tab_links.get(&tab.tab_id).map(String::as_str);
129 match tab_action(&tab, resolved) {
130 TabAction::Browser(url) => cx.open_url(&url),
131 TabAction::ResolveLink => self.resolve_tab_link(tab, channel_id, cx),
132 }
133 }
134
135 fn resolve_tab_link(
136 &mut self,
137 tab: ChannelTabRecord,
138 channel_id: String,
139 cx: &mut Context<Self>,
140 ) {
141 let fallback = fallback_tab_link(&tab, &channel_id);
142 let state = self.app.read(cx);
143 let engine = state.engine.clone().filter(|_| !state.mode.demo);
144 let Some(engine) = engine else {
145 cx.open_url(&fallback);
146 return;
147 };
148 let tab_id = tab.tab_id;
149 let lookup = {
150 let tab_id = tab_id.clone();
151 runtime::spawn(async move { engine.channel_tab_web_url(&channel_id, &tab_id).await })
152 };
153 cx.spawn(async move |this, cx| {
154 let link = lookup.await.ok().and_then(Result::ok).flatten();
155 this.update(cx, |this, cx| {
156 let target = match link {
157 Some(link) => {
158 this.tab_links.insert(tab_id, link.clone());
159 link
160 }
161 None => fallback,
162 };
163 cx.open_url(&target);
164 })
165 .ok();
166 })
167 .detach();
168 }
169
170 pub(super) fn select_pane(&mut self, pane: ChannelPane, cx: &mut Context<Self>) {
171 if self.pane == pane {
172 return;
173 }
174 self.pane = pane;
175 if pane == ChannelPane::Shared {
176 self.refresh_shared_items(cx);
177 if self.shared.path.is_none() {
178 self.load_library(cx);
179 }
180 }
181 if pane == ChannelPane::Recap {
182 self.open_recap_pane(cx);
183 }
184 cx.notify();
185 }
186
187 pub(super) fn refresh_shared_items(&mut self, cx: &mut Context<Self>) {
188 let Some(conversation_id) = self.conversation_id() else {
189 return;
190 };
191 let store = self.app.read(cx).store.clone();
192 let records = store
193 .messages(&conversation_id, None, ITEM_SCAN_LIMIT)
194 .unwrap_or_default();
195 self.shared.items = shared_items(&records);
196 }
197
198 fn download_library_entry(
199 &mut self,
200 conversation_id: &str,
201 entry: &DriveEntry,
202 cx: &mut Context<Self>,
203 ) {
204 let source =
205 DownloadSource::Library(library_file(entry, self.shared.listed_at, Instant::now()));
206 self.activate_file(conversation_id, LIBRARY_KEY, file_card(entry), source, cx);
207 }
208
209 fn library_entry(&self, index: usize) -> Option<DriveEntry> {
210 match &self.shared.listing {
211 Listing::Ready(entries) => entries.get(index).cloned(),
212 _ => None,
213 }
214 }
215
216 fn library_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
217 let conversation_id = self.conversation_id().unwrap_or_default();
218 let Listing::Ready(entries) = &self.shared.listing else {
219 return Vec::new();
220 };
221 entries
222 .iter()
223 .map(|entry| {
224 let key = DownloadKey::new(&conversation_id, LIBRARY_KEY, &entry.web_url);
225 self.downloads.state(&key).cloned()
226 })
227 .collect()
228 }
229
230 pub(super) fn item_download_states(&self) -> Vec<Option<crate::downloads::DownloadState>> {
231 let conversation_id = self.conversation_id().unwrap_or_default();
232 self.shared
233 .items
234 .iter()
235 .map(|item| match &item.content {
236 SharedContent::File(card) => {
237 let key = DownloadKey::new(&conversation_id, &item.message_id, &card.open_url);
238 self.downloads.state(&key).cloned()
239 }
240 SharedContent::Link(_) => None,
241 })
242 .collect()
243 }
244
245 pub(super) fn render_shared(&self, cx: &mut Context<Self>) -> AnyElement {
246 let view = cx.weak_entity();
247 let run: SharedRun = Rc::new(move |command, window, cx| {
248 view.update(cx, |this, cx| this.run_shared(command, window, cx))
249 .ok();
250 });
251 match self.shared.scope {
252 SharedScope::Library => {
253 let status = (self.shared.uploads_running > 0)
254 .then(|| format!("Uploading {} ...", self.shared.uploads_running));
255 render_library(
256 LibraryView {
257 path: self.shared.path.as_ref(),
258 listing: &self.shared.listing,
259 new_folder: self
260 .new_folder_input
261 .as_ref()
262 .filter(|_| self.shared.new_folder_open),
263 status: status.as_deref(),
264 download_states: self.library_download_states(),
265 },
266 &run,
267 )
268 }
269 SharedScope::Messages => render_messages(
270 MessagesView {
271 items: &self.shared.items,
272 filter: self.shared.filter,
273 download_states: self.item_download_states(),
274 },
275 &run,
276 ),
277 }
278 }
279
280 pub(super) fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
281 let conversation_id = self.conversation_id().unwrap_or_default();
282 match command {
283 SharedCommand::Scope(scope) => {
284 self.shared.scope = scope;
285 if scope == SharedScope::Messages {
286 self.refresh_shared_items(cx);
287 }
288 cx.notify();
289 }
290 SharedCommand::Filter(filter) => {
291 self.shared.filter = filter;
292 cx.notify();
293 }
294 SharedCommand::Crumb(index) => {
295 if let Some(path) = self.shared.path.as_mut() {
296 path.go_to(index);
297 }
298 self.shared.new_folder_open = false;
299 self.load_library(cx);
300 }
301 SharedCommand::Open(index) => {
302 let Some(entry) = self.library_entry(index) else {
303 return;
304 };
305 if entry.is_folder() {
306 if let Some(path) = self.shared.path.as_mut() {
307 path.enter(&entry);
308 }
309 self.shared.new_folder_open = false;
310 self.load_library(cx);
311 } else {
312 self.download_library_entry(&conversation_id, &entry, cx);
313 }
314 }
315 SharedCommand::OpenInBrowser(index) => {
316 if let Some(entry) = self.library_entry(index) {
317 cx.open_url(&entry.web_url);
318 }
319 }
320 SharedCommand::Download(index) => {
321 if let Some(entry) = self.library_entry(index) {
322 self.download_library_entry(&conversation_id, &entry, cx);
323 }
324 }
325 SharedCommand::CopyLink(index) => {
326 if let Some(entry) = self.library_entry(index) {
327 cx.write_to_clipboard(ClipboardItem::new_string(entry.web_url));
328 self.app.update(cx, |state, cx| {
329 state.raise_notice("Link copied".to_owned(), None, cx)
330 });
331 }
332 }
333 SharedCommand::Retry => self.load_library(cx),
334 SharedCommand::ToggleNewFolder => self.toggle_new_folder(window, cx),
335 SharedCommand::Upload => self.pick_upload(cx),
336 SharedCommand::OpenSharePoint => {
337 if let Some(path) = &self.shared.path {
338 cx.open_url(path.current_web_url());
339 }
340 }
341 SharedCommand::OpenItem(index) => {
342 let Some(item) = self.shared.items.get(index).cloned() else {
343 return;
344 };
345 match item.content {
346 SharedContent::File(card) => self.activate_file(
347 &conversation_id,
348 &item.message_id,
349 card,
350 DownloadSource::Share,
351 cx,
352 ),
353 SharedContent::Link(url) => cx.open_url(&url),
354 }
355 }
356 SharedCommand::JumpToPost(index) => {
357 let Some(message_id) = self
358 .shared
359 .items
360 .get(index)
361 .map(|item| item.message_id.clone())
362 else {
363 return;
364 };
365 self.jump_to_message(&conversation_id, &message_id, cx);
366 }
367 }
368 }
369
370 fn load_library(&mut self, cx: &mut Context<Self>) {
371 let Some(channel_id) = self.channel_id() else {
372 return;
373 };
374 self.shared.generation += 1;
375 let generation = self.shared.generation;
376 self.shared.listing = Listing::Loading;
377 cx.notify();
378 let state = self.app.read(cx);
379 let (demo, engine) = (state.mode.demo, state.engine.clone());
380 let folder = self.shared.path.as_ref().map(|path| path.current().clone());
381 if demo {
382 self.load_demo_library(&channel_id, folder.is_none());
383 return;
384 }
385 let Some(engine) = engine else {
386 self.shared.listing = Listing::Failed("not connected".to_owned());
387 return;
388 };
389 let receiver = runtime::spawn(async move {
390 let (root, target) = match folder {
391 Some(folder) => (None, folder),
392 None => {
393 let root = engine.channel_library_root(&channel_id).await?;
394 let target = root.folder();
395 (Some(root), target)
396 }
397 };
398 let entries = engine.library_children(&target).await?;
399 Ok::<_, teams_core::Error>((root, entries))
400 });
401 cx.spawn(async move |this, cx| {
402 let outcome = match receiver.await {
403 Ok(Ok(loaded)) => Ok(loaded),
404 Ok(Err(error)) => Err(short_error(&error)),
405 Err(error) => Err(short_error(&error)),
406 };
407 this.update(cx, |this, cx| {
408 this.finish_library_load(generation, outcome, cx)
409 })
410 .ok();
411 })
412 .detach();
413 }
414
415 fn finish_library_load(
416 &mut self,
417 generation: u64,
418 outcome: Result<(Option<DriveEntry>, Vec<DriveEntry>), String>,
419 cx: &mut Context<Self>,
420 ) {
421 if generation != self.shared.generation {
422 return;
423 }
424 match outcome {
425 Ok((root, entries)) => {
426 if let Some(root) = root {
427 self.shared.path = Some(LibraryPath::new(Crumb {
428 name: root.name.clone(),
429 folder: root.folder(),
430 web_url: root.web_url,
431 }));
432 }
433 self.shared.listing = Listing::Ready(sorted_entries(entries));
434 self.shared.listed_at = Some(Instant::now());
435 }
436 Err(reason) => self.shared.listing = Listing::Failed(reason),
437 }
438 cx.notify();
439 }
440
441 fn load_demo_library(&mut self, channel_id: &str, at_root: bool) {
442 if at_root {
443 let name = self
444 .current
445 .as_ref()
446 .map(|current| current.title.clone())
447 .unwrap_or_default();
448 let root = self.demo_library.root(channel_id, &name);
449 self.shared.path = Some(LibraryPath::new(Crumb {
450 name: root.name.clone(),
451 folder: root.folder(),
452 web_url: root.web_url,
453 }));
454 }
455 let Some(path) = &self.shared.path else {
456 return;
457 };
458 let entries = self.demo_library.children(&path.current().item_id);
459 self.shared.listing = Listing::Ready(sorted_entries(entries));
460 }
461
462 fn toggle_new_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
463 if self.shared.new_folder_open {
464 self.shared.new_folder_open = false;
465 cx.notify();
466 return;
467 }
468 let input = match &self.new_folder_input {
469 Some(input) => input.clone(),
470 None => {
471 let input =
472 cx.new(|cx| InputState::new(window, cx).placeholder(NEW_FOLDER_PLACEHOLDER));
473 let subscription = cx.subscribe_in(&input, window, Self::on_new_folder_event);
474 self._subscriptions.push(subscription);
475 self.new_folder_input = Some(input.clone());
476 input
477 }
478 };
479 input.update(cx, |input, cx| {
480 input.set_value("", window, cx);
481 input.focus(window, cx);
482 });
483 self.shared.new_folder_open = true;
484 cx.notify();
485 }
486
487 fn on_new_folder_event(
488 &mut self,
489 _: &Entity<InputState>,
490 event: &InputEvent,
491 _: &mut Window,
492 cx: &mut Context<Self>,
493 ) {
494 if matches!(event, InputEvent::PressEnter { .. }) {
495 self.create_folder(cx);
496 }
497 }
498
499 pub(super) fn close_new_folder(&mut self, cx: &mut Context<Self>) -> bool {
500 if !self.shared.new_folder_open {
501 return false;
502 }
503 self.shared.new_folder_open = false;
504 cx.notify();
505 true
506 }
507
508 fn create_folder(&mut self, cx: &mut Context<Self>) {
509 let Some(input) = self.new_folder_input.clone() else {
510 return;
511 };
512 let name = input.read(cx).value().trim().to_owned();
513 let Some(parent) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
514 return;
515 };
516 if name.is_empty() {
517 return;
518 }
519 self.shared.new_folder_open = false;
520 let state = self.app.read(cx);
521 let (demo, engine) = (state.mode.demo, state.engine.clone());
522 if demo {
523 self.demo_library.create_folder(&parent.item_id, &name);
524 self.load_library(cx);
525 return;
526 }
527 let Some(engine) = engine else {
528 return;
529 };
530 let target = parent.clone();
531 let receiver =
532 runtime::spawn(async move { engine.create_library_folder(&target, &name).await });
533 cx.spawn(async move |this, cx| {
534 let outcome = match receiver.await {
535 Ok(Ok(_)) => Ok(()),
536 Ok(Err(error)) => Err(short_error(&error)),
537 Err(error) => Err(short_error(&error)),
538 };
539 this.update(cx, |this, cx| {
540 this.finish_change(&parent, outcome, "Folder not created", cx)
541 })
542 .ok();
543 })
544 .detach();
545 }
546
547 fn finish_change(
548 &mut self,
549 folder: &DriveFolder,
550 outcome: Result<(), String>,
551 failure: &str,
552 cx: &mut Context<Self>,
553 ) {
554 if let Err(reason) = outcome {
555 self.notice = Some(format!("{failure}: {reason}"));
556 }
557 let still_open = self
558 .shared
559 .path
560 .as_ref()
561 .is_some_and(|path| path.current() == folder);
562 if still_open {
563 self.load_library(cx);
564 } else {
565 cx.notify();
566 }
567 }
568
569 fn pick_upload(&mut self, cx: &mut Context<Self>) {
570 let receiver = cx.prompt_for_paths(PathPromptOptions {
571 files: true,
572 directories: false,
573 multiple: true,
574 prompt: None,
575 });
576 cx.spawn(async move |this, cx| {
577 if let Ok(Ok(Some(paths))) = receiver.await {
578 this.update(cx, |this, cx| this.upload_paths(paths, cx))
579 .ok();
580 }
581 })
582 .detach();
583 }
584
585 pub(super) fn upload_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
586 let Some(folder) = self.shared.path.as_ref().map(|path| path.current().clone()) else {
587 return;
588 };
589 let state = self.app.read(cx);
590 let (demo, engine) = (state.mode.demo, state.engine.clone());
591 for path in paths {
592 self.shared.uploads_running += 1;
593 let (folder, engine) = (folder.clone(), engine.clone());
594 cx.spawn(async move |this, cx| {
595 let name = display_name(&path);
596 let loaded = cx
597 .background_executor()
598 .spawn(async move { read_attachment(&path) })
599 .await;
600 let outcome = match loaded {
601 Err(reason) => Err(reason),
602 Ok(file) if demo => {
603 let size = file.bytes.len() as u64;
604 let (folder_id, file_name) = (folder.item_id.clone(), name.clone());
605 this.update(cx, |this, _| {
606 this.demo_library.add_file(&folder_id, &file_name, size);
607 })
608 .ok();
609 Ok(())
610 }
611 Ok(file) => match engine {
612 None => Err("not connected".to_owned()),
613 Some(engine) => {
614 let (target, file_name) = (folder.clone(), name.clone());
615 let receiver = runtime::spawn(async move {
616 engine
617 .upload_to_library(&target, &file_name, &file.bytes, |_| {})
618 .await
619 });
620 match receiver.await {
621 Ok(Ok(_)) => Ok(()),
622 Ok(Err(error)) => Err(short_error(&error)),
623 Err(error) => Err(short_error(&error)),
624 }
625 }
626 },
627 };
628 this.update(cx, |this, cx| {
629 this.shared.uploads_running = this.shared.uploads_running.saturating_sub(1);
630 let failure = format!("{name} not uploaded");
631 if this.shared.uploads_running == 0 || outcome.is_err() {
632 this.finish_change(&folder, outcome, &failure, cx);
633 } else {
634 cx.notify();
635 }
636 })
637 .ok();
638 })
639 .detach();
640 }
641 cx.notify();
642 }
643}