aboutsummaryrefslogtreecommitdiff
path: root/matrix/rooms/room.go
blob: 99c9a66236d5f08066f49163c4600de06d9afd2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// 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 (
	"fmt"
	"sort"
	"sync"

	"maunium.net/go/gomatrix"
)

type RoomNameSource int

const (
	ExplicitRoomName RoomNameSource = iota
	CanonicalAliasRoomName
	AliasRoomName
	MemberRoomName
)

// Room represents a single Matrix room.
type Room struct {
	*gomatrix.Room

	// The first batch of events that has been fetched for this room.
	// Used for fetching additional history.
	PrevBatch string
	// The MXID of the user whose session this room was created for.
	SessionUserID string

	// The number of unread messages that were notified about.
	UnreadMessages int
	// Whether or not any of the unread messages were highlights.
	Highlighted bool
	// Whether or not the room contains any new messages.
	// This can be true even when UnreadMessages is zero if there's
	// a notificationless message like bot notices.
	HasNewMessages bool

	// MXID -> Member cache calculated from membership events.
	memberCache map[string]*Member
	// The first non-SessionUserID member in the room. Calculated at
	// the same time as memberCache.
	firstMemberCache string
	// The name of the room. Calculated from the state event name,
	// canonical_alias or alias or the member cache.
	nameCache string
	// The event type from which the name cache was calculated from.
	nameCacheSource RoomNameSource
	// The topic of the room. Directly fetched from the m.room.topic state event.
	topicCache string
	// The canonical alias of the room. Directly fetched from the m.room.canonical_alias state event.
	canonicalAliasCache string
	// The list of aliases. Directly fetched from the m.room.aliases state event.
	aliasesCache []string

	// fetchHistoryLock is used to make sure multiple goroutines don't fetch
	// history for this room at the same time.
	fetchHistoryLock *sync.Mutex
}

// LockHistory locks the history fetching mutex.
// If the mutex is nil, it will be created.
func (room *Room) LockHistory() {
	if room.fetchHistoryLock == nil {
		room.fetchHistoryLock = &sync.Mutex{}
	}
	room.fetchHistoryLock.Lock()
}

// UnlockHistory unlocks the history fetching mutex.
// If the mutex is nil, this does nothing.
func (room *Room) UnlockHistory() {
	if room.fetchHistoryLock != nil {
		room.fetchHistoryLock.Unlock()
	}
}

// MarkRead clears the new message statuses on this room.
func (room *Room) MarkRead() {
	room.UnreadMessages = 0
	room.Highlighted = false
	room.HasNewMessages = false
}

// 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) {
	_, exists := room.State[event.Type]
	if !exists {
		room.State[event.Type] = make(map[string]*gomatrix.Event)
	}
	switch event.Type {
	case "m.room.name":
		room.nameCache = ""
	case "m.room.canonical_alias":
		if room.nameCacheSource >= CanonicalAliasRoomName {
			room.nameCache = ""
		}
		room.canonicalAliasCache = ""
	case "m.room.aliases":
		if room.nameCacheSource >= AliasRoomName {
			room.nameCache = ""
		}
		room.aliasesCache = nil
	case "m.room.member":
		room.memberCache = nil
		room.firstMemberCache = ""
		if room.nameCacheSource >= MemberRoomName {
			room.nameCache = ""
		}
	case "m.room.topic":
		room.topicCache = ""
	}
	if event.StateKey == nil {
		room.State[event.Type][""] = event
	} else {
		room.State[event.Type][*event.StateKey] = 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 {
	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 {
	stateEventMap, _ := room.State[eventType]
	return stateEventMap
}

// GetTopic returns the topic of the room.
func (room *Room) GetTopic() string {
	if len(room.topicCache) == 0 {
		topicEvt := room.GetStateEvent("m.room.topic", "")
		if topicEvt != nil {
			room.topicCache, _ = topicEvt.Content["topic"].(string)
		}
	}
	return room.topicCache
}

func (room *Room) GetCanonicalAlias() string {
	if len(room.canonicalAliasCache) == 0 {
		canonicalAliasEvt := room.GetStateEvent("m.room.canonical_alias", "")
		if canonicalAliasEvt != nil {
			room.canonicalAliasCache, _ = canonicalAliasEvt.Content["alias"].(string)
		} else {
			room.canonicalAliasCache = "-"
		}
	}
	if room.canonicalAliasCache == "-" {
		return ""
	}
	return room.canonicalAliasCache
}

// 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")
		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
		}
	}
	return room.aliasesCache
}

