|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "regexp" |
| 7 | + "strconv" |
| 8 | + |
| 9 | + "github.com/UDL-TF/UnitedAPI/internal/response" |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | +) |
| 12 | + |
| 13 | +// GetDemo handles GET /api/v1/demos |
| 14 | +// Query params: match_id, round_id |
| 15 | +// Returns the demo file for the given match and round |
| 16 | +func GetDemo(c *gin.Context) { |
| 17 | + matchID := c.Query("match_id") |
| 18 | + roundID := c.Query("round_id") |
| 19 | + |
| 20 | + if matchID == "" || roundID == "" { |
| 21 | + response.BadRequest(c, "Missing match_id or round_id") |
| 22 | + return |
| 23 | + } |
| 24 | + |
| 25 | + // Force matchID and roundID to be numbers for security |
| 26 | + matchIDNum, err := strconv.Atoi(matchID) |
| 27 | + if err != nil { |
| 28 | + response.BadRequest(c, "Match ID is not a number") |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + roundIDNum, err := strconv.Atoi(roundID) |
| 33 | + if err != nil { |
| 34 | + response.BadRequest(c, "Round ID is not a number") |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + // Get demo path from environment variable or use default |
| 39 | + uploadPath := os.Getenv("DEMO_PATH") |
| 40 | + if uploadPath == "" { |
| 41 | + uploadPath = "./demo" |
| 42 | + } |
| 43 | + |
| 44 | + // Find the file with the given match ID and round ID using regex |
| 45 | + filePattern := fmt.Sprintf(`match-%d-round-%d`, matchIDNum, roundIDNum) |
| 46 | + files, err := os.ReadDir(uploadPath) |
| 47 | + if err != nil { |
| 48 | + response.InternalServerError(c, "Error reading demo directory") |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + var demoFile string |
| 53 | + var maxSize int64 |
| 54 | + |
| 55 | + for _, file := range files { |
| 56 | + if !file.IsDir() && matchRegex(file.Name(), filePattern) { |
| 57 | + fileInfo, err := file.Info() |
| 58 | + if err != nil { |
| 59 | + continue |
| 60 | + } |
| 61 | + // Get the largest matching file |
| 62 | + if fileInfo.Size() > maxSize { |
| 63 | + maxSize = fileInfo.Size() |
| 64 | + demoFile = file.Name() |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + if demoFile == "" { |
| 70 | + response.NotFound(c, "Demo file not found") |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + fmt.Printf("Downloading demo file: %s\n", demoFile) |
| 75 | + |
| 76 | + // Set the original file name in the response header |
| 77 | + c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", demoFile)) |
| 78 | + c.File(fmt.Sprintf("%s/%s", uploadPath, demoFile)) |
| 79 | +} |
| 80 | + |
| 81 | +// matchRegex checks if a string matches a regex pattern |
| 82 | +func matchRegex(str, pattern string) bool { |
| 83 | + pattern = regexp.QuoteMeta(pattern) |
| 84 | + matched, _ := regexp.MatchString(pattern, str) |
| 85 | + return matched |
| 86 | +} |
0 commit comments