Files
mtusi2026lab4/backend/internal/application/usecase/attachments.go
T

70 lines
2.1 KiB
Go

package usecase
import (
"backend/internal/domain/model"
"backend/internal/domain/port"
"backend/internal/domain/repository"
"context"
"github.com/google/uuid"
"io"
)
type Attachments struct {
repo repository.AttachmentRepository
messenger *Messenger
objects port.Objects
}
func NewAttachments(r repository.AttachmentRepository, m *Messenger, o port.Objects) *Attachments {
return &Attachments{r, m, o}
}
func ObjectKey(id uuid.UUID) string { return "originals/" + id.String() }
func (a *Attachments) Upload(ctx context.Context, caller, chat uuid.UUID, name, mime, sha string, size int64, body io.Reader) (model.Attachment, error) {
if _, e := a.messenger.GetChat(ctx, caller, chat); e != nil {
return model.Attachment{}, e
}
row, e := a.repo.ReserveAttachment(ctx, model.Attachment{ID: uuid.New(), ChatID: chat, OwnerID: caller, Filename: name, ContentType: mime, SHA256: sha, SizeBytes: size})
if e != nil {
return model.Attachment{}, e
}
if e = a.objects.Put(ctx, ObjectKey(row.ID), body, size, mime); e != nil {
return model.Attachment{}, model.ErrUnavailable
}
ok, e := a.repo.SetAttachmentStatus(ctx, row.ID, "uploading", "ready")
if e != nil {
return model.Attachment{}, e
}
if !ok {
return model.Attachment{}, model.ErrUnavailable
}
return a.repo.GetAttachment(ctx, row.ID)
}
func (a *Attachments) Get(ctx context.Context, caller, id uuid.UUID) (model.Attachment, error) {
row, e := a.repo.GetAttachment(ctx, id)
if e != nil {
return model.Attachment{}, e
}
if _, e = a.messenger.GetChat(ctx, caller, row.ChatID); e != nil {
return model.Attachment{}, e
}
if row.Status != "ready" {
return model.Attachment{}, model.ErrUnavailable
}
return row, nil
}
func (a *Attachments) Content(ctx context.Context, caller, id uuid.UUID) (model.Attachment, io.ReadCloser, error) {
row, e := a.Get(ctx, caller, id)
if e != nil {
return row, nil, e
}
info, e := a.objects.Stat(ctx, ObjectKey(id))
if e != nil || info.Size != row.SizeBytes {
return row, nil, model.ErrUnavailable
}
r, e := a.objects.Get(ctx, ObjectKey(id))
if e != nil {
return row, nil, model.ErrUnavailable
}
return row, r, nil
}