acter/api/
rsvp.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
pub use acter_core::events::rsvp::RsvpStatus;
use acter_core::{
    events::rsvp::RsvpBuilder,
    models::{self, ActerModel, AnyActerModel},
    referencing::{IndexKey, SectionIndex},
};
use anyhow::{bail, Result};
use core::time::Duration;
use futures::stream::StreamExt;
use matrix_sdk::room::Room;
use matrix_sdk_base::{
    ruma::{events::MessageLikeEventType, OwnedEventId, OwnedUserId},
    RoomState,
};
use std::{ops::Deref, str::FromStr};
use tokio::sync::broadcast::Receiver;
use tokio_stream::{wrappers::BroadcastStream, Stream};
use tracing::{error, warn};

use super::{calendar_events::CalendarEvent, client::Client, common::OptionRsvpStatus, RUNTIME};

impl Client {
    pub async fn wait_for_rsvp(&self, key: String, timeout: Option<u8>) -> Result<Rsvp> {
        let me = self.clone();
        RUNTIME
            .spawn(async move {
                let AnyActerModel::Rsvp(rsvp) = me.wait_for(key.clone(), timeout).await? else {
                    bail!("{key} is not a rsvp");
                };
                let room = me.room_by_id_typed(&rsvp.meta.room_id)?;
                Ok(Rsvp {
                    client: me.clone(),
                    room,
                    inner: rsvp,
                })
            })
            .await?
    }

    pub async fn all_upcoming_events(
        &self,
        secs_from_now: Option<u32>,
    ) -> Result<Vec<CalendarEvent>> {
        let me = self.clone();
        RUNTIME
            .spawn(async move {
                let mut cal_events = vec![];
                for mdl in me
                    .store()
                    .get_list(&IndexKey::Section(SectionIndex::Calendar))
                    .await?
                {
                    if let AnyActerModel::CalendarEvent(inner) = mdl {
                        let now = chrono::Utc::now();
                        let start_time = inner.utc_start();
                        if now > start_time {
                            // skip past events
                            continue;
                        }
                        if let Some(secs) = secs_from_now {
                            if start_time > now + chrono::Duration::seconds(secs as i64) {
                                // skip too far events
                                continue;
                            }
                        }
                        let room = me.room_by_id_typed(inner.room_id())?;
                        let cal_event = CalendarEvent::new(me.clone(), room, inner);
                        cal_events.push(cal_event);
                    } else {
                        warn!(
                            "Non calendar_event model found in `calendar_events` index: {:?}",
                            mdl
                        );
                    }
                }
                cal_events.sort();
                Ok(cal_events)
            })
            .await?
    }

    pub async fn my_upcoming_events(
        &self,
        secs_from_now: Option<u32>,
    ) -> Result<Vec<CalendarEvent>> {
        let me = self.clone();
        RUNTIME
            .spawn(async move {
                let mut cal_events = vec![];
                for mdl in me
                    .store()
                    .get_list(&IndexKey::Section(SectionIndex::Calendar))
                    .await?
                {
                    if let AnyActerModel::CalendarEvent(inner) = mdl {
                        let now = chrono::Utc::now();
                        let start_time = inner.utc_start();
                        if now > start_time {
                            // skip past events
                            continue;
                        }
                        if let Some(secs) = secs_from_now {
                            if start_time > now + chrono::Duration::seconds(secs as i64) {
                                // skip too far events
                                continue;
                            }
                        }
                        let room = me.room_by_id_typed(inner.room_id())?;
                        let cal_event = CalendarEvent::new(me.clone(), room, inner);
                        // fliter only events that i sent rsvp
                        let rsvp_manager = cal_event.rsvps().await?;
                        let status = rsvp_manager.responded_by_me().await?;
                        match status.status() {
                            Some(RsvpStatus::Yes) | Some(RsvpStatus::Maybe) => {
                                cal_events.push(cal_event);
                            }
                            _ => {}
                        }
                    } else {
                        warn!(
                            "Non calendar_event model found in `calendar_events` index: {:?}",
                            mdl
                        );
                    }
                }
                Ok(cal_events)
            })
            .await?
    }

    pub async fn my_past_events(&self, secs_from_now: Option<u32>) -> Result<Vec<CalendarEvent>> {
        let me = self.clone();
        RUNTIME
            .spawn(async move {
                let mut cal_events = vec![];
                for mdl in me
                    .store()
                    .get_list(&IndexKey::Section(SectionIndex::Calendar))
                    .await?
                {
                    if let AnyActerModel::CalendarEvent(inner) = mdl {
                        let now = chrono::Utc::now();
                        let start_time = inner.utc_start();
                        if start_time > now {
                            // skip upcoming events
                            continue;
                        }
                        if let Some(secs) = secs_from_now {
                            if start_time < now - chrono::Duration::seconds(secs as i64) {
                                // skip too far events
                                continue;
                            }
                        }
                        let room = me.room_by_id_typed(inner.room_id())?;
                        let cal_event = CalendarEvent::new(me.clone(), room, inner);
                        // fliter only events that i sent rsvp
                        let rsvp_manager = cal_event.rsvps().await?;
                        let status = rsvp_manager.responded_by_me().await?;
                        match status.status() {
                            Some(RsvpStatus::Yes) | Some(RsvpStatus::Maybe) => {
                                cal_events.push(cal_event);
                            }
                            _ => {}
                        }
                    } else {
                        warn!(
                            "Non calendar_event model found in `calendar_events` index: {:?}",
                            mdl
                        );
                    }
                }
                Ok(cal_events)
            })
            .await?
    }
}

