BlueGit

ict rusty-teams

Files

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

shared.rs

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