forked from mtusi2026/mtusi2026lab6
156 lines
4.8 KiB
Go
156 lines
4.8 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"regexp"
|
|
"time"
|
|
|
|
"messenger/src/backend/repositories"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type DirectUploadInput struct {
|
|
Filename string `json:"filename"`
|
|
ContentType string `json:"content_type"`
|
|
SizeBytes int64 `json:"size_bytes"`
|
|
SHA256 string `json:"sha256"`
|
|
}
|
|
|
|
type DirectUploadResponse struct {
|
|
repositories.DirectUpload
|
|
Upload repositories.PostUpload `json:"upload"`
|
|
}
|
|
|
|
type DirectObjects interface {
|
|
AttachmentObjects
|
|
PresignDirect(context.Context, string, string, int64, time.Time) (repositories.PostUpload, error)
|
|
Stat(context.Context, string) (repositories.StoredObject, error)
|
|
Copy(context.Context, string, string, string) error
|
|
}
|
|
|
|
var checksumPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
|
|
|
func (s *AttachmentService) InitDirect(ctx context.Context, user, chat string, input DirectUploadInput) (DirectUploadResponse, error) {
|
|
if err := ValidateFilename(input.Filename); err != nil {
|
|
return DirectUploadResponse{}, err
|
|
}
|
|
if input.ContentType != "image/png" && input.ContentType != "image/jpeg" {
|
|
return DirectUploadResponse{}, ErrUnsupportedMedia
|
|
}
|
|
if input.SizeBytes > MaxUploadBytes {
|
|
return DirectUploadResponse{}, ErrPayloadTooLarge
|
|
}
|
|
if input.SizeBytes < 1 || !checksumPattern.MatchString(input.SHA256) {
|
|
return DirectUploadResponse{}, InvalidInput{"size must be positive and sha256 must contain 64 lowercase hex characters"}
|
|
}
|
|
objects, ok := s.objects.(DirectObjects)
|
|
if !ok {
|
|
return DirectUploadResponse{}, errors.New("direct uploads unavailable")
|
|
}
|
|
id, attachment := uuid.NewString(), uuid.NewString()
|
|
u, err := s.metadata.CreateDirect(ctx, repositories.DirectUpload{ID: id, AttachmentID: attachment, OwnerID: user, ChatID: chat, Filename: input.Filename, ContentType: input.ContentType, SizeBytes: input.SizeBytes, SHA256: input.SHA256, StagingKey: "staging/direct/" + id, FinalKey: "originals/" + attachment})
|
|
if err != nil {
|
|
return DirectUploadResponse{}, err
|
|
}
|
|
post, err := objects.PresignDirect(ctx, u.StagingKey, u.ContentType, u.SizeBytes, u.ExpiresAt)
|
|
return DirectUploadResponse{DirectUpload: u, Upload: post}, err
|
|
}
|
|
|
|
func (s *AttachmentService) CompleteDirect(ctx context.Context, user, chat, id string) (repositories.Attachment, error) {
|
|
u, err := s.metadata.GetDirect(ctx, id, chat, user)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return repositories.Attachment{}, ErrAttachmentNotFound
|
|
}
|
|
if err != nil {
|
|
return repositories.Attachment{}, err
|
|
}
|
|
if u.State == "ready" {
|
|
return s.Get(ctx, u.AttachmentID, user)
|
|
}
|
|
objects, ok := s.objects.(DirectObjects)
|
|
if !ok {
|
|
return repositories.Attachment{}, errors.New("direct uploads unavailable")
|
|
}
|
|
select {
|
|
case s.uploadSlot <- struct{}{}:
|
|
defer func() { <-s.uploadSlot }()
|
|
case <-ctx.Done():
|
|
return repositories.Attachment{}, ctx.Err()
|
|
}
|
|
a, err := s.metadata.CompleteDirect(ctx, id, chat, user, func(ctx context.Context, u repositories.DirectUpload) error {
|
|
info, err := objects.Stat(ctx, u.StagingKey)
|
|
if repositories.IsObjectMissing(err) {
|
|
return repositories.DirectError("upload_not_uploaded")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if info.Size > MaxUploadBytes {
|
|
return repositories.DirectError("payload_too_large")
|
|
}
|
|
if info.Size != u.SizeBytes {
|
|
return repositories.DirectError("upload_size_mismatch")
|
|
}
|
|
// A signed staging key remains writable until expiry. Validate the isolated
|
|
// final object, never a staging object that can change after validation.
|
|
if err = objects.Copy(ctx, u.StagingKey, u.FinalKey, info.ETag); err != nil {
|
|
return err
|
|
}
|
|
reader, err := objects.Get(ctx, u.FinalKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer reader.Close()
|
|
file, err := os.CreateTemp(os.Getenv("UPLOAD_TMP_DIR"), "direct-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
if err = os.Remove(file.Name()); err != nil {
|
|
return err
|
|
}
|
|
hash := sha256.New()
|
|
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(reader, MaxUploadBytes+1), make([]byte, 32*1024))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if size > MaxUploadBytes {
|
|
return repositories.DirectError("payload_too_large")
|
|
}
|
|
if size != u.SizeBytes {
|
|
return repositories.DirectError("upload_size_mismatch")
|
|
}
|
|
if hex.EncodeToString(hash.Sum(nil)) != u.SHA256 {
|
|
return repositories.DirectError("upload_checksum_mismatch")
|
|
}
|
|
if err = ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
_, err = ValidateImageReader(file, u.ContentType)
|
|
if errors.Is(err, ErrPayloadTooLarge) {
|
|
return repositories.DirectError("payload_too_large")
|
|
}
|
|
if errors.Is(err, ErrUnsupportedMedia) {
|
|
return repositories.DirectError("unsupported_media_type")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return ctx.Err()
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return a, ErrAttachmentNotFound
|
|
}
|
|
return a, err
|
|
}
|