BlueGit

ict rusty-teams

Files

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

shared.rs

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