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

Commit ff716b4

Browse files
authored
Return attrs for more media repo APIs. (#16611)
1 parent 91587d4 commit ff716b4

File tree

10 files changed

+148
-110
lines changed

10 files changed

+148
-110
lines changed

changelog.d/16611.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve type hints.

synapse/handlers/profile.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
import logging
1515
import random
16-
from typing import TYPE_CHECKING, Optional
16+
from typing import TYPE_CHECKING, Optional, Union
1717

1818
from synapse.api.errors import (
1919
AuthError,
@@ -23,6 +23,7 @@
2323
StoreError,
2424
SynapseError,
2525
)
26+
from synapse.storage.databases.main.media_repository import LocalMedia, RemoteMedia
2627
from synapse.types import JsonDict, Requester, UserID, create_requester
2728
from synapse.util.caches.descriptors import cached
2829
from synapse.util.stringutils import parse_and_validate_mxc_uri
@@ -306,7 +307,9 @@ async def check_avatar_size_and_mime_type(self, mxc: str) -> bool:
306307
server_name = host
307308

308309
if self._is_mine_server_name(server_name):
309-
media_info = await self.store.get_local_media(media_id)
310+
media_info: Optional[
311+
Union[LocalMedia, RemoteMedia]
312+
] = await self.store.get_local_media(media_id)
310313
else:
311314
media_info = await self.store.get_cached_remote_media(server_name, media_id)
312315

@@ -322,25 +325,25 @@ async def check_avatar_size_and_mime_type(self, mxc: str) -> bool:
322325

323326
if self.max_avatar_size:
324327
# Ensure avatar does not exceed max allowed avatar size
325-
if media_info["media_length"] > self.max_avatar_size:
328+
if media_info.media_length > self.max_avatar_size:
326329
logger.warning(
327330
"Forbidding avatar change to %s: %d bytes is above the allowed size "
328331
"limit",
329332
mxc,
330-
media_info["media_length"],
333+
media_info.media_length,
331334
)
332335
return False
333336

334337
if self.allowed_avatar_mimetypes:
335338
# Ensure the avatar's file type is allowed
336339
if (
337340
self.allowed_avatar_mimetypes
338-
and media_info["media_type"] not in self.allowed_avatar_mimetypes
341+
and media_info.media_type not in self.allowed_avatar_mimetypes
339342
):
340343
logger.warning(
341344
"Forbidding avatar change to %s: mimetype %s not allowed",
342345
mxc,
343-
media_info["media_type"],
346+
media_info.media_type,
344347
)
345348
return False
346349

synapse/handlers/sso.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,7 @@ def is_allowed_mime_type(content_type: str) -> bool:
806806
media_id = profile["avatar_url"].split("/")[-1]
807807
if self._is_mine_server_name(server_name):
808808
media = await self._media_repo.store.get_local_media(media_id)
809-
if media is not None and upload_name == media["upload_name"]:
809+
if media is not None and upload_name == media.upload_name:
810810
logger.info("skipping saving the user avatar")
811811
return True
812812

synapse/media/media_repository.py

Lines changed: 40 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from io import BytesIO
2020
from typing import IO, TYPE_CHECKING, Dict, List, Optional, Set, Tuple
2121

22+
import attr
2223
from matrix_common.types.mxc_uri import MXCUri
2324

2425
import twisted.internet.error
@@ -50,6 +51,7 @@
5051
from synapse.media.thumbnailer import Thumbnailer, ThumbnailError
5152
from synapse.media.url_previewer import UrlPreviewer
5253
from synapse.metrics.background_process_metrics import run_as_background_process
54+
from synapse.storage.databases.main.media_repository import RemoteMedia
5355
from synapse.types import UserID
5456
from synapse.util.async_helpers import Linearizer
5557
from synapse.util.retryutils import NotRetryingDestination
@@ -245,18 +247,18 @@ async def get_local_media(
245247
Resolves once a response has successfully been written to request
246248
"""
247249
media_info = await self.store.get_local_media(media_id)
248-
if not media_info or media_info["quarantined_by"]:
250+
if not media_info or media_info.quarantined_by:
249251
respond_404(request)
250252
return
251253

252254
self.mark_recently_accessed(None, media_id)
253255

254-
media_type = media_info["media_type"]
256+
media_type = media_info.media_type
255257
if not media_type:
256258
media_type = "application/octet-stream"
257-
media_length = media_info["media_length"]
258-
upload_name = name if name else media_info["upload_name"]
259-
url_cache = media_info["url_cache"]
259+
media_length = media_info.media_length
260+
upload_name = name if name else media_info.upload_name
261+
url_cache = media_info.url_cache
260262

261263
file_info = FileInfo(None, media_id, url_cache=bool(url_cache))
262264

@@ -310,16 +312,20 @@ async def get_remote_media(
310312

311313
# We deliberately stream the file outside the lock
312314
if responder:
313-
media_type = media_info["media_type"]
314-
media_length = media_info["media_length"]
315-
upload_name = name if name else media_info["upload_name"]
315+
upload_name = name if name else media_info.upload_name
316316
await respond_with_responder(
317-
request, responder, media_type, media_length, upload_name
317+
request,
318+
responder,
319+
media_info.media_type,
320+
media_info.media_length,
321+
upload_name,
318322
)
319323
else:
320324
respond_404(request)
321325

322-
async def get_remote_media_info(self, server_name: str, media_id: str) -> dict:
326+
async def get_remote_media_info(
327+
self, server_name: str, media_id: str
328+
) -> RemoteMedia:
323329
"""Gets the media info associated with the remote file, downloading
324330
if necessary.
325331
@@ -353,7 +359,7 @@ async def get_remote_media_info(self, server_name: str, media_id: str) -> dict:
353359

354360
async def _get_remote_media_impl(
355361
self, server_name: str, media_id: str
356-
) -> Tuple[Optional[Responder], dict]:
362+
) -> Tuple[Optional[Responder], RemoteMedia]:
357363
"""Looks for media in local cache, if not there then attempt to
358364
download from remote server.
359365
@@ -373,15 +379,17 @@ async def _get_remote_media_impl(
373379

374380
# If we have an entry in the DB, try and look for it
375381
if media_info:
376-
file_id = media_info["filesystem_id"]
382+
file_id = media_info.filesystem_id
377383
file_info = FileInfo(server_name, file_id)
378384

379-
if media_info["quarantined_by"]:
385+
if media_info.quarantined_by:
380386
logger.info("Media is quarantined")
381387
raise NotFoundError()
382388

383-
if not media_info["media_type"]:
384-
media_info["media_type"] = "application/octet-stream"
389+
if not media_info.media_type:
390+
media_info = attr.evolve(
391+
media_info, media_type="application/octet-stream"
392+
)
385393

386394
responder = await self.media_storage.fetch_media(file_info)
387395
if responder:
@@ -403,9 +411,9 @@ async def _get_remote_media_impl(
403411
if not media_info:
404412
raise e
405413

406-
file_id = media_info["filesystem_id"]
407-
if not media_info["media_type"]:
408-
media_info["media_type"] = "application/octet-stream"
414+
file_id = media_info.filesystem_id
415+
if not media_info.media_type:
416+
media_info = attr.evolve(media_info, media_type="application/octet-stream")
409417
file_info = FileInfo(server_name, file_id)
410418

411419
# We generate thumbnails even if another process downloaded the media
@@ -415,7 +423,7 @@ async def _get_remote_media_impl(
415423
# otherwise they'll request thumbnails and get a 404 if they're not
416424
# ready yet.
417425
await self._generate_thumbnails(
418-
server_name, media_id, file_id, media_info["media_type"]
426+
server_name, media_id, file_id, media_info.media_type
419427
)
420428

421429
responder = await self.media_storage.fetch_media(file_info)
@@ -425,7 +433,7 @@ async def _download_remote_file(
425433
self,
426434
server_name: str,
427435
media_id: str,
428-
) -> dict:
436+
) -> RemoteMedia:
429437
"""Attempt to download the remote file from the given server name,
430438
using the given file_id as the local id.
431439
@@ -518,23 +526,25 @@ async def _download_remote_file(
518526
origin=server_name,
519527
media_id=media_id,
520528
media_type=media_type,
521-
time_now_ms=self.clock.time_msec(),
529+
time_now_ms=time_now_ms,
522530
upload_name=upload_name,
523531
media_length=length,
524532
filesystem_id=file_id,
525533
)
526534

527535
logger.info("Stored remote media in file %r", fname)
528536

529-
media_info = {
530-
"media_type": media_type,
531-
"media_length": length,
532-
"upload_name": upload_name,
533-
"created_ts": time_now_ms,
534-
"filesystem_id": file_id,
535-
}
536-
537-
return media_info
537+
return RemoteMedia(
538+
media_origin=server_name,
539+
media_id=media_id,
540+
media_type=media_type,
541+
media_length=length,
542+
upload_name=upload_name,
543+
created_ts=time_now_ms,
544+
filesystem_id=file_id,
545+
last_access_ts=time_now_ms,
546+
quarantined_by=None,
547+
)
538548

539549
def _get_thumbnail_requirements(
540550
self, media_type: str

synapse/media/url_previewer.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -240,15 +240,14 @@ async def _do_preview(self, url: str, user: UserID, ts: int) -> bytes:
240240
cache_result = await self.store.get_url_cache(url, ts)
241241
if (
242242
cache_result
243-
and cache_result["expires_ts"] > ts
244-
and cache_result["response_code"] / 100 == 2
243+
and cache_result.expires_ts > ts
244+
and cache_result.response_code // 100 == 2
245245
):
246246
# It may be stored as text in the database, not as bytes (such as
247247
# PostgreSQL). If so, encode it back before handing it on.
248-
og = cache_result["og"]
249-
if isinstance(og, str):
250-
og = og.encode("utf8")
251-
return og
248+
if isinstance(cache_result.og, str):
249+
return cache_result.og.encode("utf8")
250+
return cache_result.og
252251

253252
# If this URL can be accessed via an allowed oEmbed, use that instead.
254253
url_to_download = url

synapse/rest/media/thumbnail_resource.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ async def _respond_local_thumbnail(
119119
if not media_info:
120120
respond_404(request)
121121
return
122-
if media_info["quarantined_by"]:
122+
if media_info.quarantined_by:
123123
logger.info("Media is quarantined")
124124
respond_404(request)
125125
return
@@ -134,7 +134,7 @@ async def _respond_local_thumbnail(
134134
thumbnail_infos,
135135
media_id,
136136
media_id,
137-
url_cache=bool(media_info["url_cache"]),
137+
url_cache=bool(media_info.url_cache),
138138
server_name=None,
139139
)
140140

@@ -152,7 +152,7 @@ async def _select_or_generate_local_thumbnail(
152152
if not media_info:
153153
respond_404(request)
154154
return
155-
if media_info["quarantined_by"]:
155+
if media_info.quarantined_by:
156156
logger.info("Media is quarantined")
157157
respond_404(request)
158158
return
@@ -168,7 +168,7 @@ async def _select_or_generate_local_thumbnail(
168168
file_info = FileInfo(
169169
server_name=None,
170170
file_id=media_id,
171-
url_cache=media_info["url_cache"],
171+
url_cache=bool(media_info.url_cache),
172172
thumbnail=info,
173173
)
174174

@@ -188,7 +188,7 @@ async def _select_or_generate_local_thumbnail(
188188
desired_height,
189189
desired_method,
190190
desired_type,
191-
url_cache=bool(media_info["url_cache"]),
191+
url_cache=bool(media_info.url_cache),
192192
)
193193

194194
if file_path:
@@ -213,7 +213,7 @@ async def _select_or_generate_remote_thumbnail(
213213
server_name, media_id
214214
)
215215

216-
file_id = media_info["filesystem_id"]
216+
file_id = media_info.filesystem_id
217217

218218
for info in thumbnail_infos:
219219
t_w = info.width == desired_width
@@ -224,7 +224,7 @@ async def _select_or_generate_remote_thumbnail(
224224
if t_w and t_h and t_method and t_type:
225225
file_info = FileInfo(
226226
server_name=server_name,
227-
file_id=media_info["filesystem_id"],
227+
file_id=file_id,
228228
thumbnail=info,
229229
)
230230

@@ -280,7 +280,7 @@ async def _respond_remote_thumbnail(
280280
m_type,
281281
thumbnail_infos,
282282
media_id,
283-
media_info["filesystem_id"],
283+
media_info.filesystem_id,
284284
url_cache=False,
285285
server_name=server_name,
286286
)

0 commit comments

Comments
 (0)