Interactive/pkg/server/attachments_api.go

62 lines
1.6 KiB
Go
Raw Normal View History

2024-02-04 10:40:20 +00:00
package server
import (
"path/filepath"
2024-03-20 12:57:21 +00:00
"git.solsynth.dev/hydrogen/interactive/pkg/models"
"git.solsynth.dev/hydrogen/interactive/pkg/services"
2024-02-04 10:40:20 +00:00
"github.com/gofiber/fiber/v2"
"github.com/spf13/viper"
)
func readAttachment(c *fiber.Ctx) error {
2024-02-04 10:40:20 +00:00
id := c.Params("fileId")
basepath := viper.GetString("content")
return c.SendFile(filepath.Join(basepath, id))
}
func uploadAttachment(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
2024-03-24 11:01:18 +00:00
hashcode := c.FormValue("hashcode")
if len(hashcode) != 64 {
return fiber.NewError(fiber.StatusBadRequest, "please provide a SHA256 hashcode, length should be 64 characters")
}
2024-02-04 10:40:20 +00:00
file, err := c.FormFile("attachment")
if err != nil {
return err
}
2024-03-24 11:01:18 +00:00
attachment, err := services.NewAttachment(user, file, hashcode)
2024-02-04 10:40:20 +00:00
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
if err := c.SaveFile(file, attachment.GetStoragePath()); err != nil {
return err
}
return c.JSON(fiber.Map{
"info": attachment,
"url": attachment.GetAccessPath(),
})
}
2024-03-24 10:31:36 +00:00
func deleteAttachment(c *fiber.Ctx) error {
2024-03-24 11:01:18 +00:00
id, _ := c.ParamsInt("id", 0)
2024-03-24 10:31:36 +00:00
user := c.Locals("principal").(models.Account)
2024-03-24 11:01:18 +00:00
attachment, err := services.GetAttachmentByID(uint(id))
2024-03-24 10:31:36 +00:00
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
} else if attachment.AuthorID != user.ID {
return fiber.NewError(fiber.StatusNotFound, "record not created by you")
}
if err := services.DeleteAttachment(attachment); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
return c.SendStatus(fiber.StatusOK)
}
}