BlueGit

ict rusty-teams

Files

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

scheduled.rs

scheduled.rs 16.1 KiB Download Raw
1use std::rc::Rc;
2
3use chrono::{DateTime, Utc};
4use gpui_kit::*;
5use store::OutboxTarget;
6use teams_core::ScheduledDraft;
7use uuid::Uuid;
8
9use super::{ConversationView, HoverSlot, ViewMode};
10use crate::backend::Engine;
11use crate::notice::{short_error, truncated};
12use crate::outbox::{deliver, new_outbox_id, outbox_record};
13use crate::rows::MessageRow;
14use crate::runtime;
15use crate::scheduled::{conversation_of, thread_root_of};
16use crate::scheduled_rows::{
17 draft_id_of, draft_key, scheduled_feed_rows, scheduled_outgoing, scheduled_rows,
18};
19use crate::views::composer::{EditPreview, Outgoing};
20use crate::views::message_actions::Action;
21use crate::views::toolbar_placement::HoverChange;
22use crate::views::message_row::{DeliveryActions, RowAction};
23use crate::views::scheduled_toolbar::ScheduledMenu;
24use std::sync::Arc;
25
26const EXCERPT_CHARS: usize = 140;
27
28#[derive(Clone)]
29pub(super) enum ScheduledAction {
30 Update(String),
31 SendNow,
32 Delete,
33}
34
35pub(super) struct ScheduledFailure {
36 draft_id: String,
37 action: ScheduledAction,
38}
39
40pub(super) struct ScheduledRowActions {
41 pub delivery: DeliveryActions,
42 pub menu: Option<ScheduledMenu>,
43 pub hovered: HoverChange,
44}
45
46fn demo_draft(inner_thread_id: &str, html: &str, send_at: DateTime<Utc>) -> ScheduledDraft {
47 ScheduledDraft {
48 id: Uuid::new_v4().to_string(),
49 client_message_id: Uuid::new_v4().to_string(),
50 inner_thread_id: inner_thread_id.to_owned(),
51 send_at,
52 html: html.to_owned(),
53 delivery_state: None,
54 }
55}
56
57impl ConversationView {
58 fn scheduled_thread_id(&self) -> Option<String> {
59 let current = self.current.as_ref()?;
60 let conversation_id = current.selection.conversation_id();
61 Some(match &current.mode {
62 ViewMode::Thread(root_id) => format!("{conversation_id};messageid={root_id}"),
63 _ => conversation_id.to_owned(),
64 })
65 }
66
67 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<MessageRow> {
68 let (Some(inner_thread_id), Some(conversation_id)) =
69 (self.scheduled_thread_id(), self.conversation_id())
70 else {
71 return Vec::new();
72 };
73 let change_failed = self
74 .scheduled_failure
75 .as_ref()
76 .map(|failure| failure.draft_id.as_str());
77 let drafts = &self.app.read(cx).scheduled;
78 if self.in_feed() {
79 return scheduled_feed_rows(
80 drafts,
81 &conversation_id,
82 my_user_id,
83 Utc::now(),
84 change_failed,
85 );
86 }
87 scheduled_rows(
88 drafts,
89 &inner_thread_id,
90 &conversation_id,
91 my_user_id,
92 Utc::now(),
93 change_failed,
94 )
95 }
96
97 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
98 self.app
99 .read(cx)
100 .scheduled
101 .iter()
102 .find(|draft| draft_key(draft) == draft_id)
103 .cloned()
104 }
105
106 fn scheduled_engine(&mut self, cx: &mut Context<Self>) -> Option<Arc<Engine>> {
107 let state = self.app.read(cx);
108 let engine = state.engine.clone().filter(|_| !state.mode.read_only);
109 if engine.is_none() {
110 self.notice = Some("Read-only mode: nothing was changed".to_owned());
111 cx.notify();
112 }
113 engine
114 }
115
116 pub(super) fn schedule(
117 &mut self,
118 outgoing: Outgoing,
119 send_at: DateTime<Utc>,
120 window: &mut Window,
121 cx: &mut Context<Self>,
122 ) {
123 let (Some(inner_thread_id), Some(conversation_id)) =
124 (self.scheduled_thread_id(), self.conversation_id())
125 else {
126 return;
127 };
128 if self.in_feed() && self.has_subject(cx) {
129 self.notice = Some("Can't schedule a post with a subject yet".to_owned());
130 self.composer
131 .update(cx, |composer, cx| composer.fail_schedule(cx));
132 cx.notify();
133 return;
134 }
135 let html = outgoing.html();
136 if self.app.read(cx).mode.demo {
137 let draft = demo_draft(&inner_thread_id, &html, send_at);
138 self.app
139 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
140 self.finish_scheduling(&conversation_id, window, cx);
141 return;
142 }
143 let Some(engine) = self.scheduled_engine(cx) else {
144 self.composer
145 .update(cx, |composer, cx| composer.fail_schedule(cx));
146 return;
147 };
148 let thread_root_id = match self.current.as_ref().map(|current| &current.mode) {
149 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
150 _ => None,
151 };
152 let target = conversation_id.clone();
153 let receiver = runtime::spawn(async move {
154 engine
155 .schedule_message(&target, thread_root_id.as_deref(), &html, send_at)
156 .await
157 });
158 cx.spawn_in(window, async move |this, cx| {
159 let result = receiver.await;
160 this.update_in(cx, |this, window, cx| match result {
161 Ok(Ok(draft)) => {
162 this.app
163 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
164 this.finish_scheduling(&conversation_id, window, cx);
165 }
166 Ok(Err(error)) => this.fail_scheduling(&short_error(&error), cx),
167 Err(error) => this.fail_scheduling(&short_error(&error), cx),
168 })
169 .ok();
170 })
171 .detach();
172 }
173
174 fn finish_scheduling(
175 &mut self,
176 conversation_id: &str,
177 window: &mut Window,
178 cx: &mut Context<Self>,
179 ) {
180 self.notice = None;
181 self.composer.update(cx, |composer, cx| {
182 composer.finish_schedule(conversation_id, window, cx)
183 });
184 if self.in_feed() {
185 self.close_new_post(cx);
186 }
187 self.rebuild(false, cx);
188 if !self.in_feed() {
189 self.scroller
190 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
191 }
192 }
193
194 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
195 self.notice = Some(format!("Couldn't schedule: {error}"));
196 self.composer
197 .update(cx, |composer, cx| composer.fail_schedule(cx));
198 cx.notify();
199 }
200
201 pub(super) fn begin_scheduled_edit(
202 &mut self,
203 draft_id: &str,
204 window: &mut Window,
205 cx: &mut Context<Self>,
206 ) {
207 let Some(draft) = self
208 .scheduled_draft(draft_id, cx)
209 .filter(|draft| !draft.id.is_empty())
210 else {
211 return;
212 };
213 let mut outgoing = scheduled_outgoing(&draft.html);
214 let excerpt = outgoing
215 .text()
216 .lines()
217 .map(str::trim)
218 .find(|line| !line.is_empty())
219 .map(|line| truncated(line, EXCERPT_CHARS))
220 .unwrap_or_default();
221 outgoing.edit = Some(EditPreview {
222 message_id: draft.id,
223 excerpt,
224 scheduled: Some(draft.send_at),
225 });
226 self.show_main_composer(cx);
227 self.composer
228 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
229 }
230
231 pub(super) fn send_scheduled_edit(
232 &mut self,
233 outgoing: Outgoing,
234 window: &mut Window,
235 cx: &mut Context<Self>,
236 ) {
237 let Some(edit) = outgoing.edit.as_ref() else {
238 return;
239 };
240 self.change_scheduled(
241 &edit.message_id.clone(),
242 ScheduledAction::Update(outgoing.html()),
243 window,
244 cx,
245 );
246 }
247
248 pub(super) fn send_scheduled_now(
249 &mut self,
250 draft_id: &str,
251 window: &mut Window,
252 cx: &mut Context<Self>,
253 ) {
254 self.change_scheduled(draft_id, ScheduledAction::SendNow, window, cx);
255 }
256
257 pub(super) fn delete_scheduled(
258 &mut self,
259 draft_id: &str,
260 window: &mut Window,
261 cx: &mut Context<Self>,
262 ) {
263 self.change_scheduled(draft_id, ScheduledAction::Delete, window, cx);
264 }
265
266 pub(super) fn retry_scheduled(&mut self, window: &mut Window, cx: &mut Context<Self>) {
267 if let Some(failure) = self.scheduled_failure.take() {
268 self.change_scheduled(&failure.draft_id, failure.action, window, cx);
269 }
270 }
271
272 fn change_scheduled(
273 &mut self,
274 draft_id: &str,
275 action: ScheduledAction,
276 window: &mut Window,
277 cx: &mut Context<Self>,
278 ) {
279 let Some(draft) = self
280 .scheduled_draft(draft_id, cx)
281 .filter(|draft| !draft.id.is_empty())
282 else {
283 return;
284 };
285 if !self.scheduled_in_flight.insert(draft.id.clone()) {
286 return;
287 }
288 self.scheduled_failure = None;
289 if self.app.read(cx).mode.demo {
290 self.scheduled_in_flight.remove(&draft.id);
291 self.apply_scheduled_change(&draft, &action, cx);
292 return;
293 }
294 let Some(engine) = self.scheduled_engine(cx) else {
295 self.scheduled_in_flight.remove(&draft.id);
296 return;
297 };
298 let (call_draft, call_action) = (draft.clone(), action.clone());
299 let receiver = runtime::spawn(async move {
300 match call_action {
301 ScheduledAction::Update(html) => {
302 engine.update_scheduled(&call_draft, &html).await.map(Some)
303 }
304 ScheduledAction::SendNow | ScheduledAction::Delete => {
305 engine.cancel_scheduled(&call_draft.id).await.map(|_| None)
306 }
307 }
308 });
309 cx.spawn_in(window, async move |this, cx| {
310 let result = receiver.await;
311 this.update_in(cx, |this, _, cx| {
312 this.scheduled_in_flight.remove(&draft.id);
313 match result {
314 Ok(Ok(Some(updated))) => {
315 this.app
316 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
317 this.rebuild(false, cx);
318 }
319 Ok(Ok(None)) => this.apply_scheduled_change(&draft, &action, cx),
320 _ => {
321 this.scheduled_failure = Some(ScheduledFailure {
322 draft_id: draft.id.clone(),
323 action,
324 });
325 this.rebuild(false, cx);
326 }
327 }
328 })
329 .ok();
330 })
331 .detach();
332 }
333
334 fn apply_scheduled_change(
335 &mut self,
336 draft: &ScheduledDraft,
337 action: &ScheduledAction,
338 cx: &mut Context<Self>,
339 ) {
340 match action {
341 ScheduledAction::Update(html) => {
342 let updated = ScheduledDraft {
343 html: html.clone(),
344 ..draft.clone()
345 };
346 self.app
347 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
348 }
349 ScheduledAction::Delete => self
350 .app
351 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx)),
352 ScheduledAction::SendNow => {
353 self.app
354 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx));
355 self.deliver_now(draft, cx);
356 }
357 }
358 self.rebuild(false, cx);
359 }
360
361 fn deliver_now(&mut self, draft: &ScheduledDraft, cx: &mut Context<Self>) {
362 let state = self.app.read(cx);
363 let (Some(engine), store) = (state.engine.clone(), state.store.clone()) else {
364 return;
365 };
366 if state.mode.demo {
367 return;
368 }
369 let conversation_id = conversation_of(&draft.inner_thread_id).to_owned();
370 let thread_root_id = thread_root_of(&draft.inner_thread_id).map(str::to_owned);
371 let target = match (&thread_root_id, store.channel(&conversation_id)) {
372 (Some(_), _) => OutboxTarget::Thread,
373 (None, Ok(Some(_))) => OutboxTarget::Post,
374 (None, _) => OutboxTarget::Flat,
375 };
376 let outgoing = scheduled_outgoing(&draft.html);
377 let outbox_id = new_outbox_id();
378 if let Some(record) = outbox_record(
379 &outbox_id,
380 &conversation_id,
381 target,
382 thread_root_id.as_deref(),
383 &outgoing,
384 Utc::now(),
385 ) {
386 store.put_outbox(&record).ok();
387 }
388 let app = self.app.clone();
389 app.update(cx, |state, cx| {
390 state.outbox_changed(conversation_id.clone(), cx)
391 });
392 let delivery_target = conversation_id.clone();
393 let receiver = runtime::spawn(async move {
394 deliver(
395 &engine,
396 &delivery_target,
397 target,
398 thread_root_id.as_deref(),
399 &outgoing,
400 )
401 .await
402 });
403 cx.spawn(async move |_, cx| {
404 let failure = match receiver.await {
405 Ok(Ok(())) => None,
406 Ok(Err(error)) => Some(short_error(&error)),
407 Err(error) => Some(short_error(&error)),
408 };
409 match failure {
410 None => store.delete_outbox(&outbox_id).ok(),
411 Some(error) => store.mark_outbox_failed(&outbox_id, &error).ok(),
412 };
413 app.update(cx, |state, cx| state.outbox_changed(conversation_id, cx));
414 })
415 .detach();
416 }
417
418 pub(super) fn scheduled_row_actions(
419 &self,
420 row: &MessageRow,
421 view: &WeakEntity<Self>,
422 window: &Window,
423 cx: &App,
424 ) -> Option<ScheduledRowActions> {
425 let draft_id = draft_id_of(&row.key)?.to_owned();
426 let handle = window.window_handle();
427 let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {
428 let (view, draft_id) = (view.clone(), draft_id.clone());
429 Some(Box::new(move |cx: &mut App| {
430 let (view, draft_id) = (view.clone(), draft_id.clone());
431 handle
432 .update(cx, move |_, window, cx| {
433 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
434 .ok();
435 })
436 .ok();
437 }))
438 };
439 let retry: RowAction = {
440 let view = view.clone();
441 Some(Box::new(move |cx: &mut App| {
442 let view = view.clone();
443 handle
444 .update(cx, move |_, window, cx| {
445 view.update(cx, |this, cx| this.retry_scheduled(window, cx))
446 .ok();
447 })
448 .ok();
449 }))
450 };
451 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
452 let (view, draft_id) = (view.clone(), draft_id.clone());
453 Rc::new(move |window, cx| {
454 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
455 .ok();
456 })
457 };
458 let hover = |slot: HoverSlot| -> HoverChange {
459 let (view, key) = (view.clone(), row.key.clone());
460 Rc::new(move |hovered: bool, cx: &mut App| {
461 view.update(cx, |this, cx| this.set_hover(slot, &key, hovered, cx))
462 .ok();
463 })
464 };
465 let visible = view
466 .upgrade()
467 .is_some_and(|entity| entity.read(cx).toolbar_visible(&row.key));
468 Some(ScheduledRowActions {
469 delivery: DeliveryActions {
470 retry,
471 delete: link(Self::delete_scheduled),
472 send_now: link(Self::send_scheduled_now),
473 },
474 menu: visible.then(|| ScheduledMenu {
475 key: row.key.clone(),
476 edit: action(Self::begin_scheduled_edit),
477 send_now: action(Self::send_scheduled_now),
478 delete: action(Self::delete_scheduled),
479 hover: hover(HoverSlot::Toolbar),
480 }),
481 hovered: hover(HoverSlot::Row),
482 })
483 }
484}