Use exceptions for get_profile

This commit is contained in:
miruka 2019-11-12 08:47:03 -04:00
parent 6558bdc87f
commit 4cc2ebf6e3
2 changed files with 20 additions and 17 deletions

View File

@ -8,12 +8,11 @@ import nio
from . import utils
from .app import App
from .matrix_client import MatrixClient, MatrixError
from .errors import MatrixError
from .matrix_client import MatrixClient
from .models.items import Account, Device, Event, Member, Room, Upload
from .models.model_store import ModelStore
ProfileResponse = Union[nio.ProfileGetResponse, nio.ProfileGetError]
class Backend:
def __init__(self, app: App) -> None:
@ -169,7 +168,7 @@ class Backend:
return (settings, ui_state, theme)
async def get_profile(self, user_id: str) -> ProfileResponse:
async def get_profile(self, user_id: str) -> nio.ProfileGetResponse:
if user_id in self.profile_cache:
return self.profile_cache[user_id]
@ -185,7 +184,7 @@ class Backend:
response = await client.get_profile(user_id)
if isinstance(response, nio.ProfileGetError):
log.warning("%s: %s", user_id, response)
raise MatrixError.from_nio(response)
self.profile_cache[user_id] = response
return response

View File

@ -130,12 +130,14 @@ class MatrixClient(nio.AsyncClient):
async def start(self) -> None:
def on_profile_response(future) -> None:
resp = future.result()
if isinstance(resp, nio.ProfileGetResponse):
account = self.models[Account][self.user_id]
account.profile_updated = datetime.now()
account.display_name = resp.displayname or ""
account.avatar_url = resp.avatar_url or ""
if future.exception():
return
resp = future.result()
account = self.models[Account][self.user_id]
account.profile_updated = datetime.now()
account.display_name = resp.displayname or ""
account.avatar_url = resp.avatar_url or ""
ft = asyncio.ensure_future(self.backend.get_profile(self.user_id))
ft.add_done_callback(on_profile_response)
@ -409,7 +411,9 @@ class MatrixClient(nio.AsyncClient):
if invite == self.user_id:
raise InvalidUserInContext(invite)
if isinstance(await self.get_profile(invite), nio.ProfileGetError):
try:
await self.get_profile(invite)
except MatrixError:
raise UserNotFound(invite)
response = await super().room_create(
@ -786,11 +790,11 @@ class MatrixClient(nio.AsyncClient):
try:
item = self.models[Member, room_id][user_id]
except KeyError: # e.g. user is not anymore in the room
info = await self.backend.get_profile(user_id)
return (info.displayname or "", info.avatar_url or "") \
if isinstance(info, nio.ProfileGetResponse) else \
("", "")
try:
info = await self.backend.get_profile(user_id)
return (info.displayname or "", info.avatar_url or "")
except MatrixError:
return ("", "")
else:
return (item.display_name, item.avatar_url)