Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 1 | package requests |
| 2 | |
| 3 | import ( |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 4 | "errors" |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 5 | "fmt" |
| 6 | "io" |
| 7 | "net/http" |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 8 | "strconv" |
| 9 | "strings" |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 10 | |
Philipp Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 11 | "github.com/frc971/971-Robot-Code/scouting/db" |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 12 | "github.com/frc971/971-Robot-Code/scouting/scraping" |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 13 | "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/error_response" |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 14 | "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 Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 16 | "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 Schrader | acf9623 | 2022-03-01 22:03:30 -0800 | [diff] [blame] | 18 | "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 Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 20 | "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 Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 22 | "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 Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 28 | type SubmitDataScouting = submit_data_scouting.SubmitDataScouting |
| 29 | type RequestAllMatches = request_all_matches.RequestAllMatches |
| 30 | type RequestAllMatchesResponseT = request_all_matches_response.RequestAllMatchesResponseT |
Philipp Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 31 | type RequestMatchesForTeam = request_matches_for_team.RequestMatchesForTeam |
| 32 | type RequestMatchesForTeamResponseT = request_matches_for_team_response.RequestMatchesForTeamResponseT |
Philipp Schrader | acf9623 | 2022-03-01 22:03:30 -0800 | [diff] [blame] | 33 | type RequestDataScouting = request_data_scouting.RequestDataScouting |
| 34 | type RequestDataScoutingResponseT = request_data_scouting_response.RequestDataScoutingResponseT |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 35 | type RefreshMatchList = refresh_match_list.RefreshMatchList |
| 36 | type RefreshMatchListResponseT = refresh_match_list_response.RefreshMatchListResponseT |
Philipp Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 37 | |
Philipp Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 38 | // The interface we expect the database abstraction to conform to. |
| 39 | // We use an interface here because it makes unit testing easier. |
| 40 | type Database interface { |
| 41 | AddToMatch(db.Match) error |
| 42 | AddToStats(db.Stats) error |
| 43 | ReturnMatches() ([]db.Match, error) |
| 44 | ReturnStats() ([]db.Stats, error) |
Philipp Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 45 | QueryMatches(int32) ([]db.Match, error) |
Philipp Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 46 | QueryStats(int) ([]db.Stats, error) |
| 47 | } |
| 48 | |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 49 | type ScrapeMatchList func(int32, string) ([]scraping.Match, error) |
| 50 | |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 51 | // Handles unknown requests. Just returns a 404. |
| 52 | func unknown(w http.ResponseWriter, req *http.Request) { |
| 53 | w.WriteHeader(http.StatusNotFound) |
| 54 | } |
| 55 | |
| 56 | func 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 | |
| 65 | func respondNotImplemented(w http.ResponseWriter) { |
| 66 | respondWithError(w, http.StatusNotImplemented, "") |
| 67 | } |
| 68 | |
| 69 | // TODO(phil): Can we turn this into a generic? |
Philipp Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 70 | func parseSubmitDataScouting(w http.ResponseWriter, buf []byte) (*SubmitDataScouting, bool) { |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 71 | 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 Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 83 | type submitDataScoutingHandler struct { |
| 84 | db Database |
| 85 | } |
| 86 | |
| 87 | func (handler submitDataScoutingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 88 | 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 Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 100 | // We have access to the database via "handler.db" here. For example: |
| 101 | // stats := handler.db.ReturnStats() |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 102 | |
| 103 | respondNotImplemented(w) |
| 104 | } |
| 105 | |
Philipp Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 106 | // TODO(phil): Can we turn this into a generic? |
| 107 | func 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. |
| 120 | type requestAllMatchesHandler struct { |
| 121 | db Database |
| 122 | } |
| 123 | |
| 124 | func (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 Schrader | 2e7eb000 | 2022-03-02 22:52:39 -0800 | [diff] [blame] | 139 | return |
Philipp Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 140 | } |
| 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 Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 162 | // TODO(phil): Can we turn this into a generic? |
| 163 | func 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. |
| 176 | type requestMatchesForTeamHandler struct { |
| 177 | db Database |
| 178 | } |
| 179 | |
| 180 | func (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 Schrader | 2e7eb000 | 2022-03-02 22:52:39 -0800 | [diff] [blame] | 195 | return |
Philipp Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 196 | } |
| 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 Schrader | acf9623 | 2022-03-01 22:03:30 -0800 | [diff] [blame] | 218 | // TODO(phil): Can we turn this into a generic? |
| 219 | func 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. |
| 232 | type requestDataScoutingHandler struct { |
| 233 | db Database |
| 234 | } |
| 235 | |
| 236 | func (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 Schrader | 2e7eb000 | 2022-03-02 22:52:39 -0800 | [diff] [blame] | 251 | return |
Philipp Schrader | acf9623 | 2022-03-01 22:03:30 -0800 | [diff] [blame] | 252 | } |
| 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 Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 275 | // TODO(phil): Can we turn this into a generic? |
| 276 | func 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 | |
| 288 | func 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. |
| 296 | func 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 | |
| 326 | type refreshMatchListHandler struct { |
| 327 | db Database |
| 328 | scrape ScrapeMatchList |
| 329 | } |
| 330 | |
| 331 | func (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 | |
| 378 | func HandleRequests(db Database, scrape ScrapeMatchList, scoutingServer server.ScoutingServer) { |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 379 | scoutingServer.HandleFunc("/requests", unknown) |
Philipp Schrader | 8747f1b | 2022-02-23 23:56:22 -0800 | [diff] [blame] | 380 | scoutingServer.Handle("/requests/submit/data_scouting", submitDataScoutingHandler{db}) |
Philipp Schrader | cbf5c6a | 2022-02-27 23:25:19 -0800 | [diff] [blame] | 381 | scoutingServer.Handle("/requests/request/all_matches", requestAllMatchesHandler{db}) |
Philipp Schrader | d1c4bef | 2022-02-28 22:51:30 -0800 | [diff] [blame] | 382 | scoutingServer.Handle("/requests/request/matches_for_team", requestMatchesForTeamHandler{db}) |
Philipp Schrader | acf9623 | 2022-03-01 22:03:30 -0800 | [diff] [blame] | 383 | scoutingServer.Handle("/requests/request/data_scouting", requestDataScoutingHandler{db}) |
Philipp Schrader | d3fac19 | 2022-03-02 20:35:46 -0800 | [diff] [blame] | 384 | scoutingServer.Handle("/requests/refresh_match_list", refreshMatchListHandler{db, scrape}) |
Philipp Schrader | cdb5cfc | 2022-02-20 14:57:07 -0800 | [diff] [blame] | 385 | } |