feat: separate upload method
This commit is contained in:
parent
e622815da3
commit
6e7df85a5f
1 changed files with 20 additions and 14 deletions
|
@ -92,6 +92,21 @@ class AppService:
|
|||
else:
|
||||
return "https://" + self.homeserver + self._MEDIA_API_ROOT
|
||||
|
||||
async def upload(self, content: bytes, content_type: str, filename: str = "") -> str:
|
||||
async with self._client.request(
|
||||
method="POST",
|
||||
url=f"{self.media_api}/upload",
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.as_token}",
|
||||
"Content-Type": content_type,
|
||||
},
|
||||
data=content,
|
||||
params={"filename": filename or str(uuid.uuid4())},
|
||||
) as res:
|
||||
res.raise_for_status()
|
||||
doc = await res.json()
|
||||
return doc["content_uri"]
|
||||
|
||||
@property
|
||||
def api_headers(self) -> dict[str, str]:
|
||||
return {
|
||||
|
@ -127,21 +142,12 @@ class AppService:
|
|||
return doc["user_id"]
|
||||
|
||||
async def set_avatar(self, mxid: str, avatar_url: str) -> None:
|
||||
async with self._client.get(avatar_url) as res:
|
||||
res.raise_for_status()
|
||||
async with self._client.request(
|
||||
method="POST",
|
||||
url=f"{self.media_api}/upload",
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.as_token}",
|
||||
"Content-Type": res.content_type,
|
||||
},
|
||||
data=await res.content.read(),
|
||||
params={"filename":str(uuid.uuid4())},
|
||||
) as res:
|
||||
if avatar_url.startswith("mxc://"): # TODO is this check enough?
|
||||
avatar_uri = avatar_url
|
||||
else:
|
||||
async with self._client.get(avatar_url) as res:
|
||||
res.raise_for_status()
|
||||
doc = await res.json()
|
||||
avatar_uri = doc["content_uri"]
|
||||
avatar_uri = await self.upload(await res.content.read(), res.content_type)
|
||||
async with self._client.request(
|
||||
method="PUT",
|
||||
url=f"{self.client_api}/profile/{mxid}/avatar_url",
|
||||
|
|
Loading…
Reference in a new issue