Improve MatrixError.from_nio, use it for upload()

This commit is contained in:
miruka 2019-11-11 06:08:31 -04:00
parent dbdb7b9bb0
commit de7053f196
2 changed files with 24 additions and 30 deletions

View File

@ -15,7 +15,7 @@
- Video: missing buttons and small size problems
- Audio: online playback is buggy, must download+play file
- EventLink
- Downloading (right click on media > save as...)
- EventFile & Downloading (right click on media > save as...)
- RoomMessageNotice

View File

@ -36,6 +36,7 @@ CryptDict = Dict[str, Any]
@dataclass
class MatrixError(Exception):
http_code: int = 400
m_code: str = "M_UNKNOWN"
@classmethod
@ -44,19 +45,31 @@ class MatrixError(Exception):
if subcls.m_code == response.status_code:
return subcls()
return cls(response.status_code)
for subcls in cls.__subclasses__():
if subcls.http_code == response.transport_response.status:
return subcls()
@dataclass
class MatrixNotFound(MatrixError):
m_code: str = "M_NOT_FOUND"
return cls(response.transport_response.status, response.status_code)
@dataclass
class MatrixForbidden(MatrixError):
http_code: int = 403
m_code: str = "M_FORBIDDEN"
@dataclass
class MatrixNotFound(MatrixError):
http_code: int = 404
m_code: str = "M_NOT_FOUND"
@dataclass
class MatrixTooLarge(MatrixError):
http_code: int = 413
m_code: str = "M_TOO_LARGE"
@dataclass
class UserNotFound(Exception):
user_id: str = field()
@ -66,19 +79,6 @@ class UserNotFound(Exception):
class InvalidUserInContext(Exception):
user_id: str = field()
@dataclass
class UploadError(Exception):
http_code: Optional[int] = None
@dataclass
class UploadForbidden(UploadError):
http_code: Optional[int] = 403
@dataclass
class UploadTooLarge(UploadError):
http_code: Optional[int] = 413
@dataclass
class UneededThumbnail(Exception):
@ -656,17 +656,11 @@ class MatrixClient(nio.AsyncClient):
) -> str:
response = await super().upload(data, mime, filename)
if not isinstance(response, nio.ErrorResponse):
if isinstance(response, nio.UploadError):
raise MatrixError.from_nio(response)
return response.content_uri
if response.status_code == 403:
raise UploadForbidden()
if response.status_code == 413:
raise UploadTooLarge()
raise UploadError(response.status_code)
async def set_avatar_from_file(self, path: Union[Path, str]) -> None:
# TODO: check if mime is image