BlueGit

ict rusty-teams

Files

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

shared.rs

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