forked from mtusi2026/mtusi2026lab5
69 lines
2.4 KiB
Go
69 lines
2.4 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/url"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
)
|
|
|
|
type PostUpload struct {
|
|
Method string `json:"method"`
|
|
URL string `json:"url"`
|
|
Fields map[string]string `json:"fields"`
|
|
}
|
|
|
|
type StoredObject struct {
|
|
Size int64
|
|
ETag string
|
|
}
|
|
|
|
func IsObjectMissing(err error) bool {
|
|
code := minio.ToErrorResponse(err).Code
|
|
return code == "NoSuchKey" || code == "NoSuchObject" || code == "NotFound"
|
|
}
|
|
|
|
func (s *ObjectStore) PresignDirect(ctx context.Context, key, mime string, size int64, expires time.Time) (PostUpload, error) {
|
|
endpoint, err := url.Parse(os.Getenv("S3_PUBLIC_ENDPOINT"))
|
|
if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.Path != "" || endpoint.RawQuery != "" || endpoint.User != nil {
|
|
return PostUpload{}, errors.New("invalid S3_PUBLIC_ENDPOINT")
|
|
}
|
|
access, err := readS3Secret("S3_ACCESS_KEY_ID_FILE")
|
|
if err != nil {
|
|
return PostUpload{}, err
|
|
}
|
|
secret, err := readS3Secret("S3_SECRET_ACCESS_KEY_FILE")
|
|
if err != nil {
|
|
return PostUpload{}, err
|
|
}
|
|
signer, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION"), BucketLookup: minio.BucketLookupPath})
|
|
if err != nil {
|
|
return PostUpload{}, err
|
|
}
|
|
policy := minio.NewPostPolicy()
|
|
for _, err = range []error{policy.SetBucket(s.bucket), policy.SetKey(key), policy.SetExpires(expires), policy.SetContentType(mime), policy.SetContentLengthRange(size, size), policy.SetSuccessStatusAction("204")} {
|
|
if err != nil {
|
|
return PostUpload{}, err
|
|
}
|
|
}
|
|
target, fields, err := signer.PresignedPostPolicy(ctx, policy)
|
|
if err != nil {
|
|
return PostUpload{}, errors.New("cannot sign upload policy")
|
|
}
|
|
return PostUpload{Method: "POST", URL: target.String(), Fields: fields}, nil
|
|
}
|
|
|
|
func (s *ObjectStore) Stat(ctx context.Context, key string) (StoredObject, error) {
|
|
object, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
|
return StoredObject{Size: object.Size, ETag: object.ETag}, err
|
|
}
|
|
|
|
func (s *ObjectStore) Copy(ctx context.Context, source, destination, etag string) error {
|
|
_, err := s.client.CopyObject(ctx, minio.CopyDestOptions{Bucket: s.bucket, Object: destination}, minio.CopySrcOptions{Bucket: s.bucket, Object: source, MatchETag: etag})
|
|
return err
|
|
}
|