diff options
Diffstat (limited to 'matrix')
-rw-r--r-- | matrix/matrix.go | 69 | ||||
-rw-r--r-- | matrix/pushrules/condition.go | 19 | ||||
-rw-r--r-- | matrix/pushrules/pushrules.go | 16 | ||||
-rw-r--r-- | matrix/pushrules/rule.go | 3 | ||||
-rw-r--r-- | matrix/rooms/member.go | 63 | ||||
-rw-r--r-- | matrix/rooms/member_test.go | 17 | ||||
-rw-r--r-- | matrix/rooms/room.go | 65 | ||||
-rw-r--r-- | matrix/sync.go | 17 |
8 files changed, 81 insertions, 188 deletions
diff --git a/matrix/matrix.go b/matrix/matrix.go index 9b90ffe..060becd 100644 --- a/matrix/matrix.go +++ b/matrix/matrix.go @@ -175,6 +175,8 @@ func (c *Container) PushRules() *pushrules.PushRuleset { return c.config.PushRules } +var AccountDataGomuksPreferences = gomatrix.NewEventType("net.maunium.gomuks.preferences") + // OnLogin initializes the syncer and updates the room list. func (c *Container) OnLogin() { c.ui.OnLogin() @@ -183,14 +185,14 @@ func (c *Container) OnLogin() { debug.Print("Initializing syncer") c.syncer = NewGomuksSyncer(c.config) - c.syncer.OnEventType("m.room.message", c.HandleMessage) - c.syncer.OnEventType("m.room.member", c.HandleMembership) - c.syncer.OnEventType("m.receipt", c.HandleReadReceipt) - c.syncer.OnEventType("m.typing", c.HandleTyping) - c.syncer.OnEventType("m.direct", c.HandleDirectChatInfo) - c.syncer.OnEventType("m.push_rules", c.HandlePushRules) - c.syncer.OnEventType("m.tag", c.HandleTag) - c.syncer.OnEventType("net.maunium.gomuks.preferences", c.HandlePreferences) + 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(AccountDataGomuksPreferences, c.HandlePreferences) c.syncer.InitDoneCallback = func() { c.config.AuthCache.InitialSyncDone = true c.config.SaveAuthCache() @@ -301,10 +303,10 @@ func (c *Container) HandleMembership(source EventSource, evt *gomatrix.Event) { } func (c *Container) processOwnMembershipChange(evt *gomatrix.Event) { - membership, _ := evt.Content["membership"].(string) - prevMembership := "leave" + membership := evt.Content.Membership + prevMembership := gomatrix.MembershipLeave if evt.Unsigned.PrevContent != nil { - prevMembership, _ = evt.Unsigned.PrevContent["membership"].(string) + prevMembership = evt.Unsigned.PrevContent.Membership } debug.Printf("Processing own membership change: %s->%s in %s", prevMembership, membership, evt.RoomID) if membership == prevMembership { @@ -326,7 +328,7 @@ func (c *Container) processOwnMembershipChange(evt *gomatrix.Event) { func (c *Container) parseReadReceipt(evt *gomatrix.Event) (largestTimestampEvent string) { var largestTimestamp int64 - for eventID, rawContent := range evt.Content { + for eventID, rawContent := range evt.Content.Raw { content, ok := rawContent.(map[string]interface{}) if !ok { continue @@ -368,7 +370,7 @@ func (c *Container) HandleReadReceipt(source EventSource, evt *gomatrix.Event) { func (c *Container) parseDirectChatInfo(evt *gomatrix.Event) map[*rooms.Room]bool { directChats := make(map[*rooms.Room]bool) - for _, rawRoomIDList := range evt.Content { + for _, rawRoomIDList := range evt.Content.Raw { roomIDList, ok := rawRoomIDList.([]interface{}) if !ok { continue @@ -416,15 +418,12 @@ func (c *Container) HandlePushRules(source EventSource, evt *gomatrix.Event) { func (c *Container) HandleTag(source EventSource, evt *gomatrix.Event) { room := c.config.GetRoom(evt.RoomID) - tags, _ := evt.Content["tags"].(map[string]interface{}) - newTags := make([]rooms.RoomTag, len(tags)) + newTags := make([]rooms.RoomTag, len(evt.Content.RoomTags)) index := 0 - for tag, infoifc := range tags { - info, _ := infoifc.(map[string]interface{}) + for tag, info := range evt.Content.RoomTags { order := "0.5" - rawOrder, ok := info["order"] - if ok { - order = fmt.Sprintf("%v", rawOrder) + if len(info.Order) > 0 { + order = info.Order } newTags[index] = rooms.RoomTag{ Tag: tag, @@ -440,13 +439,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) { - users := evt.Content["user_ids"].([]interface{}) - - strUsers := make([]string, len(users)) - for i, user := range users { - strUsers[i] = user.(string) - } - c.ui.MainView().SetTyping(evt.RoomID, strUsers) + c.ui.MainView().SetTyping(evt.RoomID, evt.Content.TypingUserIDs) } func (c *Container) MarkRead(roomID, eventID string) { @@ -455,11 +448,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, msgtype, text string) (string, error) { +func (c *Container) SendMessage(roomID string, msgtype gomatrix.MessageType, text string) (string, error) { defer debug.Recover() c.SendTyping(roomID, false) - resp, err := c.client.SendMessageEvent(roomID, "m.room.message", - gomatrix.TextMessage{MsgType: msgtype, Body: text}) + resp, err := c.client.SendMessageEvent(roomID, gomatrix.EventMessage, + gomatrix.Content{MsgType: msgtype, Body: text}) if err != nil { return "", err } @@ -498,7 +491,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, msgtype, text string) (string, error) { +func (c *Container) SendMarkdownMessage(roomID string, msgtype gomatrix.MessageType, text string) (string, error) { defer debug.Recover() html := c.renderMarkdown(text) @@ -511,12 +504,12 @@ func (c *Container) SendMarkdownMessage(roomID, msgtype, text string) (string, e text = roomRegex.ReplaceAllString(text, "$1") c.SendTyping(roomID, false) - resp, err := c.client.SendMessageEvent(roomID, "m.room.message", - map[string]interface{}{ - "msgtype": msgtype, - "body": text, - "format": "org.matrix.custom.html", - "formatted_body": html, + resp, err := c.client.SendMessageEvent(roomID, gomatrix.EventMessage, + gomatrix.Content{ + MsgType: msgtype, + Body: text, + Format: gomatrix.FormatHTML, + FormattedBody: html, }) if err != nil { return "", err @@ -567,7 +560,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) ([]*gomatrix.Event, string, error) { resp, err := c.client.Messages(roomID, prevBatch, "", 'b', limit) if err != nil { return nil, "", err diff --git a/matrix/pushrules/condition.go b/matrix/pushrules/condition.go index 08958a3..22d59aa 100644 --- a/matrix/pushrules/condition.go +++ b/matrix/pushrules/condition.go @@ -23,14 +23,13 @@ import ( "maunium.net/go/gomatrix" "maunium.net/go/gomuks/lib/glob" - "maunium.net/go/gomuks/matrix/rooms" ) // Room is an interface with the functions that are needed for processing room-specific push conditions type Room interface { - GetMember(mxid string) *rooms.Member - GetMembers() map[string]*rooms.Member - GetSessionOwner() *rooms.Member + GetMember(mxid string) *gomatrix.Member + GetMembers() map[string]*gomatrix.Member + GetSessionOwner() string } // PushCondKind is the type of a push condition. @@ -89,7 +88,7 @@ func (cond *PushCondition) matchValue(room Room, event *gomatrix.Event) bool { switch key { case "type": - return pattern.MatchString(event.Type) + return pattern.MatchString(event.Type.String()) case "sender": return pattern.MatchString(event.Sender) case "room_id": @@ -100,7 +99,7 @@ func (cond *PushCondition) matchValue(room Room, event *gomatrix.Event) bool { } return pattern.MatchString(*event.StateKey) case "content": - val, _ := event.Content[subkey].(string) + val, _ := event.Content.Raw[subkey].(string) return pattern.MatchString(val) default: return false @@ -108,12 +107,12 @@ func (cond *PushCondition) matchValue(room Room, event *gomatrix.Event) bool { } func (cond *PushCondition) matchDisplayName(room Room, event *gomatrix.Event) bool { - member := room.GetSessionOwner() - if member == nil || member.UserID == event.Sender { + ownerID := room.GetSessionOwner() + if ownerID == event.Sender { return false } - text, _ := event.Content["body"].(string) - return strings.Contains(text, member.DisplayName) + member := room.GetMember(ownerID) + return strings.Contains(event.Content.Body, member.Displayname) } func (cond *PushCondition) matchMemberCount(room Room, event *gomatrix.Event) bool { diff --git a/matrix/pushrules/pushrules.go b/matrix/pushrules/pushrules.go index 876713b..b383c66 100644 --- a/matrix/pushrules/pushrules.go +++ b/matrix/pushrules/pushrules.go @@ -21,19 +21,17 @@ func GetScopedPushRules(client *gomatrix.Client, scope string) (resp *PushRulese return } +type contentWithRuleset struct { + Ruleset *PushRuleset `json:"global"` +} + // EventToPushRules converts a m.push_rules event to a PushRuleset by passing the data through JSON. func EventToPushRules(event *gomatrix.Event) (*PushRuleset, error) { - content, _ := event.Content["global"] - raw, err := json.Marshal(content) - if err != nil { - return nil, err - } - - ruleset := &PushRuleset{} - err = json.Unmarshal(raw, ruleset) + content := &contentWithRuleset{} + err := json.Unmarshal(event.Content.VeryRaw, content) if err != nil { return nil, err } - return ruleset, nil + return content.Ruleset, nil } diff --git a/matrix/pushrules/rule.go b/matrix/pushrules/rule.go index 5ede895..71f71e5 100644 --- a/matrix/pushrules/rule.go +++ b/matrix/pushrules/rule.go @@ -154,6 +154,5 @@ func (rule *PushRule) matchPattern(room Room, event *gomatrix.Event) bool { if err != nil { return false } - text, _ := event.Content["body"].(string) - return pattern.MatchString(text) + return pattern.MatchString(event.Content.Body) } diff --git a/matrix/rooms/member.go b/matrix/rooms/member.go deleted file mode 100644 index aee7533..0000000 --- a/matrix/rooms/member.go +++ /dev/null @@ -1,63 +0,0 @@ -// gomuks - A terminal Matrix client written in Go. -// Copyright (C) 2018 Tulir Asokan -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// 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 -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see <http://www.gnu.org/licenses/>. - -package rooms - -import ( - "maunium.net/go/gomatrix" -) - -// Membership is an enum specifying the membership state of a room member. -type Membership string - -// The allowed membership states as specified in spec section 10.5.5. -const ( - MembershipJoin Membership = "join" - MembershipLeave Membership = "leave" - MembershipInvite Membership = "invite" - MembershipBan Membership = "ban" - MembershipKnock Membership = "knock" -) - -// Member represents a member in a room. -type Member struct { - // The MXID of the member. - UserID string `json:"-"` - // The membership status. Defaults to leave. - Membership Membership `json:"membership"` - // The display name of the user. Defaults to the user ID. - DisplayName string `json:"displayname"` - // The avatar URL of the user. Defaults to an empty string. - AvatarURL string `json:"avatar_url"` -} - -// eventToRoomMember converts a m.room.member state event into a Member object. -func eventToRoomMember(userID string, event *gomatrix.Event) *Member { - membership, _ := event.Content["membership"].(string) - avatarURL, _ := event.Content["avatar_url"].(string) - - displayName, _ := event.Content["displayname"].(string) - if len(displayName) == 0 { - displayName = userID - } - - return &Member{ - UserID: userID, - Membership: Membership(membership), - DisplayName: displayName, - AvatarURL: avatarURL, - } -} diff --git a/matrix/rooms/member_test.go b/matrix/rooms/member_test.go deleted file mode 100644 index c3a4cfe..0000000 --- a/matrix/rooms/member_test.go +++ /dev/null @@ -1,17 +0,0 @@ -// gomuks - A terminal Matrix client written in Go. -// Copyright (C) 2018 Tulir Asokan -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// 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 -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see <http://www.gnu.org/licenses/>. - -package rooms_test diff --git a/matrix/rooms/room.go b/matrix/rooms/room.go index 598f0ea..bd233f8 100644 --- a/matrix/rooms/room.go +++ b/matrix/rooms/room.go @@ -82,10 +82,10 @@ type Room struct { LastReceivedMessage time.Time // MXID -> Member cache calculated from membership events. - memberCache map[string]*Member + memberCache map[string]*gomatrix.Member // The first non-SessionUserID member in the room. Calculated at // the same time as memberCache. - firstMemberCache *Member + firstMemberCache *gomatrix.Member // The name of the room. Calculated from the state event name, // canonical_alias or alias or the member cache. nameCache string @@ -222,25 +222,25 @@ func (room *Room) UpdateState(event *gomatrix.Event) { room.State[event.Type] = make(map[string]*gomatrix.Event) } switch event.Type { - case "m.room.name": + case gomatrix.StateRoomName: room.nameCache = "" - case "m.room.canonical_alias": + case gomatrix.StateCanonicalAlias: if room.nameCacheSource >= CanonicalAliasRoomName { room.nameCache = "" } room.canonicalAliasCache = "" - case "m.room.aliases": + case gomatrix.StateAliases: if room.nameCacheSource >= AliasRoomName { room.nameCache = "" } room.aliasesCache = nil - case "m.room.member": + case gomatrix.StateMember: room.memberCache = nil room.firstMemberCache = nil if room.nameCacheSource >= MemberRoomName { room.nameCache = "" } - case "m.room.topic": + case gomatrix.StateTopic: room.topicCache = "" } @@ -248,7 +248,7 @@ func (room *Room) UpdateState(event *gomatrix.Event) { if event.StateKey != nil { stateKey = *event.StateKey } - if event.Type != "m.room.member" { + if event.Type != gomatrix.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 string, stateKey string) *gomatrix.Event { +func (room *Room) GetStateEvent(eventType gomatrix.EventType, stateKey string) *gomatrix.Event { stateEventMap, _ := room.State[eventType] event, _ := stateEventMap[stateKey] return event } // GetStateEvents returns the state events for the given type. -func (room *Room) GetStateEvents(eventType string) map[string]*gomatrix.Event { +func (room *Room) GetStateEvents(eventType gomatrix.EventType) map[string]*gomatrix.Event { stateEventMap, _ := room.State[eventType] return stateEventMap } @@ -275,9 +275,9 @@ func (room *Room) GetStateEvents(eventType string) map[string]*gomatrix.Event { // GetTopic returns the topic of the room. func (room *Room) GetTopic() string { if len(room.topicCache) == 0 { - topicEvt := room.GetStateEvent("m.room.topic", "") + topicEvt := room.GetStateEvent(gomatrix.StateTopic, "") if topicEvt != nil { - room.topicCache, _ = topicEvt.Content["topic"].(string) + room.topicCache = topicEvt.Content.Topic } } return room.topicCache @@ -285,9 +285,9 @@ func (room *Room) GetTopic() string { func (room *Room) GetCanonicalAlias() string { if len(room.canonicalAliasCache) == 0 { - canonicalAliasEvt := room.GetStateEvent("m.room.canonical_alias", "") + canonicalAliasEvt := room.GetStateEvent(gomatrix.StateCanonicalAlias, "") if canonicalAliasEvt != nil { - room.canonicalAliasCache, _ = canonicalAliasEvt.Content["alias"].(string) + room.canonicalAliasCache = canonicalAliasEvt.Content.Alias } else { room.canonicalAliasCache = "-" } @@ -301,17 +301,10 @@ 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("m.room.aliases") + aliasEvents := room.GetStateEvents(gomatrix.StateAliases) room.aliasesCache = []string{} for _, event := range aliasEvents { - aliases, _ := event.Content["aliases"].([]interface{}) - - newAliases := make([]string, len(room.aliasesCache)+len(aliases)) - copy(newAliases, room.aliasesCache) - for index, alias := range aliases { - newAliases[len(room.aliasesCache)+index], _ = alias.(string) - } - room.aliasesCache = newAliases + room.aliasesCache = append(room.aliasesCache, event.Content.Aliases...) } } return room.aliasesCache @@ -319,9 +312,9 @@ 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("m.room.name", "") + nameEvt := room.GetStateEvent(gomatrix.StateRoomName, "") if nameEvt != nil { - room.nameCache, _ = nameEvt.Content["name"].(string) + room.nameCache = nameEvt.Content.Name } } @@ -353,9 +346,9 @@ func (room *Room) updateNameFromMembers() { } else if room.firstMemberCache == nil { room.nameCache = "Room" } else if len(members) == 2 { - room.nameCache = room.firstMemberCache.DisplayName + room.nameCache = room.firstMemberCache.Displayname } else { - firstMember := room.firstMemberCache.DisplayName + firstMember := room.firstMemberCache.Displayname room.nameCache = fmt.Sprintf("%s and %d others", firstMember, len(members)-2) } } @@ -391,18 +384,18 @@ func (room *Room) GetTitle() string { } // createMemberCache caches all member events into a easily processable MXID -> *Member map. -func (room *Room) createMemberCache() map[string]*Member { - cache := make(map[string]*Member) - events := room.GetStateEvents("m.room.member") +func (room *Room) createMemberCache() map[string]*gomatrix.Member { + cache := make(map[string]*gomatrix.Member) + events := room.GetStateEvents(gomatrix.StateMember) room.firstMemberCache = nil if events != nil { for userID, event := range events { - member := eventToRoomMember(userID, event) + member := &event.Content.Member if room.firstMemberCache == nil && userID != room.SessionUserID { room.firstMemberCache = member } if member.Membership != "leave" { - cache[member.UserID] = member + cache[userID] = member } } } @@ -414,7 +407,7 @@ func (room *Room) createMemberCache() map[string]*Member { // // The members are returned from the cache. // If the cache is empty, it is updated first. -func (room *Room) GetMembers() map[string]*Member { +func (room *Room) GetMembers() map[string]*gomatrix.Member { if len(room.memberCache) == 0 || room.firstMemberCache == nil { room.createMemberCache() } @@ -423,7 +416,7 @@ func (room *Room) GetMembers() map[string]*Member { // GetMember returns the member with the given MXID. // If the member doesn't exist, nil is returned. -func (room *Room) GetMember(userID string) *Member { +func (room *Room) GetMember(userID string) *gomatrix.Member { if len(room.memberCache) == 0 { room.createMemberCache() } @@ -432,8 +425,8 @@ func (room *Room) GetMember(userID string) *Member { } // GetSessionOwner returns the Member instance of the user whose session this room was created for. -func (room *Room) GetSessionOwner() *Member { - return room.GetMember(room.SessionUserID) +func (room *Room) GetSessionOwner() string { + return room.SessionUserID } // NewRoom creates a new Room with the given ID diff --git a/matrix/sync.go b/matrix/sync.go index 2037fcd..6d5def7 100644 --- a/matrix/sync.go +++ b/matrix/sync.go @@ -51,7 +51,7 @@ type EventHandler func(source EventSource, event *gomatrix.Event) // pattern to notify callers about incoming events. See GomuksSyncer.OnEventType for more information. type GomuksSyncer struct { Session SyncerSession - listeners map[string][]EventHandler // event type to listeners array + listeners map[gomatrix.EventType][]EventHandler // event type to listeners array FirstSyncDone bool InitDoneCallback func() } @@ -60,7 +60,7 @@ type GomuksSyncer struct { func NewGomuksSyncer(session SyncerSession) *GomuksSyncer { return &GomuksSyncer{ Session: session, - listeners: make(map[string][]EventHandler), + listeners: make(map[gomatrix.EventType][]EventHandler), FirstSyncDone: false, } } @@ -114,20 +114,11 @@ func (s *GomuksSyncer) processSyncEvents(room *rooms.Room, events []*gomatrix.Ev } } -func isState(event *gomatrix.Event) bool { - switch event.Type { - case "m.room.member", "m.room.name", "m.room.topic", "m.room.aliases", "m.room.canonical_alias": - return true - default: - return false - } -} - func (s *GomuksSyncer) processSyncEvent(room *rooms.Room, event *gomatrix.Event, source EventSource) { if room != nil { event.RoomID = room.ID } - if isState(event) { + if event.Type.Class == gomatrix.StateEventType { room.UpdateState(event) } s.notifyListeners(source, event) @@ -135,7 +126,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 string, callback EventHandler) { +func (s *GomuksSyncer) OnEventType(eventType gomatrix.EventType, callback EventHandler) { _, exists := s.listeners[eventType] if !exists { s.listeners[eventType] = []EventHandler{} |