You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.8 KiB

  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package eventsource
  5. import (
  6. "sync"
  7. )
  8. // Manager manages the eventsource Messengers
  9. type Manager struct {
  10. mutex sync.Mutex
  11. messengers map[int64]*Messenger
  12. }
  13. var manager *Manager
  14. func init() {
  15. manager = &Manager{
  16. messengers: make(map[int64]*Messenger),
  17. }
  18. }
  19. // GetManager returns a Manager and initializes one as singleton if there's none yet
  20. func GetManager() *Manager {
  21. return manager
  22. }
  23. // Register message channel
  24. func (m *Manager) Register(uid int64) <-chan *Event {
  25. m.mutex.Lock()
  26. messenger, ok := m.messengers[uid]
  27. if !ok {
  28. messenger = NewMessenger(uid)
  29. m.messengers[uid] = messenger
  30. }
  31. m.mutex.Unlock()
  32. return messenger.Register()
  33. }
  34. // Unregister message channel
  35. func (m *Manager) Unregister(uid int64, channel <-chan *Event) {
  36. m.mutex.Lock()
  37. defer m.mutex.Unlock()
  38. messenger, ok := m.messengers[uid]
  39. if !ok {
  40. return
  41. }
  42. if messenger.Unregister(channel) {
  43. delete(m.messengers, uid)
  44. }
  45. }
  46. // UnregisterAll message channels
  47. func (m *Manager) UnregisterAll() {
  48. m.mutex.Lock()
  49. defer m.mutex.Unlock()
  50. for _, messenger := range m.messengers {
  51. messenger.UnregisterAll()
  52. }
  53. m.messengers = map[int64]*Messenger{}
  54. }
  55. // SendMessage sends a message to a particular user
  56. func (m *Manager) SendMessage(uid int64, message *Event) {
  57. m.mutex.Lock()
  58. messenger, ok := m.messengers[uid]
  59. m.mutex.Unlock()
  60. if ok {
  61. messenger.SendMessage(message)
  62. }
  63. }
  64. // SendMessageBlocking sends a message to a particular user
  65. func (m *Manager) SendMessageBlocking(uid int64, message *Event) {
  66. m.mutex.Lock()
  67. messenger, ok := m.messengers[uid]
  68. m.mutex.Unlock()
  69. if ok {
  70. messenger.SendMessageBlocking(message)
  71. }
  72. }