forked from samwho/streamdeck
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
285 lines (239 loc) · 7.88 KB
/
client.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package streamdeck
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"sync"
"time"
sdcontext "github.com/FlowingSPDG/streamdeck/context"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
var (
logger = log.New(io.Discard, "streamdeck", log.LstdFlags)
)
// Log Get logger
func Log() *log.Logger {
return logger
}
// EventHandler Event handler func
type EventHandler func(ctx context.Context, client *Client, event Event) error
// Client StreamDeck communicating client
type Client struct {
ctx context.Context
params RegistrationParams
c *websocket.Conn
actions actions
handlers eventHandlers
done chan struct{}
sendMutex sync.Mutex
}
// map[string]*Action
type actions struct {
m sync.Map
}
// NewClient Get new client from specified context/params. you can specify "os.Args".
func NewClient(ctx context.Context, params RegistrationParams) *Client {
return &Client{
ctx: ctx,
params: params,
c: nil,
actions: actions{
m: sync.Map{},
},
handlers: eventHandlers{
m: sync.Map{},
},
done: make(chan struct{}),
sendMutex: sync.Mutex{},
}
}
// UUID get plugin UUID
func (client *Client) UUID() string {
return client.params.PluginUUID
}
// Action Get action from uuid.
func (client *Client) Action(uuid string) *Action {
v := newAction(uuid)
val, ok := client.actions.m.LoadOrStore(uuid, v)
if !ok {
v = newAction(uuid)
client.actions.m.Store(uuid, v)
} else {
v = val.(*Action)
}
return v
}
// RegisterNoActionHandler register event handler with no action such as "applicationDidLaunch".
func (client *Client) RegisterNoActionHandler(eventName string, handler EventHandler) {
eh := eventHandlerSlice{
mutex: &sync.Mutex{},
eh: []EventHandler{},
}
ehi, loaded := client.handlers.m.LoadOrStore(eventName, eh)
if loaded {
eh = ehi.(eventHandlerSlice)
}
eh.mutex.Lock()
defer eh.mutex.Unlock()
eh.eh = append(eh.eh, handler)
client.handlers.m.Store(eventName, eh)
}
// Run Start communicating with StreamDeck software
func (client *Client) Run(ctx context.Context) error {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: fmt.Sprintf("127.0.0.1:%d", client.params.Port)}
c, _, err := websocket.Dial(ctx, u.String(), nil)
if err != nil {
return err
}
client.c = c
go func() {
defer close(client.done)
for {
_, message, err := client.c.Read(ctx)
if err != nil {
logger.Printf("read error: %v\n", err)
return
}
event := Event{}
if err := json.Unmarshal(message, &event); err != nil {
logger.Printf("failed to unmarshal received event: %s\n", string(message))
continue
}
logger.Println("recv: ", string(message))
ctx := sdcontext.WithContext(client.ctx, event.Context)
ctx = sdcontext.WithDevice(ctx, event.Device)
ctx = sdcontext.WithAction(ctx, event.Action)
if event.Action == "" {
v, ok := client.handlers.m.Load(event.Event)
if ok {
eh := v.(eventHandlerSlice)
eh.Execute(ctx, client, event)
}
continue
}
var action *Action
a, ok := client.actions.m.Load(event.Action)
if !ok {
action = client.Action(event.Action)
action.addContext(ctx)
} else {
action = a.(*Action)
}
v, ok := action.handlers.m.Load(event.Event)
if ok {
eh := v.(eventHandlerSlice)
eh.Execute(ctx, client, event)
}
}
}()
if err := client.register(ctx, client.params); err != nil {
return err
}
select {
case <-client.done:
return nil
case <-interrupt:
logger.Printf("interrupted, closing...\n")
return client.Close()
}
}
// Check if WebSocket connection is non-nil.
func (client *Client) IsConnected() bool {
return client.c != nil
}
func (client *Client) register(ctx context.Context, params RegistrationParams) error {
if err := client.send(ctx, Event{UUID: params.PluginUUID, Event: params.RegisterEvent}); err != nil {
client.Close()
return err
}
return nil
}
func (client *Client) send(ctx context.Context, event Event) error {
client.sendMutex.Lock()
defer client.sendMutex.Unlock()
return wsjson.Write(ctx, client.c, event)
}
// SetSettings Save data persistently for the action's instance.
func (client *Client) SetSettings(ctx context.Context, settings any) error {
return client.send(ctx, NewEvent(ctx, SetSettings, settings))
}
// GetSettings Request the persistent data for the action's instance.
func (client *Client) GetSettings(ctx context.Context) error {
return client.send(ctx, NewEvent(ctx, GetSettings, nil))
}
// SetGlobalSettings Save data securely and globally for the plugin.
func (client *Client) SetGlobalSettings(ctx context.Context, settings any) error {
return client.send(ctx, NewEvent(ctx, SetGlobalSettings, settings))
}
// GetGlobalSettings Request the global persistent data
func (client *Client) GetGlobalSettings(ctx context.Context) error {
return client.send(ctx, NewEvent(ctx, GetGlobalSettings, nil))
}
// OpenURL Open an URL in the default browser.
func (client *Client) OpenURL(ctx context.Context, u url.URL) error {
return client.send(ctx, NewEvent(ctx, OpenURL, OpenURLPayload{URL: u.String()}))
}
// LogMessage Write a debug log to the logs file.
func (client *Client) LogMessage(ctx context.Context, message string) error {
return client.send(ctx, NewEvent(nil, LogMessage, LogMessagePayload{Message: message}))
}
// SetTitle Dynamically change the title of an instance of an action.
func (client *Client) SetTitle(ctx context.Context, title string, target Target) error {
return client.send(ctx, NewEvent(ctx, SetTitle, SetTitlePayload{Title: title, Target: target}))
}
// SetImage Dynamically change the image displayed by an instance of an action.
func (client *Client) SetImage(ctx context.Context, base64image string, target Target) error {
return client.send(ctx, NewEvent(ctx, SetImage, SetImagePayload{Base64Image: base64image, Target: target}))
}
// SetFeedback The plugin can send a setFeedback event to the Stream Deck application to dynamically change properties of items on the Stream Deck + touch display layout.
func (client *Client) SetFeedback(ctx context.Context, payload any) error {
return client.send(ctx, NewEvent(ctx, SetFeedback, payload))
}
// SetFeedbackLayout
func (client *Client) SetFeedbackLayout(ctx context.Context, layout string) error {
return client.send(ctx, NewEvent(ctx, SetImage, SetFeedbackLayoutPayload{Layout: layout}))
}
// ShowAlert Temporarily show an alert icon on the image displayed by an instance of an action.
func (client *Client) ShowAlert(ctx context.Context) error {
return client.send(ctx, NewEvent(ctx, ShowAlert, nil))
}
// ShowOk Temporarily show an OK checkmark icon on the image displayed by an instance of an action
func (client *Client) ShowOk(ctx context.Context) error {
return client.send(ctx, NewEvent(ctx, ShowOk, nil))
}
// SetState Change the state of the action's instance supporting multiple states.
func (client *Client) SetState(ctx context.Context, state int) error {
return client.send(ctx, NewEvent(ctx, SetState, SetStatePayload{State: state}))
}
// SwitchToProfile Switch to one of the preconfigured read-only profiles.
func (client *Client) SwitchToProfile(ctx context.Context, profile string) error {
return client.send(ctx, NewEvent(ctx, SwitchToProfile, SwitchProfilePayload{Profile: profile}))
}
// SendToPropertyInspector Send a payload to the Property Inspector.
func (client *Client) SendToPropertyInspector(ctx context.Context, payload any) error {
return client.send(ctx, NewEvent(ctx, SendToPropertyInspector, payload))
}
// SendToPlugin Send a payload to the plugin.
func (client *Client) SendToPlugin(ctx context.Context, payload any) error {
return client.send(ctx, NewEvent(ctx, SendToPlugin, payload))
}
// Close close client
func (client *Client) Close() error {
err := client.c.Close(websocket.StatusNormalClosure, "")
if err != nil {
return err
}
select {
case <-client.done:
case <-time.After(time.Second):
}
return nil
}