| 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 | package rooms |
| 18 | |
| 19 | import ( |
| 20 | "compress/gzip" |
| 21 | "encoding/gob" |
| 22 | "encoding/json" |
| 23 | "fmt" |
| 24 | "os" |
| 25 | "time" |
| 26 | |
| 27 | sync "github.com/sasha-s/go-deadlock" |
| 28 | |
| 29 | "maunium.net/go/mautrix" |
| 30 | "maunium.net/go/mautrix/event" |
| 31 | "maunium.net/go/mautrix/id" |
| 32 | |
| 33 | "maunium.net/go/gomuks/debug" |
| 34 | ) |
| 35 | |
| 36 | func init() { |
| 37 | gob.Register(map[string]interface{}{}) |
| 38 | gob.Register([]interface{}{}) |
| 39 | } |
| 40 | |
| 41 | type RoomNameSource int |
| 42 | |
| 43 | const ( |
| 44 | UnknownRoomName RoomNameSource = iota |
| 45 | MemberRoomName |
| 46 | CanonicalAliasRoomName |
| 47 | ExplicitRoomName |
| 48 | ) |
| 49 | |
| 50 | // RoomTag is a tag given to a specific room. |
| 51 | type RoomTag struct { |
| 52 | // The name of the tag. |
| 53 | Tag string |
| 54 | // The order of the tag. |
| 55 | Order json.Number |
| 56 | } |
| 57 | |
| 58 | type UnreadMessage struct { |
| 59 | EventID id.EventID |
| 60 | Counted bool |
| 61 | Highlight bool |
| 62 | } |
| 63 | |
| 64 | type Member struct { |
| 65 | event.MemberEventContent |
| 66 | |
| 67 | // The user who sent the membership event |
| 68 | Sender id.UserID `json:"-"` |
| 69 | } |
| 70 | |
| 71 | // Room represents a single Matrix room. |
| 72 | type Room struct { |
| 73 | // The room ID. |
| 74 | ID id.RoomID |
| 75 | |
| 76 | // Whether or not the user has left the room. |
| 77 | HasLeft bool |
| 78 | // Whether or not the room is encrypted. |
| 79 | Encrypted bool |
| 80 | |
| 81 | // The first batch of events that has been fetched for this room. |
| 82 | // Used for fetching additional history. |
| 83 | PrevBatch string |
| 84 | // The last_batch field from the most recent sync. Used for fetching member lists. |
| 85 | LastPrevBatch string |
| 86 | // The MXID of the user whose session this room was created for. |
| 87 | SessionUserID id.UserID |
| 88 | SessionMember *Member |
| 89 | |
| 90 | // The number of unread messages that were notified about. |
| 91 | UnreadMessages []UnreadMessage |
| 92 | unreadCountCache *int |
| 93 | highlightCache *bool |
| 94 | lastMarkedRead id.EventID |
| 95 | // Whether or not this room is marked as a direct chat. |
| 96 | IsDirect bool |
| 97 | OtherUser id.UserID |
| 98 | |
| 99 | // List of tags given to this room. |
| 100 | RawTags []RoomTag |
| 101 | // Timestamp of previously received actual message. |
| 102 | LastReceivedMessage time.Time |
| 103 | |
| 104 | // The lazy loading summary for this room. |
| 105 | Summary mautrix.LazyLoadSummary |
| 106 | // Whether or not the members for this room have been fetched from the server. |
| 107 | MembersFetched bool |
| 108 | // Room state cache. |
| 109 | state map[event.Type]map[string]*event.Event |
| 110 | // MXID -> Member cache calculated from membership events. |
| 111 | memberCache map[id.UserID]*Member |
| 112 | exMemberCache map[id.UserID]*Member |
| 113 | // The first two non-SessionUserID members in the room. Calculated at |
| 114 | // the same time as memberCache. |
| 115 | firstMemberCache *Member |
| 116 | secondMemberCache *Member |
| 117 | // The name of the room. Calculated from the state event name, |
| 118 | // canonical_alias or alias or the member cache. |
| 119 | NameCache string |
| 120 | // The event type from which the name cache was calculated from. |
| 121 | nameCacheSource RoomNameSource |
| 122 | // The topic of the room. Directly fetched from the m.room.topic state event. |
| 123 | topicCache string |
| 124 | // The canonical alias of the room. Directly fetched from the m.room.canonical_alias state event. |
| 125 | CanonicalAliasCache id.RoomAlias |
| 126 | // Whether or not the room has been tombstoned. |
| 127 | replacedCache bool |
| 128 | // The room ID that replaced this room. |
| 129 | replacedByCache *id.RoomID |
| 130 | |
| 131 | // Path for state store file. |
| 132 | path string |
| 133 | // Room cache object |
| 134 | cache *RoomCache |
| 135 | // Lock for state and other room stuff. |
| 136 | lock sync.RWMutex |
| 137 | // Pre/post un/load hooks |
| 138 | preUnload func() bool |
| 139 | preLoad func() bool |
| 140 | postUnload func() |
| 141 | postLoad func() |
| 142 | // Whether or not the room state has changed |
| 143 | changed bool |
| 144 | |
| 145 | // Room state cache linked list. |
| 146 | prev *Room |
| 147 | next *Room |
| 148 | touch int64 |
| 149 | } |
| 150 | |
| 151 | func debugPrintError(fn func() error, message string) { |
| 152 | if err := fn(); err != nil { |
| 153 | debug.Printf("%s: %v", message, err) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func (room *Room) Loaded() bool { |
| 158 | return room.state != nil |
| 159 | } |
| 160 | |
| 161 | func (room *Room) Load() { |
| 162 | room.cache.TouchNode(room) |
| 163 | if room.Loaded() { |
| 164 | return |
| 165 | } |
| 166 | if room.preLoad != nil && !room.preLoad() { |
| 167 | return |
| 168 | } |
| 169 | room.lock.Lock() |
| 170 | room.load() |
| 171 | room.lock.Unlock() |
| 172 | if room.postLoad != nil { |
| 173 | room.postLoad() |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | func (room *Room) load() { |
| 178 | if room.Loaded() { |
| 179 | return |
| 180 | } |
| 181 | debug.Print("Loading state for room", room.ID, "from disk") |
| 182 | room.state = make(map[event.Type]map[string]*event.Event) |
| 183 | file, err := os.OpenFile(room.path, os.O_RDONLY, 0600) |
| 184 | if err != nil { |
| 185 | if !os.IsNotExist(err) { |
| 186 | debug.Print("Failed to open room state file for reading:", err) |
| 187 | } else { |
| 188 | debug.Print("Room state file for", room.ID, "does not exist") |
| 189 | } |
| 190 | return |
| 191 | } |
| 192 | defer debugPrintError(file.Close, "Failed to close room state file after reading") |
| 193 | cmpReader, err := gzip.NewReader(file) |
| 194 | if err != nil { |
| 195 | debug.Print("Failed to open room state gzip reader:", err) |
| 196 | return |
| 197 | } |
| 198 | defer debugPrintError(cmpReader.Close, "Failed to close room state gzip reader") |
| 199 | dec := gob.NewDecoder(cmpReader) |
| 200 | if err = dec.Decode(&room.state); err != nil { |
| 201 | debug.Print("Failed to decode room state:", err) |
| 202 | } |
| 203 | room.changed = false |
| 204 | } |
| 205 | |
| 206 | func (room *Room) Touch() { |
| 207 | room.cache.TouchNode(room) |
| 208 | } |
| 209 | |
| 210 | func (room *Room) Unload() bool { |
| 211 | if room.preUnload != nil && !room.preUnload() { |
| 212 | return false |
| 213 | } |
| 214 | debug.Print("Unloading", room.ID) |
| 215 | room.Save() |
| 216 | room.state = nil |
| 217 | room.memberCache = nil |
| 218 | room.exMemberCache = nil |
| 219 | room.firstMemberCache = nil |
| 220 | room.secondMemberCache = nil |
| 221 | if room.postUnload != nil { |
| 222 | room.postUnload() |
| 223 | } |
| 224 | return true |
| 225 | } |
| 226 | |
| 227 | func (room *Room) SetPreUnload(fn func() bool) { |
| 228 | room.preUnload = fn |
| 229 | } |
| 230 | |
| 231 | func (room *Room) SetPreLoad(fn func() bool) { |
| 232 | room.preLoad = fn |
| 233 | } |
| 234 | |
| 235 | func (room *Room) SetPostUnload(fn func()) { |
| 236 | room.postUnload = fn |
| 237 | } |
| 238 | |
| 239 | func (room *Room) SetPostLoad(fn func()) { |
| 240 | room.postLoad = fn |
| 241 | } |
| 242 | |
| 243 | func (room *Room) Save() { |
| 244 | if !room.Loaded() { |
| 245 | debug.Print("Failed to save room", room.ID, "state: room not loaded") |
| 246 | return |
| 247 | } |
| 248 | if !room.changed { |
| 249 | debug.Print("Not saving", room.ID, "as state hasn't changed") |
| 250 | return |
| 251 | } |
| 252 | debug.Print("Saving state for room", room.ID, "to disk") |
| 253 | file, err := os.OpenFile(room.path, os.O_WRONLY|os.O_CREATE, 0600) |
| 254 | if err != nil { |
| 255 | debug.Print("Failed to open room state file for writing:", err) |
| 256 | return |
| 257 | } |
| 258 | defer debugPrintError(file.Close, "Failed to close room state file after writing") |
| 259 | cmpWriter := gzip.NewWriter(file) |
| 260 | defer debugPrintError(cmpWriter.Close, "Failed to close room state gzip writer") |
| 261 | enc := gob.NewEncoder(cmpWriter) |
| 262 | room.lock.RLock() |
| 263 | defer room.lock.RUnlock() |
| 264 | if err := enc.Encode(&room.state); err != nil { |
| 265 | debug.Print("Failed to encode room state:", err) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | // MarkRead clears the new message statuses on this room. |
| 270 | func (room *Room) MarkRead(eventID id.EventID) bool { |
| 271 | room.lock.Lock() |
| 272 | defer room.lock.Unlock() |
| 273 | if room.lastMarkedRead == eventID { |
| 274 | return false |
| 275 | } |
| 276 | room.lastMarkedRead = eventID |
| 277 | readToIndex := -1 |
| 278 | for index, unreadMessage := range room.UnreadMessages { |
| 279 | if unreadMessage.EventID == eventID { |
| 280 | readToIndex = index |
| 281 | } |
| 282 | } |
| 283 | if readToIndex >= 0 { |
| 284 | room.UnreadMessages = room.UnreadMessages[readToIndex+1:] |
| 285 | room.highlightCache = nil |
| 286 | room.unreadCountCache = nil |
| 287 | } |
| 288 | return true |
| 289 | } |
| 290 | |
| 291 | func (room *Room) UnreadCount() int { |
| 292 | room.lock.Lock() |
| 293 | defer room.lock.Unlock() |
| 294 | if room.unreadCountCache == nil { |
| 295 | room.unreadCountCache = new(int) |
| 296 | for _, unreadMessage := range room.UnreadMessages { |
| 297 | if unreadMessage.Counted { |
| 298 | *room.unreadCountCache++ |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | return *room.unreadCountCache |
| 303 | } |
| 304 | |
| 305 | func (room *Room) Highlighted() bool { |
| 306 | room.lock.Lock() |
| 307 | defer room.lock.Unlock() |
| 308 | if room.highlightCache == nil { |
| 309 | room.highlightCache = new(bool) |
| 310 | for _, unreadMessage := range room.UnreadMessages { |
| 311 | if unreadMessage.Highlight { |
| 312 | *room.highlightCache = true |
| 313 | break |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | return *room.highlightCache |
| 318 | } |
| 319 | |
| 320 | func (room *Room) HasNewMessages() bool { |
| 321 | return len(room.UnreadMessages) > 0 |
| 322 | } |
| 323 | |
| 324 | func (room *Room) AddUnread(eventID id.EventID, counted, highlight bool) { |
| 325 | room.lock.Lock() |
| 326 | defer room.lock.Unlock() |
| 327 | room.UnreadMessages = append(room.UnreadMessages, UnreadMessage{ |
| 328 | EventID: eventID, |
| 329 | Counted: counted, |
| 330 | Highlight: highlight, |
| 331 | }) |
| 332 | if counted { |
| 333 | if room.unreadCountCache == nil { |
| 334 | room.unreadCountCache = new(int) |
| 335 | } |
| 336 | *room.unreadCountCache++ |
| 337 | } |
| 338 | if highlight { |
| 339 | if room.highlightCache == nil { |
| 340 | room.highlightCache = new(bool) |
| 341 | } |
| 342 | *room.highlightCache = true |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | var ( |
| 347 | tagDirect = RoomTag{"net.maunium.gomuks.fake.direct", "0.5"} |
| 348 | tagInvite = RoomTag{"net.maunium.gomuks.fake.invite", "0.5"} |
| 349 | tagDefault = RoomTag{"", "0.5"} |
| 350 | tagLeave = RoomTag{"net.maunium.gomuks.fake.leave", "0.5"} |
| 351 | ) |
| 352 | |
| 353 | func (room *Room) Tags() []RoomTag { |
| 354 | room.lock.RLock() |
| 355 | defer room.lock.RUnlock() |
| 356 | if len(room.RawTags) == 0 { |
| 357 | if room.IsDirect { |
| 358 | return []RoomTag{tagDirect} |
| 359 | } else if room.SessionMember != nil && room.SessionMember.Membership == event.MembershipInvite { |
| 360 | return []RoomTag{tagInvite} |
| 361 | } else if room.SessionMember != nil && room.SessionMember.Membership != event.MembershipJoin { |
| 362 | return []RoomTag{tagLeave} |
| 363 | } |
| 364 | return []RoomTag{tagDefault} |
| 365 | } |
| 366 | return room.RawTags |
| 367 | } |
| 368 | |
| 369 | func (room *Room) UpdateSummary(summary mautrix.LazyLoadSummary) { |
| 370 | if summary.JoinedMemberCount != nil { |
| 371 | room.Summary.JoinedMemberCount = summary.JoinedMemberCount |
| 372 | } |
| 373 | if summary.InvitedMemberCount != nil { |
| 374 | room.Summary.InvitedMemberCount = summary.InvitedMemberCount |
| 375 | } |
| 376 | if summary.Heroes != nil { |
| 377 | room.Summary.Heroes = summary.Heroes |
| 378 | } |
| 379 | if room.nameCacheSource <= MemberRoomName { |
| 380 | room.NameCache = "" |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | // UpdateState updates the room's current state with the given Event. This will clobber events based |
| 385 | // on the type/state_key combination. |
| 386 | func (room *Room) UpdateState(evt *event.Event) { |
| 387 | if evt.StateKey == nil { |
| 388 | panic("Tried to UpdateState() event with no state key.") |
| 389 | } |
| 390 | room.Load() |
| 391 | room.lock.Lock() |
| 392 | defer room.lock.Unlock() |
| 393 | room.changed = true |
| 394 | _, exists := room.state[evt.Type] |
| 395 | if !exists { |
| 396 | room.state[evt.Type] = make(map[string]*event.Event) |
| 397 | } |
| 398 | switch content := evt.Content.Parsed.(type) { |
| 399 | case *event.RoomNameEventContent: |
| 400 | room.NameCache = content.Name |
| 401 | room.nameCacheSource = ExplicitRoomName |
| 402 | case *event.CanonicalAliasEventContent: |
| 403 | if room.nameCacheSource <= CanonicalAliasRoomName { |
| 404 | room.NameCache = string(content.Alias) |
| 405 | room.nameCacheSource = CanonicalAliasRoomName |
| 406 | } |
| 407 | room.CanonicalAliasCache = content.Alias |
| 408 | case *event.MemberEventContent: |
| 409 | if room.nameCacheSource <= MemberRoomName { |
| 410 | room.NameCache = "" |
| 411 | } |
| 412 | room.updateMemberState(id.UserID(evt.GetStateKey()), evt.Sender, content) |
| 413 | case *event.TopicEventContent: |
| 414 | room.topicCache = content.Topic |
| 415 | case *event.EncryptionEventContent: |
| 416 | if content.Algorithm == id.AlgorithmMegolmV1 { |
| 417 | room.Encrypted = true |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | if evt.Type != event.StateMember { |
| 422 | debug.Printf("Updating state %s#%s for %s", evt.Type.String(), evt.GetStateKey(), room.ID) |
| 423 | } |
| 424 | |
| 425 | room.state[evt.Type][*evt.StateKey] = evt |
| 426 | } |
| 427 | |
| 428 | func (room *Room) updateMemberState(userID, sender id.UserID, content *event.MemberEventContent) { |
| 429 | if userID == room.SessionUserID { |
| 430 | debug.Print("Updating session user state:", content) |
| 431 | room.SessionMember = room.eventToMember(userID, sender, content) |
| 432 | } |
| 433 | if room.memberCache != nil { |
| 434 | member := room.eventToMember(userID, sender, content) |
| 435 | if member.Membership.IsInviteOrJoin() { |
| 436 | existingMember, ok := room.memberCache[userID] |
| 437 | if ok { |
| 438 | *existingMember = *member |
| 439 | } else { |
| 440 | delete(room.exMemberCache, userID) |
| 441 | room.memberCache[userID] = member |
| 442 | room.updateNthMemberCache(userID, member) |
| 443 | } |
| 444 | } else { |
| 445 | existingExMember, ok := room.exMemberCache[userID] |
| 446 | if ok { |
| 447 | *existingExMember = *member |
| 448 | } else { |
| 449 | delete(room.memberCache, userID) |
| 450 | room.exMemberCache[userID] = member |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | // GetStateEvent returns the state event for the given type/state_key combo, or nil. |
| 457 | func (room *Room) GetStateEvent(eventType event.Type, stateKey string) *event.Event { |
| 458 | room.Load() |
| 459 | room.lock.RLock() |
| 460 | defer room.lock.RUnlock() |
| 461 | stateEventMap, _ := room.state[eventType] |
| 462 | evt, _ := stateEventMap[stateKey] |
| 463 | return evt |
| 464 | } |
| 465 | |
| 466 | // getStateEvents returns the state events for the given type. |
| 467 | func (room *Room) getStateEvents(eventType event.Type) map[string]*event.Event { |
| 468 | stateEventMap, _ := room.state[eventType] |
| 469 | return stateEventMap |
| 470 | } |
| 471 | |
| 472 | // GetTopic returns the topic of the room. |
| 473 | func (room *Room) GetTopic() string { |
| 474 | if len(room.topicCache) == 0 { |
| 475 | topicEvt := room.GetStateEvent(event.StateTopic, "") |
| 476 | if topicEvt != nil { |
| 477 | room.topicCache = topicEvt.Content.AsTopic().Topic |
| 478 | } |
| 479 | } |
| 480 | return room.topicCache |
| 481 | } |
| 482 | |
| 483 | func (room *Room) GetCanonicalAlias() id.RoomAlias { |
| 484 | if len(room.CanonicalAliasCache) == 0 { |
| 485 | canonicalAliasEvt := room.GetStateEvent(event.StateCanonicalAlias, "") |
| 486 | if canonicalAliasEvt != nil { |
| 487 | room.CanonicalAliasCache = canonicalAliasEvt.Content.AsCanonicalAlias().Alias |
| 488 | } else { |
| 489 | room.CanonicalAliasCache = "-" |
| 490 | } |
| 491 | } |
| 492 | if room.CanonicalAliasCache == "-" { |
| 493 | return "" |
| 494 | } |
| 495 | return room.CanonicalAliasCache |
| 496 | } |
| 497 | |
| 498 | // updateNameFromNameEvent updates the room display name to be the name set in the name event. |
| 499 | func (room *Room) updateNameFromNameEvent() { |
| 500 | nameEvt := room.GetStateEvent(event.StateRoomName, "") |
| 501 | if nameEvt != nil { |
| 502 | room.NameCache = nameEvt.Content.AsRoomName().Name |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | // updateNameFromMembers updates the room display name based on the members in this room. |
| 507 | // |
| 508 | // The room name depends on the number of users: |
| 509 | // |
| 510 | // Less than two users -> "Empty room" |
| 511 | // Exactly two users -> The display name of the other user. |
| 512 | // More than two users -> The display name of one of the other users, followed |
| 513 | // by "and X others", where X is the number of users |
| 514 | // excluding the local user and the named user. |
| 515 | func (room *Room) updateNameFromMembers() { |
| 516 | members := room.GetMembers() |
| 517 | if len(members) <= 1 { |
| 518 | room.NameCache = "Empty room" |
| 519 | } else if room.firstMemberCache == nil { |
| 520 | room.NameCache = "Room" |
| 521 | } else if len(members) == 2 { |
| 522 | room.NameCache = room.firstMemberCache.Displayname |
| 523 | } else if len(members) == 3 && room.secondMemberCache != nil { |
| 524 | room.NameCache = fmt.Sprintf("%s and %s", room.firstMemberCache.Displayname, room.secondMemberCache.Displayname) |
| 525 | } else { |
| 526 | members := room.firstMemberCache.Displayname |
| 527 | count := len(members) - 2 |
| 528 | if room.secondMemberCache != nil { |
| 529 | members += ", " + room.secondMemberCache.Displayname |
| 530 | count-- |
| 531 | } |
| 532 | room.NameCache = fmt.Sprintf("%s and %d others", members, count) |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | // updateNameCache updates the room display name based on the room state in the order |
| 537 | // specified in spec section 11.2.2.5. |
| 538 | func (room *Room) updateNameCache() { |
| 539 | if len(room.NameCache) == 0 { |
| 540 | room.updateNameFromNameEvent() |
| 541 | room.nameCacheSource = ExplicitRoomName |
| 542 | } |
| 543 | if len(room.NameCache) == 0 { |
| 544 | room.NameCache = string(room.GetCanonicalAlias()) |
| 545 | room.nameCacheSource = CanonicalAliasRoomName |
| 546 | } |
| 547 | if len(room.NameCache) == 0 { |
| 548 | room.updateNameFromMembers() |
| 549 | room.nameCacheSource = MemberRoomName |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | // GetTitle returns the display name of the room. |
| 554 | // |
| 555 | // The display name is returned from the cache. |
| 556 | // If the cache is empty, it is updated first. |
| 557 | func (room *Room) GetTitle() string { |
| 558 | room.updateNameCache() |
| 559 | return room.NameCache |
| 560 | } |
| 561 | |
| 562 | func (room *Room) IsReplaced() bool { |
| 563 | if room.replacedByCache == nil { |
| 564 | evt := room.GetStateEvent(event.StateTombstone, "") |
| 565 | var replacement id.RoomID |
| 566 | if evt != nil { |
| 567 | content, ok := evt.Content.Parsed.(*event.TombstoneEventContent) |
| 568 | if ok { |
| 569 | replacement = content.ReplacementRoom |
| 570 | } |
| 571 | } |
| 572 | room.replacedCache = evt != nil |
| 573 | room.replacedByCache = &replacement |
| 574 | } |
| 575 | return room.replacedCache |
| 576 | } |
| 577 | |
| 578 | func (room *Room) ReplacedBy() id.RoomID { |
| 579 | if room.replacedByCache == nil { |
| 580 | room.IsReplaced() |
| 581 | } |
| 582 | return *room.replacedByCache |
| 583 | } |
| 584 | |
| 585 | func (room *Room) eventToMember(userID, sender id.UserID, member *event.MemberEventContent) *Member { |
| 586 | if len(member.Displayname) == 0 { |
| 587 | member.Displayname = string(userID) |
| 588 | } |
| 589 | return &Member{ |
| 590 | MemberEventContent: *member, |
| 591 | Sender: sender, |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | func (room *Room) updateNthMemberCache(userID id.UserID, member *Member) { |
| 596 | if userID != room.SessionUserID { |
| 597 | if room.firstMemberCache == nil { |
| 598 | room.firstMemberCache = member |
| 599 | } else if room.secondMemberCache == nil { |
| 600 | room.secondMemberCache = member |
| 601 | } |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | // createMemberCache caches all member events into a easily processable MXID -> *Member map. |
| 606 | func (room *Room) createMemberCache() map[id.UserID]*Member { |
| 607 | if len(room.memberCache) > 0 { |
| 608 | return room.memberCache |
| 609 | } |
| 610 | cache := make(map[id.UserID]*Member) |
| 611 | exCache := make(map[id.UserID]*Member) |
| 612 | room.lock.RLock() |
| 613 | memberEvents := room.getStateEvents(event.StateMember) |
| 614 | room.firstMemberCache = nil |
| 615 | room.secondMemberCache = nil |
| 616 | if memberEvents != nil { |
| 617 | for userIDStr, evt := range memberEvents { |
| 618 | userID := id.UserID(userIDStr) |
| 619 | member := room.eventToMember(userID, evt.Sender, evt.Content.AsMember()) |
| 620 | if member.Membership.IsInviteOrJoin() { |
| 621 | cache[userID] = member |
| 622 | room.updateNthMemberCache(userID, member) |
| 623 | } else { |
| 624 | exCache[userID] = member |
| 625 | } |
| 626 | if userID == room.SessionUserID { |
| 627 | room.SessionMember = member |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | if len(room.Summary.Heroes) > 1 { |
| 632 | room.firstMemberCache, _ = cache[room.Summary.Heroes[0]] |
| 633 | } |
| 634 | if len(room.Summary.Heroes) > 2 { |
| 635 | room.secondMemberCache, _ = cache[room.Summary.Heroes[1]] |
| 636 | } |
| 637 | room.lock.RUnlock() |
| 638 | room.lock.Lock() |
| 639 | room.memberCache = cache |
| 640 | room.exMemberCache = exCache |
| 641 | room.lock.Unlock() |
| 642 | return cache |
| 643 | } |
| 644 | |
| 645 | // GetMembers returns the members in this room. |
| 646 | // |
| 647 | // The members are returned from the cache. |
| 648 | // If the cache is empty, it is updated first. |
| 649 | func (room *Room) GetMembers() map[id.UserID]*Member { |
| 650 | room.Load() |
| 651 | room.createMemberCache() |
| 652 | return room.memberCache |
| 653 | } |
| 654 | |
| 655 | func (room *Room) GetMemberList() []id.UserID { |
| 656 | members := room.GetMembers() |
| 657 | memberList := make([]id.UserID, len(members)) |
| 658 | index := 0 |
| 659 | for userID, _ := range members { |
| 660 | memberList[index] = userID |
| 661 | index++ |
| 662 | } |
| 663 | return memberList |
| 664 | } |
| 665 | |
| 666 | // GetMember returns the member with the given MXID. |
| 667 | // If the member doesn't exist, nil is returned. |
| 668 | func (room *Room) GetMember(userID id.UserID) *Member { |
| 669 | if userID == room.SessionUserID && room.SessionMember != nil { |
| 670 | return room.SessionMember |
| 671 | } |
| 672 | room.Load() |
| 673 | room.createMemberCache() |
| 674 | room.lock.RLock() |
| 675 | member, ok := room.memberCache[userID] |
| 676 | if ok { |
| 677 | room.lock.RUnlock() |
| 678 | return member |
| 679 | } |
| 680 | exMember, ok := room.exMemberCache[userID] |
| 681 | if ok { |
| 682 | room.lock.RUnlock() |
| 683 | return exMember |
| 684 | } |
| 685 | room.lock.RUnlock() |
| 686 | return nil |
| 687 | } |
| 688 | |
| 689 | func (room *Room) GetMemberCount() int { |
| 690 | if room.memberCache == nil && room.Summary.JoinedMemberCount != nil { |
| 691 | return *room.Summary.JoinedMemberCount |
| 692 | } |
| 693 | return len(room.GetMembers()) |
| 694 | } |
| 695 | |
| 696 | // GetSessionOwner returns the ID of the user whose session this room was created for. |
| 697 | func (room *Room) GetOwnDisplayname() string { |
| 698 | member := room.GetMember(room.SessionUserID) |
| 699 | if member != nil { |
| 700 | return member.Displayname |
| 701 | } |
| 702 | return "" |
| 703 | } |
| 704 | |
| 705 | // NewRoom creates a new Room with the given ID |
| 706 | func NewRoom(roomID id.RoomID, cache *RoomCache) *Room { |
| 707 | return &Room{ |
| 708 | ID: roomID, |
| 709 | state: make(map[event.Type]map[string]*event.Event), |
| 710 | path: cache.roomPath(roomID), |
| 711 | cache: cache, |
| 712 | |
| 713 | SessionUserID: cache.getOwner(), |
| 714 | } |
| 715 | } |