diff options
author | zeripath <art27@cantab.net> | 2020-05-07 22:49:00 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-05-07 22:49:00 +0100 |
commit | 791353c03ba81d1c67393a04256a77293307ecad (patch) | |
tree | b0771f7e1683db318c5e5606a312319578392dcd /modules/eventsource/manager.go | |
parent | 486e4c8087746ca91c05a693cadd563ac061a913 (diff) | |
download | gitea-791353c03ba81d1c67393a04256a77293307ecad.tar.gz gitea-791353c03ba81d1c67393a04256a77293307ecad.zip |
Add EventSource support (#11235)
If the browser supports EventSource switch to use this instead of
polling notifications.
Signed-off-by: Andrew Thornton art27@cantab.net
Diffstat (limited to 'modules/eventsource/manager.go')
-rw-r--r-- | modules/eventsource/manager.go | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/modules/eventsource/manager.go b/modules/eventsource/manager.go new file mode 100644 index 0000000000..212fe60569 --- /dev/null +++ b/modules/eventsource/manager.go @@ -0,0 +1,84 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package eventsource + +import ( + "sync" +) + +// Manager manages the eventsource Messengers +type Manager struct { + mutex sync.Mutex + + messengers map[int64]*Messenger +} + +var manager *Manager + +func init() { + manager = &Manager{ + messengers: make(map[int64]*Messenger), + } +} + +// GetManager returns a Manager and initializes one as singleton if there's none yet +func GetManager() *Manager { + return manager +} + +// Register message channel +func (m *Manager) Register(uid int64) <-chan *Event { + m.mutex.Lock() + messenger, ok := m.messengers[uid] + if !ok { + messenger = NewMessenger(uid) + m.messengers[uid] = messenger + } + m.mutex.Unlock() + return messenger.Register() +} + +// Unregister message channel +func (m *Manager) Unregister(uid int64, channel <-chan *Event) { + m.mutex.Lock() + defer m.mutex.Unlock() + messenger, ok := m.messengers[uid] + if !ok { + return + } + if messenger.Unregister(channel) { + delete(m.messengers, uid) + } +} + +// UnregisterAll message channels +func (m *Manager) UnregisterAll() { + m.mutex.Lock() + defer m.mutex.Unlock() + for _, messenger := range m.messengers { + messenger.UnregisterAll() + } + m.messengers = map[int64]*Messenger{} +} + +// SendMessage sends a message to a particular user +func (m *Manager) SendMessage(uid int64, message *Event) { + m.mutex.Lock() + messenger, ok := m.messengers[uid] + m.mutex.Unlock() + if ok { + messenger.SendMessage(message) + } +} + +// SendMessageBlocking sends a message to a particular user +func (m *Manager) SendMessageBlocking(uid int64, message *Event) { + m.mutex.Lock() + messenger, ok := m.messengers[uid] + m.mutex.Unlock() + if ok { + messenger.SendMessageBlocking(message) + } +} |