forked from JustaPenguin/assetto-server-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_administration.go
437 lines (345 loc) · 11.7 KB
/
server_administration.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
package servermanager
import (
"encoding/json"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/mitchellh/go-wordwrap"
"github.com/sirupsen/logrus"
)
type ServerAdministrationHandler struct {
*BaseHandler
store Store
raceManager *RaceManager
championshipManager *ChampionshipManager
raceWeekendManager *RaceWeekendManager
process ServerProcess
acsrClient *ACSRClient
}
func NewServerAdministrationHandler(
baseHandler *BaseHandler,
store Store,
raceManager *RaceManager,
championshipManager *ChampionshipManager,
raceWeekendManager *RaceWeekendManager,
process ServerProcess,
acsrClient *ACSRClient,
) *ServerAdministrationHandler {
return &ServerAdministrationHandler{
BaseHandler: baseHandler,
store: store,
raceManager: raceManager,
championshipManager: championshipManager,
raceWeekendManager: raceWeekendManager,
process: process,
acsrClient: acsrClient,
}
}
type homeTemplateVars struct {
BaseTemplateVars
RaceDetails *CustomRace
PerformanceMode bool
}
// homeHandler serves content to /
func (sah *ServerAdministrationHandler) home(w http.ResponseWriter, r *http.Request) {
currentRace, entryList := sah.raceManager.CurrentRace()
var customRace *CustomRace
if currentRace != nil {
customRace = &CustomRace{EntryList: entryList, RaceConfig: currentRace.CurrentRaceConfig}
}
sah.viewRenderer.MustLoadTemplate(w, r, "home.html", &homeTemplateVars{
RaceDetails: customRace,
PerformanceMode: config.Server.PerformanceMode,
})
}
const MOTDFilename = "motd.txt"
type motdTemplateVars struct {
BaseTemplateVars
MOTDText string
Opts *GlobalServerConfig
}
func (sah *ServerAdministrationHandler) motd(w http.ResponseWriter, r *http.Request) {
opts, err := sah.store.LoadServerOptions()
if err != nil {
logrus.WithError(err).Error("couldn't load server options")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if r.Method == http.MethodPost {
wrapped := wordwrap.WrapString(r.FormValue("motd"), 140)
success := true
err := ioutil.WriteFile(filepath.Join(ServerInstallPath, MOTDFilename), []byte(wrapped), 0644)
if err != nil {
logrus.WithError(err).Error("couldn't save message of the day")
AddErrorFlash(w, r, "Failed to save message changes")
success = false
}
opts.ServerJoinMessage = r.FormValue("serverJoinMessage")
opts.ContentManagerWelcomeMessage = r.FormValue("contentManagerWelcomeMessage")
if err := sah.store.UpsertServerOptions(opts); err != nil {
logrus.WithError(err).Error("couldn't save messages")
AddErrorFlash(w, r, "Failed to save message changes")
success = false
}
if success {
AddFlash(w, r, "Messages successfully saved!")
}
}
b, err := ioutil.ReadFile(filepath.Join(ServerInstallPath, MOTDFilename))
if err != nil && !os.IsNotExist(err) {
logrus.WithError(err).Error("couldn't find motd.txt")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sah.viewRenderer.MustLoadTemplate(w, r, "server/motd.html", &motdTemplateVars{
MOTDText: string(b),
Opts: opts,
})
}
type currentCFGTemplateVars struct {
BaseTemplateVars
ConfigText string
EntryListText string
}
func (sah *ServerAdministrationHandler) currentConfig(w http.ResponseWriter, r *http.Request) {
config := &ServerConfig{}
entryList := &EntryList{}
configText, err := config.ReadString()
if err != nil {
logrus.WithError(err).Error("Couldn't load server config")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
entryListText, err := entryList.ReadString()
if err != nil {
logrus.WithError(err).Error("Couldn't load entry list")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sah.viewRenderer.MustLoadTemplate(w, r, "server/current-config.html", ¤tCFGTemplateVars{
ConfigText: configText,
EntryListText: entryListText,
})
}
type serverOptionsTemplateVars struct {
BaseTemplateVars
Form template.HTML
}
func (sah *ServerAdministrationHandler) options(w http.ResponseWriter, r *http.Request) {
serverOpts, err := sah.raceManager.LoadServerOptions()
if err != nil {
logrus.WithError(err).Errorf("couldn't load server options")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if r.Method == http.MethodPost {
err := DecodeFormData(serverOpts, r)
if err != nil {
logrus.WithError(err).Errorf("couldn't submit form")
}
UseShortenedDriverNames = serverOpts.UseShortenedDriverNames == 1
UseFallBackSorting = serverOpts.FallBackResultsSorting == 1
// save the config
err = sah.raceManager.SaveServerOptions(serverOpts)
if err != nil {
logrus.WithError(err).Errorf("couldn't save config")
AddErrorFlash(w, r, "Failed to save server options")
} else {
AddFlash(w, r, "Server options successfully saved!")
}
// update ACSR options to the client
sah.acsrClient.AccountID = serverOpts.ACSRAccountID
sah.acsrClient.APIKey = serverOpts.ACSRAPIKey
sah.acsrClient.Enabled = serverOpts.EnableACSR
}
form, err := EncodeFormData(serverOpts, r)
if err != nil {
logrus.WithError(err).Errorf("Couldn't encode form data")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sah.viewRenderer.MustLoadTemplate(w, r, "server/options.html", &serverOptionsTemplateVars{
Form: form,
})
}
type serverBlacklistTemplateVars struct {
BaseTemplateVars
Text string
}
func (sah *ServerAdministrationHandler) blacklist(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// save to blacklist.txt
var text string
if r.FormValue("type") == "single" {
// we're adding a single GUID, load the existing blacklist list then append
b, err := ioutil.ReadFile(filepath.Join(ServerInstallPath, "blacklist.txt"))
if err != nil {
logrus.WithError(err).Error("couldn't find blacklist.txt")
}
text = string(b) + r.FormValue("blacklist")
} else {
text = r.FormValue("blacklist")
}
if !strings.HasSuffix(text, "\n") {
text += "\n"
}
err := ioutil.WriteFile(filepath.Join(ServerInstallPath, "blacklist.txt"), []byte(text), 0644)
if err != nil {
logrus.WithError(err).Error("couldn't save blacklist")
AddErrorFlash(w, r, "Failed to save Server blacklist changes")
} else {
AddFlash(w, r, "Server blacklist successfully changed!")
}
}
// load blacklist.txt
b, err := ioutil.ReadFile(filepath.Join(ServerInstallPath, "blacklist.txt")) // just pass the file name
if err != nil {
logrus.WithError(err).Error("couldn't find blacklist.txt")
}
// render blacklist edit page
sah.viewRenderer.MustLoadTemplate(w, r, "server/blacklist.html", &serverBlacklistTemplateVars{
Text: string(b),
})
}
type autoFillEntrantListTemplateVars struct {
BaseTemplateVars
Entrants []*Entrant
}
func (sah *ServerAdministrationHandler) autoFillEntrantList(w http.ResponseWriter, r *http.Request) {
entrants, err := sah.raceManager.ListAutoFillEntrants()
if err != nil {
logrus.WithError(err).Error("could not list entrants")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sah.viewRenderer.MustLoadTemplate(w, r, "server/autofill-entrants.html", &autoFillEntrantListTemplateVars{
Entrants: entrants,
})
}
func (sah *ServerAdministrationHandler) autoFillEntrantDelete(w http.ResponseWriter, r *http.Request) {
err := sah.raceManager.store.DeleteEntrant(chi.URLParam(r, "entrantID"))
if err != nil {
logrus.WithError(err).Error("could not delete entrant")
AddErrorFlash(w, r, "Could not delete entrant")
} else {
AddFlash(w, r, "Successfully deleted entrant")
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
func (sah *ServerAdministrationHandler) logs(w http.ResponseWriter, r *http.Request) {
sah.viewRenderer.MustLoadTemplate(w, r, "server/logs.html", &BaseTemplateVars{
WideContainer: true,
})
}
type logData struct {
ServerLog, ManagerLog, PluginsLog string
}
func (sah *ServerAdministrationHandler) logsAPI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(logData{
ServerLog: sah.process.Logs(),
ManagerLog: logOutput.String(),
PluginsLog: pluginsOutput.String(),
})
}
// downloading logfiles
func (sah *ServerAdministrationHandler) logsDownload(w http.ResponseWriter, r *http.Request) {
logFile := chi.URLParam(r, "logFile")
var outputString string
if logFile == "server" {
outputString = sah.process.Logs()
} else if logFile == "manager" {
outputString = logOutput.String()
} else if logFile == "plugins" {
outputString = pluginsOutput.String()
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
// tell the browser this is a file download
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename= \""+logFile+"_"+time.Now().Format(time.RFC3339)+".log\"")
_, err := w.Write([]byte(outputString))
if err != nil {
logrus.WithError(err).Error("failed to return log " + logFile + " as file via http")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
// serverProcessHandler modifies the server process.
func (sah *ServerAdministrationHandler) serverProcess(w http.ResponseWriter, r *http.Request) {
var err error
var txt string
event := sah.process.Event()
switch chi.URLParam(r, "action") {
case "stop":
if event.IsChampionship() && !event.IsPractice() {
err = sah.championshipManager.StopActiveEvent()
} else if event.IsRaceWeekend() && !event.IsPractice() {
err = sah.raceWeekendManager.StopActiveSession()
} else {
err = sah.process.Stop()
}
txt = "stopped"
case "restart":
if event.IsChampionship() && !event.IsPractice() {
err = sah.championshipManager.RestartActiveEvent()
} else if event.IsRaceWeekend() && !event.IsPractice() {
err = sah.raceWeekendManager.RestartActiveSession()
} else {
err = sah.process.Restart()
}
txt = "restarted"
}
noun := "Server"
if event.IsChampionship() {
noun = "Championship"
} else if event.IsRaceWeekend() {
noun = "Race Weekend"
}
if event.IsPractice() {
noun += " Practice"
}
if err != nil {
logrus.WithError(err).Errorf("could not change " + noun + " status")
AddErrorFlash(w, r, "Unable to change "+noun+" status")
} else {
AddFlash(w, r, noun+" successfully "+txt)
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
type changelogTemplateVars struct {
BaseTemplateVars
Changelog template.HTML
}
func (sah *ServerAdministrationHandler) changelog(w http.ResponseWriter, r *http.Request) {
sah.viewRenderer.MustLoadTemplate(w, r, "changelog.html", &changelogTemplateVars{
Changelog: Changelog,
})
}
func (sah *ServerAdministrationHandler) robots(w http.ResponseWriter, r *http.Request) {
// do we want to let robots on the internet know things about us?!?
serverOpts, err := sah.store.LoadServerOptions()
if err != nil {
logrus.WithError(err).Errorf("couldn't load server options")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var response string
w.Header().Set("Content-Type", "text/plain")
if serverOpts.PreventWebCrawlers == 1 {
response = "User-agent: *\nDisallow: /"
} else {
response = "User-agent: *\nDisallow:"
}
_, err = w.Write([]byte(response))
if err != nil {
logrus.WithError(err).Errorf("couldn't write response text")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}