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

109 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-08-18 04:30 +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 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(self.set_avatar(avatar)) 

66 

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

68 if self.avatar is None: 

69 return avatar is not None 

70 if avatar is None: 

71 return self.avatar is not None 

72 

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

74 return self.avatar.unique_id != avatar.unique_id 

75 

76 if ( 

77 self.avatar.url is not None 

78 and avatar.url is not None 

79 and self.avatar.url == avatar.url 

80 ): 

81 return await avatar_cache.url_modified(avatar.url) 

82 

83 if avatar.path is not None: 

84 cached = self.get_cached_avatar() 

85 if cached is not None: 

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

87 

88 return True 

89 

90 async def set_avatar( 

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

92 ) -> None: 

93 """ 

94 Set an avatar for this entity 

95 

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

97 ID 

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

99 it once used or not. 

100 """ 

101 avatar = convert_avatar(avatar) 

102 

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

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

105 avatar = Avatar( 

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

107 ) 

108 

109 try: 

110 if not await self.__has_changed(avatar): 

111 return 

112 except Exception: 

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

114 return 

115 

116 if avatar is None: 

117 cached_avatar = None 

118 else: 

119 try: 

120 cached_avatar = await avatar_cache.convert_or_get(avatar) 

121 except UnidentifiedImageError: 

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

123 cached_avatar = None 

124 except Exception: 

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

126 cached_avatar = None 

127 

128 if delete: 

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

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

131 else: 

132 avatar.path.unlink() 

133 

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

135 if not self._updating_info: 

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

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

138 orm.refresh(self.stored) 

139 

140 self.stored.avatar = stored_avatar 

141 self.commit() 

142 

143 self._post_avatar_update(cached_avatar) 

144 

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

146 try: 

147 if self.stored.avatar is None: 

148 return None 

149 except DetachedInstanceError: 

150 self.merge() 

151 if self.stored.avatar is None: 

152 return None 

153 return avatar_cache.get(self.stored.avatar) 

154 

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

156 cached_avatar = self.get_cached_avatar() 

157 if cached_avatar is None: 

158 return None 

159 from ..pubsub import PepAvatar 

160 

161 item = PepAvatar() 

162 item.set_avatar_from_cache(cached_avatar) 

163 return item 

164 

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

166 raise NotImplementedError 

167 

168 

169def convert_avatar( 

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

171) -> Avatar | None: 

172 if isinstance(avatar, Path): 

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

174 if isinstance(avatar, str): 

175 return Avatar(url=avatar) 

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

177 return None 

178 return avatar