-
Notifications
You must be signed in to change notification settings - Fork 1
/
device.go
97 lines (80 loc) · 2.45 KB
/
device.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
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"io/ioutil"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const DEVICE_API_URL = "https://wdm-a.wbx2.com/wdm/api/v1/devices"
type Device struct {
Token string
WebSocketUrl string
Url string
UserID string
Services map[string]string
logger *log.Entry
}
func NewDevice(token string) (*Device, error) {
logger := log.WithField("type", "Device")
deviceRegisterRequest, err := json.Marshal(struct {
DeviceName string `json:"deviceName"`
DeviceType string `json:"deviceType"`
LocalizedModel string `json:"localizedModel"`
Model string `json:"model"`
Name string `json:"name"`
SystemName string `json:"systemName"`
SystemVersion string `json:"systemVersion"`
}{
"webinc",
"DESKTOP",
"webinc",
"webinc",
"webinc",
"webinc",
buildVersion,
})
if err != nil {
return nil, errors.Wrap(err, "failed to marshal deviceRegisterRequest")
}
request, err := http.NewRequest("POST", DEVICE_API_URL, bytes.NewBuffer(deviceRegisterRequest))
if err != nil {
return nil, errors.Wrap(err, "failed to create http request")
}
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
logger.Trace("Create device")
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, errors.Wrap(err, "failed to create device")
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
responseError, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read error response")
}
return nil, errors.Errorf("failed to register device: %s", responseError)
}
var device Device
err = json.NewDecoder(response.Body).Decode(&device)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal device info")
}
logger = logger.WithField("device", device)
logger.Trace("Device created")
device.Token = token
device.logger = logger
return &device, nil
}
func (d *Device) RequestService(method string, service string, url string, data io.Reader) (*http.Response, error) {
httpRequest, err := http.NewRequest(method, d.Services[service]+url, data)
if err != nil {
return nil, errors.Wrap(err, "failed to create kms http request")
}
httpRequest.Header.Set("Authorization", "Bearer "+d.Token)
httpRequest.Header.Set("Content-type", "application/json")
return http.DefaultClient.Do(httpRequest)
}