mirror of
https://git.anonymousland.org/anonymousland/synapse.git
synced 2024-10-01 11:49:51 -04:00
158d73ebdd
Revert "Sort internal changes in changelog" Revert "Update CHANGES.md" Revert "1.49.0rc1" Revert "Revert "Move `glob_to_regex` and `re_word_boundary` to `matrix-python-common` (#11505) (#11527)" Revert "Refactors in `_generate_sync_entry_for_rooms` (#11515)" Revert "Correctly register shutdown handler for presence workers (#11518)" Revert "Fix `ModuleApi.looping_background_call` for non-async functions (#11524)" Revert "Fix 'delete room' admin api to work on incomplete rooms (#11523)" Revert "Correctly ignore invites from ignored users (#11511)" Revert "Fix the test breakage introduced by #11435 as a result of concurrent PRs (#11522)" Revert "Stabilise support for MSC2918 refresh tokens as they have now been merged into the Matrix specification. (#11435)" Revert "Save the OIDC session ID (sid) with the device on login (#11482)" Revert "Add admin API to get some information about federation status (#11407)" Revert "Include bundled aggregations in /sync and related fixes (#11478)" Revert "Move `glob_to_regex` and `re_word_boundary` to `matrix-python-common` (#11505)" Revert "Update backward extremity docs to make it clear that it does not indicate whether we have fetched an events' `prev_events` (#11469)" Revert "Support configuring the lifetime of non-refreshable access tokens separately to refreshable access tokens. (#11445)" Revert "Add type hints to `synapse/tests/rest/admin` (#11501)" Revert "Revert accidental commits to develop." Revert "Newsfile" Revert "Give `tests.server.setup_test_homeserver` (nominally!) the same behaviour" Revert "Move `tests.utils.setup_test_homeserver` to `tests.server`" Revert "Convert one of the `setup_test_homeserver`s to `make_test_homeserver_synchronous`" Revert "Disambiguate queries on `state_key` (#11497)" Revert "Comments on the /sync tentacles (#11494)" Revert "Clean up tests.storage.test_appservice (#11492)" Revert "Clean up `tests.storage.test_main` to remove use of legacy code. (#11493)" Revert "Clean up `tests.test_visibility` to remove legacy code. (#11495)" Revert "Minor cleanup on recently ported doc pages (#11466)" Revert "Add most of the missing type hints to `synapse.federation`. (#11483)" Revert "Avoid waiting for zombie processes in `synctl stop` (#11490)" Revert "Fix media repository failing when media store path contains symlinks (#11446)" Revert "Add type annotations to `tests.storage.test_appservice`. (#11488)" Revert "`scripts-dev/sign_json`: support for signing events (#11486)" Revert "Add MSC3030 experimental client and federation API endpoints to get the closest event to a given timestamp (#9445)" Revert "Port wiki pages to documentation website (#11402)" Revert "Add a license header and comment. (#11479)" Revert "Clean-up get_version_string (#11468)" Revert "Link background update controller docs to summary (#11475)" Revert "Additional type hints for config module. (#11465)" Revert "Register the login redirect endpoint for v3. (#11451)" Revert "Update openid.md" Revert "Remove mention of OIDC certification from Dex (#11470)" Revert "Add a note about huge pages to our Postgres doc (#11467)" Revert "Don't start Synapse master process if `worker_app` is set (#11416)" Revert "Expose worker & homeserver as entrypoints in `setup.py` (#11449)" Revert "Bundle relations of relations into the `/relations` result. (#11284)" Revert "Fix `LruCache` corruption bug with a `size_callback` that can return 0 (#11454)" Revert "Eliminate a few `Any`s in `LruCache` type hints (#11453)" Revert "Remove unnecessary `json.dumps` from `tests.rest.admin` (#11461)" Revert "Merge branch 'master' into develop" This reverts commit26b5d2320f
. This reverts commitbce4220f38
. This reverts commit966b5d0fa0
. This reverts commit088d748f2c
. This reverts commit14d593f72d
. This reverts commit2a3ec6facf
. This reverts commiteccc49d755
. This reverts commitb1ecd19c5d
. This reverts commit9c55dedc8c
. This reverts commit2d42e586a8
. This reverts commit2f053f3f82
. This reverts commita15a893df8
. This reverts commit8b4b153c9e
. This reverts commit494ebd7347
. This reverts commita77c369897
. This reverts commit4eb77965cd
. This reverts commit637df95de6
. This reverts commite5f426cd54
. This reverts commit8cd68b8102
. This reverts commit6cae125e20
. This reverts commit7be88fbf48
. This reverts commitb3fd99b74a
. This reverts commitf7ec6e7d9e
. This reverts commit5640992d17
. This reverts commitd26808dd85
. This reverts commitf91624a595
. This reverts commit16d39a5490
. This reverts commit8a4c296987
. This reverts commit49e1356ee3
. This reverts commitd2279f471b
. This reverts commitb50e39df57
. This reverts commit858d80bf0f
. This reverts commit435f044807
. This reverts commitf61462e1be
. This reverts commita6f1a3abec
. This reverts commit84dc50e160
. This reverts commited635d3285
. This reverts commit7b62791e00
. This reverts commit153194c771
. This reverts commitf44d729d4c
. This reverts commita265fbd397
. This reverts commitb9fef1a7cd
. This reverts commitb0eb64ff7b
. This reverts commitf1795463bf
. This reverts commit70cbb1a5e3
. This reverts commit42bf020463
. This reverts commit379f2650cf
. This reverts commit7ff22d6da4
. This reverts commit5a0b652d36
. This reverts commit432a174bc1
. This reverts commitb14f8a1baf
, reversing changes made toe713855dca
.
483 lines
17 KiB
Python
483 lines
17 KiB
Python
# Copyright 2016 OpenMarket Ltd
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import logging
|
|
from typing import TYPE_CHECKING, List, Optional, Tuple
|
|
|
|
from twisted.internet import defer
|
|
|
|
from synapse.api.constants import EduTypes, EventTypes, Membership
|
|
from synapse.api.errors import SynapseError
|
|
from synapse.events.validator import EventValidator
|
|
from synapse.handlers.presence import format_user_presence_state
|
|
from synapse.handlers.receipts import ReceiptEventSource
|
|
from synapse.logging.context import make_deferred_yieldable, run_in_background
|
|
from synapse.storage.roommember import RoomsForUser
|
|
from synapse.streams.config import PaginationConfig
|
|
from synapse.types import JsonDict, Requester, RoomStreamToken, StreamToken, UserID
|
|
from synapse.util import unwrapFirstError
|
|
from synapse.util.async_helpers import concurrently_execute
|
|
from synapse.util.caches.response_cache import ResponseCache
|
|
from synapse.visibility import filter_events_for_client
|
|
|
|
if TYPE_CHECKING:
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class InitialSyncHandler:
|
|
def __init__(self, hs: "HomeServer"):
|
|
self.store = hs.get_datastore()
|
|
self.auth = hs.get_auth()
|
|
self.state_handler = hs.get_state_handler()
|
|
self.hs = hs
|
|
self.state = hs.get_state_handler()
|
|
self.clock = hs.get_clock()
|
|
self.validator = EventValidator()
|
|
self.snapshot_cache: ResponseCache[
|
|
Tuple[
|
|
str,
|
|
Optional[StreamToken],
|
|
Optional[StreamToken],
|
|
str,
|
|
Optional[int],
|
|
bool,
|
|
bool,
|
|
]
|
|
] = ResponseCache(hs.get_clock(), "initial_sync_cache")
|
|
self._event_serializer = hs.get_event_client_serializer()
|
|
self.storage = hs.get_storage()
|
|
self.state_store = self.storage.state
|
|
|
|
async def snapshot_all_rooms(
|
|
self,
|
|
user_id: str,
|
|
pagin_config: PaginationConfig,
|
|
as_client_event: bool = True,
|
|
include_archived: bool = False,
|
|
) -> JsonDict:
|
|
"""Retrieve a snapshot of all rooms the user is invited or has joined.
|
|
|
|
This snapshot may include messages for all rooms where the user is
|
|
joined, depending on the pagination config.
|
|
|
|
Args:
|
|
user_id: The ID of the user making the request.
|
|
pagin_config: The pagination config used to determine how many
|
|
messages *PER ROOM* to return.
|
|
as_client_event: True to get events in client-server format.
|
|
include_archived: True to get rooms that the user has left
|
|
Returns:
|
|
A JsonDict with the same format as the response to `/intialSync`
|
|
API
|
|
"""
|
|
key = (
|
|
user_id,
|
|
pagin_config.from_token,
|
|
pagin_config.to_token,
|
|
pagin_config.direction,
|
|
pagin_config.limit,
|
|
as_client_event,
|
|
include_archived,
|
|
)
|
|
|
|
return await self.snapshot_cache.wrap(
|
|
key,
|
|
self._snapshot_all_rooms,
|
|
user_id,
|
|
pagin_config,
|
|
as_client_event,
|
|
include_archived,
|
|
)
|
|
|
|
async def _snapshot_all_rooms(
|
|
self,
|
|
user_id: str,
|
|
pagin_config: PaginationConfig,
|
|
as_client_event: bool = True,
|
|
include_archived: bool = False,
|
|
) -> JsonDict:
|
|
|
|
memberships = [Membership.INVITE, Membership.JOIN]
|
|
if include_archived:
|
|
memberships.append(Membership.LEAVE)
|
|
|
|
room_list = await self.store.get_rooms_for_local_user_where_membership_is(
|
|
user_id=user_id, membership_list=memberships
|
|
)
|
|
|
|
user = UserID.from_string(user_id)
|
|
|
|
rooms_ret = []
|
|
|
|
now_token = self.hs.get_event_sources().get_current_token()
|
|
|
|
presence_stream = self.hs.get_event_sources().sources.presence
|
|
presence, _ = await presence_stream.get_new_events(
|
|
user, from_key=None, include_offline=False
|
|
)
|
|
|
|
joined_rooms = [r.room_id for r in room_list if r.membership == Membership.JOIN]
|
|
receipt = await self.store.get_linearized_receipts_for_rooms(
|
|
joined_rooms,
|
|
to_key=int(now_token.receipt_key),
|
|
)
|
|
if self.hs.config.experimental.msc2285_enabled:
|
|
receipt = ReceiptEventSource.filter_out_hidden(receipt, user_id)
|
|
|
|
tags_by_room = await self.store.get_tags_for_user(user_id)
|
|
|
|
account_data, account_data_by_room = await self.store.get_account_data_for_user(
|
|
user_id
|
|
)
|
|
|
|
public_room_ids = await self.store.get_public_room_ids()
|
|
|
|
limit = pagin_config.limit
|
|
if limit is None:
|
|
limit = 10
|
|
|
|
async def handle_room(event: RoomsForUser) -> None:
|
|
d: JsonDict = {
|
|
"room_id": event.room_id,
|
|
"membership": event.membership,
|
|
"visibility": (
|
|
"public" if event.room_id in public_room_ids else "private"
|
|
),
|
|
}
|
|
|
|
if event.membership == Membership.INVITE:
|
|
time_now = self.clock.time_msec()
|
|
d["inviter"] = event.sender
|
|
|
|
invite_event = await self.store.get_event(event.event_id)
|
|
d["invite"] = await self._event_serializer.serialize_event(
|
|
invite_event, time_now, as_client_event
|
|
)
|
|
|
|
rooms_ret.append(d)
|
|
|
|
if event.membership not in (Membership.JOIN, Membership.LEAVE):
|
|
return
|
|
|
|
try:
|
|
if event.membership == Membership.JOIN:
|
|
room_end_token = now_token.room_key
|
|
deferred_room_state = run_in_background(
|
|
self.state_handler.get_current_state, event.room_id
|
|
)
|
|
elif event.membership == Membership.LEAVE:
|
|
room_end_token = RoomStreamToken(
|
|
None,
|
|
event.stream_ordering,
|
|
)
|
|
deferred_room_state = run_in_background(
|
|
self.state_store.get_state_for_events, [event.event_id]
|
|
)
|
|
deferred_room_state.addCallback(
|
|
lambda states: states[event.event_id]
|
|
)
|
|
|
|
(messages, token), current_state = await make_deferred_yieldable(
|
|
defer.gatherResults(
|
|
[
|
|
run_in_background(
|
|
self.store.get_recent_events_for_room,
|
|
event.room_id,
|
|
limit=limit,
|
|
end_token=room_end_token,
|
|
),
|
|
deferred_room_state,
|
|
]
|
|
)
|
|
).addErrback(unwrapFirstError)
|
|
|
|
messages = await filter_events_for_client(
|
|
self.storage, user_id, messages
|
|
)
|
|
|
|
start_token = now_token.copy_and_replace("room_key", token)
|
|
end_token = now_token.copy_and_replace("room_key", room_end_token)
|
|
time_now = self.clock.time_msec()
|
|
|
|
d["messages"] = {
|
|
"chunk": (
|
|
await self._event_serializer.serialize_events(
|
|
messages, time_now=time_now, as_client_event=as_client_event
|
|
)
|
|
),
|
|
"start": await start_token.to_string(self.store),
|
|
"end": await end_token.to_string(self.store),
|
|
}
|
|
|
|
d["state"] = await self._event_serializer.serialize_events(
|
|
current_state.values(),
|
|
time_now=time_now,
|
|
as_client_event=as_client_event,
|
|
)
|
|
|
|
account_data_events = []
|
|
tags = tags_by_room.get(event.room_id)
|
|
if tags:
|
|
account_data_events.append(
|
|
{"type": "m.tag", "content": {"tags": tags}}
|
|
)
|
|
|
|
account_data = account_data_by_room.get(event.room_id, {})
|
|
for account_data_type, content in account_data.items():
|
|
account_data_events.append(
|
|
{"type": account_data_type, "content": content}
|
|
)
|
|
|
|
d["account_data"] = account_data_events
|
|
except Exception:
|
|
logger.exception("Failed to get snapshot")
|
|
|
|
await concurrently_execute(handle_room, room_list, 10)
|
|
|
|
account_data_events = []
|
|
for account_data_type, content in account_data.items():
|
|
account_data_events.append({"type": account_data_type, "content": content})
|
|
|
|
now = self.clock.time_msec()
|
|
|
|
ret = {
|
|
"rooms": rooms_ret,
|
|
"presence": [
|
|
{
|
|
"type": "m.presence",
|
|
"content": format_user_presence_state(event, now),
|
|
}
|
|
for event in presence
|
|
],
|
|
"account_data": account_data_events,
|
|
"receipts": receipt,
|
|
"end": await now_token.to_string(self.store),
|
|
}
|
|
|
|
return ret
|
|
|
|
async def room_initial_sync(
|
|
self, requester: Requester, room_id: str, pagin_config: PaginationConfig
|
|
) -> JsonDict:
|
|
"""Capture the a snapshot of a room. If user is currently a member of
|
|
the room this will be what is currently in the room. If the user left
|
|
the room this will be what was in the room when they left.
|
|
|
|
Args:
|
|
requester: The user to get a snapshot for.
|
|
room_id: The room to get a snapshot of.
|
|
pagin_config: The pagination config used to determine how many
|
|
messages to return.
|
|
Raises:
|
|
AuthError if the user wasn't in the room.
|
|
Returns:
|
|
A JSON serialisable dict with the snapshot of the room.
|
|
"""
|
|
|
|
blocked = await self.store.is_room_blocked(room_id)
|
|
if blocked:
|
|
raise SynapseError(403, "This room has been blocked on this server")
|
|
|
|
user_id = requester.user.to_string()
|
|
|
|
(
|
|
membership,
|
|
member_event_id,
|
|
) = await self.auth.check_user_in_room_or_world_readable(
|
|
room_id,
|
|
user_id,
|
|
allow_departed_users=True,
|
|
)
|
|
is_peeking = member_event_id is None
|
|
|
|
if membership == Membership.JOIN:
|
|
result = await self._room_initial_sync_joined(
|
|
user_id, room_id, pagin_config, membership, is_peeking
|
|
)
|
|
elif membership == Membership.LEAVE:
|
|
# The member_event_id will always be available if membership is set
|
|
# to leave.
|
|
assert member_event_id
|
|
|
|
result = await self._room_initial_sync_parted(
|
|
user_id, room_id, pagin_config, membership, member_event_id, is_peeking
|
|
)
|
|
|
|
account_data_events = []
|
|
tags = await self.store.get_tags_for_room(user_id, room_id)
|
|
if tags:
|
|
account_data_events.append({"type": "m.tag", "content": {"tags": tags}})
|
|
|
|
account_data = await self.store.get_account_data_for_room(user_id, room_id)
|
|
for account_data_type, content in account_data.items():
|
|
account_data_events.append({"type": account_data_type, "content": content})
|
|
|
|
result["account_data"] = account_data_events
|
|
|
|
return result
|
|
|
|
async def _room_initial_sync_parted(
|
|
self,
|
|
user_id: str,
|
|
room_id: str,
|
|
pagin_config: PaginationConfig,
|
|
membership: str,
|
|
member_event_id: str,
|
|
is_peeking: bool,
|
|
) -> JsonDict:
|
|
room_state = await self.state_store.get_state_for_event(member_event_id)
|
|
|
|
limit = pagin_config.limit if pagin_config else None
|
|
if limit is None:
|
|
limit = 10
|
|
|
|
leave_position = await self.store.get_position_for_event(member_event_id)
|
|
stream_token = leave_position.to_room_stream_token()
|
|
|
|
messages, token = await self.store.get_recent_events_for_room(
|
|
room_id, limit=limit, end_token=stream_token
|
|
)
|
|
|
|
messages = await filter_events_for_client(
|
|
self.storage, user_id, messages, is_peeking=is_peeking
|
|
)
|
|
|
|
start_token = StreamToken.START.copy_and_replace("room_key", token)
|
|
end_token = StreamToken.START.copy_and_replace("room_key", stream_token)
|
|
|
|
time_now = self.clock.time_msec()
|
|
|
|
return {
|
|
"membership": membership,
|
|
"room_id": room_id,
|
|
"messages": {
|
|
"chunk": (
|
|
await self._event_serializer.serialize_events(messages, time_now)
|
|
),
|
|
"start": await start_token.to_string(self.store),
|
|
"end": await end_token.to_string(self.store),
|
|
},
|
|
"state": (
|
|
await self._event_serializer.serialize_events(
|
|
room_state.values(), time_now
|
|
)
|
|
),
|
|
"presence": [],
|
|
"receipts": [],
|
|
}
|
|
|
|
async def _room_initial_sync_joined(
|
|
self,
|
|
user_id: str,
|
|
room_id: str,
|
|
pagin_config: PaginationConfig,
|
|
membership: str,
|
|
is_peeking: bool,
|
|
) -> JsonDict:
|
|
current_state = await self.state.get_current_state(room_id=room_id)
|
|
|
|
# TODO: These concurrently
|
|
time_now = self.clock.time_msec()
|
|
state = await self._event_serializer.serialize_events(
|
|
current_state.values(), time_now
|
|
)
|
|
|
|
now_token = self.hs.get_event_sources().get_current_token()
|
|
|
|
limit = pagin_config.limit if pagin_config else None
|
|
if limit is None:
|
|
limit = 10
|
|
|
|
room_members = [
|
|
m
|
|
for m in current_state.values()
|
|
if m.type == EventTypes.Member
|
|
and m.content["membership"] == Membership.JOIN
|
|
]
|
|
|
|
presence_handler = self.hs.get_presence_handler()
|
|
|
|
async def get_presence() -> List[JsonDict]:
|
|
# If presence is disabled, return an empty list
|
|
if not self.hs.config.server.use_presence:
|
|
return []
|
|
|
|
states = await presence_handler.get_states(
|
|
[m.user_id for m in room_members]
|
|
)
|
|
|
|
return [
|
|
{
|
|
"type": EduTypes.Presence,
|
|
"content": format_user_presence_state(s, time_now),
|
|
}
|
|
for s in states
|
|
]
|
|
|
|
async def get_receipts() -> List[JsonDict]:
|
|
receipts = await self.store.get_linearized_receipts_for_room(
|
|
room_id, to_key=now_token.receipt_key
|
|
)
|
|
if not receipts:
|
|
return []
|
|
if self.hs.config.experimental.msc2285_enabled:
|
|
receipts = ReceiptEventSource.filter_out_hidden(receipts, user_id)
|
|
return receipts
|
|
|
|
presence, receipts, (messages, token) = await make_deferred_yieldable(
|
|
defer.gatherResults(
|
|
[
|
|
run_in_background(get_presence),
|
|
run_in_background(get_receipts),
|
|
run_in_background(
|
|
self.store.get_recent_events_for_room,
|
|
room_id,
|
|
limit=limit,
|
|
end_token=now_token.room_key,
|
|
),
|
|
],
|
|
consumeErrors=True,
|
|
).addErrback(unwrapFirstError)
|
|
)
|
|
|
|
messages = await filter_events_for_client(
|
|
self.storage, user_id, messages, is_peeking=is_peeking
|
|
)
|
|
|
|
start_token = now_token.copy_and_replace("room_key", token)
|
|
end_token = now_token
|
|
|
|
time_now = self.clock.time_msec()
|
|
|
|
ret = {
|
|
"room_id": room_id,
|
|
"messages": {
|
|
"chunk": (
|
|
await self._event_serializer.serialize_events(messages, time_now)
|
|
),
|
|
"start": await start_token.to_string(self.store),
|
|
"end": await end_token.to_string(self.store),
|
|
},
|
|
"state": state,
|
|
"presence": presence,
|
|
"receipts": receipts,
|
|
}
|
|
if not is_peeking:
|
|
ret["membership"] = membership
|
|
|
|
return ret
|