This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
event.go
93 lines (79 loc) · 2.26 KB
/
event.go
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
package kook
// EventHandler is the interface for objects handling event.
type EventHandler interface {
Type() string
Handle(EventContext)
}
// EventHandlerProvider is the interface for objects providing event handlers.
type EventHandlerProvider interface {
Type() string
New() EventContext
}
// EventContext is the interface for objects containing context for event handlers.
type EventContext interface {
GetExtra() interface{}
GetCommon() *EventHandlerCommonContext
}
var registeredEventHandler = map[string]EventHandlerProvider{}
func registerEventHandler(eh EventHandlerProvider) {
if _, ok := registeredEventHandler[eh.Type()]; ok {
return
}
registeredEventHandler[eh.Type()] = eh
}
type eventHandlerInstance struct {
eventHandler EventHandler
}
func (s *Session) addEventHandler(handler EventHandler) func() {
s.handlersMu.Lock()
defer s.handlersMu.Unlock()
if s.handlers == nil {
//s.log(LogTrace, "creating initial handlers")
addCaller(s.Logger.Trace()).Msg("creating initial handlers")
s.handlers = map[string][]*eventHandlerInstance{}
}
ehi := &eventHandlerInstance{eventHandler: handler}
s.handlers[handler.Type()] = append(s.handlers[handler.Type()], ehi)
return func() {
s.removeEventHandler(handler.Type(), ehi)
}
}
// AddHandler adds event handlers to session, and provides additional type check.
func (s *Session) AddHandler(h interface{}) func() {
eh := handlerForInterface(h)
if eh == nil {
//s.log(LogError, "Invalid handler type, ignored")
addCaller(s.Logger.Error()).Msg("Invalid handler type, ignored")
return func() {
// TODO: add remover.
}
}
return s.addEventHandler(eh)
}
func (s *Session) removeEventHandler(t string, ehi *eventHandlerInstance) {
s.handlersMu.Lock()
defer s.handlersMu.Unlock()
handlers := s.handlers[t]
for i := range handlers {
if handlers[i] == ehi {
s.handlers[t] = append(handlers[:i], handlers[i+1:]...)
}
}
}
func (s *Session) handle(t string, i EventContext) {
for _, eh := range s.handlers[t] {
if s.Sync {
eh.eventHandler.Handle(i)
} else {
go eh.eventHandler.Handle(i)
}
}
}
func (s *Session) handleEvent(t string, edg *EventDataGeneral, i EventContext) {
s.handlersMu.RLock()
defer s.handlersMu.RUnlock()
c := i.GetCommon()
c.Common = edg
c.Session = s
s.handle(t, i)
}