-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclienthandler.go
More file actions
634 lines (536 loc) · 15.9 KB
/
clienthandler.go
File metadata and controls
634 lines (536 loc) · 15.9 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
socketio "github.com/doquangtan/socketio/v4"
things "github.com/thingsdb/go-thingsdb"
)
// For backwards compatability
var oldConnFile = ".things-gui_config"
var lastUsedKey = "lastUsedKey"
// client type
type client struct {
connection *things.Conn
connectionsPath string
cookie *http.Cookie
host string
logCh chan string
pass string
port uint16
roomStore *roomStore
sessionPath string
socketConn *socketio.Socket
ssl *tls.Config
tmpFiles *tmpFiles
token string
user string
}
// connResp type
type connResp struct {
Connected bool
}
// loginData type
type loginData struct {
Address string `json:"address"`
InsecureSkipVerify bool `json:"insecureSkipVerify"`
IsToken bool `json:"isToken"`
Memo string `json:"memo"`
Name string `json:"name"`
Password string `json:"password"`
SecureConnection bool `json:"secureConnection"`
Token string `json:"token"`
User string `json:"user"`
}
// loginResp type
type loginResp struct {
Address string `json:"address"`
InsecureSkipVerify bool `json:"insecureSkipVerify"`
IsToken bool `json:"isToken"`
Memo string `json:"memo"`
Name string `json:"name"`
SecureConnection bool `json:"secureConnection"`
User string `json:"user"`
}
type lMapping map[string]map[string]interface{}
type lData map[string]interface{}
type procedure struct {
Arguments interface{} `json:"arguments"`
Name string `json:"name"`
}
// Data struct that is received
type dataReq struct {
Arguments interface{} `json:"arguments"`
Blob interface{} `json:"blob"`
Id string `json:"id"`
Procedure procedure `json:"procedure"`
Query string `json:"query"`
Scope string `json:"scope"`
Wait int `json:"wait"`
}
func connectedResp() connResp {
return connResp{
Connected: true,
}
}
func disconnectedResp() connResp {
return connResp{
Connected: false,
}
}
func (client *client) connect(data loginData) (connResp, error) {
hp := strings.Split(data.Address, ":")
if len(hp) != 2 {
return disconnectedResp(), fmt.Errorf("invalid node name/address")
}
port, err := strconv.ParseUint(hp[1], 10, 16)
if err != nil {
return disconnectedResp(), err
}
host := hp[0]
client.ssl = nil // if ssl not supported, this will reset the ssl prop
if data.SecureConnection {
client.ssl = &tls.Config{}
client.ssl.InsecureSkipVerify = data.InsecureSkipVerify
}
client.host = host
client.port = uint16(port)
client.connection = things.NewConn(host, uint16(port), client.ssl)
client.connection.LogCh = client.logCh
client.connection.DefaultTimeout = time.Duration(timeout) * time.Second
client.connection.LogLevel = things.LogDebug
client.connection.ReconnectionAttempts = 7
s := client.socketConn
client.connection.OnNodeStatus = func(ns *things.NodeStatus) {
s.Emit("OnNodeStatus", *ns)
}
client.connection.OnWarning = func(we *things.WarnEvent) {
s.Emit("OnWarning", *we)
}
client.user = ""
client.pass = ""
client.token = ""
if !client.connection.IsConnected() {
err := client.connection.Connect()
if err != nil {
return disconnectedResp(), err
}
}
if data.IsToken {
err := client.connection.AuthToken(data.Token)
if err != nil {
return disconnectedResp(), err
}
client.token = data.Token
} else {
err := client.connection.AuthPassword(data.User, data.Password)
if err != nil {
return disconnectedResp(), err
}
client.user = data.User
client.pass = data.Password
}
// Store session in local file (~/.config/ThingsGUI/thingsgui.session).
if useLocalSession {
err = client.saveLastUsedConnection(data)
if err != nil {
client.logCh <- fmt.Sprintf("Last used connection could not be saved: %s.", err)
}
}
// Store session in memory
if useCookieSession && client.cookie != nil {
addSession(*client.cookie, data, cookieMaxAge)
}
return connectedResp(), nil
}
// connected returns if a connection with ThingsDB is established
func (client *client) connected() (int, connResp, message) {
resp := disconnectedResp()
conn := client.connection
switch {
case conn == nil:
if useLocalSession {
resp, _ = client.connectViaCache(client.sessionPath, lastUsedKey)
}
if !resp.Connected && useCookieSession && client.cookie != nil {
if data := getSession(client.cookie.Value); data != nil {
resp, _ = client.connect(*data)
}
}
case conn.IsConnected():
resp.Connected = true
default:
resp.Connected = false
}
message := successMsg()
return message.Status, resp, message
}
// connectToNew connects to a new ThingsDB connnection
func (client *client) connectToNew(data loginData) (int, connResp, message) {
var message message
resp, err := client.connect(data)
if resp.Connected {
message = successMsg()
} else {
message = failedMsg(err)
}
return message.Status, resp, message
}
// handlerConnectViaCache connects via cached auth data to ThingsDB
func (client *client) handlerConnectViaCache(data loginData) (int, connResp, message) {
message := successMsg()
resp, err := client.connectViaCache(client.connectionsPath, data.Name)
if !resp.Connected {
message = failedMsg(err)
}
return message.Status, resp, message
}
// connectViaCache connects via cached auth data to ThingsDB
func (client *client) connectViaCache(path string, name string) (connResp, error) {
fileNotExist := fileNotExist(path)
if fileNotExist {
return disconnectedResp(), fmt.Errorf("file does not exist")
}
var mapping = make(map[string]loginData)
err := readEncryptedFile(path, &mapping, client.logCh)
if err != nil {
return disconnectedResp(), err
}
resp, err := client.connect(mapping[name])
return resp, err
}
// authKey connects to ThingsDB via a key and API request to get the access token
func (client *client) authKey(data map[string]string) (int, interface{}, message) {
jsonData := map[string]string{"key": data["key"]} // url.Query().Get("key")}
jsonValue, _ := json.Marshal(jsonData)
response, err := http.Post(thingsguiTokenApi, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
return internalError(err)
}
if response.StatusCode < 200 || response.StatusCode > 299 {
return internalError(fmt.Errorf("invalid key"))
}
type Resp struct {
Token string `json:"token"`
}
var resp Resp
json.NewDecoder(response.Body).Decode(&resp)
d := map[string]string{"token": resp.Token}
return client.authToken(d)
}
// authToken connects to ThingsDB using the token and env variables
func (client *client) authToken(data map[string]string) (int, interface{}, message) {
message := successMsg()
mapping := loginData{
Address: thingsguiAddress,
InsecureSkipVerify: thingsguiAic,
IsToken: true,
SecureConnection: thingsguiSsl,
Token: data["token"],
}
resp, err := client.connect(mapping)
if !resp.Connected {
message = failedMsg(err)
}
return message.Status, resp, message
}
// authPass connects to ThingsDB using a user+pass and env variables
func (client *client) authPass(data map[string]string) (int, interface{}, message) {
message := successMsg()
mapping := loginData{
Address: thingsguiAddress,
InsecureSkipVerify: thingsguiAic,
IsToken: false,
Password: data["pass"],
SecureConnection: thingsguiSsl,
User: data["user"],
}
resp, err := client.connect(mapping)
if !resp.Connected {
message = failedMsg(err)
}
return message.Status, resp, message
}
func (client *client) seekConnection() bool {
if client.connection.IsConnected() {
client.logCh <- "Node is still closing."
return false
}
err := client.connection.Connect()
if err != nil {
client.logCh <- err.Error()
return false
}
if client.token == "" {
err := client.connection.AuthPassword(client.user, client.pass)
if err != nil {
client.logCh <- err.Error()
return false
}
} else {
err := client.connection.AuthToken(client.token)
if err != nil {
client.logCh <- err.Error()
return false
}
}
return true
}
// reconnect to ThingsDB when a connection is lost.
func (client *client) reconnect() (int, connResp, message) {
maxInterval := 60
interval := 1
timeoutCh := make(chan bool, 1)
for interval < maxInterval {
if success := client.seekConnection(); success {
resp := connectedResp()
message := successMsg()
return message.Status, resp, message
}
interval *= 2
client.logCh <- fmt.Sprintf("connecting to %s:%d failed, \ntry next connect in %d seconds", client.host, client.port, interval)
go func() {
time.Sleep(time.Duration(interval) * time.Second)
timeoutCh <- true
}()
<-timeoutCh
}
resp := disconnectedResp()
message := failedMsg(fmt.Errorf("reconnecting has stopped, timeout reached"))
return message.Status, resp, message
}
// disconnect closes a connection to ThingsDB
func (client *client) disconnect() (int, connResp, message) {
if useLocalSession {
client.saveLastUsedConnection(loginData{})
}
if useCookieSession && client.cookie != nil {
resetSession(client.cookie.Value)
}
client.closeSingleConn()
message := successMsg()
return message.Status, disconnectedResp(), message
}
// closeSingleConn closes a connection to ThingsDB
func (client *client) closeSingleConn() {
if client.connection != nil {
client.connection.Close()
}
}
// getCachedConnections gets all the cached connections
func (client *client) getCachedConnections() (int, interface{}, message) {
message := successMsg()
var mapping = make(map[string]loginResp)
err := readEncryptedFile(client.connectionsPath, &mapping, client.logCh)
if err != nil {
client.logCh <- err.Error()
// For backwards compatability
oldPath := getHomePath(oldConnFile)
if notExist := fileNotExist(oldPath); !notExist {
err = readEncryptedFile(oldPath, &mapping, client.logCh)
if err != nil {
client.logCh <- err.Error()
return message.Status, nil, message
}
_, err := createFile(client.connectionsPath, client.logCh)
if err != nil {
client.logCh <- err.Error()
return message.Status, nil, message
}
err = writeEncryptedFile(client.connectionsPath, mapping, client.logCh)
if err != nil {
client.logCh <- err.Error()
return message.Status, nil, message
}
err = deleteFile(getHomePath(oldConnFile), client.logCh)
if err != nil {
client.logCh <- err.Error()
return message.Status, nil, message
}
} else {
return message.Status, nil, message
}
}
return message.Status, mapping, message
}
// newCachedConnection saves a new connection locally
func (client *client) newCachedConnection(data lData) (int, interface{}, message) {
message := successMsg()
fn := func(mapping lMapping) error {
name := data["name"].(string)
if _, ok := mapping[name]; ok {
return fmt.Errorf("\"%s\" does already exist", name)
}
mapping[name] = data
return nil
}
err := changeFile(client.connectionsPath, client.logCh, fn)
if err != nil {
return internalError(err)
}
return message.Status, nil, message
}
// editCachedConnection edits a connection locally
func (client *client) editCachedConnection(data lData) (int, interface{}, message) {
message := successMsg()
fn := func(mapping lMapping) error {
name := data["name"].(string)
for k, v := range data {
mapping[name][k] = v
}
return nil
}
err := changeFile(client.connectionsPath, client.logCh, fn)
if err != nil {
return internalError(err)
}
return message.Status, nil, message
}
// renameCachedConnection renames a connection locally
func (client *client) renameCachedConnection(data lData) (int, interface{}, message) {
message := successMsg()
fn := func(mapping lMapping) error {
newName := data["newName"].(string)
oldName := data["oldName"].(string)
if _, ok := mapping[newName]; ok {
return fmt.Errorf("\"%s\" does already exist", newName)
}
mapping[newName] = mapping[oldName]
mapping[newName]["name"] = newName
delete(mapping, oldName)
return nil
}
err := changeFile(client.connectionsPath, client.logCh, fn)
if err != nil {
return internalError(err)
}
return message.Status, nil, message
}
// delCachedConnection deletes a saved connection
func (client *client) delCachedConnection(data loginData) (int, interface{}, message) {
message := successMsg()
fileNotExist := fileNotExist(client.connectionsPath)
if fileNotExist {
return internalError(fmt.Errorf("file does not exist"))
}
var mapping = make(map[string]loginData)
err := readEncryptedFile(client.connectionsPath, &mapping, client.logCh)
if err != nil {
return internalError(err)
}
delete(mapping, data.Name)
err = writeEncryptedFile(client.connectionsPath, mapping, client.logCh)
if err != nil {
return internalError(err)
}
return message.Status, nil, message
}
// saveLastUsedConnection saved the last used successfull connection.
func (client *client) saveLastUsedConnection(data loginData) error {
// Convert loginData to lData
ldata := make(lData)
lbytes, _ := json.Marshal(data)
json.Unmarshal(lbytes, &ldata)
fn := func(mapping lMapping) error {
mapping[lastUsedKey] = ldata
return nil
}
return changeFile(client.sessionPath, client.logCh, fn)
}
// query sends a query to ThingsDB and receives a result
func (client *client) query(data dataReq) (int, interface{}, message) {
var arguments map[string]interface{}
if data.Arguments != nil {
args := convertFloatToInt(data.Arguments)
arguments = args.(map[string]interface{})
}
if data.Blob != nil {
decodedBlob, err := decodeBase64(data.Blob)
if err != nil {
message := failedMsg(err)
return message.Status, "", message
}
blob := decodedBlob.(map[string]interface{})
for k, v := range blob {
if arguments == nil {
arguments = make(map[string]interface{})
}
arguments[k] = v
}
}
resp, err := client.connection.Query(
data.Scope,
data.Query,
arguments)
if err != nil {
message := createThingsDBError(err)
return message.Status, "", message
}
var r interface{}
r, err = client.tmpFiles.replaceBinStrWithLink(resp)
message := msg(err)
if r != nil {
resp = r
}
return message.Status, resp, message
}
// Join a room
func (client *client) join(socket *socketio.Socket, data dataReq) (int, interface{}, message) {
client.roomStore.mux.Lock()
defer client.roomStore.mux.Unlock()
scope := data.Scope
id := data.Id
wait := time.Duration(data.Wait) * time.Second
idInt, _ := strconv.ParseUint(id, 10, 64)
room := things.NewRoomFromId(scope, idInt)
client.roomStore.store[room.Id()] = room
room.OnInit = func(room *things.Room) {
socket.Emit("onInit", room.Id())
}
room.OnJoin = func(room *things.Room) {
socket.Emit("onJoin", room.Id())
}
room.OnLeave = func(room *things.Room) {
socket.Emit("onLeave", room.Id())
delete(client.roomStore.store, room.Id())
}
room.OnDelete = func(room *things.Room) {
socket.Emit("onDelete", room.Id())
delete(client.roomStore.store, room.Id())
}
room.OnEmit = func(room *things.Room, event string, args []interface{}) {
socket.Emit("onEmit", room.Id(), id, event, args)
}
err := room.Join(client.connection, wait)
message := msg(err)
return message.Status, nil, message
}
// Leave a room
func (client *client) leave(data dataReq) (int, interface{}, message) {
id := data.Id
roomId, _ := strconv.ParseUint(id, 10, 64)
var err error
if room, ok := client.roomStore.getRoom(roomId); ok {
err = room.Leave()
}
message := msg(err)
return message.Status, nil, message
}
// run the procedure that is provided
func (client *client) run(data dataReq) (int, interface{}, message) {
var args interface{}
message := successMsg()
if data.Procedure.Name != "" && data.Procedure.Arguments != nil {
args = convertFloatToInt(data.Procedure.Arguments)
}
resp, err := client.connection.Run(data.Scope, data.Procedure.Name, args)
if err != nil {
message = createThingsDBError(err)
}
return message.Status, resp, message
}