BlueGit

ict rusty-teams

Files

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

shared.rs

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