-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
board_request.go
293 lines (243 loc) · 6.98 KB
/
board_request.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
)
var (
itemSplit = ";"
)
// ImportBoard pulls in bots from the provided db
func (m *Manager) ImportBoard() {
// query
rows, err := m.DB.Query("SELECT clientID, token, name, nickname, color, crypto, header, items, frequency FROM boards")
if err != nil {
logger.Warningf("Unable to query tokens in db: %s", err)
return
}
// load existing bots from db
for rows.Next() {
var importedBoard Board
var itemsBulk string
err = rows.Scan(&importedBoard.ClientID, &importedBoard.Token, &importedBoard.Name, &importedBoard.Nickname, &importedBoard.Color, &importedBoard.Crypto, &importedBoard.Header, &itemsBulk, &importedBoard.Frequency)
if err != nil {
logger.Errorf("Unable to load token from db: %s", err)
continue
}
importedBoard.Items = strings.Split(itemsBulk, itemSplit)
if importedBoard.Crypto {
go importedBoard.watchCryptoPrice()
m.WatchBoard(&importedBoard)
} else {
go importedBoard.watchStockPrice()
m.WatchBoard(&importedBoard)
}
logger.Infof("Loaded board from db: %s", importedBoard.label())
}
rows.Close()
// check all entries have id
for _, board := range m.WatchingBoard {
if board.ClientID == "" {
id, err := getIDToken(board.Token)
if err != nil {
logger.Errorf("Unable to get id from token: %s", err)
continue
}
stmt, err := m.DB.Prepare("UPDATE boards SET clientId = ? WHERE token = ?")
if err != nil {
logger.Errorf("Unable to prepare id update: %s", err)
continue
}
res, err := stmt.Exec(id, board.Token)
if err != nil {
logger.Errorf("Unable to update db: %s", err)
continue
}
_, err = res.LastInsertId()
if err != nil {
logger.Errorf("Unable to confirm db update: %s", err)
continue
} else {
logger.Infof("Updated id in db for %s", board.label())
board.ClientID = id
}
}
}
}
// AddBoard adds a new board to the list of what to watch
func (m *Manager) AddBoard(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
logger.Debugf("Got an API request to add a board")
// read body
body, err := io.ReadAll(r.Body)
if err != nil {
logger.Errorf("Error: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// unmarshal into struct
var boardReq Board
if err := json.Unmarshal(body, &boardReq); err != nil {
logger.Errorf("Error unmarshalling: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// ensure token is set
if boardReq.Token == "" {
logger.Error("Discord token required")
w.WriteHeader(http.StatusBadRequest)
return
}
// make sure token is valid
if boardReq.ClientID == "" {
id, err := getIDToken(boardReq.Token)
if err != nil {
logger.Errorf("Unable to authenticate with discord token: %s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
boardReq.ClientID = id
}
// ensure frequency is set
if boardReq.Frequency <= 0 {
boardReq.Frequency = 60
}
// ensure name is set
if boardReq.Name == "" {
logger.Error("Board Name required")
w.WriteHeader(http.StatusBadRequest)
return
}
// add stock or crypto board
if boardReq.Crypto {
// check if already existing
if _, ok := m.WatchingBoard[boardReq.label()]; ok {
logger.Error("Error: board already exists")
w.WriteHeader(http.StatusConflict)
return
}
go boardReq.watchCryptoPrice()
m.WatchBoard(&boardReq)
} else {
// check if already existing
if _, ok := m.WatchingBoard[boardReq.label()]; ok {
logger.Error("Error: board already exists")
w.WriteHeader(http.StatusConflict)
return
}
go boardReq.watchStockPrice()
m.WatchBoard(&boardReq)
}
if *db != "" {
m.StoreBoard(&boardReq)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(boardReq)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
}
logger.Infof("Added board: %s\n", boardReq.Name)
}
func (m *Manager) WatchBoard(board *Board) {
boardCount.Inc()
id := board.label()
m.WatchingBoard[id] = board
}
// StoreBoard puts a board into the db
func (m *Manager) StoreBoard(board *Board) {
// store new entry in db
stmt, err := m.DB.Prepare("INSERT INTO boards(clientId, token, name, nickname, color, crypto, header, items, frequency) values(?,?,?,?,?,?,?,?,?)")
if err != nil {
logger.Warningf("Unable to store board in db %s: %s", board.label(), err)
return
}
res, err := stmt.Exec(board.ClientID, board.Token, board.Name, board.Nickname, board.Color, board.Crypto, board.Header, strings.Join(board.Items, itemSplit), board.Frequency)
if err != nil {
logger.Warningf("Unable to store board in db %s: %s", board.label(), err)
return
}
_, err = res.LastInsertId()
if err != nil {
logger.Warningf("Unable to store board in db %s: %s", board.label(), err)
return
}
}
// DeleteBoard removes a board
func (m *Manager) DeleteBoard(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
logger.Debugf("Got an API request to delete a board")
vars := mux.Vars(r)
id := vars["id"]
if _, ok := m.WatchingBoard[id]; !ok {
logger.Error("Error: no board found")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Error: board not found")
return
}
// send shutdown sign
m.WatchingBoard[id].Shutdown()
boardCount.Dec()
var noDB *sql.DB
if m.DB != noDB {
// remove from db
stmt, err := m.DB.Prepare("DELETE FROM boards WHERE name = ?")
if err != nil {
logger.Warningf("Unable to query board in db %s: %s", id, err)
return
}
_, err = stmt.Exec(m.WatchingBoard[id].Name)
if err != nil {
logger.Warningf("Unable to query board in db %s: %s", id, err)
return
}
}
// remove from cache
delete(m.WatchingBoard, id)
logger.Infof("Deleted board %s", id)
w.WriteHeader(http.StatusNoContent)
}
// RestartBoard stops and starts a board
func (m *Manager) RestartBoard(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
logger.Debugf("Got an API request to restart a board")
vars := mux.Vars(r)
id := vars["id"]
if _, ok := m.WatchingBoard[id]; !ok {
logger.Error("Error: no board found")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Error: board not found")
return
}
// send shutdown sign
m.WatchingBoard[id].Shutdown()
// wait twice the update time
time.Sleep(time.Duration(m.WatchingBoard[id].Frequency) * 2 * time.Second)
// start the board again
if m.WatchingBoard[id].Crypto {
go m.WatchingBoard[id].watchCryptoPrice()
} else {
go m.WatchingBoard[id].watchStockPrice()
}
logger.Infof("Restarted board %s", id)
w.WriteHeader(http.StatusNoContent)
}
// GetBoards returns a list of what the manager is watching
func (m *Manager) GetBoards(w http.ResponseWriter, r *http.Request) {
m.RLock()
defer m.RUnlock()
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(m.WatchingBoard); err != nil {
logger.Errorf("Error serving request: %v", err)
fmt.Fprintf(w, "Error: %v", err)
}
}