forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentDownload struct {
|
||||
Body io.ReadCloser
|
||||
ContentType string
|
||||
Filename string
|
||||
SizeBytes int64
|
||||
}
|
||||
|
||||
func (s *Service) GetAttachment(ctx context.Context, attachmentID, actorID string) (domain.Attachment, error) {
|
||||
return s.repository.GetAttachment(ctx, attachmentID, actorID)
|
||||
}
|
||||
|
||||
func (s *Service) DownloadAttachment(ctx context.Context, attachmentID, actorID, variantName 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 s.objectStore == nil {
|
||||
return AttachmentDownload{}, ErrStorageUnavailable
|
||||
}
|
||||
if variantName == "" {
|
||||
variantName = "original"
|
||||
}
|
||||
key := attachment.ObjectKey
|
||||
contentType := attachment.ContentType
|
||||
sizeBytes := attachment.SizeBytes
|
||||
filename := attachment.Filename
|
||||
if variantName != "original" {
|
||||
found := false
|
||||
for _, variant := range attachment.Variants {
|
||||
if variant.Name == variantName {
|
||||
key = variant.ObjectKey
|
||||
contentType = variant.ContentType
|
||||
sizeBytes = variant.SizeBytes
|
||||
filename = variant.Name + ".jpg"
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return AttachmentDownload{}, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
object, err := s.objectStore.Get(ctx, key)
|
||||
if err != nil {
|
||||
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
|
||||
}
|
||||
if object.Body == nil || object.SizeBytes != sizeBytes {
|
||||
if object.Body != nil {
|
||||
_ = object.Body.Close()
|
||||
}
|
||||
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
|
||||
}
|
||||
return AttachmentDownload{Body: object.Body, ContentType: contentType, Filename: filename, SizeBytes: sizeBytes}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user