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