forked from Luzifer/ed-fast-travel
/
web.go
359 lines (298 loc) · 8.63 KB
/
web.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
package main
import (
"context"
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"time"
"github.com/Luzifer/go_helpers/github"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/nicksnyder/go-i18n/i18n"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Maximum message size allowed from peer.
maxMessageSize = 8192
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Number of concurrent calculations per socket
calculationPoolSize = 3
)
var upgrader = websocket.Upgrader{}
type routeRequest struct {
StartSystemID int64 `json:"start_system_id"`
TargetSystemID int64 `json:"target_system_id"`
RouteRequestID string `json:"route_request_id"`
StopDistance float64 `json:"stop_distance"`
}
type routeResponse struct {
Counter int64 `json:"counter"`
Success bool `json:"success"`
ErrorMessage string `json:"error_message"`
RouteRequestID string `json:"route_request_id"`
Result traceResult `json:"result"`
}
type jsonResponse struct {
Success bool `json:"success"`
ErrorMessage string `json:"error_message"`
Data map[string]interface{} `json:"data"`
}
func (j jsonResponse) Send(res http.ResponseWriter, cachingAllowed bool) error {
res.Header().Set("Content-Type", "application/json")
if cachingAllowed {
res.Header().Set("Cache-Control", "public, max-age=3600")
} else {
res.Header().Set("Cache-Control", "no-cache")
}
return json.NewEncoder(res).Encode(j)
}
func startWebService() {
r := mux.NewRouter()
r.HandleFunc("/", handleFrontend)
r.HandleFunc("/assets/application.js", handleJS)
r.HandleFunc("/api/system-by-name", handleSystemByName)
r.HandleFunc("/api/route", handleRouteSocket)
r.HandleFunc("/api/control/shutdown", handleShutdown)
r.HandleFunc("/api/control/update", handleUpdate)
r.HandleFunc("/api/control/update-database", handleUpdateDatabase)
verboseLog("Webserver started and listening on %s", cfg.Listen)
log.Fatalf("Unable to listen for web connections: %s", http.ListenAndServe(cfg.Listen, r))
}
func getTranslator(r *http.Request) i18n.TranslateFunc {
c, _ := r.Cookie("lang")
var cookieLang string
if c != nil {
cookieLang = c.Value
}
acceptLang := r.Header.Get("Accept-Language")
defaultLang := "en-US" // known valid language
T, _ := i18n.Tfunc(cookieLang, acceptLang, defaultLang)
return T
}
func handleFrontend(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
frontend, err := Asset("assets/frontend.html")
if err != nil {
http.Error(res, "Could not load frontend: "+err.Error(), http.StatusInternalServerError)
return
}
tpl, err := template.New("frontend").Funcs(template.FuncMap{"T": T}).Parse(string(frontend))
if err != nil {
http.Error(res, "Could not parse frontend: "+err.Error(), http.StatusInternalServerError)
return
}
if err := tpl.Execute(res, map[string]interface{}{
"version": version,
"disableSoftwareControl": cfg.DisableSoftwareControl,
}); err != nil {
http.Error(res, "Could not execute frontend: "+err.Error(), http.StatusInternalServerError)
return
}
}
func handleJS(res http.ResponseWriter, r *http.Request) {
js, _ := Asset("assets/application.js")
res.Header().Set("Content-Type", "application/javascript")
res.Write(js)
}
func handleShutdown(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
defer os.Exit(0)
jsonResponse{
Success: true,
ErrorMessage: T("warn_service_will_shutdown"),
}.Send(res, false)
<-time.After(time.Second) // Give the response a second to send
}
func handleUpdate(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
updater, err := github.NewUpdater(autoUpdateRepo, version)
if err != nil {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_new_version_found"),
}.Send(res, false)
log.Printf("Could not initialize update engine: %s", err)
return
}
if hasUpdate, err := updater.HasUpdate(true); err != nil {
jsonResponse{
Success: false,
ErrorMessage: err.Error(),
}.Send(res, false)
return
} else {
if !hasUpdate {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_new_version_found"),
}.Send(res, false)
return
}
}
if err := updater.Apply(); err != nil {
jsonResponse{
Success: false,
ErrorMessage: err.Error(),
}.Send(res, false)
} else {
jsonResponse{
Success: true,
ErrorMessage: T("warn_service_update_success"),
}.Send(res, false)
}
}
func handleUpdateDatabase(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
if err := refreshEDSMData(); err != nil {
jsonResponse{
Success: false,
ErrorMessage: T("warn_database_update_failed"),
}.Send(res, false)
log.Printf("Database update failed: %s", err)
return
}
jsonResponse{
Success: true,
ErrorMessage: T("warn_database_update_success"),
}.Send(res, false)
}
func handleSystemByName(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
search := r.URL.Query().Get("system_name")
if len(search) < 3 {
jsonResponse{
Success: false,
ErrorMessage: T("warn_too_few_characers"),
}.Send(res, true)
return
}
if sys := starSystems.GetSystemByName(search); sys != nil {
jsonResponse{
Success: true,
Data: map[string]interface{}{
"system": sys,
},
}.Send(res, true)
} else {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_matching_system_found"),
}.Send(res, true)
return
}
}
func handleRouteSocket(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
// In case socket quits also quit all child operations
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ws, err := upgrader.Upgrade(res, r, nil)
if err != nil {
http.Error(res, "Could not open socket", http.StatusInternalServerError)
return
}
defer ws.Close()
doneChan := make(chan struct{})
defer close(doneChan)
go pingSocket(ws, doneChan)
messageChan := make(chan routeResponse, 500)
defer close(messageChan)
go func(ws *websocket.Conn, m chan routeResponse) {
for msg := range m {
ws.WriteJSON(msg)
}
}(ws, messageChan)
ws.SetReadLimit(maxMessageSize)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
calculationPool := make(chan *struct{}, calculationPoolSize)
for {
msg := routeRequest{}
if err := ws.ReadJSON(&msg); err != nil {
log.Printf("Experienced error: %s", err)
break
}
if msg.RouteRequestID == "" || msg.StartSystemID == 0 || msg.TargetSystemID == 0 {
messageChan <- routeResponse{
Success: false,
ErrorMessage: T("warn_required_field_missing"),
}
continue
}
if msg.StopDistance < cfg.WebRouteStopMin {
messageChan <- routeResponse{
Success: false,
ErrorMessage: T("warn_stop_distance_too_small", cfg),
}
continue
}
go processSocketRouting(ctx, messageChan, msg, calculationPool)
}
cancel()
}
func processSocketRouting(parentCtx context.Context, msgChan chan routeResponse, r routeRequest, calculationPool chan *struct{}) {
start := starSystems.GetSystemByID(r.StartSystemID)
target := starSystems.GetSystemByID(r.TargetSystemID)
calculationPool <- nil
defer func() { <-calculationPool }()
ctx, cancel := context.WithTimeout(parentCtx, cfg.WebRouteTimeout)
defer cancel()
rChan, eChan := starSystems.CalculateRoute(ctx, start, target, r.StopDistance)
var counter int64
for {
select {
case stop, ok := <-rChan:
if ok {
msgChan <- routeResponse{
Counter: counter,
Success: true,
RouteRequestID: r.RouteRequestID,
Result: stop,
}
if stop.TraceType == traceTypeFlightStop {
counter++
}
} else {
return
}
case err := <-eChan:
if err != nil {
msgChan <- routeResponse{
Success: false,
ErrorMessage: err.Error(),
}
return
}
}
}
}
func pingSocket(ws *websocket.Conn, done chan struct{}) {
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait))
case <-done:
return
}
}
}