forked from TheCacophonyProject/go-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
483 lines (412 loc) · 11.1 KB
/
api.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
// go-api - Client for the Cacophony API server.
// Copyright (C) 2018, The Cacophony Project
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"strconv"
"time"
)
const (
httpTimeout = 60 * time.Second
timeout = 30 * time.Second
apiBasePath = "/api/v1"
regURL = "/devices"
authURL = "/authenticate_device"
)
type CacophonyDevice struct {
group string
name string
password string
}
type CacophonyAPI struct {
device *CacophonyDevice
httpClient *http.Client
serverURL string
token string
justRegistered bool
}
// joinURL creates an absolute url with supplied baseURL, and all paths
func joinURL(baseURL string, paths ...string) string {
u, err := url.Parse(baseURL)
if err != nil {
return ""
}
url := path.Join(paths...)
u.Path = path.Join(u.Path, url)
return u.String()
}
func (api *CacophonyAPI) getAPIURL() string {
return joinURL(api.serverURL, apiBasePath)
}
func (api *CacophonyAPI) getAuthURL() string {
return joinURL(api.serverURL, authURL)
}
func (api *CacophonyAPI) getRegURL() string {
return joinURL(api.serverURL, apiBasePath, regURL)
}
func (api *CacophonyAPI) Password() string {
return api.device.password
}
func (api *CacophonyAPI) JustRegistered() bool {
return api.justRegistered
}
// NewAPIFromConfig prases the supplied configFile and creates a new CacophonyAPI with the configFile information
// and saves the generated password to privConfigFileName(configFile)
func NewAPIFromConfig(configFile string) (*CacophonyAPI, error) {
conf, err := ParseConfigFile(configFile)
if err != nil {
return nil, fmt.Errorf("configuration error: %v", err)
}
privConfigFilename := privConfigFilename(configFile)
confPassword := NewConfigPassword(privConfigFilename)
password, err := confPassword.ReadPassword()
if err != nil {
return nil, err
}
if password == "" {
locked, err := confPassword.GetExLock()
if locked == false || err != nil {
return nil, err
}
defer confPassword.Unlock()
//read again incase was just written to while waiting for exlock
password, err = confPassword.ReadPassword()
if err != nil {
return nil, err
}
}
api, err := NewAPI(conf.ServerURL, conf.Group, conf.DeviceName, password)
if err != nil {
return nil, err
}
if api.JustRegistered() {
err := confPassword.WritePassword(api.Password())
if err != nil {
return nil, err
}
}
return api, nil
}
// createAPI creates a CacophonyAPI instance and obtains a fresh JSON Web
// Token. If no password is given then the device is registered.
func NewAPI(serverURL, group, deviceName, password string) (*CacophonyAPI, error) {
if deviceName == "" {
return nil, errors.New("no device name")
}
device := &CacophonyDevice{
group: group,
name: deviceName,
password: password,
}
api := &CacophonyAPI{
serverURL: serverURL,
device: device,
httpClient: newHTTPClient(),
}
if device.password == "" {
err := api.register()
if err != nil {
return nil, err
}
} else {
err := api.authenticate()
if err != nil {
return nil, err
}
}
return api, nil
}
// authenticate a device with Cacophony API and retrieves the token
func (api *CacophonyAPI) authenticate() error {
if api.device.password == "" {
return errors.New("no password set")
}
payload, err := json.Marshal(map[string]string{
"devicename": api.device.name,
"password": api.device.password,
})
if err != nil {
return err
}
postResp, err := api.httpClient.Post(
api.getAuthURL(),
"application/json",
bytes.NewReader(payload),
)
if err != nil {
return err
}
defer postResp.Body.Close()
if err := handleHTTPResponse(postResp); err != nil {
return err
}
var resp tokenResponse
d := json.NewDecoder(postResp.Body)
if err := d.Decode(&resp); err != nil {
return fmt.Errorf("decode: %v", err)
}
api.token = resp.Token
return nil
}
// newHTTPClient initializes and returns a http.Client with default settings
func newHTTPClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: timeout, // connection timeout
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
TLSHandshakeTimeout: timeout,
ResponseHeaderTimeout: timeout,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConns: 5,
IdleConnTimeout: 90 * time.Second,
},
}
}
// register a device with Cacophony API and retrieves it's token
func (api *CacophonyAPI) register() error {
if api.device.password != "" {
return errors.New("already registered")
}
password := randString(20)
payload, err := json.Marshal(map[string]string{
"group": api.device.group,
"devicename": api.device.name,
"password": password,
})
if err != nil {
return err
}
postResp, err := api.httpClient.Post(
api.getRegURL(),
"application/json",
bytes.NewReader(payload),
)
if err != nil {
return err
}
defer postResp.Body.Close()
if err := handleHTTPResponse(postResp); err != nil {
return err
}
var respData tokenResponse
d := json.NewDecoder(postResp.Body)
if err := d.Decode(&respData); err != nil {
return fmt.Errorf("decode: %v", err)
}
api.device.password = password
api.token = respData.Token
api.justRegistered = true
return nil
}
// UploadThermalRaw uploads the file to Cacophony API as a multipartmessage
// with data of type thermalRaw specified
func (api *CacophonyAPI) UploadThermalRaw(r io.Reader) error {
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)
// JSON encoded "data" parameter.
dataBuf, err := json.Marshal(map[string]string{
"type": "thermalRaw",
})
if err != nil {
return err
}
if err := w.WriteField("data", string(dataBuf)); err != nil {
return err
}
// Add the file as a new MIME part.
fw, err := w.CreateFormFile("file", "file")
if err != nil {
return err
}
io.Copy(fw, r)
w.Close()
req, err := http.NewRequest("POST", joinURL(api.serverURL, apiBasePath, "/recordings"), buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Authorization", api.token)
resp, err := api.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err := handleHTTPResponse(resp); err != nil {
return err
}
return nil
}
type tokenResponse struct {
Messages []string
Token string
}
// message gets the first message of the supplised tokenResponse if present
// otherwise default of "unknown"
func (r *tokenResponse) message() string {
if len(r.Messages) > 0 {
return r.Messages[0]
}
return "unknown"
}
// getFileFromJWT downloads a file from the Cacophony API using supplied JWT
// and saves it to the supplied path
func (api *CacophonyAPI) getFileFromJWT(jwt, path string) error {
out, err := os.Create(path)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(joinURL(api.serverURL, apiBasePath, "/signedUrl?jwt="+jwt))
if err != nil {
return err
}
defer resp.Body.Close()
// Check server response
if err := handleHTTPResponse(resp); err != nil {
return err
}
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
type FileResponse struct {
File FileInfo
Jwt string
}
type FileInfo struct {
Details FileDetails
Type string
}
type FileDetails struct {
Name string
OriginalName string
}
// GetFileDetails of the supplied fileID from the Cacophony API and return FileResponse info.
// This can then be parsed into DownloadFile to download the file
func (api *CacophonyAPI) GetFileDetails(fileID int) (*FileResponse, error) {
buf := new(bytes.Buffer)
req, err := http.NewRequest("GET", joinURL(api.serverURL, apiBasePath, "/files/"+strconv.Itoa(fileID)), buf)
req.Header.Set("Authorization", api.token)
resp, err := api.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var fr FileResponse
d := json.NewDecoder(resp.Body)
if err := d.Decode(&fr); err != nil {
return &fr, err
}
return &fr, nil
}
// DownloadFile specified by fileResponse and save it to filePath
func (api *CacophonyAPI) DownloadFile(fileResponse *FileResponse, filePath string) error {
if _, err := os.Stat(filePath); err == nil {
return err
}
return api.getFileFromJWT(fileResponse.Jwt, filePath)
}
// ReportEvent described by jsonDetails and timestamps to the Cacophony API
func (api *CacophonyAPI) ReportEvent(jsonDetails []byte, times []time.Time) error {
// Deserialise the JSON event details into a map.
var details map[string]interface{}
err := json.Unmarshal(jsonDetails, &details)
if err != nil {
return err
}
// Convert the event times for sending and add to the map to send.
dateTimes := make([]string, 0, len(times))
for _, t := range times {
dateTimes = append(dateTimes, formatTimestamp(t))
}
details["dateTimes"] = dateTimes
// Serialise the map back to JSON for sending.
jsonAll, err := json.Marshal(details)
if err != nil {
return err
}
// Prepare request.
req, err := http.NewRequest("POST", joinURL(api.serverURL, apiBasePath, "/events"), bytes.NewReader(jsonAll))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", api.token)
resp, err := api.httpClient.Do(req)
if err != nil {
return temporaryError(err)
}
defer resp.Body.Close()
if err := handleHTTPResponse(resp); err != nil {
return err
}
return nil
}
// handleHTTPResponse checks StatusCode of a response for success and returns an http error
// described in error.go
func handleHTTPResponse(resp *http.Response) error {
if !(isHTTPSuccess(resp.StatusCode)) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return temporaryError(fmt.Errorf("request failed (%d) and body read failed: %v", resp.StatusCode, err))
}
return &Error{
message: fmt.Sprintf("HTTP request failed (%d): %s", resp.StatusCode, body),
permanent: isHTTPClientError(resp.StatusCode),
}
}
return nil
}
//formatTimestamp to time.RFC3339 format
func formatTimestamp(t time.Time) string {
return t.UTC().Format(time.RFC3339)
}
func isHTTPSuccess(code int) bool {
return code >= 200 && code < 300
}
func isHTTPClientError(code int) bool {
return code >= 400 && code < 500
}
// GetSchedule will get the audio schedule
func (api *CacophonyAPI) GetSchedule() ([]byte, error) {
req, err := http.NewRequest("GET", joinURL(api.serverURL, apiBasePath, "schedules"), nil)
req.Header.Set("Authorization", api.token)
//client := new(http.Client)
resp, err := api.httpClient.Do(req)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}