112 lines
2.5 KiB
Go
112 lines
2.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"mime"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
"high-loud-apps-labs/internal/httpapi/dto"
|
|
"high-loud-apps-labs/internal/httpapi/middleware"
|
|
"high-loud-apps-labs/internal/service"
|
|
)
|
|
|
|
type AttachmentHandler struct {
|
|
svc *service.AttachmentService
|
|
}
|
|
|
|
func NewAttachmentHandler(svc *service.AttachmentService) *AttachmentHandler {
|
|
return &AttachmentHandler{svc: svc}
|
|
}
|
|
|
|
func (h *AttachmentHandler) Upload(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
chatID, err := parseUUIDPathParam(c, "chat_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
filename := c.Query("filename")
|
|
if filename == "" {
|
|
respondError(c, &domain.ValidationError{
|
|
Field: "filename",
|
|
Message: "обязателен",
|
|
})
|
|
return
|
|
}
|
|
|
|
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
|
if err != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
|
|
respondError(c, &domain.UnsupportedMediaTypeError{
|
|
MediaType: c.GetHeader("Content-Type"),
|
|
Expected: "image/png или image/jpeg",
|
|
})
|
|
return
|
|
}
|
|
|
|
att, err := h.svc.Upload(c.Request.Context(), me.ID, chatID, filename, c.Request.Body)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusAccepted, dto.AttachmentFromDomain(att))
|
|
}
|
|
|
|
func (h *AttachmentHandler) Get(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
a, err := h.svc.Get(c.Request.Context(), me.ID, attachmentID)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.AttachmentFromDomain(a))
|
|
}
|
|
|
|
func (h *AttachmentHandler) Content(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
variant := c.DefaultQuery("variant", "original")
|
|
|
|
rc, size, contentType, err := h.svc.Download(c.Request.Context(), me.ID, attachmentID, variant)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
defer func() { _ = rc.Close() }()
|
|
|
|
c.DataFromReader(http.StatusOK, size, contentType, rc, nil)
|
|
}
|
|
|
|
func (h *AttachmentHandler) Replay(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
if err := h.svc.Replay(c.Request.Context(), me.ID, attachmentID); err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
c.Status(http.StatusAccepted)
|
|
}
|