summaryrefslogtreecommitdiff
path: root/src/api/client_server/read_marker.rs
blob: a5553d25b838d430e55089b5bf320462fb1adfca (plain)
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
use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma};
use ruma::{
    api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
    events::{
        receipt::{ReceiptThread, ReceiptType},
        RoomAccountDataEventType,
    },
    MilliSecondsSinceUnixEpoch,
};
use std::collections::BTreeMap;

/// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers`
///
/// Sets different types of read markers.
///
/// - Updates fully-read account data event to `fully_read`
/// - If `read_receipt` is set: Update private marker and public read receipt EDU
pub async fn set_read_marker_route(
    body: Ruma<set_read_marker::v3::Request>,
) -> Result<set_read_marker::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if let Some(fully_read) = &body.fully_read {
        let fully_read_event = ruma::events::fully_read::FullyReadEvent {
            content: ruma::events::fully_read::FullyReadEventContent {
                event_id: fully_read.clone(),
            },
        };
        services().account_data.update(
            Some(&body.room_id),
            sender_user,
            RoomAccountDataEventType::FullyRead,
            &serde_json::to_value(fully_read_event).expect("to json value always works"),
        )?;
    }

    if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
        services()
            .rooms
            .user
            .reset_notification_counts(sender_user, &body.room_id)?;
    }

    if let Some(event) = &body.private_read_receipt {
        let count = services()
            .rooms
            .timeline
            .get_pdu_count(event)?
            .ok_or(Error::BadRequest(
                ErrorKind::InvalidParam,
                "Event does not exist.",
            ))?;
        let count = match count {
            PduCount::Backfilled(_) => {
                return Err(Error::BadRequest(
                    ErrorKind::InvalidParam,
                    "Read receipt is in backfilled timeline",
                ))
            }
            PduCount::Normal(c) => c,
        };
        services()
            .rooms
            .edus
            .read_receipt
            .private_read_set(&body.room_id, sender_user, count)?;
    }

    if let Some(event) = &body.read_receipt {
        let mut user_receipts = BTreeMap::new();
        user_receipts.insert(
            sender_user.clone(),
            ruma::events::receipt::Receipt {
                ts: Some(MilliSecondsSinceUnixEpoch::now()),
                thread: ReceiptThread::Unthreaded,
            },
        );

        let mut receipts = BTreeMap::new();
        receipts.insert(ReceiptType::Read, user_receipts);

        let mut receipt_content = BTreeMap::new();
        receipt_content.insert(event.to_owned(), receipts);

        services().rooms.edus.read_receipt.readreceipt_update(
            sender_user,
            &body.room_id,
            ruma::events::receipt::ReceiptEvent {
                content: ruma::events::receipt::ReceiptEventContent(receipt_content),
                room_id: body.room_id.clone(),
            },
        )?;
    }

    Ok(set_read_marker::v3::Response {})
}

/// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`
///
/// Sets private read marker and public read receipt EDU.
pub async fn create_receipt_route(
    body: Ruma<create_receipt::v3::Request>,
) -> Result<create_receipt::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    if matches!(
        &body.receipt_type,
        create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
    ) {
        services()
            .rooms
            .user
            .reset_notification_counts(sender_user, &body.room_id)?;
    }

    match body.receipt_type {
        create_receipt::v3::ReceiptType::FullyRead => {
            let fully_read_event = ruma::events::fully_read::FullyReadEvent {
                content: ruma::events::fully_read::FullyReadEventContent {
                    event_id: body.event_id.clone(),
                },
            };
            services().account_data.update(
                Some(&body.room_id),
                sender_user,
                RoomAccountDataEventType::FullyRead,
                &serde_json::to_value(fully_read_event).expect("to json value always works"),
            )?;
        }
        create_receipt::v3::ReceiptType::Read => {
            let mut user_receipts = BTreeMap::new();
            user_receipts.insert(
                sender_user.clone(),
                ruma::events::receipt::Receipt {
                    ts: Some(MilliSecondsSinceUnixEpoch::now()),
                    thread: ReceiptThread::Unthreaded,
                },
            );
            let mut receipts = BTreeMap::new();
            receipts.insert(ReceiptType::Read, user_receipts);

            let mut receipt_content = BTreeMap::new();
            receipt_content.insert(body.event_id.to_owned(), receipts);

            services().rooms.edus.read_receipt.readreceipt_update(
                sender_user,
                &body.room_id,
                ruma::events::receipt::ReceiptEvent {
                    content: ruma::events::receipt::ReceiptEventContent(receipt_content),
                    room_id: body.room_id.clone(),
                },
            )?;
        }
        create_receipt::v3::ReceiptType::ReadPrivate => {
            let count = services()
                .rooms
                .timeline
                .get_pdu_count(&body.event_id)?
                .ok_or(Error::BadRequest(
                    ErrorKind::InvalidParam,
                    "Event does not exist.",
                ))?;
            let count = match count {
                PduCount::Backfilled(_) => {
                    return Err(Error::BadRequest(
                        ErrorKind::InvalidParam,
                        "Read receipt is in backfilled timeline",
                    ))
                }
                PduCount::Normal(c) => c,
            };
            services().rooms.edus.read_receipt.private_read_set(
                &body.room_id,
                sender_user,
                count,
            )?;
        }
        _ => return Err(Error::bad_database("Unsupported receipt type")),
    }

    Ok(create_receipt::v3::Response {})
}