Coverage for slidge / group / archive.py: 98%

90 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-02-15 09:02 +0000

1import logging 

2import uuid 

3import warnings 

4from collections.abc import Collection 

5from copy import copy 

6from datetime import UTC, datetime 

7from typing import TYPE_CHECKING, Optional 

8 

9from slixmpp import Iq, Message 

10 

11from ..db.models import ArchivedMessage, ArchivedMessageSource, Room 

12from ..db.store import SlidgeStore 

13from ..util.archive_msg import HistoryMessage 

14from ..util.types import HoleBound 

15 

16if TYPE_CHECKING: 

17 from .participant import LegacyParticipant 

18 

19 

20class MessageArchive: 

21 def __init__(self, room: Room, store: SlidgeStore) -> None: 

22 self.room = room 

23 self.__rooms_store = store.rooms 

24 self.__store = store.mam 

25 

26 def add( 

27 self, 

28 msg: Message, 

29 participant: Optional["LegacyParticipant"] = None, 

30 archive_only: bool = False, 

31 legacy_msg_id=None, 

32 ) -> None: 

33 """ 

34 Add a message to the archive if it is deemed archivable 

35 

36 :param msg: 

37 :param participant: 

38 :param archive_only: 

39 :param legacy_msg_id: 

40 """ 

41 if not archivable(msg): 

42 return 

43 new_msg = copy(msg) 

44 if participant and not participant.muc.is_anonymous: 

45 new_msg["muc"]["role"] = participant.role or "participant" 

46 new_msg["muc"]["affiliation"] = participant.affiliation or "member" 

47 if participant.contact: 

48 new_msg["muc"]["jid"] = participant.contact.jid.bare 

49 elif participant.is_user: 

50 new_msg["muc"]["jid"] = participant.user_jid.bare 

51 elif participant.is_system: 

52 new_msg["muc"]["jid"] = participant.muc.jid 

53 else: 

54 warnings.warn( 

55 f"No real JID for participant '{participant.nickname}' in '{self.room.name}'" 

56 ) 

57 new_msg["muc"]["jid"] = ( 

58 f"{uuid.uuid4()}@{participant.xmpp.boundjid.bare}" 

59 ) 

60 

61 with self.__store.session(expire_on_commit=False) as orm: 

62 if self.room.id is None: 

63 self.room = self.__rooms_store.get( 

64 orm, self.room.user_account_id, self.room.legacy_id 

65 ) 

66 self.__store.add_message( 

67 orm, 

68 self.room.id, 

69 HistoryMessage(new_msg), 

70 archive_only, 

71 None if legacy_msg_id is None else str(legacy_msg_id), 

72 ) 

73 orm.commit() 

74 

75 def __iter__(self): 

76 return iter(self.get_all()) 

77 

78 @staticmethod 

79 def __to_bound(stored: ArchivedMessage): 

80 return HoleBound( 

81 stored.legacy_id, # type:ignore 

82 stored.timestamp.replace(tzinfo=UTC), 

83 ) 

84 

85 def get_hole_bounds(self) -> tuple[HoleBound | None, HoleBound | None]: 

86 with self.__store.session() as orm: 

87 most_recent = self.__store.get_most_recent_with_legacy_id(orm, self.room.id) 

88 if most_recent is None: 

89 return None, None 

90 if most_recent.source == ArchivedMessageSource.BACKFILL: 

91 # most recent = only backfill, fetch everything since last backfill 

92 return self.__to_bound(most_recent), None 

93 

94 most_recent_back_filled = self.__store.get_most_recent_with_legacy_id( 

95 orm, self.room.id, ArchivedMessageSource.BACKFILL 

96 ) 

97 if most_recent_back_filled is None: 

98 # group was never back-filled, fetch everything before first live 

99 least_recent_live = self.__store.get_first(orm, self.room.id, True) 

100 assert least_recent_live is not None 

101 return None, self.__to_bound(least_recent_live) 

102 

103 assert most_recent_back_filled.legacy_id is not None 

104 least_recent_live = self.__store.get_least_recent_with_legacy_id_after( 

105 orm, self.room.id, most_recent_back_filled.legacy_id 

106 ) 

107 assert least_recent_live is not None 

108 # this is a hole caused by slidge downtime 

109 return self.__to_bound(most_recent_back_filled), self.__to_bound( 

110 least_recent_live 

111 ) 

112 

113 def get_all( 

114 self, 

115 start_date: datetime | None = None, 

116 end_date: datetime | None = None, 

117 before_id: str | None = None, 

118 after_id: str | None = None, 

119 ids: Collection[str] = (), 

120 last_page_n: int | None = None, 

121 sender: str | None = None, 

122 flip: bool = False, 

123 ): 

124 with self.__store.session() as orm: 

125 yield from self.__store.get_messages( 

126 orm, 

127 self.room.id, 

128 before_id=before_id, 

129 after_id=after_id, 

130 ids=ids, 

131 last_page_n=last_page_n, 

132 sender=sender, 

133 start_date=start_date, 

134 end_date=end_date, 

135 flip=flip, 

136 ) 

137 

138 async def send_metadata(self, iq: Iq) -> None: 

139 """ 

140 Send archive extent, as per the spec 

141 

142 :param iq: 

143 :return: 

144 """ 

145 reply = iq.reply() 

146 with self.__store.session() as orm: 

147 messages = self.__store.get_first_and_last(orm, self.room.id) 

148 if messages: 

149 for x, m in [("start", messages[0]), ("end", messages[-1])]: 

150 reply["mam_metadata"][x]["id"] = m.id 

151 reply["mam_metadata"][x]["timestamp"] = m.sent_on.replace(tzinfo=UTC) 

152 else: 

153 reply.enable("mam_metadata") 

154 reply.send() 

155 

156 

157def archivable(msg: Message) -> bool: 

158 """ 

159 Determine if a message stanza is worth archiving, ie, convey meaningful 

160 info 

161 

162 :param msg: 

163 :return: 

164 """ 

165 

166 if msg.get_plugin("no-store", check=True): 

167 return False 

168 

169 if msg.get_plugin("no-permanent-store", check=True): 

170 return False 

171 

172 if msg.get_plugin("store", check=True): 

173 return True 

174 

175 if msg["body"]: 

176 return True 

177 

178 if msg.get_plugin("retract", check=True): 

179 return True 

180 

181 if msg.get_plugin("reactions", check=True): 

182 return True 

183 

184 if msg.get_plugin("displayed", check=True): 

185 return True 

186 

187 if msg["thread"] and msg["subject"]: 

188 return True 

189 

190 return False 

191 

192 

193log = logging.getLogger(__name__)