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

88 statements  

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

1import logging 

2import uuid 

3import warnings 

4from collections.abc import Collection, Iterator 

5from copy import copy 

6from datetime import UTC, datetime 

7 

8from slixmpp import Iq, Message 

9 

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

11from ..db.store import SlidgeStore 

12from ..util.types import AnyParticipant, HoleBound 

13 

14 

15class MessageArchive: 

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

17 self.room = room 

18 self.__rooms_store = store.rooms 

19 self.__store = store.mam 

20 

21 def add( 

22 self, 

23 msg: Message, 

24 participant: "AnyParticipant | None" = None, 

25 archive_only: bool = False, 

26 legacy_msg_id: str | None = None, 

27 ) -> None: 

28 """ 

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

30 

31 :param msg: 

32 :param participant: 

33 :param archive_only: 

34 :param legacy_msg_id: 

35 """ 

36 if not archivable(msg): 

37 return 

38 new_msg = copy(msg) 

39 if participant and not participant.muc.is_anonymous: 

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

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

42 if participant.contact: 

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

44 elif participant.is_user: 

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

46 elif participant.is_system: 

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

48 else: 

49 warnings.warn( 

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

51 ) 

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

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

54 ) 

55 

56 if "replace" in msg: 

57 legacy_msg_id = None 

58 

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

60 if self.room.id is None: 

61 self.room = self.__rooms_store.get( 

62 orm, self.room.user_account_id, self.room.legacy_id 

63 ) 

64 self.__store.add_message( 

65 orm, 

66 self.room.id, 

67 new_msg, 

68 archive_only, 

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

70 from_user=participant is not None and participant.is_user, 

71 ) 

72 orm.commit() 

73 

74 def __iter__(self) -> Iterator[ArchivedMessage]: 

75 return iter(self.get_all()) 

76 

77 @staticmethod 

78 def __to_bound(stored: ArchivedMessage) -> HoleBound: 

79 return HoleBound( 

80 stored.legacy_id, # type:ignore 

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

82 ) 

83 

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

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

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

87 if most_recent is None: 

88 return None, None 

89 if most_recent.source == ArchivedMessageSource.BACKFILL: 

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

91 return self.__to_bound(most_recent), None 

92 

93 most_recent_back_filled = self.__store.get_most_recent_with_legacy_id( 

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

95 ) 

96 if most_recent_back_filled is None: 

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

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

99 assert least_recent_live is not None 

100 return None, self.__to_bound(least_recent_live) 

101 

102 assert most_recent_back_filled.legacy_id is not None 

103 least_recent_live = self.__store.get_least_recent_with_legacy_id_after( 

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

105 ) 

106 assert least_recent_live is not None 

107 # this is a hole caused by slidge downtime 

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

109 least_recent_live 

110 ) 

111 

112 def get_all( 

113 self, 

114 start_date: datetime | None = None, 

115 end_date: datetime | None = None, 

116 before_id: str | None = None, 

117 after_id: str | None = None, 

118 ids: Collection[str] = (), 

119 last_page_n: int | None = None, 

120 author_resource: str | None = None, 

121 flip: bool = False, 

122 ) -> Iterator[ArchivedMessage]: 

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

124 yield from self.__store.get_messages( 

125 orm, 

126 self.room.id, 

127 before_id=before_id, 

128 after_id=after_id, 

129 ids=ids, 

130 last_page_n=last_page_n, 

131 author_resource=author_resource, 

132 start_date=start_date, 

133 end_date=end_date, 

134 flip=flip, 

135 ) 

136 

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

138 """ 

139 Send archive extent, as per the spec 

140 

141 :param iq: 

142 :return: 

143 """ 

144 reply = iq.reply() 

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

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

147 if messages: 

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

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

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

151 else: 

152 reply.enable("mam_metadata") 

153 reply.send() 

154 

155 

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

157 """ 

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

159 info 

160 

161 :param msg: 

162 :return: 

163 """ 

164 

165 if "no-store" in msg: 

166 return False 

167 

168 if "no-permanent-store" in msg: 

169 return False 

170 

171 if "store" in msg: 

172 return True 

173 

174 if msg["body"]: 

175 return True 

176 

177 if "retract" in msg: 

178 return True 

179 

180 if "reactions" in msg: 

181 return True 

182 

183 if "displayed" in msg: 

184 return True 

185 

186 return bool(msg["thread"] and msg["subject"]) 

187 

188 

189log = logging.getLogger(__name__)