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