forked from mtusi2026/mtusi2026lab7
81 lines
2.4 KiB
Go
81 lines
2.4 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.AsyncAttachments
|
|
messenger *Messenger
|
|
objects port.Objects
|
|
}
|
|
|
|
func NewAttachments(r repository.AsyncAttachments, 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, "staging/"+row.ID.String(), body, size, mime); e != nil {
|
|
return model.Attachment{}, model.ErrUnavailable
|
|
}
|
|
carrier := model.TraceFrom(ctx)
|
|
return a.repo.QueueAttachment(ctx, row, carrier.Traceparent, carrier.Tracestate)
|
|
}
|
|
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
|
|
}
|
|
return row, nil
|
|
}
|
|
func (a *Attachments) Content(ctx context.Context, caller, id uuid.UUID, variant string) (model.Attachment, io.ReadCloser, error) {
|
|
row, e := a.Get(ctx, caller, id)
|
|
if e != nil {
|
|
return row, nil, e
|
|
}
|
|
if row.Status != "ready" {
|
|
return row, nil, model.ErrConflict
|
|
}
|
|
key := ObjectKey(id)
|
|
if variant != "original" {
|
|
found := false
|
|
for _, v := range row.Variants {
|
|
if v.Name == variant {
|
|
found = true
|
|
key = VariantKey(id, row.PipelineVersion, variant)
|
|
row.SizeBytes = v.SizeBytes
|
|
row.ContentType = v.ContentType
|
|
row.SHA256 = v.SHA256
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
return row, nil, model.ErrNotFound
|
|
}
|
|
}
|
|
info, e := a.objects.Stat(ctx, key)
|
|
if e != nil || info.Size != row.SizeBytes {
|
|
return row, nil, model.ErrUnavailable
|
|
}
|
|
r, e := a.objects.Get(ctx, key)
|
|
if e != nil {
|
|
return row, nil, model.ErrUnavailable
|
|
}
|
|
return row, r, nil
|
|
}
|