Files
orbits/internal/api/routes_file.go
T

78 lines
1.8 KiB
Go

package api
import (
"eden-server/internal/crypto"
"eden-server/internal/database"
"eden-server/internal/runtime"
"log/slog"
"net/http"
"path/filepath"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
)
func spawnFileRoutes(file *gin.RouterGroup, env runtime.Environment, db *gorm.DB) {
// /file/<file-name>
file.GET("/:filename", func(c *gin.Context) {
f := c.Param("filename")
p := filepath.Join(env.DataDirectory, "content", f)
c.File(p)
})
// define the upload route
// /file/upload
file.POST("/upload", func(c *gin.Context) {
f, err := c.FormFile("file")
if err != nil {
slog.Error("failed to get file details from request", "error", err)
c.JSON(http.StatusBadRequest, RespObj{
Msg: "a file is required",
})
return
}
e := filepath.Ext(f.Filename)
m := categorizeFilemode(e)
if m == database.Unspecified {
slog.Warn("discarding file since its filetype is unsupported")
c.JSON(http.StatusUnsupportedMediaType, RespObj{
Msg: "unsupported filetype",
})
return
}
safeName := uuid.New().String()[:8] + "_" + string(m) + e
destPath := filepath.Join(env.DataDirectory, "content", safeName)
if err := c.SaveUploadedFile(f, destPath); err != nil {
slog.Error("failed to receive the file over http:", "error", err)
c.JSON(http.StatusInternalServerError, RespObj{
Msg: ieMes,
})
return
}
cSum, err := crypto.CalculateHash(destPath)
if err != nil {
slog.Error("failed to calculate hash of file at given path", "error", err)
c.JSON(http.StatusInternalServerError, RespObj{
Msg: ieMes,
})
}
fData := database.File{
MediaType: m,
GivenName: f.Filename,
Filepath: destPath,
Checksum: cSum,
}
database.RegisterFile(db, fData)
c.JSON(http.StatusCreated, RespObj{
Msg: "file has succesfully been uploaded",
})
})
}