BlueGit

ict rusty-teams

Files

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

shared.rs

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