94 lines
2.1 KiB
Go
94 lines
2.1 KiB
Go
package picture
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.umbach.dev/app-idea/rest-api/modules/config"
|
|
"git.umbach.dev/app-idea/rest-api/modules/database"
|
|
"git.umbach.dev/app-idea/rest-api/modules/rabbitmq"
|
|
"git.umbach.dev/app-idea/rest-api/modules/structs"
|
|
"git.umbach.dev/app-idea/rest-api/routers/api/v1/user"
|
|
"github.com/gofiber/fiber/v2"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func Save(c *fiber.Ctx) error {
|
|
log.Infoln("header", string(c.Request().Header.ContentType()))
|
|
|
|
log.Infoln("formValue", c.FormValue("image"))
|
|
|
|
file, err := c.FormFile("image")
|
|
|
|
if err != nil {
|
|
log.Infoln("err1", err)
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
f, err := file.Open()
|
|
|
|
if err != nil {
|
|
log.Info("err001")
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
if _, err := io.Copy(buf, f); err != nil {
|
|
log.Info("err002")
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
log.Infoln("bytes", len(buf.Bytes()))
|
|
|
|
user, err := user.GetUserBySessionId(c.Cookies(config.Cfg.Settings.Cookies.SessionId))
|
|
|
|
if err != nil {
|
|
log.Infoln("err004", err)
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
log.Infoln("userId", user.Id)
|
|
|
|
filename := strings.Replace(file.Filename, "-", "", -1)
|
|
|
|
rabbitmq.PublishPicture(structs.RabbitmqPictureMessage{Picture: buf.Bytes(), UserId: user.Id, Filename: filename})
|
|
|
|
db := database.DB
|
|
|
|
res := db.Create(&structs.Picture{UserId: user.Id, PictureId: filename, CreatedAt: time.Now()})
|
|
|
|
if res.Error != nil {
|
|
log.Warnln("Failed to insert user to db:", res.Error)
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
return c.SendStatus(fiber.StatusOK)
|
|
}
|
|
|
|
func GetPictures(c *fiber.Ctx) error {
|
|
db := database.DB
|
|
|
|
pictures := []map[string]interface{}{}
|
|
|
|
db.Model(structs.Picture{}).Select("user_id", "picture_id", "likes", "description").Find(&pictures)
|
|
|
|
return c.JSON(pictures)
|
|
}
|
|
|
|
func GetPicturesByUserId(c *fiber.Ctx) error {
|
|
db := database.DB
|
|
|
|
log.Infoln("")
|
|
|
|
pictures := []structs.APIPicture{}
|
|
|
|
db.Model(structs.Picture{}).Where("user_id", c.Params("id")).Find(&pictures)
|
|
|
|
return c.JSON(pictures)
|
|
}
|