BlueGit

ict rusty-teams

Files

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

scheduled.rs

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