BlueGit

ict rusty-teams

Files

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

scheduled.rs

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