1010import asyncio
1111import time
1212
13+ from yarl import URL
14+
1315from mautrix import __optional_imports__
1416from mautrix .api import MediaPath , Method
1517from mautrix .errors import MatrixResponseError , make_request_error
1921 MediaRepoConfig ,
2022 MXOpenGraph ,
2123 SerializerError ,
24+ SpecVersions ,
2225)
2326from mautrix .util import background_task
2427from mautrix .util .async_body import async_iter_bytes
@@ -178,13 +181,17 @@ async def download_media(self, url: ContentURI, timeout_ms: int | None = None) -
178181 Returns:
179182 The raw downloaded data.
180183 """
181- url = self .api .get_download_url (url )
184+ authenticated = (await self .versions ()).supports (SpecVersions .V111 )
185+ url = self .api .get_download_url (url , authenticated = authenticated )
182186 query_params : dict [str , Any ] = {"allow_redirect" : "true" }
183187 if timeout_ms is not None :
184188 query_params ["timeout_ms" ] = timeout_ms
189+ headers : dict [str , str ] = {}
190+ if authenticated :
191+ headers ["Authorization" ] = f"Bearer { self .api .token } "
185192 req_id = self .api .log_download_request (url , query_params )
186193 start = time .monotonic ()
187- async with self .api .session .get (url , params = query_params ) as response :
194+ async with self .api .session .get (url , params = query_params , headers = headers ) as response :
188195 try :
189196 response .raise_for_status ()
190197 return await response .read ()
@@ -223,7 +230,10 @@ async def download_thumbnail(
223230 Returns:
224231 The raw downloaded data.
225232 """
226- url = self .api .get_download_url (url , download_type = "thumbnail" )
233+ authenticated = (await self .versions ()).supports (SpecVersions .V111 )
234+ url = self .api .get_download_url (
235+ url , download_type = "thumbnail" , authenticated = authenticated
236+ )
227237 query_params : dict [str , Any ] = {"allow_redirect" : "true" }
228238 if width is not None :
229239 query_params ["width" ] = width
@@ -235,9 +245,12 @@ async def download_thumbnail(
235245 query_params ["allow_remote" ] = str (allow_remote ).lower ()
236246 if timeout_ms is not None :
237247 query_params ["timeout_ms" ] = timeout_ms
248+ headers : dict [str , str ] = {}
249+ if authenticated :
250+ headers ["Authorization" ] = f"Bearer { self .api .token } "
238251 req_id = self .api .log_download_request (url , query_params )
239252 start = time .monotonic ()
240- async with self .api .session .get (url , params = query_params ) as response :
253+ async with self .api .session .get (url , params = query_params , headers = headers ) as response :
241254 try :
242255 response .raise_for_status ()
243256 return await response .read ()
0 commit comments