File: thread_subscriptions.py

package info (click to toggle)
matrix-synapse 1.146.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,992 kB
  • sloc: python: 261,671; javascript: 7,230; sql: 4,758; sh: 1,302; perl: 626; makefile: 207
file content (247 lines) | stat: -rw-r--r-- 9,036 bytes parent folder | download
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
from http import HTTPStatus
from typing import TYPE_CHECKING

import attr
from typing_extensions import TypeAlias

from synapse.api.errors import Codes, NotFoundError, SynapseError
from synapse.http.server import HttpServer
from synapse.http.servlet import (
    RestServlet,
    parse_and_validate_json_object_from_request,
    parse_integer,
    parse_string,
)
from synapse.http.site import SynapseRequest
from synapse.rest.client._base import client_patterns
from synapse.types import (
    JsonDict,
    RoomID,
    SlidingSyncStreamToken,
    ThreadSubscriptionsToken,
)
from synapse.types.handlers.sliding_sync import SlidingSyncResult
from synapse.types.rest import RequestBodyModel
from synapse.util.pydantic_models import AnyEventId

if TYPE_CHECKING:
    from synapse.server import HomeServer

_ThreadSubscription: TypeAlias = (
    SlidingSyncResult.Extensions.ThreadSubscriptionsExtension.ThreadSubscription
)
_ThreadUnsubscription: TypeAlias = (
    SlidingSyncResult.Extensions.ThreadSubscriptionsExtension.ThreadUnsubscription
)


class ThreadSubscriptionsRestServlet(RestServlet):
    PATTERNS = client_patterns(
        "/io.element.msc4306/rooms/(?P<room_id>[^/]*)/thread/(?P<thread_root_id>[^/]*)/subscription$",
        unstable=True,
        releases=(),
    )
    CATEGORY = "Thread Subscriptions requests (unstable)"

    def __init__(self, hs: "HomeServer"):
        self.auth = hs.get_auth()
        self.is_mine = hs.is_mine
        self.store = hs.get_datastores().main
        self.handler = hs.get_thread_subscriptions_handler()

    class PutBody(RequestBodyModel):
        automatic: AnyEventId | None = None
        """
        If supplied, the event ID of an event giving rise to this automatic subscription.

        If omitted, this subscription is a manual subscription.
        """

    async def on_GET(
        self, request: SynapseRequest, room_id: str, thread_root_id: str
    ) -> tuple[int, JsonDict]:
        RoomID.from_string(room_id)
        if not thread_root_id.startswith("$"):
            raise SynapseError(
                HTTPStatus.BAD_REQUEST, "Invalid event ID", errcode=Codes.INVALID_PARAM
            )
        requester = await self.auth.get_user_by_req(request)

        subscription = await self.handler.get_thread_subscription_settings(
            requester.user,
            room_id,
            thread_root_id,
        )

        if subscription is None:
            raise NotFoundError("Not subscribed.")

        return HTTPStatus.OK, {"automatic": subscription.automatic}

    async def on_PUT(
        self, request: SynapseRequest, room_id: str, thread_root_id: str
    ) -> tuple[int, JsonDict]:
        RoomID.from_string(room_id)
        if not thread_root_id.startswith("$"):
            raise SynapseError(
                HTTPStatus.BAD_REQUEST, "Invalid event ID", errcode=Codes.INVALID_PARAM
            )
        body = parse_and_validate_json_object_from_request(request, self.PutBody)

        requester = await self.auth.get_user_by_req(request)

        await self.handler.subscribe_user_to_thread(
            requester.user,
            room_id,
            thread_root_id,
            automatic_event_id=body.automatic,
        )

        return HTTPStatus.OK, {}

    async def on_DELETE(
        self, request: SynapseRequest, room_id: str, thread_root_id: str
    ) -> tuple[int, JsonDict]:
        RoomID.from_string(room_id)
        if not thread_root_id.startswith("$"):
            raise SynapseError(
                HTTPStatus.BAD_REQUEST, "Invalid event ID", errcode=Codes.INVALID_PARAM
            )
        requester = await self.auth.get_user_by_req(request)

        await self.handler.unsubscribe_user_from_thread(
            requester.user,
            room_id,
            thread_root_id,
        )

        return HTTPStatus.OK, {}


