diff options
author | Tulir Asokan <tulir@maunium.net> | 2018-11-14 00:00:35 +0200 |
---|---|---|
committer | Tulir Asokan <tulir@maunium.net> | 2018-11-14 00:00:35 +0200 |
commit | ba387764ca1590625d349e74eb8a8a64d1849b67 (patch) | |
tree | bc8f02156a63eac99dcddaed38e45b7c312b40c0 /matrix | |
parent | cfb2cc057c32330be0ca0a68cfbd245cb2b8e31b (diff) |
Fix things
Diffstat (limited to 'matrix')
-rw-r--r-- | matrix/doc.go | 2 | ||||
-rw-r--r-- | matrix/matrix.go | 86 | ||||
-rw-r--r-- | matrix/matrix_test.go | 10 | ||||
-rw-r--r-- | matrix/pushrules/condition.go | 14 | ||||
-rw-r--r-- | matrix/pushrules/condition_test.go | 10 | ||||
-rw-r--r-- | matrix/pushrules/pushrules.go | 8 | ||||
-rw-r--r-- | matrix/pushrules/pushrules_test.go | 4 | ||||
-rw-r--r-- | matrix/pushrules/rule.go | 14 | ||||
-rw-r--r-- | matrix/pushrules/ruleset.go | 4 | ||||
-rw-r--r-- | matrix/rooms/room.go | 48 | ||||
-rw-r--r-- | matrix/rooms/room_test.go | 18 | ||||
-rw-r--r-- | matrix/sync.go | 43 | ||||
-rw-r--r-- | matrix/sync_test.go | 66 |
13 files changed, 169 insertions, 158 deletions
diff --git a/matrix/doc.go b/matrix/doc.go index 2cd54e2..f789895 100644 --- a/matrix/doc.go +++ b/matrix/doc.go @@ -1,2 +1,2 @@ -// Package matrix contains wrappers for gomatrix for use by the UI of gomuks. +// Package matrix contains wrappers for mautrix for use by the UI of gomuks. package matrix diff --git a/matrix/matrix.go b/matrix/matrix.go index 060becd..cf9e463 100644 --- a/matrix/matrix.go +++ b/matrix/matrix.go @@ -34,20 +34,20 @@ import ( "encoding/json" "gopkg.in/russross/blackfriday.v2" - "maunium.net/go/gomatrix" "maunium.net/go/gomuks/config" "maunium.net/go/gomuks/debug" "maunium.net/go/gomuks/interface" "maunium.net/go/gomuks/lib/bfhtml" "maunium.net/go/gomuks/matrix/pushrules" "maunium.net/go/gomuks/matrix/rooms" + "maunium.net/go/mautrix" ) -// Container is a wrapper for a gomatrix Client and some other stuff. +// Container is a wrapper for a mautrix Client and some other stuff. // // It is used for all Matrix calls from the UI and Matrix event handlers. type Container struct { - client *gomatrix.Client + client *mautrix.Client syncer *GomuksSyncer gmx ifc.Gomuks ui ifc.GomuksUI @@ -69,12 +69,18 @@ func NewContainer(gmx ifc.Gomuks) *Container { return c } -// Client returns the underlying gomatrix Client. -func (c *Container) Client() *gomatrix.Client { +// Client returns the underlying mautrix Client. +func (c *Container) Client() *mautrix.Client { return c.client } -// InitClient initializes the gomatrix client and connects to the homeserver specified in the config. +type mxLogger struct{} + +func (log mxLogger) Debugfln(message string, args ...interface{}) { + debug.Printf("[Matrix] "+message, args...) +} + +// InitClient initializes the mautrix client and connects to the homeserver specified in the config. func (c *Container) InitClient() error { if len(c.config.HS) == 0 { return fmt.Errorf("no homeserver in config") @@ -92,10 +98,11 @@ func (c *Container) InitClient() error { } var err error - c.client, err = gomatrix.NewClient(c.config.HS, mxid, accessToken) + c.client, err = mautrix.NewClient(c.config.HS, mxid, accessToken) if err != nil { return err } + c.client.Logger = mxLogger{} allowInsecure := len(os.Getenv("GOMUKS_ALLOW_INSECURE_CONNECTIONS")) > 0 if allowInsecure { @@ -112,14 +119,14 @@ func (c *Container) InitClient() error { return nil } -// Initialized returns whether or not the gomatrix client is initialized (see InitClient()) +// Initialized returns whether or not the mautrix client is initialized (see InitClient()) func (c *Container) Initialized() bool { return c.client != nil } // Login sends a password login request with the given username and password. func (c *Container) Login(user, password string) error { - resp, err := c.client.Login(&gomatrix.ReqLogin{ + resp, err := c.client.Login(&mautrix.ReqLogin{ Type: "m.login.password", User: user, Password: password, @@ -175,7 +182,7 @@ func (c *Container) PushRules() *pushrules.PushRuleset { return c.config.PushRules } -var AccountDataGomuksPreferences = gomatrix.NewEventType("net.maunium.gomuks.preferences") +var AccountDataGomuksPreferences = mautrix.NewEventType("net.maunium.gomuks.preferences") // OnLogin initializes the syncer and updates the room list. func (c *Container) OnLogin() { @@ -185,15 +192,16 @@ func (c *Container) OnLogin() { debug.Print("Initializing syncer") c.syncer = NewGomuksSyncer(c.config) - c.syncer.OnEventType(gomatrix.EventMessage, c.HandleMessage) - c.syncer.OnEventType(gomatrix.StateMember, c.HandleMembership) - c.syncer.OnEventType(gomatrix.EphemeralEventReceipt, c.HandleReadReceipt) - c.syncer.OnEventType(gomatrix.EphemeralEventTyping, c.HandleTyping) - c.syncer.OnEventType(gomatrix.AccountDataDirectChats, c.HandleDirectChatInfo) - c.syncer.OnEventType(gomatrix.AccountDataPushRules, c.HandlePushRules) - c.syncer.OnEventType(gomatrix.AccountDataRoomTags, c.HandleTag) + c.syncer.OnEventType(mautrix.EventMessage, c.HandleMessage) + c.syncer.OnEventType(mautrix.StateMember, c.HandleMembership) + c.syncer.OnEventType(mautrix.EphemeralEventReceipt, c.HandleReadReceipt) + c.syncer.OnEventType(mautrix.EphemeralEventTyping, c.HandleTyping) + c.syncer.OnEventType(mautrix.AccountDataDirectChats, c.HandleDirectChatInfo) + c.syncer.OnEventType(mautrix.AccountDataPushRules, c.HandlePushRules) + c.syncer.OnEventType(mautrix.AccountDataRoomTags, c.HandleTag) c.syncer.OnEventType(AccountDataGomuksPreferences, c.HandlePreferences) c.syncer.InitDoneCallback = func() { + debug.Print("Initial sync done") c.config.AuthCache.InitialSyncDone = true c.config.SaveAuthCache() c.ui.MainView().InitialSyncDone() @@ -227,7 +235,7 @@ func (c *Container) Start() { return default: if err := c.client.Sync(); err != nil { - if httpErr, ok := err.(gomatrix.HTTPError); ok && httpErr.Code == http.StatusUnauthorized { + if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.Code == http.StatusUnauthorized { debug.Print("Sync() errored with ", err, " -> logging out") c.Logout() } else { @@ -240,7 +248,7 @@ func (c *Container) Start() { } } -func (c *Container) HandlePreferences(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandlePreferences(source EventSource, evt *mautrix.Event) { orig := c.config.Preferences rt, _ := json.Marshal(&evt.Content) json.Unmarshal(rt, &c.config.Preferences) @@ -259,7 +267,7 @@ func (c *Container) SendPreferencesToMatrix() { } // HandleMessage is the event handler for the m.room.message timeline event. -func (c *Container) HandleMessage(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleMessage(source EventSource, evt *mautrix.Event) { if source&EventSourceLeave != 0 { return } @@ -286,7 +294,7 @@ func (c *Container) HandleMessage(source EventSource, evt *gomatrix.Event) { } // HandleMembership is the event handler for the m.room.member state event. -func (c *Container) HandleMembership(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleMembership(source EventSource, evt *mautrix.Event) { isLeave := source&EventSourceLeave != 0 isTimeline := source&EventSourceTimeline != 0 isNonTimelineLeave := isLeave && !isTimeline @@ -302,9 +310,9 @@ func (c *Container) HandleMembership(source EventSource, evt *gomatrix.Event) { c.HandleMessage(source, evt) } -func (c *Container) processOwnMembershipChange(evt *gomatrix.Event) { +func (c *Container) processOwnMembershipChange(evt *mautrix.Event) { membership := evt.Content.Membership - prevMembership := gomatrix.MembershipLeave + prevMembership := mautrix.MembershipLeave if evt.Unsigned.PrevContent != nil { prevMembership = evt.Unsigned.PrevContent.Membership } @@ -326,7 +334,7 @@ func (c *Container) processOwnMembershipChange(evt *gomatrix.Event) { } } -func (c *Container) parseReadReceipt(evt *gomatrix.Event) (largestTimestampEvent string) { +func (c *Container) parseReadReceipt(evt *mautrix.Event) (largestTimestampEvent string) { var largestTimestamp int64 for eventID, rawContent := range evt.Content.Raw { content, ok := rawContent.(map[string]interface{}) @@ -353,7 +361,7 @@ func (c *Container) parseReadReceipt(evt *gomatrix.Event) (largestTimestampEvent return } -func (c *Container) HandleReadReceipt(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleReadReceipt(source EventSource, evt *mautrix.Event) { if source&EventSourceLeave != 0 { return } @@ -368,7 +376,7 @@ func (c *Container) HandleReadReceipt(source EventSource, evt *gomatrix.Event) { c.ui.Render() } -func (c *Container) parseDirectChatInfo(evt *gomatrix.Event) map[*rooms.Room]bool { +func (c *Container) parseDirectChatInfo(evt *mautrix.Event) map[*rooms.Room]bool { directChats := make(map[*rooms.Room]bool) for _, rawRoomIDList := range evt.Content.Raw { roomIDList, ok := rawRoomIDList.([]interface{}) @@ -391,7 +399,7 @@ func (c *Container) parseDirectChatInfo(evt *gomatrix.Event) map[*rooms.Room]boo return directChats } -func (c *Container) HandleDirectChatInfo(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleDirectChatInfo(source EventSource, evt *mautrix.Event) { directChats := c.parseDirectChatInfo(evt) for _, room := range c.config.Rooms { shouldBeDirect := directChats[room] @@ -403,7 +411,7 @@ func (c *Container) HandleDirectChatInfo(source EventSource, evt *gomatrix.Event } // HandlePushRules is the event handler for the m.push_rules account data event. -func (c *Container) HandlePushRules(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandlePushRules(source EventSource, evt *mautrix.Event) { debug.Print("Received updated push rules") var err error c.config.PushRules, err = pushrules.EventToPushRules(evt) @@ -415,7 +423,7 @@ func (c *Container) HandlePushRules(source EventSource, evt *gomatrix.Event) { } // HandleTag is the event handler for the m.tag account data event. -func (c *Container) HandleTag(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleTag(source EventSource, evt *mautrix.Event) { room := c.config.GetRoom(evt.RoomID) newTags := make([]rooms.RoomTag, len(evt.Content.RoomTags)) @@ -423,7 +431,7 @@ func (c *Container) HandleTag(source EventSource, evt *gomatrix.Event) { for tag, info := range evt.Content.RoomTags { order := "0.5" if len(info.Order) > 0 { - order = info.Order + order = info.Order.String() } newTags[index] = rooms.RoomTag{ Tag: tag, @@ -438,7 +446,7 @@ func (c *Container) HandleTag(source EventSource, evt *gomatrix.Event) { } // HandleTyping is the event handler for the m.typing event. -func (c *Container) HandleTyping(source EventSource, evt *gomatrix.Event) { +func (c *Container) HandleTyping(source EventSource, evt *mautrix.Event) { c.ui.MainView().SetTyping(evt.RoomID, evt.Content.TypingUserIDs) } @@ -448,11 +456,11 @@ func (c *Container) MarkRead(roomID, eventID string) { } // SendMessage sends a message with the given text to the given room. -func (c *Container) SendMessage(roomID string, msgtype gomatrix.MessageType, text string) (string, error) { +func (c *Container) SendMessage(roomID string, msgtype mautrix.MessageType, text string) (string, error) { defer debug.Recover() c.SendTyping(roomID, false) - resp, err := c.client.SendMessageEvent(roomID, gomatrix.EventMessage, - gomatrix.Content{MsgType: msgtype, Body: text}) + resp, err := c.client.SendMessageEvent(roomID, mautrix.EventMessage, + mautrix.Content{MsgType: msgtype, Body: text}) if err != nil { return "", err } @@ -491,7 +499,7 @@ var roomRegex = regexp.MustCompile("\\[.+?]\\(https://matrix.to/#/(#.+?:[^/]+?)\ // // If the given text contains markdown formatting symbols, it will be rendered into HTML before sending. // Otherwise, it will be sent as plain text. -func (c *Container) SendMarkdownMessage(roomID string, msgtype gomatrix.MessageType, text string) (string, error) { +func (c *Container) SendMarkdownMessage(roomID string, msgtype mautrix.MessageType, text string) (string, error) { defer debug.Recover() html := c.renderMarkdown(text) @@ -504,11 +512,11 @@ func (c *Container) SendMarkdownMessage(roomID string, msgtype gomatrix.MessageT text = roomRegex.ReplaceAllString(text, "$1") c.SendTyping(roomID, false) - resp, err := c.client.SendMessageEvent(roomID, gomatrix.EventMessage, - gomatrix.Content{ + resp, err := c.client.SendMessageEvent(roomID, mautrix.EventMessage, + mautrix.Content{ MsgType: msgtype, Body: text, - Format: gomatrix.FormatHTML, + Format: mautrix.FormatHTML, FormattedBody: html, }) if err != nil { @@ -560,7 +568,7 @@ func (c *Container) LeaveRoom(roomID string) error { } // GetHistory fetches room history. -func (c *Container) GetHistory(roomID, prevBatch string, limit int) ([]*gomatrix.Event, string, error) { +func (c *Container) GetHistory(roomID, prevBatch string, limit int) ([]*mautrix.Event, string, error) { resp, err := c.client.Messages(roomID, prevBatch, "", 'b', limit) if err != nil { return nil, "", err diff --git a/matrix/matrix_test.go b/matrix/matrix_test.go index b6511ec..0d8bc3c 100644 --- a/matrix/matrix_test.go +++ b/matrix/matrix_test.go @@ -21,7 +21,7 @@ import ( "fmt" "github.com/stretchr/testify/assert" "io/ioutil" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/config" "net/http" "os" @@ -80,7 +80,7 @@ func TestContainer_SendMarkdownMessage_WithMarkdown(t *testing.T) { } func TestContainer_SendTyping(t *testing.T) { - var calls []gomatrix.ReqTyping + var calls []mautrix.ReqTyping c := Container{client: mockClient(func(req *http.Request) (*http.Response, error) { if req.Method != http.MethodPut || req.URL.Path != "/_matrix/client/r0/rooms/!foo:example.com/typing/@user:example.com" { return nil, fmt.Errorf("unexpected query: %s %s", req.Method, req.URL.Path) @@ -91,7 +91,7 @@ func TestContainer_SendTyping(t *testing.T) { return nil, err } - call := gomatrix.ReqTyping{} + call := mautrix.ReqTyping{} err = json.Unmarshal(rawBody, &call) if err != nil { return nil, err @@ -187,8 +187,8 @@ func TestContainer_GetHistory(t *testing.T) { assert.Equal(t, "456", prevBatch) } -func mockClient(fn func(*http.Request) (*http.Response, error)) *gomatrix.Client { - client, _ := gomatrix.NewClient("https://example.com", "@user:example.com", "foobar") +func mockClient(fn func(*http.Request) (*http.Response, error)) *mautrix.Client { + client, _ := mautrix.NewClient("https://example.com", "@user:example.com", "foobar") client.Client = &http.Client{Transport: MockRoundTripper{RT: fn}} return client } diff --git a/matrix/pushrules/condition.go b/matrix/pushrules/condition.go index 22d59aa..bacab56 100644 --- a/matrix/pushrules/condition.go +++ b/matrix/pushrules/condition.go @@ -21,14 +21,14 @@ import ( "strconv" "strings" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/lib/glob" ) // Room is an interface with the functions that are needed for processing room-specific push conditions type Room interface { - GetMember(mxid string) *gomatrix.Member - GetMembers() map[string]*gomatrix.Member + GetMember(mxid string) *mautrix.Member + GetMembers() map[string]*mautrix.Member GetSessionOwner() string } @@ -59,7 +59,7 @@ type PushCondition struct { var MemberCountFilterRegex = regexp.MustCompile("^(==|[<>]=?)?([0-9]+)$") // Match checks if this condition is fulfilled for the given event in the given room. -func (cond *PushCondition) Match(room Room, event *gomatrix.Event) bool { +func (cond *PushCondition) Match(room Room, event *mautrix.Event) bool { switch cond.Kind { case KindEventMatch: return cond.matchValue(room, event) @@ -72,7 +72,7 @@ func (cond *PushCondition) Match(room Room, event *gomatrix.Event) bool { } } -func (cond *PushCondition) matchValue(room Room, event *gomatrix.Event) bool { +func (cond *PushCondition) matchValue(room Room, event *mautrix.Event) bool { index := strings.IndexRune(cond.Key, '.') key := cond.Key subkey := "" @@ -106,7 +106,7 @@ func (cond *PushCondition) matchValue(room Room, event *gomatrix.Event) bool { } } -func (cond *PushCondition) matchDisplayName(room Room, event *gomatrix.Event) bool { +func (cond *PushCondition) matchDisplayName(room Room, event *mautrix.Event) bool { ownerID := room.GetSessionOwner() if ownerID == event.Sender { return false @@ -115,7 +115,7 @@ func (cond *PushCondition) matchDisplayName(room Room, event *gomatrix.Event) bo return strings.Contains(event.Content.Body, member.Displayname) } -func (cond *PushCondition) matchMemberCount(room Room, event *gomatrix.Event) bool { +func (cond *PushCondition) matchMemberCount(room Room, event *mautrix.Event) bool { group := MemberCountFilterRegex.FindStringSubmatch(cond.MemberCountCondition) if len(group) != 3 { return false diff --git a/matrix/pushrules/condition_test.go b/matrix/pushrules/condition_test.go index 7fd06ee..750f2c7 100644 --- a/matrix/pushrules/condition_test.go +++ b/matrix/pushrules/condition_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/matrix/pushrules" "maunium.net/go/gomuks/matrix/rooms" ) @@ -30,7 +30,7 @@ var ( blankTestRoom *rooms.Room displaynameTestRoom pushrules.Room - countConditionTestEvent *gomatrix.Event + countConditionTestEvent *mautrix.Event displaynamePushCondition *pushrules.PushCondition ) @@ -38,7 +38,7 @@ var ( func init() { blankTestRoom = rooms.NewRoom("!fakeroom:maunium.net", "@tulir:maunium.net") - countConditionTestEvent = &gomatrix.Event{ + countConditionTestEvent = &mautrix.Event{ Sender: "@tulir:maunium.net", Type: "m.room.message", Timestamp: 1523791120, @@ -56,8 +56,8 @@ func init() { } } -func newFakeEvent(evtType string, content map[string]interface{}) *gomatrix.Event { - return &gomatrix.Event{ +func newFakeEvent(evtType string, content map[string]interface{}) *mautrix.Event { + return &mautrix.Event{ Sender: "@tulir:maunium.net", Type: evtType, Timestamp: 1523791120, diff --git a/matrix/pushrules/pushrules.go b/matrix/pushrules/pushrules.go index b383c66..643f2f2 100644 --- a/matrix/pushrules/pushrules.go +++ b/matrix/pushrules/pushrules.go @@ -4,16 +4,16 @@ import ( "encoding/json" "net/url" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" ) // GetPushRules returns the push notification rules for the global scope. -func GetPushRules(client *gomatrix.Client) (*PushRuleset, error) { +func GetPushRules(client *mautrix.Client) (*PushRuleset, error) { return GetScopedPushRules(client, "global") } // GetScopedPushRules returns the push notification rules for the given scope. -func GetScopedPushRules(client *gomatrix.Client, scope string) (resp *PushRuleset, err error) { +func GetScopedPushRules(client *mautrix.Client, scope string) (resp *PushRuleset, err error) { u, _ := url.Parse(client.BuildURL("pushrules", scope)) // client.BuildURL returns the URL without a trailing slash, but the pushrules endpoint requires the slash. u.Path += "/" @@ -26,7 +26,7 @@ type contentWithRuleset struct { } // EventToPushRules converts a m.push_rules event to a PushRuleset by passing the data through JSON. -func EventToPushRules(event *gomatrix.Event) (*PushRuleset, error) { +func EventToPushRules(event *mautrix.Event) (*PushRuleset, error) { content := &contentWithRuleset{} err := json.Unmarshal(event.Content.VeryRaw, content) if err != nil { diff --git a/matrix/pushrules/pushrules_test.go b/matrix/pushrules/pushrules_test.go index 09698ac..73fa787 100644 --- a/matrix/pushrules/pushrules_test.go +++ b/matrix/pushrules/pushrules_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/matrix/pushrules" ) @@ -33,7 +33,7 @@ func init() { } func TestEventToPushRules(t *testing.T) { - event := &gomatrix.Event{ + event := &mautrix.Event{ Type: "m.push_rules", Timestamp: 1523380910, Content: mapExamplePushRules, diff --git a/matrix/pushrules/rule.go b/matrix/pushrules/rule.go index 71f71e5..62318ac 100644 --- a/matrix/pushrules/rule.go +++ b/matrix/pushrules/rule.go @@ -18,7 +18,7 @@ package pushrules import ( "encoding/gob" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/lib/glob" ) @@ -28,7 +28,7 @@ func init() { } type PushRuleCollection interface { - GetActions(room Room, event *gomatrix.Event) PushActionArray + GetActions(room Room, event *mautrix.Event) PushActionArray } type PushRuleArray []*PushRule @@ -40,7 +40,7 @@ func (rules PushRuleArray) SetType(typ PushRuleType) PushRuleArray { return rules } -func (rules PushRuleArray) GetActions(room Room, event *gomatrix.Event) PushActionArray { +func (rules PushRuleArray) GetActions(room Room, event *mautrix.Event) PushActionArray { for _, rule := range rules { if !rule.Match(room, event) { continue @@ -67,7 +67,7 @@ func (rules PushRuleArray) SetTypeAndMap(typ PushRuleType) PushRuleMap { return data } -func (ruleMap PushRuleMap) GetActions(room Room, event *gomatrix.Event) PushActionArray { +func (ruleMap PushRuleMap) GetActions(room Room, event *mautrix.Event) PushActionArray { var rule *PushRule var found bool switch ruleMap.Type { @@ -122,7 +122,7 @@ type PushRule struct { Pattern string `json:"pattern,omitempty"` } -func (rule *PushRule) Match(room Room, event *gomatrix.Event) bool { +func (rule *PushRule) Match(room Room, event *mautrix.Event) bool { if !rule.Enabled { return false } @@ -140,7 +140,7 @@ func (rule *PushRule) Match(room Room, event *gomatrix.Event) bool { } } -func (rule *PushRule) matchConditions(room Room, event *gomatrix.Event) bool { +func (rule *PushRule) matchConditions(room Room, event *mautrix.Event) bool { for _, cond := range rule.Conditions { if !cond.Match(room, event) { return false @@ -149,7 +149,7 @@ func (rule *PushRule) matchConditions(room Room, event *gomatrix.Event) bool { return true } -func (rule *PushRule) matchPattern(room Room, event *gomatrix.Event) bool { +func (rule *PushRule) matchPattern(room Room, event *mautrix.Event) bool { pattern, err := glob.Compile(rule.Pattern) if err != nil { return false diff --git a/matrix/pushrules/ruleset.go b/matrix/pushrules/ruleset.go index 940025f..366702e 100644 --- a/matrix/pushrules/ruleset.go +++ b/matrix/pushrules/ruleset.go @@ -19,7 +19,7 @@ package pushrules import ( "encoding/json" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" ) type PushRuleset struct { @@ -80,7 +80,7 @@ var DefaultPushActions = make(PushActionArray, 0) // GetActions matches the given event against all of the push rule // collections in this push ruleset in the order of priority as // specified in spec section 11.12.1.4. -func (rs *PushRuleset) GetActions(room Room, event *gomatrix.Event) (match PushActionArray) { +func (rs *PushRuleset) GetActions(room Room, event *mautrix.Event) (match PushActionArray) { // Add push rule collections to array in priority order arrays := []PushRuleCollection{rs.Override, rs.Content, rs.Room, rs.Sender, rs.Underride} // Loop until one of the push rule collections matches the room/event combo. diff --git a/matrix/rooms/room.go b/matrix/rooms/room.go index bd233f8..72251c4 100644 --- a/matrix/rooms/room.go +++ b/matrix/rooms/room.go @@ -23,7 +23,7 @@ import ( "time" "encoding/gob" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/debug" "os" ) @@ -58,7 +58,7 @@ type UnreadMessage struct { // Room represents a single Matrix room. type Room struct { - *gomatrix.Room + *mautrix.Room // Whether or not the user has left the room. HasLeft bool @@ -82,10 +82,10 @@ type Room struct { LastReceivedMessage time.Time // MXID -> Member cache calculated from membership events. - memberCache map[string]*gomatrix.Member + memberCache map[string]*mautrix.Member // The first non-SessionUserID member in the room. Calculated at // the same time as memberCache. - firstMemberCache *gomatrix.Member + firstMemberCache *mautrix.Member // The name of the room. Calculated from the state event name, // canonical_alias or alias or the member cache. nameCache string @@ -216,31 +216,31 @@ func (room *Room) Tags() []RoomTag { // UpdateState updates the room's current state with the given Event. This will clobber events based // on the type/state_key combination. -func (room *Room) UpdateState(event *gomatrix.Event) { +func (room *Room) UpdateState(event *mautrix.Event) { _, exists := room.State[event.Type] if !exists { - room.State[event.Type] = make(map[string]*gomatrix.Event) + room.State[event.Type] = make(map[string]*mautrix.Event) } switch event.Type { - case gomatrix.StateRoomName: + case mautrix.StateRoomName: room.nameCache = "" - case gomatrix.StateCanonicalAlias: + case mautrix.StateCanonicalAlias: if room.nameCacheSource >= CanonicalAliasRoomName { room.nameCache = "" } room.canonicalAliasCache = "" - case gomatrix.StateAliases: + case mautrix.StateAliases: if room.nameCacheSource >= AliasRoomName { room.nameCache = "" } room.aliasesCache = nil - case gomatrix.StateMember: + case mautrix.StateMember: room.memberCache = nil room.firstMemberCache = nil if room.nameCacheSource >= MemberRoomName { room.nameCache = "" } - case gomatrix.StateTopic: + case mautrix.StateTopic: room.topicCache = "" } @@ -248,7 +248,7 @@ func (room *Room) UpdateState(event *gomatrix.Event) { if event.StateKey != nil { stateKey = *event.StateKey } - if event.Type != gomatrix.StateMember { + if event.Type != mautrix.StateMember { debug.Printf("Updating state %s#%s for %s", event.Type, stateKey, room.ID) } @@ -260,14 +260,14 @@ func (room *Room) UpdateState(event *gomatrix.Event) { } // GetStateEvent returns the state event for the given type/state_key combo, or nil. -func (room *Room) GetStateEvent(eventType gomatrix.EventType, stateKey string) *gomatrix.Event { +func (room *Room) GetStateEvent(eventType mautrix.EventType, stateKey string) *mautrix.Event { stateEventMap, _ := room.State[eventType] event, _ := stateEventMap[stateKey] return event } // GetStateEvents returns the state events for the given type. -func (room *Room) GetStateEvents(eventType gomatrix.EventType) map[string]*gomatrix.Event { +func (room *Room) GetStateEvents(eventType mautrix.EventType) map[string]*mautrix.Event { stateEventMap, _ := room.State[eventType] return stateEventMap } @@ -275,7 +275,7 @@ func (room *Room) GetStateEvents(eventType gomatrix.EventType) map[string]*gomat // GetTopic returns the topic of the room. func (room *Room) GetTopic() string { if len(room.topicCache) == 0 { - topicEvt := room.GetStateEvent(gomatrix.StateTopic, "") + topicEvt := room.GetStateEvent(mautrix.StateTopic, "") if topicEvt != nil { room.topicCache = topicEvt.Content.Topic } @@ -285,7 +285,7 @@ func (room *Room) GetTopic() string { func (room *Room) GetCanonicalAlias() string { if len(room.canonicalAliasCache) == 0 { - canonicalAliasEvt := room.GetStateEvent(gomatrix.StateCanonicalAlias, "") + canonicalAliasEvt := room.GetStateEvent(mautrix.StateCanonicalAlias, "") if canonicalAliasEvt != nil { room.canonicalAliasCache = canonicalAliasEvt.Content.Alias } else { @@ -301,7 +301,7 @@ func (room *Room) GetCanonicalAlias() string { // GetAliases returns the list of aliases that point to this room. func (room *Room) GetAliases() []string { if room.aliasesCache == nil { - aliasEvents := room.GetStateEvents(gomatrix.StateAliases) + aliasEvents := room.GetStateEvents(mautrix.StateAliases) room.aliasesCache = []string{} for _, event := range aliasEvents { room.aliasesCache = append(room.aliasesCache, event.Content.Aliases...) @@ -312,7 +312,7 @@ func (room *Room) GetAliases() []string { // updateNameFromNameEvent updates the room display name to be the name set in the name event. func (room *Room) updateNameFromNameEvent() { - nameEvt := room.GetStateEvent(gomatrix.StateRoomName, "") + nameEvt := room.GetStateEvent(mautrix.StateRoomName, "") if nameEvt != nil { room.nameCache = nameEvt.Content.Name } @@ -384,9 +384,9 @@ func (room *Room) GetTitle() string { } // createMemberCache caches all member events into a easily processable MXID -> *Member map. -func (room *Room) createMemberCache() map[string]*gomatrix.Member { - cache := make(map[string]*gomatrix.Member) - events := room.GetStateEvents(gomatrix.StateMember) +func (room *Room) createMemberCache() map[string]*mautrix.Member { + cache := make(map[string]*mautrix.Member) + events := room.GetStateEvents(mautrix.StateMember) room.firstMemberCache = nil if events != nil { for userID, event := range events { @@ -407,7 +407,7 @@ func (room *Room) createMemberCache() map[string]*gomatrix.Member { // // The members are returned from the cache. // If the cache is empty, it is updated first. -func (room *Room) GetMembers() map[string]*gomatrix.Member { +func (room *Room) GetMembers() map[string]*mautrix.Member { if len(room.memberCache) == 0 || room.firstMemberCache == nil { room.createMemberCache() } @@ -416,7 +416,7 @@ func (room *Room) GetMembers() map[string]*gomatrix.Member { // GetMember returns the member with the given MXID. // If the member doesn't exist, nil is returned. -func (room *Room) GetMember(userID string) *gomatrix.Member { +func (room *Room) GetMember(userID string) *mautrix.Member { if len(room.memberCache) == 0 { room.createMemberCache() } @@ -432,7 +432,7 @@ func (room *Room) GetSessionOwner() string { // NewRoom creates a new Room with the given ID func NewRoom(roomID, owner string) *Room { return &Room{ - Room: gomatrix.NewRoom(roomID), + Room: mautrix.NewRoom(roomID), fetchHistoryLock: &sync.Mutex{}, SessionUserID: owner, } diff --git a/matrix/rooms/room_test.go b/matrix/rooms/room_test.go index 1fabdcc..db7f586 100644 --- a/matrix/rooms/room_test.go +++ b/matrix/rooms/room_test.go @@ -21,7 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/matrix/rooms" ) @@ -39,7 +39,7 @@ func TestNewRoom_DefaultValues(t *testing.T) { func TestRoom_GetCanonicalAlias(t *testing.T) { room := rooms.NewRoom("!test:maunium.net", "@tulir:maunium.net") - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.canonical_alias", Content: map[string]interface{}{ "alias": "#foo:maunium.net", @@ -50,7 +50,7 @@ func TestRoom_GetCanonicalAlias(t *testing.T) { func TestRoom_GetTopic(t *testing.T) { room := rooms.NewRoom("!test:maunium.net", "@tulir:maunium.net") - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.topic", Content: map[string]interface{}{ "topic": "test topic", @@ -87,7 +87,7 @@ func TestRoom_GetAliases(t *testing.T) { } func addName(room *rooms.Room) { - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.name", Content: map[string]interface{}{ "name": "Test room", @@ -96,7 +96,7 @@ func addName(room *rooms.Room) { } func addCanonicalAlias(room *rooms.Room) { - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.canonical_alias", Content: map[string]interface{}{ "alias": "#foo:maunium.net", @@ -106,7 +106,7 @@ func addCanonicalAlias(room *rooms.Room) { func addAliases(room *rooms.Room) { server1 := "maunium.net" - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.aliases", StateKey: &server1, Content: map[string]interface{}{ @@ -115,7 +115,7 @@ func addAliases(room *rooms.Room) { }) server2 := "matrix.org" - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.aliases", StateKey: &server2, Content: map[string]interface{}{ @@ -126,7 +126,7 @@ func addAliases(room *rooms.Room) { func addMembers(room *rooms.Room, count int) { user1 := "@tulir:maunium.net" - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.member", StateKey: &user1, Content: map[string]interface{}{ @@ -146,7 +146,7 @@ func addMembers(room *rooms.Room, count int) { if i%5 == 0 { content["membership"] = "invite" } - room.UpdateState(&gomatrix.Event{ + room.UpdateState(&mautrix.Event{ Type: "m.room.member", StateKey: &userN, Content: content, diff --git a/matrix/sync.go b/matrix/sync.go index 6d5def7..06c7f47 100644 --- a/matrix/sync.go +++ b/matrix/sync.go @@ -14,15 +14,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. -// Based on https://github.com/matrix-org/gomatrix/blob/master/sync.go +// Based on https://github.com/matrix-org/mautrix/blob/master/sync.go package matrix import ( "encoding/json" + "maunium.net/go/gomuks/debug" "time" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/matrix/rooms" ) @@ -44,14 +45,14 @@ const ( EventSourceEphemeral ) -type EventHandler func(source EventSource, event *gomatrix.Event) +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 { Session SyncerSession - listeners map[gomatrix.EventType][]EventHandler // event type to listeners array + listeners map[mautrix.EventType][]EventHandler // event type to listeners array FirstSyncDone bool InitDoneCallback func() } @@ -60,13 +61,14 @@ type GomuksSyncer struct { func NewGomuksSyncer(session SyncerSession) *GomuksSyncer { return &GomuksSyncer{ Session: session, - listeners: make(map[gomatrix.EventType][]EventHandler), + listeners: make(map[mautrix.EventType][]EventHandler), FirstSyncDone: false, } } // ProcessResponse processes a Matrix sync response. -func (s *GomuksSyncer) ProcessResponse(res *gomatrix.RespSync, since string) (err error) { +func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err error) { + debug.Print("Received sync response") s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence, false) s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData, false) @@ -106,7 +108,7 @@ func (s *GomuksSyncer) ProcessResponse(res *gomatrix.RespSync, since string) (er return } -func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*gomatrix.Event, source EventSource, checkStateKey bool) { +func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*mautrix.Event, source EventSource, checkStateKey bool) { for _, event := range events { if !checkStateKey || event.StateKey != nil { s.processSyncEvent(room, event, source) @@ -114,11 +116,11 @@ func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*gomatrix.Ev } } -func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, event *gomatrix.Event, source EventSource) { +func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, event *mautrix.Event, source EventSource) { if room != nil { event.RoomID = room.ID } - if event.Type.Class == gomatrix.StateEventType { + if event.Type.Class == mautrix.StateEventType { room.UpdateState(event) } s.notifyListeners(source, event) @@ -126,7 +128,7 @@ func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, event *gomatrix.Event, // OnEventType allows callers to be notified when there are new events for the given event type. // There are no duplicate checks. -func (s *GomuksSyncer) OnEventType(eventType gomatrix.EventType, callback EventHandler) { +func (s *GomuksSyncer) OnEventType(eventType mautrix.EventType, callback EventHandler) { _, exists := s.listeners[eventType] if !exists { s.listeners[eventType] = []EventHandler{} @@ -134,7 +136,7 @@ func (s *GomuksSyncer) OnEventType(eventType gomatrix.EventType, callback EventH s.listeners[eventType] = append(s.listeners[eventType], callback) } -func (s *GomuksSyncer) notifyListeners(source EventSource, event *gomatrix.Event) { +func (s *GomuksSyncer) notifyListeners(source EventSource, event *mautrix.Event) { listeners, exists := s.listeners[event.Type] if !exists { return @@ -145,16 +147,17 @@ func (s *GomuksSyncer) notifyListeners(source EventSource, event *gomatrix.Event } // OnFailedSync always returns a 10 second wait period between failed /syncs, never a fatal error. -func (s *GomuksSyncer) OnFailedSync(res *gomatrix.RespSync, err error) (time.Duration, error) { +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 { - filter := &gomatrix.Filter{ - Room: gomatrix.RoomFilter{ + filter := &mautrix.Filter{ + Room: mautrix.RoomFilter{ IncludeLeave: false, - State: gomatrix.FilterPart{ + State: mautrix.FilterPart{ Types: []string{ "m.room.member", "m.room.name", @@ -163,21 +166,21 @@ func (s *GomuksSyncer) GetFilterJSON(userID string) json.RawMessage { "m.room.aliases", }, }, - Timeline: gomatrix.FilterPart{ + Timeline: mautrix.FilterPart{ Types: []string{"m.room.message", "m.room.member"}, Limit: 50, }, - Ephemeral: gomatrix.FilterPart{ + Ephemeral: mautrix.FilterPart{ Types: []string{"m.typing", "m.receipt"}, }, - AccountData: gomatrix.FilterPart{ + AccountData: mautrix.FilterPart{ Types: []string{"m.tag"}, }, }, - AccountData: gomatrix.FilterPart{ + AccountData: mautrix.FilterPart{ Types: []string{"m.push_rules", "m.direct", "net.maunium.gomuks.preferences"}, }, - Presence: gomatrix.FilterPart{ + Presence: mautrix.FilterPart{ Types: []string{}, }, } diff --git a/matrix/sync_test.go b/matrix/sync_test.go index 49bbcb0..79cb11b 100644 --- a/matrix/sync_test.go +++ b/matrix/sync_test.go @@ -20,7 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "maunium.net/go/gomatrix" + "maunium.net/go/mautrix" "maunium.net/go/gomuks/matrix" "maunium.net/go/gomuks/matrix/rooms" ) @@ -42,13 +42,13 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { userID: "@tulir:maunium.net", rooms: map[string]*rooms.Room{ "!foo:maunium.net": { - Room: gomatrix.NewRoom("!foo:maunium.net"), + Room: mautrix.NewRoom("!foo:maunium.net"), }, "!bar:maunium.net": { - Room: gomatrix.NewRoom("!bar:maunium.net"), + Room: mautrix.NewRoom("!bar:maunium.net"), }, "!test:maunium.net": { - Room: gomatrix.NewRoom("!test:maunium.net"), + Room: mautrix.NewRoom("!test:maunium.net"), }, }, } @@ -58,7 +58,7 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { syncer.OnEventType("m.room.message", ml.receive) syncer.GetFilterJSON("@tulir:maunium.net") - joinEvt := &gomatrix.Event{ + joinEvt := &mautrix.Event{ ID: "!join:maunium.net", Type: "m.room.member", Sender: "@tulir:maunium.net", @@ -67,7 +67,7 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { "membership": "join", }, } - messageEvt := &gomatrix.Event{ + messageEvt := &mautrix.Event{ ID: "!msg:maunium.net", Type: "m.room.message", Content: map[string]interface{}{ @@ -75,11 +75,11 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { "msgtype": "m.text", }, } - unhandledEvt := &gomatrix.Event{ + unhandledEvt := &mautrix.Event{ ID: "!unhandled:maunium.net", Type: "m.room.unhandled_event", } - inviteEvt := &gomatrix.Event{ + inviteEvt := &mautrix.Event{ ID: "!invite:matrix.org", Type: "m.room.member", Sender: "@you:matrix.org", @@ -88,7 +88,7 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { "membership": "invite", }, } - leaveEvt := &gomatrix.Event{ + leaveEvt := &mautrix.Event{ ID: "!leave:matrix.org", Type: "m.room.member", Sender: "@you:matrix.org", @@ -100,27 +100,27 @@ func TestGomuksSyncer_ProcessResponse(t *testing.T) { resp := newRespSync() resp.Rooms.Join["!foo:maunium.net"] = join{ - State: events{Events: []*gomatrix.Event{joinEvt}}, - Timeline: timeline{Events: []*gomatrix.Event{messageEvt, unhandledEvt}}, + State: events{Events: []*mautrix.Event{joinEvt}}, + Timeline: timeline{Events: []*mautrix.Event{messageEvt, unhandledEvt}}, } resp.Rooms.Invite["!bar:maunium.net"] = struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"invite_state"` }{ - State: events{Events: []*gomatrix.Event{inviteEvt}}, + State: events{Events: []*mautrix.Event{inviteEvt}}, } resp.Rooms.Leave["!test:maunium.net"] = struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"state"` Timeline struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` Limited bool `json:"limited"` PrevBatch string `json:"prev_batch"` } `json:"timeline"` }{ - State: events{Events: []*gomatrix.Event{leaveEvt}}, + State: events{Events: []*mautrix.Event{leaveEvt}}, } syncer.ProcessResponse(resp, "since") @@ -145,28 +145,28 @@ func (mss *mockSyncerSession) GetUserID() string { } type events struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } type timeline struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` Limited bool `json:"limited"` PrevBatch string `json:"prev_batch"` } type join struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"state"` Timeline struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` Limited bool `json:"limited"` PrevBatch string `json:"prev_batch"` } `json:"timeline"` Ephemeral struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"ephemeral"` AccountData struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"account_data"` } @@ -175,42 +175,42 @@ func ptr(text string) *string { } type mockListener struct { - received []*gomatrix.Event + received []*mautrix.Event } -func (ml *mockListener) receive(source matrix.EventSource, evt *gomatrix.Event) { +func (ml *mockListener) receive(source matrix.EventSource, evt *mautrix.Event) { ml.received = append(ml.received, evt) } -func newRespSync() *gomatrix.RespSync { - resp := &gomatrix.RespSync{NextBatch: "123"} +func newRespSync() *mautrix.RespSync { + resp := &mautrix.RespSync{NextBatch: "123"} resp.Rooms.Join = make(map[string]struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"state"` Timeline struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` Limited bool `json:"limited"` PrevBatch string `json:"prev_batch"` } `json:"timeline"` Ephemeral struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"ephemeral"` AccountData struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"account_data"` }) resp.Rooms.Invite = make(map[string]struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"invite_state"` }) resp.Rooms.Leave = make(map[string]struct { State struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` } `json:"state"` Timeline struct { - Events []*gomatrix.Event `json:"events"` + Events []*mautrix.Event `json:"events"` Limited bool `json:"limited"` PrevBatch string `json:"prev_batch"` } `json:"timeline"` |