acter/api/
read_receipts.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
use acter_core::{models, referencing::ExecuteReference};
use anyhow::Result;
use futures::stream::StreamExt;
use matrix_sdk::room::Room;
use matrix_sdk_base::ruma::OwnedEventId;
use tokio::sync::broadcast::Receiver;
use tokio_stream::{wrappers::BroadcastStream, Stream};

use super::{client::Client, RUNTIME};

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

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

    pub async fn reload(&self) -> Result<ReadReceiptsManager> {
        ReadReceiptsManager::new(
            self.client.clone(),
            self.room.clone(),
            self.event_id.clone(),
        )
        .await
    }

    pub fn update_key(&self) -> ExecuteReference {
        self.inner.update_key()
    }

    pub async fn announce_read(&self) -> Result<bool> {
        let room = self.room.clone();
        let event = self.inner.construct_read_event();

        RUNTIME
            .spawn(async move {
                room.send(event).await?;
                Ok(true)
            })
            .await?
    }

    pub fn read_count(&self) -> u32 {
        self.inner.stats.total_views
    }

    pub fn read_by_me(&self) -> bool {
        self.inner.stats.user_has_read
    }

    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.update_key())
    }
}