-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathui.go
574 lines (472 loc) · 18 KB
/
ui.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
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
// Functions to deal with the agGrid (UI).
package main
import (
"database/sql"
"encoding/json"
"fmt"
"gopkg.in/guregu/null.v3/zero"
"io/ioutil"
"net/http"
"path/filepath"
"runtime"
)
// Auxiliary functions for HTTP handling
// checkErrHTTP returns an error via HTTP and also logs the error.
func checkErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
if err != nil {
http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
pc, file, line, ok := runtime.Caller(1)
Log.Error("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - error:", errorMessage, err)
}
}
// checkErrPanicHTTP returns an error via HTTP and logs the error with a panic.
func checkErrPanicHTTP(w http.ResponseWriter, httpStatus int, errorMessage string, err error) {
if err != nil {
http.Error(w, fmt.Sprintf(errorMessage, err), httpStatus)
pc, file, line, ok := runtime.Caller(1)
Log.Panic("(", http.StatusText(httpStatus), ") ", filepath.Base(file), ":", line, ":", pc, ok, " - panic:", errorMessage, err)
}
}
// logErrHTTP assumes that the error message was already composed and writes it to HTTP and logs it.
// this is mostly to avoid code duplication and make sure that all entries are written similarly
func logErrHTTP(w http.ResponseWriter, httpStatus int, errorMessage string) {
http.Error(w, errorMessage, httpStatus)
Log.Error("(" + http.StatusText(httpStatus) + ") " + errorMessage)
}
// funcName is @Sonia's solution to get the name of the function that Go is currently running.
// This will be extensively used to deal with figuring out where in the code the errors are!
// Source: https://stackoverflow.com/a/10743805/1035977 (20170708)
func funcName() string {
pc, _, _, _ := runtime.Caller(1)
return runtime.FuncForPC(pc).Name()
}
// Main functions to respond to agGrid
//
// Each function class has a struct type to deal with database requests
// objectType is a struct to hold data retrieved from the database, used by several functions (including JSON).
type ObjectType struct {
UUID zero.String
Name zero.String
BotKey zero.String
BotName zero.String
Type zero.String // `json:"string"`
Position zero.String
Rotation zero.String
Velocity zero.String
LastUpdate zero.String
Origin zero.String
Phantom zero.String // `json:"string"`
Prims zero.String // `json:"string"`
BBHi zero.String
BBLo zero.String
Coords_region string // These two are not on the database but calculated on demand (20170722)
Coords_xyz []string // can be a string since it will never be deJSONified
}
// uiObjects creates a JSON representation of the Obstacles table and spews it out.
func uiObjects(w http.ResponseWriter, r *http.Request) {
var (
rowArr []interface{}
Object ObjectType
)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanic(err)
defer db.Close()
// query
rows, err := db.Query("SELECT * FROM Obstacles")
checkErr(err)
for rows.Next() {
err = rows.Scan(
&Object.UUID,
&Object.Name,
&Object.BotKey,
&Object.BotName,
&Object.Type,
&Object.Position,
&Object.Rotation,
&Object.Velocity,
&Object.LastUpdate,
&Object.Origin,
&Object.Phantom,
&Object.Prims,
&Object.BBHi,
&Object.BBLo,
)
// Log.Debug("Row extracted:", Object)
rowArr = append(rowArr, Object)
}
checkErr(err)
defer rows.Close()
// produces neatly indented output; see https://blog.golang.org/json-and-go but especially http://stackoverflow.com/a/37084385/1035977
if data, err := json.MarshalIndent(rowArr, "", " "); err != nil {
checkErr(err)
} else {
// Log.Debugf("json.MarshalIndent:\n%s\n\n", data)
_, err := fmt.Fprintf(w, "%s", data)
//if (err == nil) { Log.Debugf("Wrote %d bytes to interface\n", n) } else { checkErr(err) }
checkErr(err)
}
// return
}
// uiObjectsUpdate receives a JSON representation of one row (from the agGrid) in order to update our database.
func uiObjectsUpdate(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) // from https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go (20170524)
checkErrPanic(err)
// Log.Debug("\nBody is >>", string(body), "<<")
var obj ObjectType
err = json.Unmarshal(body, &obj)
checkErrPanic(err)
// Log.Debug("\nJSON decoded body is >>", obj, "<<")
// update database
// open database connection and see if we can update the inventory for this object
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
stmt, err := db.Prepare("REPLACE INTO Obstacles (`UUID`, `Name`, `BotKey`, `BotName`, `Type`, `Position`, `Rotation`, `Velocity`, `LastUpdate`, `Origin`, `Phantom`, `Prims`, `BBHi`, `BBLo`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(obj.UUID, obj.Name, obj.BotKey, obj.BotName, obj.Type, obj.Position,
obj.Rotation, obj.Velocity, obj.LastUpdate, obj.Origin, obj.Phantom, obj.Prims, obj.BBHi, obj.BBLo)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace exec failed:", err)
// w.WriteHeader(http.StatusOK)
// w.Header().Set("Content-type", "text/plain; charset=utf-8")
// fmt.Fprintln(w, obj, "successfully updated.")
// Log.Debug(obj, "successfully updated.")
// return
}
// uiObjectsRemove receives a list of UUIDs to remove from the Obstacles table.
func uiObjectsRemove(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Cannot read body of HTTP Request:", err)
// Log.Debug("\nObjects body is >>", string(body), "<<")
// open database connection and see if we can remove the object UUIDs we got
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DELETE FROM Obstacles WHERE UUID IN (%s)", string(body)))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Objects remove failed:", err)
Log.Debug("Object UUIDs >>", string(body), "<< successfully removed.")
}
// agentType is a struct to hold data retrieved from the database.
type AgentType struct {
UUID zero.String
Name zero.String
OwnerName zero.String
OwnerKey zero.String
Location zero.String
Position zero.String
Rotation zero.String
Velocity zero.String
Energy zero.String
Money zero.String
Happiness zero.String
Class zero.String
SubType zero.String
PermURL zero.String
LastUpdate zero.String
BestPath zero.String
SecondBestPath zero.String
CurrentTarget zero.String
Coords_region string
Coords_xyz []string
}
// uiAgents creates a JSON representation of the Agents table and spews it out.
func uiAgents(w http.ResponseWriter, r *http.Request) {
var (
rowArr []interface{}
Agent AgentType
)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanic(err)
defer db.Close()
rows, err := db.Query("SELECT * FROM Agents")
checkErr(err)
for rows.Next() {
err = rows.Scan(
&Agent.UUID,
&Agent.Name,
&Agent.OwnerName,
&Agent.OwnerKey,
&Agent.Location,
&Agent.Position,
&Agent.Rotation,
&Agent.Velocity,
&Agent.Energy,
&Agent.Money,
&Agent.Happiness,
&Agent.Class,
&Agent.SubType,
&Agent.PermURL,
&Agent.LastUpdate,
&Agent.BestPath,
&Agent.SecondBestPath,
&Agent.CurrentTarget,
)
rowArr = append(rowArr, Agent)
}
checkErr(err)
defer rows.Close()
if data, err := json.MarshalIndent(rowArr, "", " "); err != nil {
checkErr(err)
} else {
_, err := fmt.Fprintf(w, "%s", data)
checkErr(err)
}
// return
}
// uiAgentsUpdate receives a JSON representation of one row (from the agGrid) in order to update our database.
func uiAgentsUpdate(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
var ag AgentType
err = json.Unmarshal(body, &ag)
checkErrPanic(err)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
stmt, err := db.Prepare("REPLACE INTO Agents (`UUID`, `Name`, `OwnerName`, `OwnerKey`, `Location`, `Position`, `Rotation`, `Velocity`, `Energy`, `Money`, `Happiness`, `Class`, `SubType`, `PermURL`, `LastUpdate`, `BestPath`, `SecondBestPath`, `CurrentTarget`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(ag.UUID, ag.Name, ag.OwnerName, ag.OwnerKey, ag.Location, ag.Position,
ag.Rotation, ag.Velocity, ag.Energy, ag.Money, ag.Happiness, ag.Class, ag.SubType, ag.PermURL,
ag.LastUpdate, ag.BestPath, ag.SecondBestPath, ag.CurrentTarget)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace exec failed:", err)
// return
}
// uiAgentsRemove receives a list of UUIDs to remove from the Agents table.
func uiAgentsRemove(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
// Log.Debug("\nAgents Body is >>", string(body), "<<")
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DELETE FROM Agents WHERE UUID IN (%s)", string(body)))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Agents remove failed:", err)
Log.Debug("Agents UUIDs >>", string(body), "<< successfully removed.")
}
// PositionType is a struct to hold data retrieved from the database, used by several functions (including JSON).
type PositionType struct {
PermURL zero.String
UUID zero.String
Name zero.String
OwnerName zero.String
Location zero.String
Position zero.String
Rotation zero.String
Velocity zero.String
LastUpdate zero.String
OwnerKey zero.String
ObjectType zero.String
ObjectClass zero.String
RateEnergy zero.String
RateMoney zero.String
RateHappiness zero.String
Coords_region string
Coords_xyz []string
DistanceToAgent float64 // This does not get saved to the database, since it's different for every agent (20170811).
}
// uiPositions creates a JSON representation of the Positions table and spews it out.
func uiPositions(w http.ResponseWriter, r *http.Request) {
var (
rowArr []interface{}
Position PositionType
)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanic(err)
defer db.Close()
// query
rows, err := db.Query("SELECT * FROM Positions")
checkErr(err)
for rows.Next() {
err = rows.Scan(
&Position.PermURL,
&Position.UUID,
&Position.Name,
&Position.OwnerName,
&Position.Location,
&Position.Position,
&Position.Rotation,
&Position.Velocity,
&Position.LastUpdate,
&Position.OwnerKey,
&Position.ObjectType,
&Position.ObjectClass,
&Position.RateEnergy,
&Position.RateMoney,
&Position.RateHappiness,
)
rowArr = append(rowArr, Position)
}
checkErr(err)
defer rows.Close()
if data, err := json.MarshalIndent(rowArr, "", " "); err != nil {
checkErr(err)
} else {
_, err := fmt.Fprintf(w, "%s", data)
checkErr(err)
}
// return
}
// uiPositionsUpdate receives a JSON representation of one row (from the agGrid) in order to update our database.
func uiPositionsUpdate(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
var pos PositionType
err = json.Unmarshal(body, &pos)
checkErrPanic(err)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
stmt, err := db.Prepare("REPLACE INTO Positions (`PermURL`, `UUID`, `Name`, `OwnerName`, `Location`, `Position`, `Rotation`, `Velocity`, `LastUpdate`, `OwnerKey`, `ObjectType`, `ObjectClass`, `RateEnergy`, `RateMoney`, `RateHappiness`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(pos.PermURL, pos.UUID, pos.Name, pos.OwnerName, pos.Location, pos.Position,
pos.Rotation, pos.Velocity, pos.LastUpdate, pos.OwnerKey, pos.ObjectType, pos.ObjectClass,
pos.RateEnergy, pos.RateMoney, pos.RateHappiness)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace exec failed:", err)
// return
}
// uiPositionsRemove receives a list of UUIDs to remove from the Positions table.
func uiPositionsRemove(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
// Log.Debug("\nPositions Body is >>", string(body), "<<")
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DELETE FROM Positions WHERE UUID IN (%s)", string(body)))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Positions remove failed:", err)
Log.Debug("Positions UUIDs >>", string(body), "<< successfully removed.")
}
// inventoryType is a struct to hold data retrieved from the database, used by several functions (including JSON).
type inventoryType struct {
UUID zero.String
Name zero.String
Type zero.String
LastUpdate zero.String
Permissions zero.String
}
// uiInventory creates a JSON representation of the Inventory table and spews it out.
func uiInventory(w http.ResponseWriter, r *http.Request) {
var (
rowArr []interface{}
Inventory inventoryType
)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanic(err)
defer db.Close()
// query
rows, err := db.Query("SELECT * FROM Inventory")
checkErr(err)
for rows.Next() {
err = rows.Scan(
&Inventory.UUID,
&Inventory.Name,
&Inventory.Type,
&Inventory.LastUpdate,
&Inventory.Permissions,
)
rowArr = append(rowArr, Inventory)
}
checkErr(err)
defer rows.Close()
if data, err := json.MarshalIndent(rowArr, "", " "); err != nil {
checkErr(err)
} else {
_, err := fmt.Fprintf(w, "%s", data)
checkErr(err)
}
// return
}
// uiInventoryUpdate receives a JSON representation of one row (from the agGrid) in order to update our database.
func uiInventoryUpdate(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
var inv inventoryType
err = json.Unmarshal(body, &inv)
checkErrPanic(err)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
stmt, err := db.Prepare("REPLACE INTO Inventory (`UUID`, `Name`, `Type`, `LastUpdate`, `Permissions`) VALUES (?,?,?,?,?)")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(inv.UUID, inv.Name, inv.Type, inv.LastUpdate, inv.Permissions)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace exec failed:", err)
// return
}
// uiInventoryRemove receives a list of UUIDs to remove from the Inventory table.
func uiInventoryRemove(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
// Log.Debug("\nInventory Body is >>", string(body), "<<")
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DELETE FROM Inventory WHERE UUID IN (%s)", string(body)))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Inventory remove failed:", err)
Log.Debug("Inventory UUIDs >>", string(body), "<< successfully removed.")
}
// userManagementType is a struct to hold data retrieved from the database, used by several functions (including JSON).
type userManagementType struct {
Email zero.String
Password zero.String
}
// uiUserManagement creates a JSON representation of the Users table and spews it out.
func uiUserManagement(w http.ResponseWriter, r *http.Request) {
var (
rowArr []interface{}
UserManagement userManagementType
)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanic(err)
defer db.Close()
// query
rows, err := db.Query("SELECT * FROM Users")
checkErrPanic(err)
for rows.Next() {
err = rows.Scan(
&UserManagement.Email,
&UserManagement.Password,
)
rowArr = append(rowArr, UserManagement)
}
checkErr(err)
defer rows.Close()
if data, err := json.MarshalIndent(rowArr, "", " "); err != nil {
checkErr(err)
} else {
_, err := fmt.Fprintf(w, "%s", data)
checkErr(err)
}
// return
}
// uiUserManagementUpdate receives a JSON representation of one row (from the agGrid) in order to update our database.
func uiUserManagementUpdate(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
var user userManagementType
err = json.Unmarshal(body, &user)
checkErrPanic(err)
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
stmt, err := db.Prepare("REPLACE INTO Users (`Email`, `Password`) VALUES (?,?)")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(user.Email, user.Password)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Replace exec failed:", err)
// return
}
// uiUserManagementRemove receives a list of UUIDs to remove from the UserManagement table.
func uiUserManagementRemove(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
checkErrPanic(err)
// Log.Debug("\nInventory Body is >>", string(body), "<<")
db, err := sql.Open(PDO_Prefix, GoBotDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DELETE FROM Users WHERE Email IN (%s)", string(body)))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Users remove failed:", err)
Log.Debug("User(s) Email(s) >>", string(body), "<< successfully removed.")
}