...
1
9
10 package openapi
11
12 import (
13 "context"
14 "fmt"
15 "io"
16 "log"
17 "math"
18 "net/http"
19 "os"
20 "time"
21
22 "go.formulabun.club/functional/array"
23 "go.formulabun.club/replays/store"
24 "go.formulabun.club/srb2kart/lump/replay"
25 )
26
27
28
29
30 type DefaultApiService struct {
31 db store.Client
32 }
33
34
35 func NewDefaultApiService() DefaultApiServicer {
36 c, err := store.NewClient()
37 for err != nil {
38 log.Printf("Could not establish database connection %s", err)
39 <-time.After(time.Second * 5)
40 c, err = store.NewClient()
41 }
42 log.Print("Database connection established.")
43 return &DefaultApiService{c}
44 }
45
46
47 func (s *DefaultApiService) ListGet(ctx context.Context) (ImplResponse, error) {
48 entries, err := os.ReadDir("/data")
49 if err != nil {
50 return Response(http.StatusInternalServerError, err), err
51 }
52
53 files := array.Map(entries, func(entry os.DirEntry) string {
54 return entry.Name()
55 })
56
57 return Response(http.StatusOK, files), nil
58 }
59
60
61 func (s *DefaultApiService) RootPost(ctx context.Context, data io.ReadCloser) (ImplResponse, error) {
62 header, err := replay.ReadReplay(data)
63 if err != nil {
64 return Response(http.StatusBadRequest, nil), err
65 }
66
67 if header.Time == math.MaxUint32 {
68 return Response(http.StatusBadRequest, "this replay is unfinished"), nil
69 }
70
71 id, err := s.db.InsertReplayRaw(header)
72 if err != nil {
73 if store.DuplicateEntryError.Is(err) {
74 return Response(http.StatusConflict, "This replay is already present in the database"), fmt.Errorf("Could not save replay to db: %s", err)
75 }
76 return Response(http.StatusInternalServerError, "Internal Server Error"), fmt.Errorf("Could not save replay to db: %s", err)
77 }
78
79 fileName := fmt.Sprintf("/data/%d", id)
80 _, err = os.Stat(fileName)
81 if err == nil {
82 log.Printf("File with path '%s' already exists", fileName)
83 return Response(http.StatusConflict, "File already exists"), nil
84 }
85
86 file, err := os.Create(fileName)
87 if err != nil {
88 return Response(http.StatusInternalServerError, "Could not save replay file"), err
89 }
90
91 err = header.Write(file)
92 if err != nil {
93 return Response(http.StatusInternalServerError, "Could not save replay file"), fmt.Errorf("Could not write the replay file: %s", err)
94 }
95
96 _, err = io.Copy(file, data)
97 if err != nil {
98 return Response(http.StatusInternalServerError, "Could not save replay file"), fmt.Errorf("Could not write the replay file: %s", err)
99 }
100
101 return Response(http.StatusOK, id), nil
102 }
103
View as plain text