class ThreadSubscriptionsPaginationRestServlet(RestServlet):
    PATTERNS = client_patterns(
        "/io.element.msc4308/thread_subscriptions$",
        unstable=True,
        releases=(),
    )
    CATEGORY = "Thread Subscriptions requests (unstable)"

    # Maximum number of thread subscriptions to return in one request.
    MAX_LIMIT = 512

    def __init__(self, hs: "HomeServer"):
        self.auth = hs.get_auth()
        self.is_mine = hs.is_mine
        self.store = hs.get_datastores().main

    async def on_GET(self, request: SynapseRequest) -> tuple[int, JsonDict]:
        requester = await self.auth.get_user_by_req(request)

        limit = min(
            parse_integer(request, "limit", default=100, negative=False),
            ThreadSubscriptionsPaginationRestServlet.MAX_LIMIT,
        )
        from_end_opt = parse_string(request, "from", required=False)
        to_start_opt = parse_string(request, "to", required=False)
        _direction = parse_string(request, "dir", required=True, allowed_values=("b",))

        if limit <= 0:
            # condition needed because `negative=False` still allows 0
            raise SynapseError(
                HTTPStatus.BAD_REQUEST,
                "limit must be greater than 0",
                errcode=Codes.INVALID_PARAM,
            )

        if from_end_opt is not None:
            try:
                # because of backwards pagination, the `from` token is actually the
                # bound closest to the end of the stream
                end_stream_id = ThreadSubscriptionsToken.from_string(
                    from_end_opt
                ).stream_id
            except ValueError:
                raise SynapseError(
                    HTTPStatus.BAD_REQUEST,
                    "`from` is not a valid token",
                    errcode=Codes.INVALID_PARAM,
                )
        else:
            end_stream_id = self.store.get_max_thread_subscriptions_stream_id()

        if to_start_opt is not None:
            # because of backwards pagination, the `to` token is actually the
            # bound closest to the start of the stream
            try:
                start_stream_id = ThreadSubscriptionsToken.from_string(
                    to_start_opt
                ).stream_id
            except ValueError:
                # we also accept sliding sync `pos` tokens on this parameter
                try:
                    sliding_sync_pos = await SlidingSyncStreamToken.from_string(
                        self.store, to_start_opt
                    )
                    start_stream_id = (
                        sliding_sync_pos.stream_token.thread_subscriptions_key
                    )
                except ValueError:
                    raise SynapseError(
                        HTTPStatus.BAD_REQUEST,
                        "`to` is not a valid token",
                        errcode=Codes.INVALID_PARAM,
                    )
        else:
            # the start of time is ID 1; the lower bound is exclusive though
            start_stream_id = 0

        subscriptions = (
            await self.store.get_latest_updated_thread_subscriptions_for_user(
                requester.user.to_string(),
                from_id=start_stream_id,
                to_id=end_stream_id,
                limit=limit,
            )
        )

        subscribed_threads: dict[str, dict[str, JsonDict]] = {}
        unsubscribed_threads: dict[str, dict[str, JsonDict]] = {}
        for stream_id, room_id, thread_root_id, subscribed, automatic in subscriptions:
            if subscribed:
                subscribed_threads.setdefault(room_id, {})[thread_root_id] = (
                    attr.asdict(
                        _ThreadSubscription(
                            automatic=automatic,
                            bump_stamp=stream_id,
                        )
                    )
                )
            else:
                unsubscribed_threads.setdefault(room_id, {})[thread_root_id] = (
                    attr.asdict(_ThreadUnsubscription(bump_stamp=stream_id))
                )

        result: JsonDict = {}
        if subscribed_threads:
            result["subscribed"] = subscribed_threads
        if unsubscribed_threads:
            result["unsubscribed"] = unsubscribed_threads

        if len(subscriptions) == limit:
            # We hit the limit, so there might be more entries to return.
            # Generate a new token that has moved backwards, ready for the next
            # request.
            min_returned_stream_id, _, _, _, _ = subscriptions[0]
            result["end"] = ThreadSubscriptionsToken(
                # We subtract one because the 'later in the stream' bound is inclusive,
                # and we already saw the element at index 0.
                stream_id=min_returned_stream_id - 1
            ).to_string()

        return HTTPStatus.OK, result


def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
    if hs.config.experimental.msc4306_enabled:
        ThreadSubscriptionsRestServlet(hs).register(http_server)
        ThreadSubscriptionsPaginationRestServlet(hs).register(http_server)