-
Notifications
You must be signed in to change notification settings - Fork 10
/
webhook.go
617 lines (519 loc) · 16.9 KB
/
webhook.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
package switchbot
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type WebhookService struct {
c *Client
}
func newWebhookService(c *Client) *WebhookService {
return &WebhookService{c: c}
}
func (c *Client) Webhook() *WebhookService {
return c.webhookService
}
type webhookSetupRequest struct {
Action string `json:"action"`
URL string `json:"url,omitempty"`
DeviceList string `json:"deviceList,omitempty"` // currently only ALL is supported
}
type webhookSetupResponse struct {
StatusCode int `json:"statusCode"`
Body interface{} `json:"body"`
Message string `json:"message"`
}
// Setup configures the url that all the webhook events will be sent to.
// Currently the deviceList is only supporting "ALL".
func (svc *WebhookService) Setup(ctx context.Context, url, deviceList string) error {
const path = "/v1.1/webhook/setupWebhook"
if deviceList != "ALL" {
return errors.New(`deviceList value is only supporting "ALL" for now`)
}
req := webhookSetupRequest{
Action: "setupWebhook",
URL: url,
DeviceList: deviceList,
}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return err
}
defer resp.Close()
return nil
}
type webhookQueryRequest struct {
Action WebhookQueryActionType `json:"action"`
URLs []string `json:"urls"`
}
type WebhookQueryActionType string
const (
QueryURL WebhookQueryActionType = "queryUrl"
QueryDetails WebhookQueryActionType = "queryDetails"
)
type webhookQueryResponse struct {
}
type webhookQueryUrlResponse struct {
StatusCode int `json:"statusCode"`
Message string `json:"message"`
Body webhookQueryUrlResponseBody `json:"body"`
}
type webhookQueryUrlResponseBody struct {
URLs []string `json:"urls"`
}
type webhookQueryDetailsResponse struct {
StatusCode int `json:"statusCode"`
Message string `json:"message"`
Body []WebhookQueryDetails `json:"body"`
}
type WebhookQueryDetails struct {
URL string `json:"url"`
CreateTime int64 `json:"createTime"`
LastUpdate int64 `json:"lastUpdateTime"`
DeviceList string `json:"deviceList"`
Enable bool `json:"enable"`
}
// Query retrieves the current configuration info of the webhook.
// The second argument `url` is required for QueryDetails action type.
func (svc *WebhookService) Query(ctx context.Context, action WebhookQueryActionType, url string) error {
const path = "/v1.1/webhook/queryWebhook"
req := webhookQueryRequest{
Action: action,
}
switch action {
case QueryDetails:
if url == "" {
return errors.New("URL need to be specified when the action is queryDetails")
}
req.URLs = []string{url}
}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return err
}
defer resp.Close()
return nil
}
// QueryUrl retrieves the current url configuration info of the webhook.
func (svc *WebhookService) QueryUrl(ctx context.Context) (string, error) {
const path = "/v1.1/webhook/queryWebhook"
req := webhookQueryRequest{
Action: QueryURL,
}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return "", err
}
defer resp.Close()
var response webhookQueryUrlResponse
if err := resp.DecodeJSON(&response); err != nil {
return "", err
}
if response.StatusCode == 190 {
return "", fmt.Errorf("undocumented error %d occurred for queryWebhook API: %s", response.StatusCode, response.Message)
} else if response.StatusCode != 100 {
return "", fmt.Errorf("unknown error %d from queryWebhook API: %s", response.StatusCode, response.Message)
}
if len(response.Body.URLs) < 1 {
return "", errors.New("queryWebhook API response urls is empty")
}
return response.Body.URLs[0], nil
}
// QueryDetails retrieves the current details configuration info of the webhook.
func (svc *WebhookService) QueryDetails(ctx context.Context, url string) (*WebhookQueryDetails, error) {
const path = "/v1.1/webhook/queryWebhook"
req := webhookQueryRequest{
Action: QueryDetails,
}
req.URLs = []string{url}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return nil, err
}
defer resp.Close()
var response webhookQueryDetailsResponse
if err := resp.DecodeJSON(&response); err != nil {
return nil, err
}
if response.StatusCode == 190 {
return nil, fmt.Errorf("undocumented error %d occurred for queryWebhook API: %s", response.StatusCode, response.Message)
} else if response.StatusCode != 100 {
return nil, fmt.Errorf("unknown error %d from queryWebhook API: %s", response.StatusCode, response.Message)
}
if len(response.Body) < 1 {
return nil, errors.New("queryWebhook API response body is empty")
}
return &response.Body[0], nil
}
type webhookUpdateRequest struct {
Action string `json:"action"` // the type of actions but for now this must be updateWebhook
Config webhookConfig `json:"config"`
}
type webhookConfig struct {
URL string `json:"url"`
Enable bool `json:"enable"`
}
// Update do update the configuration of the webhook.
func (svc *WebhookService) Update(ctx context.Context, url string, enable bool) error {
const path = "/v1.1/webhook/updateWebhook"
req := webhookUpdateRequest{
Action: "updateWebhook",
Config: webhookConfig{
URL: url,
Enable: enable,
},
}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return err
}
defer resp.Close()
return nil
}
type webhookDeleteRequest struct {
Action string `json:"action"` // the type of actions but for now this must be deleteWebhook
URL string `json:"url"`
}
// Delete do delete the configuration of the webhook.
func (svc *WebhookService) Delete(ctx context.Context, url string) error {
const path = "/v1.1/webhook/deleteWebhook"
req := webhookDeleteRequest{
Action: "deleteWebhook",
URL: url,
}
resp, err := svc.c.post(ctx, path, req)
if err != nil {
return err
}
defer resp.Close()
return nil
}
func deviceTypeFromWebhookRequest(r *http.Request) (string, error) {
var rawBody bytes.Buffer
var deviceTypeBody struct {
Context struct {
DeviceType string `json:"deviceType"`
} `json:"context"`
}
if err := json.NewDecoder(io.TeeReader(r.Body, &rawBody)).Decode(&deviceTypeBody); err != nil {
return "", err
}
r.Body = io.NopCloser(&rawBody)
return deviceTypeBody.Context.DeviceType, nil
}
type MotionSensorEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context MotionSensorEventContext `json:"context"`
}
type MotionSensorEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the motion state of the device, "DETECTED" stands for motion is detected;
// "NOT_DETECTED" stands for motion has not been detected for some time
DetectionState string `json:"detectionState"`
}
type ContactSensorEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context ContactSensorEventContext `json:"context"`
}
type ContactSensorEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the motion state of the device, "DETECTED" stands for motion is detected;
// "NOT_DETECTED" stands for motion has not been detected for some time
DetectionState string `json:"detectionState"`
// when the enter or exit mode gets triggered, "IN_DOOR" or "OUT_DOOR" is returned
DoorMode string `json:"doorMode"`
// the level of brightness, can be "bright" or "dim"
Brightness AmbientBrightness `json:"brightness"`
// the state of the contact sensor, can be "open" or "close" or "timeOutNotClose"
OpenState string `json:"openState"`
}
type MeterEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context MeterEventContext `json:"context"`
}
type MeterEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
Temperature float64 `json:"temperature"`
Scale string `json:"scale"`
Humidity int `json:"humidity"`
}
type MeterPlusEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context MeterPlusEventContext `json:"context"`
}
type MeterPlusEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
Temperature float64 `json:"temperature"`
Scale string `json:"scale"`
Humidity int `json:"humidity"`
}
type LockEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context LockEventContext `json:"context"`
}
type LockEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the state of the device, "LOCKED" stands for the motor is rotated to locking position;
// "UNLOCKED" stands for the motor is rotated to unlocking position; "JAMMED" stands for
// the motor is jammed while rotating
LockState string `json:"lockState"`
}
type IndoorCamEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context IndoorCamEventContext `json:"context"`
}
type IndoorCamEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the detection state of the device, "DETECTED" stands for motion is detected
DetectionState string `json:"detectionState"`
}
type PanTiltCamEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context PanTiltCamEventContext `json:"context"`
}
type PanTiltCamEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the detection state of the device, "DETECTED" stands for motion is detected
DetectionState string `json:"detectionState"`
}
type ColorBulbEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context ColorBulbEventContext `json:"context"`
}
type ColorBulbEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the current power state of the device, "ON" or "OFF"
PowerState PowerState `json:"powerState"`
// the brightness value, range from 1 to 100
Brightness int `json:"brightness"`
// the color value, in the format of RGB value, "255:255:255"
Color string `json:"color"`
// the color temperature value, range from 2700 to 6500
ColorTemperature int `json:"colorTemperature"`
}
type StripLightEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context StripLightEventContext `json:"context"`
}
type StripLightEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the current power state of the device, "ON" or "OFF"
PowerState PowerState `json:"powerState"`
// the brightness value, range from 1 to 100
Brightness int `json:"brightness"`
// the color value, in the format of RGB value, "255:255:255"
Color string `json:"color"`
}
type PlugMiniJPEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context PlugMiniJPEventContext `json:"context"`
}
type PlugMiniJPEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the current power state of the device, "ON" or "OFF"
PowerState PowerState `json:"powerState"`
}
type PlugMiniUSEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context PlugMiniUSEventContext `json:"context"`
}
type PlugMiniUSEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the current power state of the device, "ON" or "OFF"
PowerState PowerState `json:"powerState"`
}
type SweeperEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context SweeperEventContext `json:"context"`
}
type SweeperEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the working status of the device, "StandBy", "Clearing",
// "Paused", "GotoChargeBase", "Charging", "ChargeDone",
// "Dormant", "InTrouble", "InRemoteControl", or "InDustCollecting"
WorkingStatus CleanerWorkingStatus `json:"workingStatus"`
// the connection status of the device, "online" or "offline"
OnlineStatus CleanerOnlineStatus `json:"onlineStatus"`
// the battery level.
Battery int `json:"battery"`
}
type CeilingEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context CeilingEventContext `json:"context"`
}
type CeilingEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// ON/OFF state
PowerState PowerState `json:"powerState"`
// the brightness value, range from 1 to 100
Brightness int `json:"brightness"`
// the color temperature value, range from 2700 to 6500
ColorTemperature int `json:"colorTemperature"`
}
type KeypadEvent struct {
EventType string `json:"eventType"`
EventVersion string `json:"eventVersion"`
Context KeypadEventContext `json:"context"`
}
type KeypadEventContext struct {
DeviceType string `json:"deviceType"`
DeviceMac string `json:"deviceMac"`
TimeOfSample int64 `json:"timeOfSample"`
// the name fo the command being sent
EventName string `json:"eventName"`
// the command ID
CommandID string `json:"commandId"`
// the result of the command, success, failed, or timeout
Result string `json:"result"`
}
func ParseWebhookRequest(r *http.Request) (interface{}, error) {
deviceType, err := deviceTypeFromWebhookRequest(r)
if err != nil {
return nil, err
}
switch deviceType {
case "WoPresence":
// Motion Sensor
var event MotionSensorEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoContact":
// Contact Sensor
var event ContactSensorEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoLock":
// Lock
var event LockEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoCamera":
// Indoor Cam
var event IndoorCamEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoPanTiltCam":
// Pan/Tilt Cam
var event PanTiltCamEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoBulb":
// Color Bulb
var event ColorBulbEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoStrip":
// LED Strip Light
var event StripLightEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoPlugUS":
// Plug Mini (US)
var event PlugMiniUSEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoPlugJP":
// Plug Mini (JP)
var event PlugMiniJPEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoMeter":
// Meter
var event MeterEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoMeterPlus":
// Meter Plus
var event MeterPlusEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoSweeper", "WoSweeperPlus":
// Cleaner
var event SweeperEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoCeiling", "WoCeilingPro":
// Ceiling lights
var event CeilingEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
case "WoKeypad", "WoKeypadTouch":
// keypad
var event KeypadEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
return nil, err
}
return &event, nil
default:
return nil, fmt.Errorf("unknown device type: %s", deviceType)
}
}