-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
96 lines (80 loc) · 1.76 KB
/
handler.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
94
95
96
package notify
import (
"context"
"fmt"
"sync"
"encoding/json"
"github.com/go-bridget/notify/internal/pubsub"
)
type Handler struct {
sync.Mutex
context.Context
channel *pubsub.PubSub
userID string
topics []string
outgoing chan []byte
}
type StatePayload struct {
Kind string `json:"kind"`
State map[string]string `json:"state"`
}
func NewHandler(ctx context.Context, id string, topics []string) *Handler {
return &Handler{
Context: ctx,
channel: pubsub.New(),
userID: id,
topics: topics,
outgoing: make(chan []byte, 512),
}
}
func (h *Handler) Connect() error {
// send initial state to user when connecting
onStart := func() error {
values, err := h.channel.HGetAll(h, fmt.Sprintf("notify:%s:state", h.userID))
if err != nil {
return err
}
return h.Send(StatePayload{"state", values})
}
// send individual notification messages to user when received
onMessage := func(channel string, msg []byte) error {
return h.SendRaw(msg)
}
topics := h.topics
for i := range topics {
topics[i] = "notify_topic:" + topics[i]
}
return h.channel.Subscribe(h, append(topics, fmt.Sprintf("notify:%s", h.userID)), onStart, onMessage)
}
func (h *Handler) Close() {
// clean up when exiting
h.Lock()
defer h.Unlock()
if h.outgoing != nil {
close(h.outgoing)
h.outgoing = nil
}
}
func (*Handler) Incoming(msg []byte) error {
return nil
}
func (h *Handler) Send(msg interface{}) error {
h.Lock()
defer h.Unlock()
// check if still alive
if h.outgoing == nil {
return nil
}
b, err := json.Marshal(msg)
if err != nil {
return err
}
return h.SendRaw(b)
}
func (h *Handler) SendRaw(msg []byte) error {
h.outgoing <- msg
return nil
}
func (h *Handler) Outgoing() (<-chan []byte, error) {
return h.outgoing, nil
}