// 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", "")
	if nameEvt != nil {
		room.nameCache, _ = nameEvt.Content["name"].(string)
	}
}

// updateNameFromAliases updates the room display name to be the first room alias it finds.
//
// Deprecated: the Client-Server API recommends against using non-canonical aliases as display name.
func (room *Room) updateNameFromAliases() {
	// TODO the spec says clients should not use m.room.aliases for room names.
	//      However, Riot also uses m.room.aliases, so this is here now.
	aliases := room.GetAliases()
	if len(aliases) > 0 {
		sort.Sort(sort.StringSlice(aliases))
		room.nameCache = aliases[0]
	}
}

// updateNameFromMembers updates the room display name based on the members in this room.
//
// The room name depends on the number of users:
//  Less than two users -> "Empty room"
//  Exactly two users   -> The display name of the other user.
//  More than two users -> The display name of one of the other users, followed
//                         by "and X others", where X is the number of users
//                         excluding the local user and the named user.
func (room *Room) updateNameFromMembers() {
	members := room.GetMembers()
	if len(members) <= 1 {
		room.nameCache = "Empty room"
	} else if len(members) == 2 {
		room.nameCache = members[room.firstMemberCache].DisplayName
	} else {
		firstMember := members[room.firstMemberCache].DisplayName
		room.nameCache = fmt.Sprintf("%s and %d others", firstMember, len(members)-2)
	}
}

// updateNameCache updates the room display name based on the room state in the order
// specified in spec section 11.2.2.5.
func (room *Room) updateNameCache() {
	if len(room.nameCache) == 0 {
		room.updateNameFromNameEvent()
		room.nameCacheSource = ExplicitRoomName
	}
	if len(room.nameCache) == 0 {
		room.nameCache = room.GetCanonicalAlias()
		room.nameCacheSource = CanonicalAliasRoomName
	}
	if len(room.nameCache) == 0 {
		room.updateNameFromAliases()
		room.nameCacheSource = AliasRoomName
	}
	if len(room.nameCache) == 0 {
		room.updateNameFromMembers()
		room.nameCacheSource = MemberRoomName
	}
}

// GetTitle returns the display name of the room.
//
// The display name is returned from the cache.
// If the cache is empty, it is updated first.
func (room *Room) GetTitle() string {
	room.updateNameCache()
	return room.nameCache
}

// 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")
	room.firstMemberCache = ""
	if events != nil {
		for userID, event := range events {
			if len(room.firstMemberCache) == 0 && userID != room.SessionUserID {
				room.firstMemberCache = userID
			}
			member := eventToRoomMember(userID, event)
			if member.Membership != "leave" {
				cache[member.UserID] = member
			}
		}
	}
	room.memberCache = cache
	return cache
}

// GetMembers returns the members in this room.
//
// The members are returned from the cache.
// If the cache is empty, it is updated first.
func (room *Room) GetMembers() map[string]*Member {
	if len(room.memberCache) == 0 {
		room.createMemberCache()
	}
	return room.memberCache
}

// GetMember returns the member with the given MXID.
// If the member doesn't exist, nil is returned.
func (room *Room) GetMember(userID string) *Member {
	if len(room.memberCache) == 0 {
		room.createMemberCache()
	}
	member, _ := room.memberCache[userID]
	return 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)
}

// NewRoom creates a new Room with the given ID
func NewRoom(roomID, owner string) *Room {
	return &Room{
		Room:             gomatrix.NewRoom(roomID),
		fetchHistoryLock: &sync.Mutex{},
		SessionUserID:    owner,
	}
}