-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
content_cars.go
1297 lines (1024 loc) · 32.2 KB
/
content_cars.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package servermanager
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"math/rand"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/blevesearch/bleve"
"github.com/blevesearch/bleve/search/query"
"github.com/cj123/watcher"
"github.com/dimchansky/utfbom"
"github.com/go-chi/chi"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
type Car struct {
Name string
Skins []string
Tyres map[string]string
Details CarDetails
}
func (c Car) PrettyName() string {
return prettifyName(c.Name, true)
}
func (c Car) IsPaidDLC() bool {
if _, ok := isCarPaidDLC[c.Name]; ok {
return isCarPaidDLC[c.Name]
}
return false
}
func (c Car) IsMod() bool {
_, ok := isCarPaidDLC[c.Name]
return !ok
}
type Cars []*Car
func (cs Cars) AsMap() map[string][]string {
out := make(map[string][]string)
for _, car := range cs {
out[car.Name] = car.Skins
}
return out
}
type CarDetails struct {
Author string `json:"author"`
Brand string `json:"brand"`
Class string `json:"class"`
Country string `json:"country"`
Description string `json:"description"`
Name string `json:"name"`
PowerCurve [][]json.Number `json:"powerCurve"`
Specs CarSpecs `json:"specs"`
SpecsNumeric CarSpecsNumeric `json:"spec"`
Tags []string `json:"tags"`
TorqueCurve [][]json.Number `json:"torqueCurve"`
URL string `json:"url"`
Version string `json:"version"`
Year ShouldBeAnInt `json:"year"`
IsStock bool `json:"stock"`
IsDLC bool `json:"dlc"`
IsMod bool `json:"mod"`
Key string `json:"key"`
PrettifiedKey string `json:"prettified_key"`
DownloadURL string `json:"downloadURL"`
Notes string `json:"notes"`
}
// ShouldBeAnInt can be used in JSON struct definitions in places where the value provided should be an int, but isn't.
type ShouldBeAnInt int
func (i *ShouldBeAnInt) UnmarshalJSON(b []byte) error {
var number int
err := json.Unmarshal(b, &number)
if err != nil {
var str string
err := json.Unmarshal(b, &str)
if err != nil {
return err
}
*i = ShouldBeAnInt(formValueAsInt(str))
} else {
*i = ShouldBeAnInt(number)
}
return nil
}
func (cd *CarDetails) AddTag(name string) {
for _, tag := range cd.Tags {
if tag == name {
// tag exists
return
}
}
cd.Tags = append(cd.Tags, name)
}
func (cd *CarDetails) DelTag(name string) {
deleteIndex := -1
for index, tag := range cd.Tags {
if tag == name {
deleteIndex = index
}
}
if deleteIndex == -1 {
return
}
cd.Tags = append(cd.Tags[:deleteIndex], cd.Tags[deleteIndex+1:]...)
}
func (cd *CarDetails) Save(carName string) error {
uiDirectory := filepath.Join(ServerInstallPath, "content", "cars", carName, "ui")
err := os.MkdirAll(uiDirectory, 0755)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(uiDirectory, "ui_car.json"))
if err != nil {
return err
}
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
return enc.Encode(cd)
}
func (cd *CarDetails) Load(carName string) error {
f, err := os.Open(filepath.Join(ServerInstallPath, "content", "cars", carName, "ui", "ui_car.json"))
if err != nil {
return err
}
defer f.Close()
carDetailsBytes, err := ioutil.ReadAll(utfbom.SkipOnly(f))
if err != nil {
return err
}
carDetailsBytes = regexp.MustCompile(`\t*\r*\n*`).ReplaceAll(carDetailsBytes, []byte(""))
err = json.Unmarshal(carDetailsBytes, &cd)
if err != nil {
return err
}
cd.SpecsNumeric = cd.Specs.Numeric()
isDLC, isStock := isCarPaidDLC[carName]
cd.IsStock = isStock
cd.IsDLC = isDLC
cd.IsMod = !isStock && !isDLC
return nil
}
type CarSpecs struct {
Acceleration string `json:"acceleration"`
BHP string `json:"bhp"`
PWRatio string `json:"pwratio"`
TopSpeed string `json:"topspeed"`
Torque string `json:"torque"`
Weight string `json:"weight"`
}
type CarSpecsNumeric struct {
Acceleration int `json:"acceleration"`
BHP int `json:"bhp"`
PWRatio int `json:"pwratio"`
TopSpeed int `json:"topspeed"`
Torque int `json:"torque"`
Weight int `json:"weight"`
}
var keepNumericRegex = regexp.MustCompile(`[0-9]+`)
func toNumber(str string) int {
str = keepNumericRegex.FindString(str)
return formValueAsInt(str)
}
func (cs CarSpecs) Numeric() CarSpecsNumeric {
return CarSpecsNumeric{
Acceleration: toNumber(cs.Acceleration),
BHP: toNumber(cs.BHP),
PWRatio: toNumber(cs.PWRatio),
TopSpeed: toNumber(cs.TopSpeed),
Torque: toNumber(cs.Torque),
Weight: toNumber(cs.Weight),
}
}
type CarManager struct {
carIndex bleve.Index
watchFilesystemForCarChanges bool
searchMutex sync.Mutex
tyreUpdateMutex sync.Mutex
trackManager *TrackManager
}
func NewCarManager(trackManager *TrackManager, watchForCarChanges, useCarNameCache bool) *CarManager {
cm := &CarManager{trackManager: trackManager, watchFilesystemForCarChanges: watchForCarChanges}
if useCarNameCache {
cm.initCarNames()
}
return cm
}
type carNames map[string]string
var (
// carNameCache provides a map of car key -> actual name of a car
// this can be used to improve the accuracy of car naming in templates.
carNameCache carNames
carNameMutex sync.RWMutex
)
// adds the name of a car to the car details cache.
func (c carNames) add(car *Car) {
if c == nil {
return
}
carNameMutex.Lock()
defer carNameMutex.Unlock()
if car.Details.Name != "" {
carNameCache[car.Name] = car.Details.Name
}
}
// get a car name from the cache, if possible.
// if cache is not enabled, false is always returned.
func (c carNames) get(car string) (string, bool) {
if c == nil {
return "", false
}
carNameMutex.RLock()
defer carNameMutex.RUnlock()
name, ok := c[car]
return name, ok
}
// removes a car name from the cache.
func (c carNames) remove(car string) {
if c == nil {
return
}
carNameMutex.Lock()
defer carNameMutex.Unlock()
delete(carNameCache, car)
}
func (cm *CarManager) initCarNames() {
carNameCache = make(carNames)
cars, err := cm.ListCars()
if err != nil {
return
}
for _, car := range cars {
carNameCache.add(car)
}
}
// watchForChanges looks for created/removed files in the cars folder and (de-)indexes them as necessary
func (cm *CarManager) watchForCarChanges() error {
w := watcher.New()
err := w.Add(filepath.Join(ServerInstallPath, "content", "cars"))
if err != nil {
return err
}
w.SetMaxEvents(0)
w.FilterOps(watcher.Create, watcher.Remove)
w.AddFilterHook(func(info os.FileInfo, fullPath string) error {
if info.IsDir() && info.Name() != "cars" {
split := strings.Split(fullPath, fmt.Sprintf("%c", os.PathSeparator))
if len(split) > 0 && split[len(split)-2] == "cars" {
return nil // only fire the event for the car folder itself
}
}
return watcher.ErrSkip
})
go panicCapture(func() {
for {
select {
case event := <-w.Event:
var err error
var carName string
switch event.Op {
case watcher.Create, watcher.Write:
carName = filepath.Base(event.Path)
logrus.Infof("Indexing car: %s", carName)
car, err := cm.LoadCar(carName, nil)
if err != nil {
logrus.WithError(err).Errorf("Could not find car to index: %s", carName)
continue
}
err = cm.IndexCar(car)
if err != nil {
logrus.WithError(err).Errorf("Could not index car: %s", carName)
continue
}
case watcher.Remove:
carName = filepath.Base(event.OldPath)
logrus.Infof("De-indexing car: %s", carName)
err = cm.DeIndexCar(carName)
}
if err != nil {
logrus.WithError(err).Errorf("Could not update index for car: %s", carName)
continue
}
case err := <-w.Error:
logrus.WithError(err).Error("Car content watcher error")
continue
case <-w.Closed:
return
}
}
})
return w.Start(time.Second * 15)
}
func (cm *CarManager) ListCars() (Cars, error) {
var cars Cars
carFiles, err := ioutil.ReadDir(filepath.Join(ServerInstallPath, "content", "cars"))
if err != nil {
return nil, err
}
tyres, err := ListTyres()
if err != nil {
return nil, err
}
for _, carFile := range carFiles {
if !carFile.IsDir() {
continue
}
car, err := cm.LoadCar(carFile.Name(), tyres)
if err != nil && os.IsNotExist(err) {
continue
} else if err != nil {
return nil, err
}
cars = append(cars, car)
}
sort.Slice(cars, func(i, j int) bool {
return cars[i].PrettyName() < cars[j].PrettyName()
})
return cars, nil
}
// LoadCar reads a car from the content folder on the filesystem
func (cm *CarManager) LoadCar(name string, tyres Tyres) (*Car, error) {
carDirectory := filepath.Join(ServerInstallPath, "content", "cars", name)
skinFiles, err := ioutil.ReadDir(filepath.Join(carDirectory, "skins"))
var skins []string
if err == nil {
for _, skinFile := range skinFiles {
if !skinFile.IsDir() {
continue
}
skins = append(skins, skinFile.Name())
}
} else {
if os.IsNotExist(err) {
if err := os.Mkdir(filepath.Join(carDirectory, "skins"), 0755); err != nil && !os.IsNotExist(err) {
logrus.WithError(err).Warnf("Could not create skins directory for car: %s", name)
}
} else {
logrus.WithError(err).Warnf("Could not load skins for car: %s", name)
}
}
carDetails := CarDetails{}
if err := carDetails.Load(name); err != nil {
if !os.IsNotExist(err) {
logrus.WithError(err).Errorf("could not parse car details json for: %s (likely this is invalid/malformed JSON). falling back to empty car details", name)
}
// the car details don't exist or can't be loaded, just create some fake ones.
carDetails.Name = prettifyName(name, true)
}
carDetails.Key = name
carDetails.PrettifiedKey = prettifyName(name, true)
return &Car{
Name: name,
Skins: skins,
Tyres: tyres[name],
Details: carDetails,
}, nil
}
func (cm *CarManager) RandomSkin(model string) string {
car, err := cm.LoadCar(model, nil)
switch {
case err != nil:
logrus.WithError(err).Errorf("Could not load car %s. No skin will be specified", model)
return ""
case len(car.Skins) == 0:
logrus.Warnf("Car %s has no skins uploaded. No skin will be specified", model)
return ""
default:
return car.Skins[rand.Intn(len(car.Skins))]
}
}
// ResultsForCar finds results for a given car.
func (cm *CarManager) ResultsForCar(car string) ([]SessionResults, error) {
results, err := ListAllResults()
if err != nil {
return nil, err
}
var out []SessionResults
for _, result := range results {
hasCar := false
for _, driver := range result.Result {
if driver.CarModel == car {
hasCar = true
break
}
}
if hasCar {
out = append(out, result)
}
}
return out, nil
}
// DeleteCar removes a car from the file system and search index.
func (cm *CarManager) DeleteCar(carName string) error {
carsPath := filepath.Join(ServerInstallPath, "content", "cars")
existingCars, err := cm.ListCars()
if err != nil {
return err
}
for _, car := range existingCars {
if car.Name != carName {
continue
}
err := os.RemoveAll(filepath.Join(carsPath, carName))
if err != nil {
return err
}
break
}
return cm.DeIndexCar(carName)
}
const searchPageSize = 50
// CreateSearchIndex builds a search index for the cars
func (cm *CarManager) CreateOrOpenSearchIndex() error {
cm.searchMutex.Lock()
indexPath := filepath.Join(ServerInstallPath, "search-index", "cars")
var err error
cm.carIndex, err = bleve.Open(indexPath)
cm.searchMutex.Unlock()
if err == bleve.ErrorIndexPathDoesNotExist {
logrus.Infof("Creating car search index")
indexMapping := bleve.NewIndexMapping()
cm.carIndex, err = bleve.New(indexPath, indexMapping)
if err != nil {
return err
}
err = cm.IndexAllCars()
if err != nil {
return err
}
} else if err != nil {
return err
}
if cm.watchFilesystemForCarChanges {
go panicCapture(func() {
err := cm.watchForCarChanges()
if err != nil {
logrus.WithError(err).Error("Could not watch for changes in the content/cars directory")
}
})
}
return nil
}
func (cm *CarManager) UpdateTyres(car *Car) error {
if car.Name == "" {
return nil
}
cm.tyreUpdateMutex.Lock()
defer cm.tyreUpdateMutex.Unlock()
carPath := filepath.Join(ServerInstallPath, "content", "cars", car.Name)
acdPath := filepath.Join(carPath, "data.acd")
b, err := ioutil.ReadFile(acdPath)
if err == nil {
return addTyresFromDataACD(acdPath, b)
} else if !os.IsNotExist(err) {
return err
}
tyresIniPath := filepath.Join(carPath, "data", "tyres.ini")
b, err = ioutil.ReadFile(tyresIniPath)
if err != nil {
return err
}
return addTyresFromTyresIni(tyresIniPath, b)
}
// IndexCar indexes an individual car.
func (cm *CarManager) IndexCar(car *Car) error {
carNameCache.add(car)
if err := cm.UpdateTyres(car); err != nil {
logrus.WithError(err).Errorf("Could not update tyres for car: %s", car.Name)
}
return cm.carIndex.Index(car.Name, car.Details)
}
// DeIndexCar removes a car from the index.
func (cm *CarManager) DeIndexCar(name string) error {
carNameCache.remove(name)
return cm.carIndex.Delete(name)
}
// IndexAllCars loads all current cars and adds them to the search index
func (cm *CarManager) IndexAllCars() error {
logrus.Infof("Building search index for all cars")
started := time.Now()
results, _, err := cm.Search(context.Background(), "", 0, 100000)
if err == nil {
errs, _ := errgroup.WithContext(context.Background())
for _, result := range results.Hits {
result := result
errs.Go(func() error {
return cm.DeIndexCar(result.ID)
})
}
if err := errs.Wait(); err != nil {
return err
}
} else {
logrus.WithError(err).Warnf("could not de-index cars")
}
cars, err := cm.ListCars()
if err != nil {
return err
}
errs, _ := errgroup.WithContext(context.Background())
for _, car := range cars {
car := car
errs.Go(func() error {
return cm.IndexCar(car)
})
}
if err := errs.Wait(); err != nil {
return err
}
logrus.Infof("Search index build is complete (took: %s)", time.Since(started).String())
return nil
}
var (
positiveCarTypeRegex = regexp.MustCompile(`\+(mod|dlc|stock)`)
negativeCarTypeRegex = regexp.MustCompile(`-(mod|dlc|stock)`)
)
func (cm *CarManager) rebuildTerm(term string) string {
// bleve only allows searching for true/false via the ugly terms
// e.g. dlc:T* - make these a bit more user friendly (e.g. +dlc)
term = positiveCarTypeRegex.ReplaceAllString(term, "$1:T*")
term = negativeCarTypeRegex.ReplaceAllString(term, "$1:F*")
return term
}
// Search looks for cars in the search index.
func (cm *CarManager) Search(ctx context.Context, term string, from, size int) (*bleve.SearchResult, Cars, error) {
cm.searchMutex.Lock()
defer cm.searchMutex.Unlock()
var q query.Query
term = cm.rebuildTerm(term)
if term == "" {
q = bleve.NewMatchAllQuery()
} else {
q = bleve.NewQueryStringQuery(term)
}
request := bleve.NewSearchRequestOptions(q, size, from, false)
results, err := cm.carIndex.SearchInContext(ctx, request)
if err != nil {
return nil, nil, err
}
var cars Cars
for _, hit := range results.Hits {
if hit.ID == "cars" {
continue
}
car, err := cm.LoadCar(hit.ID, nil)
if err != nil {
return nil, nil, errors.Wrap(err, hit.ID)
}
cars = append(cars, car)
}
return results, cars, nil
}
func (cm *CarManager) AddTag(carName, tag string) error {
car, err := cm.LoadCar(carName, nil)
if err != nil {
return err
}
car.Details.AddTag(tag)
return cm.SaveCarDetails(carName, car)
}
func (cm *CarManager) DelTag(carName, tag string) error {
car, err := cm.LoadCar(carName, nil)
if err != nil {
return err
}
car.Details.DelTag(tag)
return cm.SaveCarDetails(carName, car)
}
// SaveCarDetails saves a car's details, and indexes that car.
func (cm *CarManager) SaveCarDetails(carName string, car *Car) error {
if err := car.Details.Save(carName); err != nil {
return err
}
return cm.IndexCar(car)
}
type carDetailsTemplateVars struct {
BaseTemplateVars
Car *Car
Results []SessionResults
Setups map[string][]string
TrackOpts []Track
}
// loadCarDetailsForTemplate loads all necessary items to generate the car details template.
func (cm *CarManager) loadCarDetailsForTemplate(carName string) (*carDetailsTemplateVars, error) {
tyres, err := ListTyres()
if err != nil {
return nil, err
}
car, err := cm.LoadCar(carName, tyres)
if err != nil {
return nil, err
}
results, err := cm.ResultsForCar(carName)
if err != nil {
return nil, err
}
setups, err := ListSetupsForCar(carName)
if err != nil {
return nil, err
}
tracks, err := cm.trackManager.ListTracks()
if err != nil {
return nil, err
}
return &carDetailsTemplateVars{
Car: car,
Results: results,
Setups: setups,
TrackOpts: tracks,
}, nil
}
func (cm *CarManager) UpdateCarMetadata(carName string, r *http.Request) error {
car, err := cm.LoadCar(carName, nil)
if err != nil {
return err
}
car.Details.Notes = r.FormValue("Notes")
car.Details.DownloadURL = r.FormValue("DownloadURL")
return car.Details.Save(carName)
}
func (cm *CarManager) UploadSkin(carName string, files map[string][]*multipart.FileHeader) error {
carDirectory := filepath.Join(ServerInstallPath, "content", "cars", carName, "skins")
for _, files := range files {
for _, fh := range files {
if err := cm.uploadSkinFile(carDirectory, fh); err != nil {
return err
}
}
}
return nil
}
func (cm *CarManager) uploadSkinFile(carDirectory string, header *multipart.FileHeader) error {
r, err := header.Open()
if err != nil {
return err
}
defer r.Close()
fileDirectory := filepath.Join(carDirectory, filepath.Dir(header.Filename))
if err := os.MkdirAll(fileDirectory, 0755); err != nil {
return err
}
w, err := os.Create(filepath.Join(fileDirectory, filepath.Base(header.Filename)))
if err != nil {
return err
}
defer w.Close()
_, err = io.Copy(w, r)
return err
}
func (cm *CarManager) DeleteSkin(car, skin string) error {
return os.RemoveAll(filepath.Join(ServerInstallPath, "content", "cars", car, "skins", skin))
}
type CarsHandler struct {
*BaseHandler
carManager *CarManager
}
func NewCarsHandler(baseHandler *BaseHandler, carManager *CarManager) *CarsHandler {
return &CarsHandler{
BaseHandler: baseHandler,
carManager: carManager,
}
}
type carListTemplateVars struct {
BaseTemplateVars
Results *bleve.SearchResult
Cars Cars
Query string
CurrentPage int
NumPages int
PageSize int
}
func (ch *CarsHandler) list(w http.ResponseWriter, r *http.Request) {
searchTerm := r.URL.Query().Get("q")
page := formValueAsInt(r.URL.Query().Get("page"))
results, cars, err := ch.carManager.Search(r.Context(), searchTerm, page*searchPageSize, searchPageSize)
if err != nil {
logrus.WithError(err).Error("Could not perform search")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
numPages := int(math.Ceil(float64(results.Total) / float64(searchPageSize)))
ch.viewRenderer.MustLoadTemplate(w, r, "content/cars.html", &carListTemplateVars{
Results: results,
Cars: cars,
Query: searchTerm,
CurrentPage: page,
NumPages: numPages,
PageSize: searchPageSize,
})
}
type carSearchResult struct {
CarName string `json:"CarName"`
CarID string `json:"CarID"`
Class string `json:"Class"`
// Tags []string `json:"Tags"`
}
func (ch *CarsHandler) searchJSON(w http.ResponseWriter, r *http.Request) {
searchTerm := r.URL.Query().Get("q")
_, cars, err := ch.carManager.Search(r.Context(), searchTerm, 0, 100000)
if err != nil {
logrus.WithError(err).Error("Could not perform search")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var searchResults []carSearchResult
for _, car := range cars {
var class string
if car.IsPaidDLC() {
class = "bg-dlc"
}
if car.IsMod() {
class = "bg-mod"
}
searchResults = append(searchResults, carSearchResult{
CarName: car.Details.Name,
CarID: car.Name,
Class: class,
// Tags: car.Details.Tags,
})
}
enc := json.NewEncoder(w)
if Debug {
enc.SetIndent("", " ")
}
_ = enc.Encode(searchResults)
}
func (ch *CarsHandler) delete(w http.ResponseWriter, r *http.Request) {
carName := chi.URLParam(r, "name")
err := ch.carManager.DeleteCar(carName)
if err != nil {
logrus.WithError(err).Errorf("Could not delete car: %s", carName)
AddErrorFlash(w, r, "couldn't get car list")
http.Redirect(w, r, r.Referer(), http.StatusFound)
return
}
AddFlash(w, r, fmt.Sprintf("Car %s successfully deleted!", carName))
http.Redirect(w, r, "/cars", http.StatusFound)
}
const defaultSkinURL = "/static/img/no-preview-car.png"
func carSkinURL(car, skin string) string {
skinPath := filepath.Join("content", "cars", car, "skins", url.PathEscape(skin), "preview.jpg")
// look to see if the car preview image exists
_, err := os.Stat(filepath.Join(ServerInstallPath, filepath.Join("content", "cars", car, "skins", skin, "preview.jpg")))