10
10
import asyncio
11
11
import time
12
12
13
+ from yarl import URL
14
+
13
15
from mautrix import __optional_imports__
14
16
from mautrix .api import MediaPath , Method
15
17
from mautrix .errors import MatrixResponseError , make_request_error
19
21
MediaRepoConfig ,
20
22
MXOpenGraph ,
21
23
SerializerError ,
24
+ SpecVersions ,
22
25
)
23
26
from mautrix .util import background_task
24
27
from mautrix .util .async_body import async_iter_bytes
@@ -178,13 +181,17 @@ async def download_media(self, url: ContentURI, timeout_ms: int | None = None) -
178
181
Returns:
179
182
The raw downloaded data.
180
183
"""
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 )
182
186
query_params : dict [str , Any ] = {"allow_redirect" : "true" }
183
187
if timeout_ms is not None :
184
188
query_params ["timeout_ms" ] = timeout_ms
189
+ headers : dict [str , str ] = {}
190
+ if authenticated :
191
+ headers ["Authorization" ] = f"Bearer { self .api .token } "
185
192
req_id = self .api .log_download_request (url , query_params )
186
193
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 :
188
195
try :
189
196
response .raise_for_status ()
190
197
return await response .read ()
@@ -223,7 +230,10 @@ async def download_thumbnail(
223
230
Returns:
224
231
The raw downloaded data.
225
232
"""
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
+ )
227
237
query_params : dict [str , Any ] = {"allow_redirect" : "true" }
228
238
if width is not None :
229
239
query_params ["width" ] = width
@@ -235,9 +245,12 @@ async def download_thumbnail(
235
245
query_params ["allow_remote" ] = str (allow_remote ).lower ()
236
246
if timeout_ms is not None :
237
247
query_params ["timeout_ms" ] = timeout_ms
248
+ headers : dict [str , str ] = {}
249
+ if authenticated :
250
+ headers ["Authorization" ] = f"Bearer { self .api .token } "
238
251
req_id = self .api .log_download_request (url , query_params )
239
252
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 :
241
254
try :
242
255
response .raise_for_status ()
243
256
return await response .read ()
0 commit comments