Files
mtusi2026lab4/internal/application/attachment_queries.go
T

66 lines
1.5 KiB
Go

package application
import (
"context"
"fmt"
"io"
"mtusi2026lab4/internal/domain"
)
type AttachmentDownload struct {
Body io.ReadCloser
ContentType string
Filename string
SizeBytes int64
}
func (s *Service) GetAttachment(
ctx context.Context,
attachmentID string,
actorID string,
) (domain.Attachment, error) {
return s.repository.GetAttachment(ctx, attachmentID, actorID)
}
func (s *Service) DownloadAttachment(
ctx context.Context,
attachmentID string,
actorID string,
variant string,
) (AttachmentDownload, error) {
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
if err != nil {
return AttachmentDownload{}, err
}
if attachment.Status != domain.AttachmentStatusReady {
return AttachmentDownload{}, ErrAttachmentNotReady
}
if variant == "" {
variant = "original"
}
if variant != "original" {
return AttachmentDownload{}, domain.ErrNotFound
}
if s.objectStore == nil {
return AttachmentDownload{}, ErrStorageUnavailable
}
object, err := s.objectStore.Get(ctx, attachment.ObjectKey)
if err != nil {
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
}
if object.Body == nil || object.SizeBytes != attachment.SizeBytes {
if object.Body != nil {
_ = object.Body.Close()
}
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
}
return AttachmentDownload{
Body: object.Body,
ContentType: attachment.ContentType,
Filename: attachment.Filename,
SizeBytes: attachment.SizeBytes,
}, nil
}