Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 7fe7b42

Browse files
author
David Robertson
committed
Formally type the UserProfile in user searches
1 parent 12d1f82 commit 7fe7b42

File tree

5 files changed

+36
-12
lines changed

5 files changed

+36
-12
lines changed

synapse/events/spamcheck.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
Awaitable,
2222
Callable,
2323
Collection,
24-
Dict,
2524
List,
2625
Optional,
2726
Tuple,
@@ -31,7 +30,7 @@
3130
from synapse.rest.media.v1._base import FileInfo
3231
from synapse.rest.media.v1.media_storage import ReadableFileWrapper
3332
from synapse.spam_checker_api import RegistrationBehaviour
34-
from synapse.types import RoomAlias
33+
from synapse.types import RoomAlias, UserProfile
3534
from synapse.util.async_helpers import maybe_awaitable
3635

3736
if TYPE_CHECKING:
@@ -50,7 +49,7 @@
5049
USER_MAY_CREATE_ROOM_CALLBACK = Callable[[str], Awaitable[bool]]
5150
USER_MAY_CREATE_ROOM_ALIAS_CALLBACK = Callable[[str, RoomAlias], Awaitable[bool]]
5251
USER_MAY_PUBLISH_ROOM_CALLBACK = Callable[[str, str], Awaitable[bool]]
53-
CHECK_USERNAME_FOR_SPAM_CALLBACK = Callable[[Dict[str, str]], Awaitable[bool]]
52+
CHECK_USERNAME_FOR_SPAM_CALLBACK = Callable[[UserProfile], Awaitable[bool]]
5453
LEGACY_CHECK_REGISTRATION_FOR_SPAM_CALLBACK = Callable[
5554
[
5655
Optional[dict],
@@ -383,7 +382,7 @@ async def user_may_publish_room(self, userid: str, room_id: str) -> bool:
383382

384383
return True
385384

386-
async def check_username_for_spam(self, user_profile: Dict[str, str]) -> bool:
385+
async def check_username_for_spam(self, user_profile: UserProfile) -> bool:
387386
"""Checks if a user ID or display name are considered "spammy" by this server.
388387
389388
If the server considers a username spammy, then it will not be included in

synapse/handlers/user_directory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules, Membership
2020
from synapse.handlers.state_deltas import MatchChange, StateDeltasHandler
2121
from synapse.metrics.background_process_metrics import run_as_background_process
22+
from synapse.storage.databases.main.user_directory import SearchResult
2223
from synapse.storage.roommember import ProfileInfo
23-
from synapse.types import JsonDict
2424
from synapse.util.metrics import Measure
2525

2626
if TYPE_CHECKING:
@@ -78,7 +78,7 @@ def __init__(self, hs: "HomeServer"):
7878

7979
async def search_users(
8080
self, user_id: str, search_term: str, limit: int
81-
) -> JsonDict:
81+
) -> SearchResult:
8282
"""Searches for users in directory
8383
8484
Returns:

synapse/rest/client/user_directory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from synapse.http.server import HttpServer
2020
from synapse.http.servlet import RestServlet, parse_json_object_from_request
2121
from synapse.http.site import SynapseRequest
22-
from synapse.types import JsonDict
22+
from synapse.types import JsonMapping
2323

2424
from ._base import client_patterns
2525

@@ -38,7 +38,7 @@ def __init__(self, hs: "HomeServer"):
3838
self.auth = hs.get_auth()
3939
self.user_directory_handler = hs.get_user_directory_handler()
4040

41-
async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
41+
async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonMapping]:
4242
"""Searches for users in directory
4343
4444
Returns:

synapse/storage/databases/main/user_directory.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
Sequence,
2424
Set,
2525
Tuple,
26+
TypedDict,
2627
cast,
2728
)
2829

@@ -40,7 +41,12 @@
4041
from synapse.storage.databases.main.state import StateFilter
4142
from synapse.storage.databases.main.state_deltas import StateDeltasStore
4243
from synapse.storage.engines import PostgresEngine, Sqlite3Engine
43-
from synapse.types import JsonDict, get_domain_from_id, get_localpart_from_id
44+
from synapse.types import (
45+
JsonDict,
46+
UserProfile,
47+
get_domain_from_id,
48+
get_localpart_from_id,
49+
)
4450
from synapse.util.caches.descriptors import cached
4551

4652
logger = logging.getLogger(__name__)
@@ -591,6 +597,11 @@ async def update_user_directory_stream_pos(self, stream_id: Optional[int]) -> No
591597
)
592598

593599

600+
class SearchResult(TypedDict):
601+
limited: bool
602+
results: List[UserProfile]
603+
604+
594605
class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
595606
# How many records do we calculate before sending it to
596607
# add_users_who_share_private_rooms?
@@ -777,7 +788,7 @@ async def get_user_directory_stream_pos(self) -> Optional[int]:
777788

778789
async def search_user_dir(
779790
self, user_id: str, search_term: str, limit: int
780-
) -> JsonDict:
791+
) -> SearchResult:
781792
"""Searches for users in directory
782793
783794
Returns:
@@ -910,8 +921,11 @@ async def search_user_dir(
910921
# This should be unreachable.
911922
raise Exception("Unrecognized database engine")
912923

913-
results = await self.db_pool.execute(
914-
"search_user_dir", self.db_pool.cursor_to_dict, sql, *args
924+
results = cast(
925+
List[UserProfile],
926+
await self.db_pool.execute(
927+
"search_user_dir", self.db_pool.cursor_to_dict, sql, *args
928+
),
915929
)
916930

917931
limited = len(results) > limit

synapse/types.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
Optional,
2828
Tuple,
2929
Type,
30+
TypedDict,
3031
TypeVar,
3132
Union,
3233
)
@@ -63,6 +64,10 @@
6364
# JSON types. These could be made stronger, but will do for now.
6465
# A JSON-serialisable dict.
6566
JsonDict = Dict[str, Any]
67+
# A JSON-serialisable mapping; roughly speaking an immutable JSONDict.
68+
# Useful when you have a TypedDict which isn't going to be mutated and you don't want
69+
# to cast to JsonDict everywhere.
70+
JsonMapping = Mapping[str, Any]
6671
# A JSON-serialisable object.
6772
JsonSerializable = object
6873

@@ -791,3 +796,9 @@ class UserInfo:
791796
is_deactivated: bool
792797
is_guest: bool
793798
is_shadow_banned: bool
799+
800+
801+
class UserProfile(TypedDict):
802+
user_id: str
803+
display_name: Optional[str]
804+
avatar_url: Optional[str]

0 commit comments

Comments
 (0)