-
Notifications
You must be signed in to change notification settings - Fork 1
/
clients.go
108 lines (85 loc) · 2.27 KB
/
clients.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
package api
import (
"encoding/json"
"errors"
"time"
"github.com/gin-gonic/gin"
"github.com/hverr/status-dashboard/server"
"github.com/hverr/status-dashboard/widgets"
)
func (api *API) registerClient(c *gin.Context) {
var r server.ClientRegistration
if err := c.BindJSON(&r); err != nil {
c.AbortWithError(400, err)
return
}
if !api.Server.AuthenticateClient(c, r.Identifier) {
return
}
if err := api.Server.RegisterClient(&r); err != nil {
c.AbortWithError(400, err)
return
}
api.Scheduler.RegisterClient(r.Identifier)
c.JSON(200, gin.H{})
}
func (api *API) bulkUpdateClient(c *gin.Context) {
client, _ := api.Server.GetClient(c.Param("client"))
if client == nil {
c.AbortWithError(404, errors.New("Client not found."))
return
}
if !api.Server.AuthenticateClient(c, client.Identifier) {
return
}
updates := make([]widgets.BulkElement, 0)
if err := c.BindJSON(&updates); err != nil {
c.AbortWithError(400, err)
return
}
updated := make([]string, 0, len(updates))
result := make([]widgets.Widget, 0, len(updates))
missing := make([]string, 0)
for _, u := range updates {
if u.Widget != nil && u.Type != "" {
initiator := widgets.AllWidgets[u.Type]
if initiator == nil {
c.AbortWithError(404, errors.New("Widget not found: "+u.Type))
return
}
widget := initiator()
if err := json.Unmarshal(u.Widget, &widget); err != nil {
c.AbortWithError(400, err)
return
}
result = append(result, widget)
} else {
missing = append(missing, u.Identifier)
}
updated = append(updated, u.Identifier)
}
for _, w := range result {
client.SetWidget(w)
}
for _, w := range missing {
client.DeleteWidget(w)
}
api.Scheduler.FulfillUpdateRequest(client.Identifier, updated)
c.JSON(200, gin.H{"status": "OK"})
}
func (api *API) requestedClientWidgets(c *gin.Context) {
client, _ := api.Server.GetClient(c.Param("client"))
if client == nil {
c.AbortWithError(404, errors.New("Client not found."))
return
}
if !api.Server.AuthenticateClient(c, client.Identifier) {
return
}
select {
case requested := <-api.Scheduler.RequestUpdateRequest(client.Identifier):
c.JSON(200, gin.H{"widgets": requested})
case <-time.After(api.Configuration.MaximumClientUpdateInterval):
c.JSON(200, gin.H{"widgets": []string{}})
}
}