blob: 93ee12874498c63a209f5f28651ff8b1a6243390 [file] [log] [blame]
Philipp Schradercdb5cfc2022-02-20 14:57:07 -08001package requests
2
3import (
Philipp Schraderd3fac192022-03-02 20:35:46 -08004 "errors"
Philipp Schradercdb5cfc2022-02-20 14:57:07 -08005 "fmt"
6 "io"
7 "net/http"
Philipp Schraderd3fac192022-03-02 20:35:46 -08008 "strconv"
9 "strings"
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080010
Philipp Schrader8747f1b2022-02-23 23:56:22 -080011 "github.com/frc971/971-Robot-Code/scouting/db"
Philipp Schraderd3fac192022-03-02 20:35:46 -080012 "github.com/frc971/971-Robot-Code/scouting/scraping"
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080013 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/error_response"
Philipp Schraderd3fac192022-03-02 20:35:46 -080014 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/refresh_match_list"
15 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/refresh_match_list_response"
Philipp Schradercbf5c6a2022-02-27 23:25:19 -080016 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_all_matches"
17 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_all_matches_response"
Philipp Schraderacf96232022-03-01 22:03:30 -080018 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_data_scouting"
19 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_data_scouting_response"
Philipp Schraderd1c4bef2022-02-28 22:51:30 -080020 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_matches_for_team"
21 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/request_matches_for_team_response"
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080022 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/submit_data_scouting"
23 _ "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/submit_data_scouting_response"
24 "github.com/frc971/971-Robot-Code/scouting/webserver/server"
25 flatbuffers "github.com/google/flatbuffers/go"
26)
27
Philipp Schradercbf5c6a2022-02-27 23:25:19 -080028type SubmitDataScouting = submit_data_scouting.SubmitDataScouting
29type RequestAllMatches = request_all_matches.RequestAllMatches
30type RequestAllMatchesResponseT = request_all_matches_response.RequestAllMatchesResponseT
Philipp Schraderd1c4bef2022-02-28 22:51:30 -080031type RequestMatchesForTeam = request_matches_for_team.RequestMatchesForTeam
32type RequestMatchesForTeamResponseT = request_matches_for_team_response.RequestMatchesForTeamResponseT
Philipp Schraderacf96232022-03-01 22:03:30 -080033type RequestDataScouting = request_data_scouting.RequestDataScouting
34type RequestDataScoutingResponseT = request_data_scouting_response.RequestDataScoutingResponseT
Philipp Schraderd3fac192022-03-02 20:35:46 -080035type RefreshMatchList = refresh_match_list.RefreshMatchList
36type RefreshMatchListResponseT = refresh_match_list_response.RefreshMatchListResponseT
Philipp Schradercbf5c6a2022-02-27 23:25:19 -080037
Philipp Schrader8747f1b2022-02-23 23:56:22 -080038// The interface we expect the database abstraction to conform to.
39// We use an interface here because it makes unit testing easier.
40type Database interface {
41 AddToMatch(db.Match) error
42 AddToStats(db.Stats) error
43 ReturnMatches() ([]db.Match, error)
44 ReturnStats() ([]db.Stats, error)
Philipp Schraderd1c4bef2022-02-28 22:51:30 -080045 QueryMatches(int32) ([]db.Match, error)
Philipp Schrader8747f1b2022-02-23 23:56:22 -080046 QueryStats(int) ([]db.Stats, error)
47}
48
Philipp Schraderd3fac192022-03-02 20:35:46 -080049type ScrapeMatchList func(int32, string) ([]scraping.Match, error)
50
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080051// Handles unknown requests. Just returns a 404.
52func unknown(w http.ResponseWriter, req *http.Request) {
53 w.WriteHeader(http.StatusNotFound)
54}
55
56func respondWithError(w http.ResponseWriter, statusCode int, errorMessage string) {
57 builder := flatbuffers.NewBuilder(1024)
58 builder.Finish((&error_response.ErrorResponseT{
59 ErrorMessage: errorMessage,
60 }).Pack(builder))
61 w.WriteHeader(statusCode)
62 w.Write(builder.FinishedBytes())
63}
64
65func respondNotImplemented(w http.ResponseWriter) {
66 respondWithError(w, http.StatusNotImplemented, "")
67}
68
69// TODO(phil): Can we turn this into a generic?
Philipp Schradercbf5c6a2022-02-27 23:25:19 -080070func parseSubmitDataScouting(w http.ResponseWriter, buf []byte) (*SubmitDataScouting, bool) {
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080071 success := true
72 defer func() {
73 if r := recover(); r != nil {
74 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse SubmitDataScouting: %v", r))
75 success = false
76 }
77 }()
78 result := submit_data_scouting.GetRootAsSubmitDataScouting(buf, 0)
79 return result, success
80}
81
82// Handles a SubmitDataScouting request.
Philipp Schrader8747f1b2022-02-23 23:56:22 -080083type submitDataScoutingHandler struct {
84 db Database
85}
86
87func (handler submitDataScoutingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Philipp Schradercdb5cfc2022-02-20 14:57:07 -080088 requestBytes, err := io.ReadAll(req.Body)
89 if err != nil {
90 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
91 return
92 }
93
94 _, success := parseSubmitDataScouting(w, requestBytes)
95 if !success {
96 return
97 }
98
99 // TODO(phil): Actually handle the request.
Philipp Schrader8747f1b2022-02-23 23:56:22 -0800100 // We have access to the database via "handler.db" here. For example:
101 // stats := handler.db.ReturnStats()
Philipp Schradercdb5cfc2022-02-20 14:57:07 -0800102
103 respondNotImplemented(w)
104}
105
Philipp Schradercbf5c6a2022-02-27 23:25:19 -0800106// TODO(phil): Can we turn this into a generic?
107func parseRequestAllMatches(w http.ResponseWriter, buf []byte) (*RequestAllMatches, bool) {
108 success := true
109 defer func() {
110 if r := recover(); r != nil {
111 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse SubmitDataScouting: %v", r))
112 success = false
113 }
114 }()
115 result := request_all_matches.GetRootAsRequestAllMatches(buf, 0)
116 return result, success
117}
118
119// Handles a RequestAllMaches request.
120type requestAllMatchesHandler struct {
121 db Database
122}
123
124func (handler requestAllMatchesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
125 requestBytes, err := io.ReadAll(req.Body)
126 if err != nil {
127 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
128 return
129 }
130
131 _, success := parseRequestAllMatches(w, requestBytes)
132 if !success {
133 return
134 }
135
136 matches, err := handler.db.ReturnMatches()
137 if err != nil {
138 respondWithError(w, http.StatusInternalServerError, fmt.Sprint("Faled to query database: ", err))
Philipp Schrader2e7eb0002022-03-02 22:52:39 -0800139 return
Philipp Schradercbf5c6a2022-02-27 23:25:19 -0800140 }
141
142 var response RequestAllMatchesResponseT
143 for _, match := range matches {
144 response.MatchList = append(response.MatchList, &request_all_matches_response.MatchT{
145 MatchNumber: match.MatchNumber,
146 Round: match.Round,
147 CompLevel: match.CompLevel,
148 R1: match.R1,
149 R2: match.R2,
150 R3: match.R3,
151 B1: match.B1,
152 B2: match.B2,
153 B3: match.B3,
154 })
155 }
156
157 builder := flatbuffers.NewBuilder(50 * 1024)
158 builder.Finish((&response).Pack(builder))
159 w.Write(builder.FinishedBytes())
160}
161
Philipp Schraderd1c4bef2022-02-28 22:51:30 -0800162// TODO(phil): Can we turn this into a generic?
163func parseRequestMatchesForTeam(w http.ResponseWriter, buf []byte) (*RequestMatchesForTeam, bool) {
164 success := true
165 defer func() {
166 if r := recover(); r != nil {
167 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse SubmitDataScouting: %v", r))
168 success = false
169 }
170 }()
171 result := request_matches_for_team.GetRootAsRequestMatchesForTeam(buf, 0)
172 return result, success
173}
174
175// Handles a RequestMatchesForTeam request.
176type requestMatchesForTeamHandler struct {
177 db Database
178}
179
180func (handler requestMatchesForTeamHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
181 requestBytes, err := io.ReadAll(req.Body)
182 if err != nil {
183 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
184 return
185 }
186
187 request, success := parseRequestMatchesForTeam(w, requestBytes)
188 if !success {
189 return
190 }
191
192 matches, err := handler.db.QueryMatches(request.Team())
193 if err != nil {
194 respondWithError(w, http.StatusInternalServerError, fmt.Sprint("Faled to query database: ", err))
Philipp Schrader2e7eb0002022-03-02 22:52:39 -0800195 return
Philipp Schraderd1c4bef2022-02-28 22:51:30 -0800196 }
197
198 var response RequestAllMatchesResponseT
199 for _, match := range matches {
200 response.MatchList = append(response.MatchList, &request_all_matches_response.MatchT{
201 MatchNumber: match.MatchNumber,
202 Round: match.Round,
203 CompLevel: match.CompLevel,
204 R1: match.R1,
205 R2: match.R2,
206 R3: match.R3,
207 B1: match.B1,
208 B2: match.B2,
209 B3: match.B3,
210 })
211 }
212
213 builder := flatbuffers.NewBuilder(50 * 1024)
214 builder.Finish((&response).Pack(builder))
215 w.Write(builder.FinishedBytes())
216}
217
Philipp Schraderacf96232022-03-01 22:03:30 -0800218// TODO(phil): Can we turn this into a generic?
219func parseRequestDataScouting(w http.ResponseWriter, buf []byte) (*RequestDataScouting, bool) {
220 success := true
221 defer func() {
222 if r := recover(); r != nil {
223 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse SubmitDataScouting: %v", r))
224 success = false
225 }
226 }()
227 result := request_data_scouting.GetRootAsRequestDataScouting(buf, 0)
228 return result, success
229}
230
231// Handles a RequestDataScouting request.
232type requestDataScoutingHandler struct {
233 db Database
234}
235
236func (handler requestDataScoutingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
237 requestBytes, err := io.ReadAll(req.Body)
238 if err != nil {
239 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
240 return
241 }
242
243 _, success := parseRequestDataScouting(w, requestBytes)
244 if !success {
245 return
246 }
247
248 stats, err := handler.db.ReturnStats()
249 if err != nil {
250 respondWithError(w, http.StatusInternalServerError, fmt.Sprint("Faled to query database: ", err))
Philipp Schrader2e7eb0002022-03-02 22:52:39 -0800251 return
Philipp Schraderacf96232022-03-01 22:03:30 -0800252 }
253
254 var response RequestDataScoutingResponseT
255 for _, stat := range stats {
256 response.StatsList = append(response.StatsList, &request_data_scouting_response.StatsT{
257 Team: stat.TeamNumber,
258 Match: stat.MatchNumber,
259 MissedShotsAuto: stat.ShotsMissedAuto,
260 UpperGoalAuto: stat.UpperGoalAuto,
261 LowerGoalAuto: stat.LowerGoalAuto,
262 MissedShotsTele: stat.ShotsMissed,
263 UpperGoalTele: stat.UpperGoalShots,
264 LowerGoalTele: stat.LowerGoalShots,
265 DefenseRating: stat.PlayedDefense,
266 Climbing: stat.Climbing,
267 })
268 }
269
270 builder := flatbuffers.NewBuilder(50 * 1024)
271 builder.Finish((&response).Pack(builder))
272 w.Write(builder.FinishedBytes())
273}
274
Philipp Schraderd3fac192022-03-02 20:35:46 -0800275// TODO(phil): Can we turn this into a generic?
276func parseRefreshMatchList(w http.ResponseWriter, buf []byte) (*RefreshMatchList, bool) {
277 success := true
278 defer func() {
279 if r := recover(); r != nil {
280 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse RefreshMatchList: %v", r))
281 success = false
282 }
283 }()
284 result := refresh_match_list.GetRootAsRefreshMatchList(buf, 0)
285 return result, success
286}
287
288func parseTeamKey(teamKey string) (int, error) {
289 // TBA prefixes teams with "frc". Not sure why. Get rid of that.
290 teamKey = strings.TrimPrefix(teamKey, "frc")
291 return strconv.Atoi(teamKey)
292}
293
294// Parses the alliance data from the specified match and returns the three red
295// teams and the three blue teams.
296func parseTeamKeys(match *scraping.Match) ([3]int32, [3]int32, error) {
297 redKeys := match.Alliances.Red.TeamKeys
298 blueKeys := match.Alliances.Blue.TeamKeys
299
300 if len(redKeys) != 3 || len(blueKeys) != 3 {
301 return [3]int32{}, [3]int32{}, errors.New(fmt.Sprintf(
302 "Found %d red teams and %d blue teams.", len(redKeys), len(blueKeys)))
303 }
304
305 var red [3]int32
306 for i, key := range redKeys {
307 team, err := parseTeamKey(key)
308 if err != nil {
309 return [3]int32{}, [3]int32{}, errors.New(fmt.Sprintf(
310 "Failed to parse red %d team '%s' as integer: %v", i+1, key, err))
311 }
312 red[i] = int32(team)
313 }
314 var blue [3]int32
315 for i, key := range blueKeys {
316 team, err := parseTeamKey(key)
317 if err != nil {
318 return [3]int32{}, [3]int32{}, errors.New(fmt.Sprintf(
319 "Failed to parse blue %d team '%s' as integer: %v", i+1, key, err))
320 }
321 blue[i] = int32(team)
322 }
323 return red, blue, nil
324}
325
326type refreshMatchListHandler struct {
327 db Database
328 scrape ScrapeMatchList
329}
330
331func (handler refreshMatchListHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
332 requestBytes, err := io.ReadAll(req.Body)
333 if err != nil {
334 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
335 return
336 }
337
338 request, success := parseRefreshMatchList(w, requestBytes)
339 if !success {
340 return
341 }
342
343 matches, err := handler.scrape(request.Year(), string(request.EventCode()))
344 if err != nil {
345 respondWithError(w, http.StatusInternalServerError, fmt.Sprint("Faled to scrape match list: ", err))
346 return
347 }
348
349 for _, match := range matches {
350 // Make sure the data is valid.
351 red, blue, err := parseTeamKeys(&match)
352 if err != nil {
353 respondWithError(w, http.StatusInternalServerError, fmt.Sprintf(
354 "TheBlueAlliance data for match %d is malformed: %v", match.MatchNumber, err))
355 return
356 }
357 // Add the match to the database.
358 handler.db.AddToMatch(db.Match{
359 MatchNumber: int32(match.MatchNumber),
360 // TODO(phil): What does Round mean?
361 Round: 1,
362 CompLevel: match.CompLevel,
363 R1: red[0],
364 R2: red[1],
365 R3: red[2],
366 B1: blue[0],
367 B2: blue[1],
368 B3: blue[2],
369 })
370 }
371
372 var response RefreshMatchListResponseT
373 builder := flatbuffers.NewBuilder(1024)
374 builder.Finish((&response).Pack(builder))
375 w.Write(builder.FinishedBytes())
376}
377
378func HandleRequests(db Database, scrape ScrapeMatchList, scoutingServer server.ScoutingServer) {
Philipp Schradercdb5cfc2022-02-20 14:57:07 -0800379 scoutingServer.HandleFunc("/requests", unknown)
Philipp Schrader8747f1b2022-02-23 23:56:22 -0800380 scoutingServer.Handle("/requests/submit/data_scouting", submitDataScoutingHandler{db})
Philipp Schradercbf5c6a2022-02-27 23:25:19 -0800381 scoutingServer.Handle("/requests/request/all_matches", requestAllMatchesHandler{db})
Philipp Schraderd1c4bef2022-02-28 22:51:30 -0800382 scoutingServer.Handle("/requests/request/matches_for_team", requestMatchesForTeamHandler{db})
Philipp Schraderacf96232022-03-01 22:03:30 -0800383 scoutingServer.Handle("/requests/request/data_scouting", requestDataScoutingHandler{db})
Philipp Schraderd3fac192022-03-02 20:35:46 -0800384 scoutingServer.Handle("/requests/refresh_match_list", refreshMatchListHandler{db, scrape})
Philipp Schradercdb5cfc2022-02-20 14:57:07 -0800385}