Shioriko/pkg/app/blob_routes.go

96 lines
2.0 KiB
Go
Raw Normal View History

2021-05-09 15:07:23 +00:00
package app
import (
2021-05-11 10:33:22 +00:00
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
2021-05-09 15:07:23 +00:00
"net/http"
2021-05-10 02:45:40 +00:00
"os"
2021-05-09 15:07:23 +00:00
"path/filepath"
"github.com/Damillora/Shioriko/pkg/config"
"github.com/Damillora/Shioriko/pkg/database"
"github.com/Damillora/Shioriko/pkg/middleware"
"github.com/Damillora/Shioriko/pkg/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func InitializeBlobRoutes(g *gin.Engine) {
protected := g.Group("/api/blob").Use(middleware.AuthMiddleware())
{
protected.POST("/upload", uploadBlob)
}
}
func uploadBlob(c *gin.Context) {
dataDir := config.CurrentConfig.DataDirectory
// Source
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
})
2021-05-11 10:33:22 +00:00
return
2021-05-09 15:07:23 +00:00
}
2021-05-11 10:33:22 +00:00
fileObj, err := file.Open()
if err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
image, _, err := image.Decode(fileObj)
if err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
width := image.Bounds().Dx()
height := image.Bounds().Dy()
2021-05-09 15:07:23 +00:00
id := uuid.NewString()
2021-05-10 02:45:40 +00:00
folder1 := id[0:2]
if _, err := os.Stat(filepath.Join(dataDir, folder1)); os.IsNotExist(err) {
os.Mkdir(filepath.Join(dataDir, folder1), 0755)
}
folder2 := id[2:4]
if _, err := os.Stat(filepath.Join(dataDir, folder1, folder2)); os.IsNotExist(err) {
os.Mkdir(filepath.Join(dataDir, folder1, folder2), 0755)
}
2021-05-09 15:07:23 +00:00
filename := id + filepath.Ext(file.Filename)
2021-05-10 02:45:40 +00:00
err = c.SaveUploadedFile(file, filepath.Join(dataDir, folder1, folder2, filename))
2021-05-09 15:07:23 +00:00
if err != nil {
c.JSON(http.StatusBadRequest, models.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
})
}
blob := database.Blob{
ID: id,
2021-05-10 02:45:40 +00:00
FilePath: filepath.Join(folder1, folder2, filename),
2021-05-11 10:33:22 +00:00
Width: width,
Height: height,
2021-05-09 15:07:23 +00:00
}
database.DB.Create(&blob)
c.JSON(http.StatusOK, models.BlobResponse{
2021-05-11 10:33:22 +00:00
ID: id,
Width: width,
Height: height,
2021-05-09 15:07:23 +00:00
})
}