#[derive(Clone, Debug)]
pub struct Rsvp {
    client: Client,
    room: Room,
    inner: models::Rsvp,
}

impl Deref for Rsvp {
    type Target = models::Rsvp;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl Rsvp {
    pub fn sender(&self) -> OwnedUserId {
        self.inner.meta.sender.clone()
    }

    pub fn origin_server_ts(&self) -> u64 {
        self.inner.meta.origin_server_ts.get().into()
    }

    pub fn status(&self) -> String {
        self.inner.status.to_string()
    }
}

pub struct RsvpDraft {
    client: Client,
    room: Room,
    inner: RsvpBuilder,
}

impl RsvpDraft {
    pub fn status(&mut self, status: String) -> &mut Self {
        if let Ok(s) = RsvpStatus::from_str(&status) {
            self.inner.status(s);
        } else {
            error!("Wrong status about RSVP");
        }
        self
    }

    pub async fn send(&self) -> Result<OwnedEventId> {
        let room = self.room.clone();
        let my_id = self.client.user_id()?;
        let inner = self.inner.build()?;

        RUNTIME
            .spawn(async move {
                let permitted = room
                    .can_user_send_message(&my_id, MessageLikeEventType::RoomMessage)
                    .await?;
                if !permitted {
                    bail!("No permissions to send message in this room");
                }
                let response = room.send(inner).await?;
                Ok(response.event_id)
            })
            .await?
    }
}

#[derive(Clone, Debug)]
pub struct RsvpManager {
    client: Client,
    room: Room,
    inner: models::RsvpManager,
}

impl Deref for RsvpManager {
    type Target = models::RsvpManager;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl RsvpManager {
    pub(crate) async fn new(
        client: Client,
        room: Room,
        event_id: OwnedEventId,
    ) -> Result<RsvpManager> {
        RUNTIME
            .spawn(async move {
                let inner =
                    models::RsvpManager::from_store_and_event_id(client.store(), &event_id).await;
                Ok(RsvpManager {
                    client,
                    room,
                    inner,
                })
            })
            .await?
    }

    pub fn stats(&self) -> models::RsvpStats {
        self.inner.stats().clone()
    }

    pub fn has_rsvp_entries(&self) -> bool {
        *self.stats().has_rsvp_entries()
    }

    pub fn total_rsvp_count(&self) -> u32 {
        *self.stats().total_rsvp_count()
    }

    pub async fn rsvp_entries(&self) -> Result<Vec<Rsvp>> {
        let manager = self.inner.clone();
        let client = self.client.clone();
        let room = self.room.clone();

        RUNTIME
            .spawn(async move {
                let res = manager
                    .rsvp_entries()
                    .await?
                    .into_iter()
                    .map(|(user_id, inner)| Rsvp {
                        client: client.clone(),
                        room: room.clone(),
                        inner,
                    })
                    .collect();
                Ok(res)
            })
            .await?
    }

    pub async fn responded_by_me(&self) -> Result<OptionRsvpStatus> {
        let manager = self.inner.clone();
        let my_id = self.client.user_id()?;
        RUNTIME
            .spawn(async move {
                let entries = manager.rsvp_entries().await?;
                let status = entries.get(&my_id).map(|x| x.status.clone());
                Ok(OptionRsvpStatus::new(status))
            })
            .await?
    }

    pub async fn count_at_status(&self, status: String) -> Result<u32> {
        let manager = self.inner.clone();
        RUNTIME
            .spawn(async move {
                let mut count = 0;
                let entries = manager.rsvp_entries().await?;
                for (user_id, entry) in entries {
                    if entry.status.to_string() == status {
                        count += 1;
                    }
                }
                Ok(count)
            })
            .await?
    }

    pub async fn users_at_status(&self, status: String) -> Result<Vec<OwnedUserId>> {
        self.users_at_status_typed(RsvpStatus::from_str(&status)?)
            .await
    }

    // ***_typed fn accepts rust-typed input, not string-based one
    pub(crate) async fn users_at_status_typed(
        &self,
        status: RsvpStatus,
    ) -> Result<Vec<OwnedUserId>> {
        let manager = self.inner.clone();
        RUNTIME
            .spawn(async move {
                let mut senders = vec![];
                let entries = manager.rsvp_entries().await?;
                for (user_id, entry) in entries {
                    if entry.status == status {
                        senders.push(user_id);
                    }
                }
                Ok(senders)
            })
            .await?
    }

    fn is_joined(&self) -> bool {
        matches!(self.room.state(), RoomState::Joined)
    }

    pub fn rsvp_draft(&self) -> Result<RsvpDraft> {
        if !self.is_joined() {
            bail!("Can do RSVP in only joined rooms");
        }
        Ok(RsvpDraft {
            client: self.client.clone(),
            room: self.room.clone(),
            inner: self.inner.draft_builder(),
        })
    }

    pub fn subscribe_stream(&self) -> impl Stream<Item = bool> {
        BroadcastStream::new(self.subscribe()).map(|f| true)
    }

    pub fn subscribe(&self) -> Receiver<()> {
        self.client.subscribe(self.inner.update_key())
    }
}