-
Notifications
You must be signed in to change notification settings - Fork 0
/
trackable.go
90 lines (80 loc) · 1.72 KB
/
trackable.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
package main
import (
"encoding/json"
"log"
"strings"
"time"
"github.com/nats-io/go-nats"
)
type trackable struct {
Service string `json:"service"`
Name string `json:"name"`
Powered *bool `json:"powered"`
}
// UpdateTrackableHandler : handler to manage trackable modifications
func UpdateTrackableHandler(msg *nats.Msg) {
i := trackable{}
if err = json.Unmarshal(msg.Data, &i); err != nil {
log.Println(err)
return
}
if i.Powered == nil {
return
} else if *i.Powered == true {
addTrackable(msg.Subject, i)
} else {
rmTrackable(msg.Subject, i)
}
}
// AddTrackableHandler : Handler to manage trackable additions
func AddTrackableHandler(msg *nats.Msg) {
i := trackable{}
if err = json.Unmarshal(msg.Data, &i); err != nil {
log.Println(err)
return
}
addTrackable(msg.Subject, i)
}
// RmTrackableHandler : Handler to manage trackable removals
func RmTrackableHandler(msg *nats.Msg) {
i := trackable{}
if err = json.Unmarshal(msg.Data, &i); err != nil {
log.Println(err)
return
}
rmTrackable(msg.Subject, i)
}
func addTrackable(subject string, i trackable) {
now := time.Now().Unix()
t := strings.Split(subject, ".")
e := Entity{
Service: i.Service,
Name: i.Name,
Type: t[0],
From: now,
}
if err := e.Save(); err != nil {
log.Println(err.Error())
} else {
log.Println("Added trackable " + t[1] + ":" + i.Name)
}
}
func rmTrackable(subject string, i trackable) {
t := strings.Split(subject, ".")
e := Entity{
Service: i.Service,
Name: i.Name,
Type: t[0],
}
for _, v := range e.Find() {
entity := v.(Entity)
if entity.To == 0 {
now := time.Now().Unix()
entity.To = now
if err := entity.Save(); err != nil {
log.Println(err.Error())
}
return
}
}
}