| 1 | // gomuks - A terminal Matrix client written in Go. |
| 2 | // Copyright (C) 2020 Tulir Asokan |
| 3 | // |
| 4 | // This program is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU Affero General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // |
| 9 | // This program is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU Affero General Public License for more details. |
| 13 | // |
| 14 | // You should have received a copy of the GNU Affero General Public License |
| 15 | // along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | |
| 17 | // Based on https://github.com/matrix-org/mautrix/blob/master/sync.go |
| 18 | |
| 19 | package matrix |
| 20 | |
| 21 | import ( |
| 22 | "sync" |
| 23 | "time" |
| 24 | |
| 25 | "maunium.net/go/mautrix" |
| 26 | "maunium.net/go/mautrix/event" |
| 27 | "maunium.net/go/mautrix/id" |
| 28 | |
| 29 | "maunium.net/go/gomuks/debug" |
| 30 | ifc "maunium.net/go/gomuks/interface" |
| 31 | "maunium.net/go/gomuks/matrix/rooms" |
| 32 | ) |
| 33 | |
| 34 | type GomuksSyncer struct { |
| 35 | rooms *rooms.RoomCache |
| 36 | globalListeners []mautrix.SyncHandler |
| 37 | listeners map[event.Type][]mautrix.EventHandler // event type to listeners array |
| 38 | FirstSyncDone bool |
| 39 | InitDoneCallback func() |
| 40 | FirstDoneCallback func() |
| 41 | Progress ifc.SyncingModal |
| 42 | } |
| 43 | |
| 44 | // NewGomuksSyncer returns an instantiated GomuksSyncer |
| 45 | func NewGomuksSyncer(rooms *rooms.RoomCache) *GomuksSyncer { |
| 46 | return &GomuksSyncer{ |
| 47 | rooms: rooms, |
| 48 | globalListeners: []mautrix.SyncHandler{}, |
| 49 | listeners: make(map[event.Type][]mautrix.EventHandler), |
| 50 | FirstSyncDone: false, |
| 51 | Progress: StubSyncingModal{}, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // ProcessResponse processes a Matrix sync response. |
| 56 | func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err error) { |
| 57 | if since == "" { |
| 58 | s.rooms.DisableUnloading() |
| 59 | } |
| 60 | debug.Print("Received sync response") |
| 61 | s.Progress.SetMessage("Processing sync response") |
| 62 | steps := len(res.Rooms.Join) + len(res.Rooms.Invite) + len(res.Rooms.Leave) |
| 63 | s.Progress.SetSteps(steps + 2 + len(s.globalListeners)) |
| 64 | |
| 65 | wait := &sync.WaitGroup{} |
| 66 | callback := func() { |
| 67 | wait.Done() |
| 68 | s.Progress.Step() |
| 69 | } |
| 70 | wait.Add(len(s.globalListeners)) |
| 71 | s.notifyGlobalListeners(res, since, callback) |
| 72 | wait.Wait() |
| 73 | |
| 74 | s.processSyncEvents(nil, res.Presence.Events, mautrix.EventSourcePresence) |
| 75 | s.Progress.Step() |
| 76 | s.processSyncEvents(nil, res.AccountData.Events, mautrix.EventSourceAccountData) |
| 77 | s.Progress.Step() |
| 78 | |
| 79 | wait.Add(steps) |
| 80 | |
| 81 | for roomID, roomData := range res.Rooms.Join { |
| 82 | go s.processJoinedRoom(roomID, roomData, callback) |
| 83 | } |
| 84 | |
| 85 | for roomID, roomData := range res.Rooms.Invite { |
| 86 | go s.processInvitedRoom(roomID, roomData, callback) |
| 87 | } |
| 88 | |
| 89 | for roomID, roomData := range res.Rooms.Leave { |
| 90 | go s.processLeftRoom(roomID, roomData, callback) |
| 91 | } |
| 92 | |
| 93 | wait.Wait() |
| 94 | s.Progress.SetMessage("Finishing sync") |
| 95 | |
| 96 | if since == "" && s.InitDoneCallback != nil { |
| 97 | s.InitDoneCallback() |
| 98 | s.rooms.EnableUnloading() |
| 99 | } |
| 100 | if !s.FirstSyncDone && s.FirstDoneCallback != nil { |
| 101 | s.FirstDoneCallback() |
| 102 | } |
| 103 | s.FirstSyncDone = true |
| 104 | return |
| 105 | } |
| 106 | |
| 107 | func (s *GomuksSyncer) notifyGlobalListeners(res *mautrix.RespSync, since string, callback func()) { |
| 108 | for _, listener := range s.globalListeners { |
| 109 | go func(listener mautrix.SyncHandler) { |
| 110 | listener(res, since) |
| 111 | callback() |
| 112 | }(listener) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func (s *GomuksSyncer) processJoinedRoom(roomID id.RoomID, roomData mautrix.SyncJoinedRoom, callback func()) { |
| 117 | defer debug.Recover() |
| 118 | room := s.rooms.GetOrCreate(roomID) |
| 119 | room.UpdateSummary(roomData.Summary) |
| 120 | s.processSyncEvents(room, roomData.State.Events, mautrix.EventSourceJoin|mautrix.EventSourceState) |
| 121 | s.processSyncEvents(room, roomData.Timeline.Events, mautrix.EventSourceJoin|mautrix.EventSourceTimeline) |
| 122 | s.processSyncEvents(room, roomData.Ephemeral.Events, mautrix.EventSourceJoin|mautrix.EventSourceEphemeral) |
| 123 | s.processSyncEvents(room, roomData.AccountData.Events, mautrix.EventSourceJoin|mautrix.EventSourceAccountData) |
| 124 | |
| 125 | if len(room.PrevBatch) == 0 { |
| 126 | room.PrevBatch = roomData.Timeline.PrevBatch |
| 127 | } |
| 128 | room.LastPrevBatch = roomData.Timeline.PrevBatch |
| 129 | callback() |
| 130 | } |
| 131 | |
| 132 | func (s *GomuksSyncer) processInvitedRoom(roomID id.RoomID, roomData mautrix.SyncInvitedRoom, callback func()) { |
| 133 | defer debug.Recover() |
| 134 | room := s.rooms.GetOrCreate(roomID) |
| 135 | room.UpdateSummary(roomData.Summary) |
| 136 | s.processSyncEvents(room, roomData.State.Events, mautrix.EventSourceInvite|mautrix.EventSourceState) |
| 137 | callback() |
| 138 | } |
| 139 | |
| 140 | func (s *GomuksSyncer) processLeftRoom(roomID id.RoomID, roomData mautrix.SyncLeftRoom, callback func()) { |
| 141 | defer debug.Recover() |
| 142 | room := s.rooms.GetOrCreate(roomID) |
| 143 | room.HasLeft = true |
| 144 | room.UpdateSummary(roomData.Summary) |
| 145 | s.processSyncEvents(room, roomData.State.Events, mautrix.EventSourceLeave|mautrix.EventSourceState) |
| 146 | s.processSyncEvents(room, roomData.Timeline.Events, mautrix.EventSourceLeave|mautrix.EventSourceTimeline) |
| 147 | |
| 148 | if len(room.PrevBatch) == 0 { |
| 149 | room.PrevBatch = roomData.Timeline.PrevBatch |
| 150 | } |
| 151 | room.LastPrevBatch = roomData.Timeline.PrevBatch |
| 152 | callback() |
| 153 | } |
| 154 | |
| 155 | func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*event.Event, source mautrix.EventSource) { |
| 156 | for _, evt := range events { |
| 157 | s.processSyncEvent(room, evt, source) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, evt *event.Event, source mautrix.EventSource) { |
| 162 | if room != nil { |
| 163 | evt.RoomID = room.ID |
| 164 | } |
| 165 | // Ensure the type class is correct. It's safe to mutate since it's not a pointer. |
| 166 | // Listeners are keyed by type structs, which means only the correct class will pass. |
| 167 | switch { |
| 168 | case evt.StateKey != nil: |
| 169 | evt.Type.Class = event.StateEventType |
| 170 | case source == mautrix.EventSourcePresence, source&mautrix.EventSourceEphemeral != 0: |
| 171 | evt.Type.Class = event.EphemeralEventType |
| 172 | case source&mautrix.EventSourceAccountData != 0: |
| 173 | evt.Type.Class = event.AccountDataEventType |
| 174 | case source == mautrix.EventSourceToDevice: |
| 175 | evt.Type.Class = event.ToDeviceEventType |
| 176 | default: |
| 177 | evt.Type.Class = event.MessageEventType |
| 178 | } |
| 179 | |
| 180 | err := evt.Content.ParseRaw(evt.Type) |
| 181 | if err != nil { |
| 182 | debug.Printf("Failed to unmarshal content of event %s (type %s) by %s in %s: %v\n%s", evt.ID, evt.Type.Repr(), evt.Sender, evt.RoomID, err, string(evt.Content.VeryRaw)) |
| 183 | // TODO might be good to let these pass to allow handling invalid events too |
| 184 | return |
| 185 | } |
| 186 | |
| 187 | if room != nil && evt.Type.IsState() { |
| 188 | room.UpdateState(evt) |
| 189 | } |
| 190 | s.notifyListeners(source, evt) |
| 191 | } |
| 192 | |
| 193 | // OnEventType allows callers to be notified when there are new events for the given event type. |
| 194 | // There are no duplicate checks. |
| 195 | func (s *GomuksSyncer) OnEventType(eventType event.Type, callback mautrix.EventHandler) { |
| 196 | _, exists := s.listeners[eventType] |
| 197 | if !exists { |
| 198 | s.listeners[eventType] = []mautrix.EventHandler{} |
| 199 | } |
| 200 | s.listeners[eventType] = append(s.listeners[eventType], callback) |
| 201 | } |
| 202 | |
| 203 | func (s *GomuksSyncer) OnSync(callback mautrix.SyncHandler) { |
| 204 | s.globalListeners = append(s.globalListeners, callback) |
| 205 | } |
| 206 | |
| 207 | func (s *GomuksSyncer) notifyListeners(source mautrix.EventSource, evt *event.Event) { |
| 208 | listeners, exists := s.listeners[evt.Type] |
| 209 | if !exists { |
| 210 | return |
| 211 | } |
| 212 | for _, fn := range listeners { |
| 213 | fn(source, evt) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // OnFailedSync always returns a 10 second wait period between failed /syncs, never a fatal error. |
| 218 | func (s *GomuksSyncer) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) { |
| 219 | debug.Printf("Sync failed: %v", err) |
| 220 | return 10 * time.Second, nil |
| 221 | } |
| 222 | |
| 223 | // GetFilterJSON returns a filter with a timeline limit of 50. |
| 224 | func (s *GomuksSyncer) GetFilterJSON(_ id.UserID) *mautrix.Filter { |
| 225 | stateEvents := []event.Type{ |
| 226 | event.StateMember, |
| 227 | event.StateRoomName, |
| 228 | event.StateTopic, |
| 229 | event.StateCanonicalAlias, |
| 230 | event.StatePowerLevels, |
| 231 | event.StateTombstone, |
| 232 | event.StateEncryption, |
| 233 | } |
| 234 | messageEvents := []event.Type{ |
| 235 | event.EventMessage, |
| 236 | event.EventRedaction, |
| 237 | event.EventEncrypted, |
| 238 | event.EventSticker, |
| 239 | event.EventReaction, |
| 240 | } |
| 241 | return &mautrix.Filter{ |
| 242 | Room: mautrix.RoomFilter{ |
| 243 | IncludeLeave: false, |
| 244 | State: mautrix.FilterPart{ |
| 245 | LazyLoadMembers: true, |
| 246 | Types: stateEvents, |
| 247 | }, |
| 248 | Timeline: mautrix.FilterPart{ |
| 249 | LazyLoadMembers: true, |
| 250 | Types: append(messageEvents, stateEvents...), |
| 251 | Limit: 50, |
| 252 | }, |
| 253 | Ephemeral: mautrix.FilterPart{ |
| 254 | Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}, |
| 255 | }, |
| 256 | AccountData: mautrix.FilterPart{ |
| 257 | Types: []event.Type{event.AccountDataRoomTags}, |
| 258 | }, |
| 259 | }, |
| 260 | AccountData: mautrix.FilterPart{ |
| 261 | Types: []event.Type{event.AccountDataPushRules, event.AccountDataDirectChats, AccountDataGomuksPreferences}, |
| 262 | }, |
| 263 | Presence: mautrix.FilterPart{ |
| 264 | NotTypes: []event.Type{event.NewEventType("*")}, |
| 265 | }, |
| 266 | } |
| 267 | } |