-
Notifications
You must be signed in to change notification settings - Fork 4
/
streamdeck.go
197 lines (161 loc) · 4.76 KB
/
streamdeck.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package sdk
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"github.com/gorilla/websocket"
)
// StreamDeck will handle events to send/received to/from the StreamDeck application.
type StreamDeck struct {
// UUID is a unique identifier string that should be used to register the plugin once the WebSocket is opened
UUID string
// Info containing the Stream Deck application information and devices information.
Info *Info
conn *websocket.Conn
readCh chan *ReceivedEvent
writeCh chan *SendEvent
// handlers will process incoming events
handlers []HandlerFunc
debug bool
}
var (
port = flag.Int("port", 0, "The port that should be used to create the WebSocket")
pluginUUID = flag.String("pluginUUID", "", "A unique identifier string that should be used to register the plugin once the WebSocket is opened")
registerEvent = flag.String("registerEvent", "", "The event type that should be used to register the plugin once the WebSocket is opened")
info = flag.String("info", "", "A stringified json containing the Stream Deck application information and devices information.")
// ErrMissingPort is returned when the port is not set.
ErrMissingPort = errors.New("missing -port")
// ErrMissingUUID is returned when the UUID is not set.
ErrMissingUUID = errors.New("missing -pluginUUID")
// ErrMissingRegisterEvent is returned when the registerEvent is not set.
ErrMissingRegisterEvent = errors.New("missing -registerEvent")
// ErrMissingOrInvalidInfo is returned when the info is not set or is not a valid json.
ErrMissingOrInvalidInfo = errors.New("missing or invalid -info")
)
// New create our plugin, listen to websocket events and register handlers.
func New(opts ...Option) (*StreamDeck, error) {
flag.Parse()
// port
if v := *port; v == 0 {
return nil, ErrMissingPort
}
// string values
if *pluginUUID == "" {
return nil, ErrMissingUUID
}
if *registerEvent == "" {
return nil, ErrMissingRegisterEvent
}
if *info == "" {
return nil, ErrMissingOrInvalidInfo
}
// info json object
var r Info
if err := json.Unmarshal([]byte(*info), &r); err != nil {
return nil, ErrMissingOrInvalidInfo
}
conn, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf("ws://localhost:%d", *port), nil)
if err != nil {
return nil, fmt.Errorf("cannot init websocket connection: %w", err)
}
streamdeck := &StreamDeck{
UUID: *pluginUUID,
Info: &r,
conn: conn,
readCh: make(chan *ReceivedEvent),
writeCh: make(chan *SendEvent),
handlers: make([]HandlerFunc, 0),
debug: false,
}
for _, opt := range opts {
opt(streamdeck)
}
if err := streamdeck.register(*registerEvent); err != nil {
return nil, fmt.Errorf("cannot register plugin: %w", err)
}
return streamdeck, nil
}
// Start to serve the plugin
// Ensure you call Handler before.
func (s *StreamDeck) Start() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
go s.reader(ctx) // read incoming events
go s.writer(ctx) // send events
s.process(ctx) // will block until ctx is closed
}
// reader listen on incoming messages and send them to dedicated channel.
func (s *StreamDeck) reader(ctx context.Context) {
defer func() {
close(s.readCh)
_ = s.conn.Close()
}()
if s.debug {
s.Log("[DEBUG] reader started")
}
for {
select {
case <-ctx.Done():
return
default:
var event ReceivedEvent
if err := s.conn.ReadJSON(&event); err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
s.Logf("[ERROR] unexpected close connection: %v", err)
return
}
s.Logf("[ERROR] read message: %v", err)
return
}
s.readCh <- &event
}
}
}
// writer listen on write channel and send messages.
func (s *StreamDeck) writer(ctx context.Context) {
defer close(s.writeCh)
if s.debug {
s.Log("[DEBUG] writer started")
}
for {
select {
case <-ctx.Done():
return
case event := <-s.writeCh:
if err := s.conn.WriteJSON(event); err != nil {
s.Logf("[ERROR] write event [%s] for action [%s]: %v", event.Event, event.Action, err)
return
}
}
}
}
// process will listen to incoming events and process them.
func (s *StreamDeck) process(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case e, ok := <-s.readCh:
if !ok {
// The channel is closed
return
}
// Send event to all to registered handlers
go func(event *ReceivedEvent) {
if s.debug {
s.Logf("[DEBUG] received event [%s] for action [%s]", event.Event, event.Action)
}
for _, h := range s.handlers {
if err := h(event); err != nil {
s.Logf("[ERROR] event [%s] action [%s]: %v", event.Event, event.Action, err)
s.Alert(event.Context)
}
}
}(e)
}
}
}