65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
|
|
"spark-server/internal/module/upload/entity"
|
|
"spark-server/internal/pkg/errs"
|
|
"spark-server/internal/pkg/i18n"
|
|
"spark-server/internal/pkg/reqctx"
|
|
"spark-server/internal/pkg/validate"
|
|
)
|
|
|
|
const maxDownloadBatch = 9
|
|
|
|
// BatchDownloadInput issues up to nine Presigned GETs (moment 九宫格) in one call.
|
|
type BatchDownloadInput struct {
|
|
ObjectKeys []string `json:"object_keys" validate:"required,min=1,max=9,dive,required,max=512" label:"field.object_key" errmsg:"required:validate.upload.key_required;max:validate.upload.download_items_invalid"`
|
|
}
|
|
|
|
func (s *Service) CreateDownloads(ctx context.Context, userID int64, in *BatchDownloadInput) (*entity.DownloadSet, error) {
|
|
if !s.ready() {
|
|
return nil, errs.ErrAvailable
|
|
}
|
|
if userID <= 0 {
|
|
return nil, errs.ErrUnauthorized
|
|
}
|
|
if in == nil {
|
|
return nil, errs.ErrInvalidArgument
|
|
}
|
|
if err := validate.StructLang(reqctx.Lang(ctx), in); err != nil {
|
|
return nil, err
|
|
}
|
|
if n := len(in.ObjectKeys); n < 1 || n > maxDownloadBatch {
|
|
return nil, errs.ErrInvalidArgument
|
|
}
|
|
if !s.allow(userID) {
|
|
return nil, errs.ErrRateLimited
|
|
}
|
|
items := make([]entity.Download, 0, len(in.ObjectKeys))
|
|
for _, key := range in.ObjectKeys {
|
|
got, err := s.issueGet(ctx, key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, *got)
|
|
}
|
|
return &entity.DownloadSet{Items: items}, nil
|
|
}
|
|
|
|
func (s *Service) issueGet(ctx context.Context, key string) (*entity.Download, error) {
|
|
if !entity.ValidObjectKey(key) {
|
|
return nil, errs.ErrInvalidArgument.WithMsg(i18n.T(reqctx.Lang(ctx), i18n.KeyUploadKeyInvalid, nil))
|
|
}
|
|
url, err := s.store.PresignGet(ctx, key, s.ttl)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &entity.Download{
|
|
ObjectKey: key,
|
|
DownloadURL: url,
|
|
Method: entity.MethodGET,
|
|
ExpiresIn: s.expiresIn(),
|
|
}, nil
|
|
}
|