Can upload new track

This commit is contained in:
nemunaire 2022-10-15 12:20:18 +02:00
commit 192ff6c4e1
4 changed files with 114 additions and 4 deletions

View file

@ -3,6 +3,9 @@ package api
import (
"fmt"
"net/http"
"os"
"path"
"strings"
"github.com/gin-gonic/gin"
@ -21,7 +24,43 @@ func declareTracksRoutes(cfg *config.Config, router *gin.RouterGroup) {
c.JSON(http.StatusOK, tracks)
})
router.POST("/tracks", func(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusNotImplemented, gin.H{"errmsg": "TODO"})
ftrack, err := c.FormFile("trackfile")
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "No track found"})
return
}
// Check file extension
if path.Ext(ftrack.Filename) != ".mp3" && path.Ext(ftrack.Filename) != ".flac" {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad file type. You should only upload .mp3 or .flac files."})
return
}
if strings.Contains(ftrack.Filename, "/") {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad file name."})
return
}
dst := path.Join(cfg.TracksDir, ftrack.Filename)
err = c.SaveUploadedFile(ftrack, dst)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Something goes wrong when saving the track: %s", err.Error())})
return
}
d, err := os.Stat(dst)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Something goes wrong when saving the track: %s", err.Error())})
return
}
track, err := reveil.LoadTrack(dst, d)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to load track: %s", err.Error())})
return
}
c.JSON(http.StatusOK, track)
})
tracksRoutes := router.Group("/tracks/:tid")