forked from mtusi2026/mtusi2026lab4
feat: attachments over S3 (grade 3)
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
originalVariant = "original"
|
||||
maxFilenameRunes = 255
|
||||
sniffBytes = 512
|
||||
)
|
||||
|
||||
type AttachmentService struct {
|
||||
chats *ChatService
|
||||
repo AttachmentRepository
|
||||
store ObjectStore
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
}
|
||||
|
||||
func NewAttachmentService(chats *ChatService, repo AttachmentRepository, store ObjectStore, maxBytes, maxPixels int64) *AttachmentService {
|
||||
return &AttachmentService{chats: chats, repo: repo, store: store, maxBytes: maxBytes, maxPixels: maxPixels}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatID uuid.UUID, filename, contentType string, body io.Reader) (domain.Attachment, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkFilename(filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if contentType != domain.ContentPNG && contentType != domain.ContentJPEG {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: content type must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
raw, err := readLimited(body, s.maxBytes)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if detected := detectImageType(raw); detected != contentType {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: body does not match the declared image type", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if err := checkPixels(raw, s.maxPixels); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkIntegrity(raw); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
sum := sha256.Sum256(raw)
|
||||
createdAt := now()
|
||||
attachment := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: actor.ID,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(raw)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: "chats/" + chatID.String() + "/" + id.String(),
|
||||
Status: domain.AttachmentReady,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: createdAt,
|
||||
}
|
||||
if err := s.store.Put(ctx, attachment.ObjectKey, bytes.NewReader(raw), attachment.SizeBytes, contentType); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := s.repo.CreateAttachment(ctx, attachment); err != nil {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.Delete(cleanupCtx, attachment.ObjectKey)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(ctx context.Context, actor domain.User, id uuid.UUID) (domain.Attachment, error) {
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Open(ctx context.Context, actor domain.User, id uuid.UUID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if variant == "" {
|
||||
variant = originalVariant
|
||||
}
|
||||
if variant != originalVariant {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: only the original variant is available", domain.ErrInvalidInput)
|
||||
}
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is not ready", domain.ErrConflict)
|
||||
}
|
||||
content, err := s.store.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
return attachment, content, nil
|
||||
}
|
||||
|
||||
func checkFilename(filename string) error {
|
||||
if n := utf8.RuneCountInString(filename); n < 1 || n > maxFilenameRunes {
|
||||
return fmt.Errorf("%w: filename must be 1 to 255 characters", domain.ErrInvalidInput)
|
||||
}
|
||||
for _, r := range filename {
|
||||
if unicode.IsControl(r) || r == '/' || r == '\\' {
|
||||
return fmt.Errorf("%w: filename contains forbidden characters", domain.ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readLimited(body io.Reader, max int64) ([]byte, error) {
|
||||
raw, err := io.ReadAll(io.LimitReader(body, max+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: cannot read the upload body", domain.ErrInvalidInput)
|
||||
}
|
||||
if int64(len(raw)) > max {
|
||||
return nil, fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, max)
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil, fmt.Errorf("%w: upload body is empty", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func detectImageType(raw []byte) string {
|
||||
sniff := raw
|
||||
if len(sniff) > sniffBytes {
|
||||
sniff = sniff[:sniffBytes]
|
||||
}
|
||||
switch http.DetectContentType(sniff) {
|
||||
case domain.ContentPNG:
|
||||
return domain.ContentPNG
|
||||
case domain.ContentJPEG:
|
||||
return domain.ContentJPEG
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkPixels(raw []byte, max int64) error {
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: image header cannot be decoded", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 {
|
||||
return fmt.Errorf("%w: image has invalid dimensions", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if int64(config.Width) > max/int64(config.Height) {
|
||||
return fmt.Errorf("%w: image exceeds %d pixels", domain.ErrTooLarge, max)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkIntegrity(raw []byte) error {
|
||||
if _, _, err := image.Decode(bytes.NewReader(raw)); err != nil {
|
||||
return fmt.Errorf("%w: image is corrupted", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user