Debian Codegraph @

sync.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package mautrix
8
9 import (
10 "fmt"
11 "runtime/debug"
12 "time"
13
14 "maunium.net/go/mautrix/event"
15 "maunium.net/go/mautrix/id"
16 )
17
18 // EventSource represents the part of the sync response that an event came from.
19 type EventSource int
20
21 const (
22 EventSourcePresence EventSource = 1 << iota
23 EventSourceJoin
24 EventSourceInvite
25 EventSourceLeave
26 EventSourceAccountData
27 EventSourceTimeline
28 EventSourceState
29 EventSourceEphemeral
30 EventSourceToDevice
31 )
32
33 func (es EventSource) String() string {
34 switch {
35 case es == EventSourcePresence:
36 return "presence"
37 case es == EventSourceAccountData:
38 return "user account data"
39 case es == EventSourceToDevice:
40 return "to-device"
41 case es&EventSourceJoin != 0:
42 es -= EventSourceJoin
43 switch es {
44 case EventSourceState:
45 return "joined state"
46 case EventSourceTimeline:
47 return "joined timeline"
48 case EventSourceEphemeral:
49 return "room ephemeral (joined)"
50 case EventSourceAccountData:
51 return "room account data (joined)"
52 }
53 case es&EventSourceInvite != 0:
54 es -= EventSourceInvite
55 switch es {
56 case EventSourceState:
57 return "invited state"
58 }
59 case es&EventSourceLeave != 0:
60 es -= EventSourceLeave
61 switch es {
62 case EventSourceState:
63 return "left state"
64 case EventSourceTimeline:
65 return "left timeline"
66 }
67 }
68 return fmt.Sprintf("unknown (%d)", es)
69 }
70
71 // EventHandler handles a single event from a sync response.
72 type EventHandler func(source EventSource, evt *event.Event)
73
74 // SyncHandler handles a whole sync response. If the return value is false, handling will be stopped completely.
75 type SyncHandler func(resp *RespSync, since string) bool
76
77 // Syncer is an interface that must be satisfied in order to do /sync requests on a client.
78 type Syncer interface {
79 // Process the /sync response. The since parameter is the since= value that was used to produce the response.
80 // This is useful for detecting the very first sync (since=""). If an error is return, Syncing will be stopped
81 // permanently.
82 ProcessResponse(resp *RespSync, since string) error
83 // OnFailedSync returns either the time to wait before retrying or an error to stop syncing permanently.
84 OnFailedSync(res *RespSync, err error) (time.Duration, error)
85 // GetFilterJSON for the given user ID. NOT the filter ID.
86 GetFilterJSON(userID id.UserID) *Filter
87 }
88
89 type ExtensibleSyncer interface {
90 OnSync(callback SyncHandler)
91 OnEvent(callback EventHandler)
92 OnEventType(eventType event.Type, callback EventHandler)
93 }
94
95 // DefaultSyncer is the default syncing implementation. You can either write your own syncer, or selectively
96 // replace parts of this default syncer (e.g. the ProcessResponse method). The default syncer uses the observer
97 // pattern to notify callers about incoming events. See DefaultSyncer.OnEventType for more information.
98 type DefaultSyncer struct {
99 // syncListeners want the whole sync response, e.g. the crypto machine
100 syncListeners []SyncHandler
101 // globalListeners want all events
102 globalListeners []EventHandler
103 // listeners want a specific event type
104 listeners map[event.Type][]EventHandler
105 // ParseEventContent determines whether or not event content should be parsed before passing to handlers.
106 ParseEventContent bool
107 // ParseErrorHandler is called when event.Content.ParseRaw returns an error.
108 // If it returns false, the event will not be forwarded to listeners.
109 ParseErrorHandler func(evt *event.Event, err error) bool
110 }
111
112 var _ Syncer = (*DefaultSyncer)(nil)
113 var _ ExtensibleSyncer = (*DefaultSyncer)(nil)
114
115 // NewDefaultSyncer returns an instantiated DefaultSyncer
116 func NewDefaultSyncer() *DefaultSyncer {
117 return &DefaultSyncer{
118 listeners: make(map[event.Type][]EventHandler),
119 syncListeners: []SyncHandler{},
120 globalListeners: []EventHandler{},
121 ParseEventContent: true,
122 ParseErrorHandler: func(evt *event.Event, err error) bool {
123 return false
124 },
125 }
126 }
127
128 // ProcessResponse processes the /sync response in a way suitable for bots. "Suitable for bots" means a stream of
129 // unrepeating events. Returns a fatal error if a listener panics.
130 func (s *DefaultSyncer) ProcessResponse(res *RespSync, since string) (err error) {
131 defer func() {
132 if r := recover(); r != nil {
133 err = fmt.Errorf("ProcessResponse panicked! since=%s panic=%s\n%s", since, r, debug.Stack())
134 }
135 }()
136
137 for _, listener := range s.syncListeners {
138 if !listener(res, since) {
139 return
140 }
141 }
142
143 s.processSyncEvents("", res.Presence.Events, EventSourcePresence)
144 s.processSyncEvents("", res.AccountData.Events, EventSourceAccountData)
145
146 for roomID, roomData := range res.Rooms.Join {
147 s.processSyncEvents(roomID, roomData.State.Events, EventSourceJoin|EventSourceState)
148 s.processSyncEvents(roomID, roomData.Timeline.Events, EventSourceJoin|EventSourceTimeline)
149 s.processSyncEvents(roomID, roomData.Ephemeral.Events, EventSourceJoin|EventSourceEphemeral)
150 s.processSyncEvents(roomID, roomData.AccountData.Events, EventSourceJoin|EventSourceAccountData)
151 }
152 for roomID, roomData := range res.Rooms.Invite {
153 s.processSyncEvents(roomID, roomData.State.Events, EventSourceInvite|EventSourceState)
154 }
155 for roomID, roomData := range res.Rooms.Leave {
156 s.processSyncEvents(roomID, roomData.State.Events, EventSourceLeave|EventSourceState)
157 s.processSyncEvents(roomID, roomData.Timeline.Events, EventSourceLeave|EventSourceTimeline)
158 }
159 return
160 }
161
162 func (s *DefaultSyncer) processSyncEvents(roomID id.RoomID, events []*event.Event, source EventSource) {
163 for _, evt := range events {
164 s.processSyncEvent(roomID, evt, source)
165 }
166 }
167
168 func (s *DefaultSyncer) processSyncEvent(roomID id.RoomID, evt *event.Event, source EventSource) {
169 evt.RoomID = roomID
170
171 // Ensure the type class is correct. It's safe to mutate the class since the event type is not a pointer.
172 // Listeners are keyed by type structs, which means only the correct class will pass.
173 switch {
174 case evt.StateKey != nil:
175 evt.Type.Class = event.StateEventType
176 case source == EventSourcePresence, source&EventSourceEphemeral != 0:
177 evt.Type.Class = event.EphemeralEventType
178 case source&EventSourceAccountData != 0:
179 evt.Type.Class = event.AccountDataEventType
180 case source == EventSourceToDevice:
181 evt.Type.Class = event.ToDeviceEventType
182 default:
183 evt.Type.Class = event.MessageEventType
184 }
185
186 if s.ParseEventContent {
187 err := evt.Content.ParseRaw(evt.Type)
188 if err != nil && !s.ParseErrorHandler(evt, err) {
189 return
190 }
191 }
192
193 s.notifyListeners(source, evt)
194 }
195
196 func (s *DefaultSyncer) notifyListeners(source EventSource, evt *event.Event) {
197 for _, fn := range s.globalListeners {
198 fn(source, evt)
199 }
200 listeners, exists := s.listeners[evt.Type]
201 if exists {
202 for _, fn := range listeners {
203 fn(source, evt)
204 }
205 }
206 }
207
208 // OnEventType allows callers to be notified when there are new events for the given event type.
209 // There are no duplicate checks.
210 func (s *DefaultSyncer) OnEventType(eventType event.Type, callback EventHandler) {
211 _, exists := s.listeners[eventType]
212 if !exists {
213 s.listeners[eventType] = []EventHandler{}
214 }
215 s.listeners[eventType] = append(s.listeners[eventType], callback)
216 }
217
218 func (s *DefaultSyncer) OnSync(callback SyncHandler) {
219 s.syncListeners = append(s.syncListeners, callback)
220 }
221
222 func (s *DefaultSyncer) OnEvent(callback EventHandler) {
223 s.globalListeners = append(s.globalListeners, callback)
224 }
225
226 // OnFailedSync always returns a 10 second wait period between failed /syncs, never a fatal error.
227 func (s *DefaultSyncer) OnFailedSync(res *RespSync, err error) (time.Duration, error) {
228 return 10 * time.Second, nil
229 }
230
231 // GetFilterJSON returns a filter with a timeline limit of 50.
232 func (s *DefaultSyncer) GetFilterJSON(userID id.UserID) *Filter {
233 return &Filter{
234 Room: RoomFilter{
235 Timeline: FilterPart{
236 Limit: 50,
237 },
238 },
239 }
240 }
241
242 // OldEventIgnorer is an utility struct for bots to ignore events from before the bot joined the room.
243 // Create a struct and call Register with your DefaultSyncer to register the sync handler.
244 type OldEventIgnorer struct {
245 UserID id.UserID
246 }
247
248 func (oei *OldEventIgnorer) Register(syncer ExtensibleSyncer) {
249 syncer.OnSync(oei.DontProcessOldEvents)
250 }
251
252 // DontProcessOldEvents returns true if a sync response should be processed. May modify the response to remove
253 // stuff that shouldn't be processed.
254 func (oei *OldEventIgnorer) DontProcessOldEvents(resp *RespSync, since string) bool {
255 if since == "" {
256 return false
257 }
258 // This is a horrible hack because /sync will return the most recent messages for a room
259 // as soon as you /join it. We do NOT want to process those events in that particular room
260 // because they may have already been processed (if you toggle the bot in/out of the room).
261 //
262 // Work around this by inspecting each room's timeline and seeing if an m.room.member event for us
263 // exists and is "join" and then discard processing that room entirely if so.
264 // TODO: We probably want to process messages from after the last join event in the timeline.
265 for roomID, roomData := range resp.Rooms.Join {
266 for i := len(roomData.Timeline.Events) - 1; i >= 0; i-- {
267 evt := roomData.Timeline.Events[i]
268 if evt.Type == event.StateMember && evt.GetStateKey() == string(oei.UserID) {
269 membership, _ := evt.Content.Raw["membership"].(string)
270 if membership == "join" {
271 _, ok := resp.Rooms.Join[roomID]
272 if !ok {
273 continue
274 }
275 delete(resp.Rooms.Join, roomID) // don't re-process messages
276 delete(resp.Rooms.Invite, roomID) // don't re-process invites
277 break
278 }
279 }
280 }
281 }
282 return true
283 }