gomuks/matrix/sync.go

244 lines
7.3 KiB
Go
Raw Normal View History

2018-03-21 22:29:58 +01:00
// gomuks - A terminal Matrix client written in Go.
2019-01-17 13:13:25 +01:00
// Copyright (C) 2019 Tulir Asokan
2018-03-21 22:29:58 +01:00
//
// This program is free software: you can redistribute it and/or modify
2019-01-17 13:13:25 +01:00
// it under the terms of the GNU Affero General Public License as published by
2018-03-21 22:29:58 +01:00
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2019-01-17 13:13:25 +01:00
// GNU Affero General Public License for more details.
2018-03-21 22:29:58 +01:00
//
2019-01-17 13:13:25 +01:00
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2018-03-21 22:29:58 +01:00
2018-11-13 23:00:35 +01:00
// Based on https://github.com/matrix-org/mautrix/blob/master/sync.go
2018-03-21 22:29:58 +01:00
2018-03-18 20:24:03 +01:00
package matrix
import (
"encoding/json"
2019-03-26 21:09:10 +01:00
"fmt"
"time"
"maunium.net/go/mautrix"
2019-01-17 13:13:25 +01:00
"maunium.net/go/gomuks/debug"
"maunium.net/go/gomuks/matrix/rooms"
)
type SyncerSession interface {
GetRoom(id string) *rooms.Room
GetUserID() string
}
type EventSource int
const (
2018-05-22 16:24:47 +02:00
EventSourcePresence EventSource = 1 << iota
EventSourceJoin
EventSourceInvite
EventSourceLeave
2018-05-15 14:39:40 +02:00
EventSourceAccountData
EventSourceTimeline
EventSourceState
EventSourceEphemeral
)
2019-03-26 21:09:10 +01:00
func (es EventSource) String() string {
2019-03-26 22:26:00 +01:00
switch {
case es == EventSourcePresence:
2019-03-26 21:09:10 +01:00
return "presence"
2019-03-26 22:26:00 +01:00
case es == EventSourceAccountData:
return "user account data"
case es&EventSourceJoin != 0:
2019-03-26 21:09:10 +01:00
es -= EventSourceJoin
switch es {
case EventSourceState:
return "joined state"
case EventSourceTimeline:
return "joined timeline"
case EventSourceEphemeral:
return "room ephemeral (joined)"
case EventSourceAccountData:
return "room account data (joined)"
}
2019-03-26 22:26:00 +01:00
case es&EventSourceInvite != 0:
2019-03-26 21:09:10 +01:00
es -= EventSourceInvite
switch es {
case EventSourceState:
return "invited state"
}
2019-03-26 22:26:00 +01:00
case es&EventSourceLeave != 0:
2019-03-26 21:09:10 +01:00
es -= EventSourceLeave
switch es {
case EventSourceState:
return "left state"
case EventSourceTimeline:
return "left timeline"
}
}
return fmt.Sprintf("unknown (%d)", es)
}
2018-11-13 23:00:35 +01:00
type EventHandler func(source EventSource, event *mautrix.Event)
// GomuksSyncer is the default syncing implementation. You can either write your own syncer, or selectively
// replace parts of this default syncer (e.g. the ProcessResponse method). The default syncer uses the observer
// pattern to notify callers about incoming events. See GomuksSyncer.OnEventType for more information.
type GomuksSyncer struct {
2018-04-24 16:12:08 +02:00
Session SyncerSession
2018-11-13 23:00:35 +01:00
listeners map[mautrix.EventType][]EventHandler // event type to listeners array
2018-04-24 16:12:08 +02:00
FirstSyncDone bool
InitDoneCallback func()
}
// NewGomuksSyncer returns an instantiated GomuksSyncer
func NewGomuksSyncer(session SyncerSession) *GomuksSyncer {
return &GomuksSyncer{
Session: session,
2018-11-13 23:00:35 +01:00
listeners: make(map[mautrix.EventType][]EventHandler),
FirstSyncDone: false,
}
}
2018-03-21 22:29:58 +01:00
// ProcessResponse processes a Matrix sync response.
2018-11-13 23:00:35 +01:00
func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err error) {
debug.Print("Received sync response")
2019-04-27 14:02:21 +02:00
// dat, _ := json.MarshalIndent(res, "", " ")
// debug.Print(string(dat))
2019-03-26 22:26:00 +01:00
s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence)
s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData)
2018-03-23 22:39:17 +01:00
for roomID, roomData := range res.Rooms.Join {
room := s.Session.GetRoom(roomID)
2019-03-26 22:26:00 +01:00
s.processSyncEvents(room, roomData.State.Events, EventSourceJoin|EventSourceState)
s.processSyncEvents(room, roomData.Timeline.Events, EventSourceJoin|EventSourceTimeline)
s.processSyncEvents(room, roomData.Ephemeral.Events, EventSourceJoin|EventSourceEphemeral)
s.processSyncEvents(room, roomData.AccountData.Events, EventSourceJoin|EventSourceAccountData)
if len(room.PrevBatch) == 0 {
room.PrevBatch = roomData.Timeline.PrevBatch
}
}
2018-03-23 22:39:17 +01:00
for roomID, roomData := range res.Rooms.Invite {
room := s.Session.GetRoom(roomID)
2019-03-26 22:26:00 +01:00
s.processSyncEvents(room, roomData.State.Events, EventSourceInvite|EventSourceState)
}
2018-03-23 22:39:17 +01:00
for roomID, roomData := range res.Rooms.Leave {
room := s.Session.GetRoom(roomID)
room.HasLeft = true
2019-03-26 22:26:00 +01:00
s.processSyncEvents(room, roomData.State.Events, EventSourceLeave|EventSourceState)
s.processSyncEvents(room, roomData.Timeline.Events, EventSourceLeave|EventSourceTimeline)
if len(room.PrevBatch) == 0 {
room.PrevBatch = roomData.Timeline.PrevBatch
}
}
2018-03-23 22:39:17 +01:00
2018-04-24 16:12:08 +02:00
if since == "" && s.InitDoneCallback != nil {
s.InitDoneCallback()
}
s.FirstSyncDone = true
return
}
2019-03-26 22:26:00 +01:00
func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*mautrix.Event, source EventSource) {
2018-03-23 22:39:17 +01:00
for _, event := range events {
2019-03-26 22:26:00 +01:00
s.processSyncEvent(room, event, source)
2018-03-23 22:39:17 +01:00
}
}
2018-11-13 23:00:35 +01:00
func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, event *mautrix.Event, source EventSource) {
2018-03-23 22:39:17 +01:00
if room != nil {
event.RoomID = room.ID
2019-03-26 21:09:10 +01:00
if source&EventSourceState != 0 || (source&EventSourceTimeline != 0 && event.Type.IsState() && event.StateKey != nil) {
room.UpdateState(event)
}
2018-03-23 22:39:17 +01:00
}
s.notifyListeners(source, event)
2018-03-23 22:39:17 +01:00
}
// OnEventType allows callers to be notified when there are new events for the given event type.
// There are no duplicate checks.
2018-11-13 23:00:35 +01:00
func (s *GomuksSyncer) OnEventType(eventType mautrix.EventType, callback EventHandler) {
_, exists := s.listeners[eventType]
if !exists {
s.listeners[eventType] = []EventHandler{}
}
s.listeners[eventType] = append(s.listeners[eventType], callback)
}
2018-11-13 23:00:35 +01:00
func (s *GomuksSyncer) notifyListeners(source EventSource, event *mautrix.Event) {
2019-03-26 21:09:10 +01:00
if (event.Type.IsState() && source&EventSourceState == 0 && event.StateKey == nil) ||
(event.Type.IsAccountData() && source&EventSourceAccountData == 0) ||
(event.Type.IsEphemeral() && source&EventSourceEphemeral == 0) {
evtJson, _ := json.Marshal(event)
debug.Printf("Event of type %s received from mismatching source %s: %s", event.Type.String(), source.String(), string(evtJson))
return
}
listeners, exists := s.listeners[event.Type]
if !exists {
return
}
for _, fn := range listeners {
fn(source, event)
}
}
// OnFailedSync always returns a 10 second wait period between failed /syncs, never a fatal error.
2018-11-13 23:00:35 +01:00
func (s *GomuksSyncer) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
debug.Printf("Sync failed: %v", err)
return 10 * time.Second, nil
}
// GetFilterJSON returns a filter with a timeline limit of 50.
func (s *GomuksSyncer) GetFilterJSON(userID string) json.RawMessage {
2018-11-13 23:00:35 +01:00
filter := &mautrix.Filter{
Room: mautrix.RoomFilter{
2018-05-10 19:56:46 +02:00
IncludeLeave: false,
2018-11-13 23:00:35 +01:00
State: mautrix.FilterPart{
2018-05-10 19:56:46 +02:00
Types: []string{
2018-04-24 15:51:40 +02:00
"m.room.member",
"m.room.name",
"m.room.topic",
"m.room.canonical_alias",
2018-05-10 19:56:46 +02:00
"m.room.aliases",
2019-04-13 13:27:50 +02:00
"m.room.power_levels",
2018-05-10 19:56:46 +02:00
},
2018-03-24 12:27:13 +01:00
},
2018-11-13 23:00:35 +01:00
Timeline: mautrix.FilterPart{
Types: []string{
"m.room.message",
"m.room.member",
"m.room.name",
"m.room.topic",
"m.room.canonical_alias",
"m.room.aliases",
2019-04-13 13:27:50 +02:00
"m.room.power_levels",
},
2018-05-10 19:56:46 +02:00
Limit: 50,
2018-03-24 12:27:13 +01:00
},
2018-11-13 23:00:35 +01:00
Ephemeral: mautrix.FilterPart{
Types: []string{"m.typing", "m.receipt"},
2018-03-24 12:27:13 +01:00
},
2018-11-13 23:00:35 +01:00
AccountData: mautrix.FilterPart{
2018-05-10 19:56:46 +02:00
Types: []string{"m.tag"},
},
},
2018-11-13 23:00:35 +01:00
AccountData: mautrix.FilterPart{
Types: []string{"m.push_rules", "m.direct", "net.maunium.gomuks.preferences"},
2018-03-24 12:27:13 +01:00
},
2018-11-13 23:00:35 +01:00
Presence: mautrix.FilterPart{
2018-05-10 19:56:46 +02:00
Types: []string{},
2018-03-24 12:27:13 +01:00
},
2018-05-10 19:56:46 +02:00
}
rawFilter, _ := json.Marshal(&filter)
return rawFilter
}