Coverage for slidge/core/mixins/avatar.py: 88%

115 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-09-10 04:45 +0000

1import hashlib 

2from asyncio import Task 

3from logging import Logger 

4from pathlib import Path 

5from typing import TYPE_CHECKING, Optional 

6 

7from PIL import UnidentifiedImageError 

8from sqlalchemy.orm.exc import DetachedInstanceError 

9 

10from ...db.avatar import AvatarDownloadError, CachedAvatar, avatar_cache 

11from ...db.models import Contact, Room 

12from ...util.types import Avatar 

13from .base import SessionBound 

14from .db import UpdateInfoMixin 

15 

16if TYPE_CHECKING: 

17 from ..pubsub import PepAvatar 

18 

19 

20class AvatarMixin(UpdateInfoMixin, SessionBound): 

21 """ 

22 Mixin for XMPP entities that have avatars that represent them. 

23 

24 Both :py:class:`slidge.LegacyContact` and :py:class:`slidge.LegacyMUC` use 

25 :py:class:`.AvatarMixin`. 

26 """ 

27 

28 stored: Contact | Room 

29 log: Logger 

30 

31 def __init__(self) -> None: 

32 super().__init__() 

33 self._set_avatar_task: Task[None] | None = None 

34 

35 @property 

36 def avatar(self) -> Avatar | None: 

37 """ 

38 This property can be used to set or unset the avatar. 

39 

40 Unlike the awaitable :func:`.set_avatar`, it schedules the update for 

41 later execution and is not blocking 

42 """ 

43 try: 

44 if self.stored.avatar is None: 

45 return None 

46 except DetachedInstanceError: 

47 self.merge() 

48 if self.stored.avatar is None: 

49 return None 

50 if self.stored.avatar.legacy_id is None: 

51 unique_id = None 

52 else: 

53 unique_id = self.stored.avatar.legacy_id 

54 return Avatar( 

55 unique_id=unique_id, 

56 url=self.stored.avatar.url, 

57 ) 

58 

59 @avatar.setter 

60 def avatar(self, avatar: Avatar | Path | str | None) -> None: 

61 avatar = convert_avatar(avatar) 

62 if self._set_avatar_task: 

63 self._set_avatar_task.cancel() 

64 self.log.debug("Setting avatar with property") 

65 self._set_avatar_task = self.session.create_task( 

66 self.set_avatar(avatar), name=f"set avatar of {self}" 

67 ) 

68 

69 async def __has_changed(self, avatar: Avatar | None) -> bool: 

70 if self.avatar is None: 

71 return avatar is not None 

72 if avatar is None: 

73 return self.avatar is not None 

74 

75 if self.avatar.unique_id is not None and avatar.unique_id is not None: 

76 return self.avatar.unique_id != avatar.unique_id 

77 

78 if ( 

79 self.avatar.url is not None 

80 and avatar.url is not None 

81 and self.avatar.url == avatar.url 

82 ): 

83 return await avatar_cache.url_modified(avatar.url) 

84 

85 if avatar.path is not None: 

86 cached = self.get_cached_avatar() 

87 if cached is not None: 

88 return cached.path.read_bytes() != avatar.path.read_bytes() 

89 

90 return True 

91 

92 async def set_avatar( 

93 self, avatar: Avatar | Path | str | None = None, delete: bool = False 

94 ) -> None: 

95 """ 

96 Set an avatar for this entity 

97 

98 :param avatar: The avatar. Should ideally come with a legacy network-wide unique 

99 ID 

100 :param delete: If the avatar is provided as a Path, whether to delete 

101 it once used or not. 

102 """ 

103 avatar = convert_avatar(avatar) 

104 

105 if avatar is not None and avatar.unique_id is None and avatar.data is not None: 

106 self.log.debug("Hashing bytes to generate a unique ID") 

107 avatar = Avatar( 

108 data=avatar.data, unique_id=hashlib.sha512(avatar.data).hexdigest() 

109 ) 

110 

111 try: 

112 if not await self.__has_changed(avatar): 

113 return 

114 except AvatarDownloadError as e: 

115 self.log.warning("Could not determine if avatar has changed: %s", e) 

116 return 

117 except Exception: 

118 self.log.exception("Could not determine if avatar has changed, giving up") 

119 return 

120 

121 if avatar is None: 

122 cached_avatar = None 

123 else: 

124 try: 

125 cached_avatar = await avatar_cache.get(avatar, self.session) 

126 except UnidentifiedImageError: 

127 self.log.warning("%s is not a valid image", avatar) 

128 cached_avatar = None 

129 except AvatarDownloadError as e: 

130 self.log.warning("Could not fetch avatar %s: %s", avatar, e) 

131 cached_avatar = None 

132 except Exception: 

133 self.log.exception("Failed to set avatar '%s'", avatar) 

134 cached_avatar = None 

135 

136 if delete: 

137 if avatar is None or avatar.path is None: 

138 self.log.warning("Requested avatar path delete, but no path provided") 

139 else: 

140 avatar.path.unlink() 

141 

142 stored_avatar = None if cached_avatar is None else cached_avatar.stored 

143 if not self._updating_info: 

144 with self.xmpp.store.session() as orm, orm.no_autoflush: 

145 self.stored = orm.merge(self.stored) 

146 orm.refresh(self.stored) 

147 

148 self.stored.avatar = stored_avatar 

149 self.commit() 

150 

151 self._post_avatar_update(cached_avatar) 

152 

153 def get_cached_avatar(self) -> Optional["CachedAvatar"]: 

154 try: 

155 if self.stored.avatar is None: 

156 return None 

157 except DetachedInstanceError: 

158 self.merge() 

159 if self.stored.avatar is None: 

160 return None 

161 return avatar_cache.from_stored(self.stored.avatar) 

162 

163 def get_avatar(self) -> Optional["PepAvatar"]: 

164 cached_avatar = self.get_cached_avatar() 

165 if cached_avatar is None: 

166 return None 

167 from ..pubsub import PepAvatar 

168 

169 item = PepAvatar() 

170 item.set_avatar_from_cache(cached_avatar) 

171 return item 

172 

173 def _post_avatar_update(self, cached_avatar: Optional["CachedAvatar"]) -> None: 

174 raise NotImplementedError 

175 

176 

177def convert_avatar( 

178 avatar: Avatar | Path | str | None, unique_id: str | None = None 

179) -> Avatar | None: 

180 if isinstance(avatar, Path): 

181 return Avatar(path=avatar, unique_id=unique_id) 

182 if isinstance(avatar, str): 

183 return Avatar(url=avatar) 

184 if avatar is None or all(x is None for x in avatar): 

185 return None 

186 return avatar