75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
package outboundimage
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
var stableImageIDRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
|
|
|
|
type ObjectWriter interface {
|
|
Put(ctx context.Context, key string, data []byte, contentType string) error
|
|
}
|
|
|
|
type StableHashPublisher struct {
|
|
store ObjectWriter
|
|
prefix string
|
|
publicBaseURL string
|
|
}
|
|
|
|
func NewStableHashPublisher(store ObjectWriter, prefix, publicBaseURL string) (*StableHashPublisher, error) {
|
|
prefix = strings.Trim(strings.TrimSpace(prefix), "/")
|
|
publicBaseURL = strings.TrimRight(strings.TrimSpace(publicBaseURL), "/")
|
|
parsed, err := url.Parse(publicBaseURL)
|
|
if store == nil || prefix == "" || err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
|
return nil, errors.New("outbound image: invalid stable publisher configuration")
|
|
}
|
|
return &StableHashPublisher{
|
|
store: store,
|
|
prefix: prefix,
|
|
publicBaseURL: publicBaseURL,
|
|
}, nil
|
|
}
|
|
|
|
func (p *StableHashPublisher) Publish(ctx context.Context, data []byte, contentType string) (string, error) {
|
|
if p == nil || p.store == nil || len(data) == 0 || p.prefix == "" || p.publicBaseURL == "" {
|
|
return "", errors.New("outbound image: invalid stable publisher configuration")
|
|
}
|
|
if imageExtension(contentType) == "" {
|
|
return "", errors.New("outbound image: unsupported image content type")
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
idBytes := sum[:16]
|
|
idBytes[6] = (idBytes[6] & 0x0f) | 0x50
|
|
idBytes[8] = (idBytes[8] & 0x3f) | 0x80
|
|
idHex := hex.EncodeToString(idBytes)
|
|
id := fmt.Sprintf("%s-%s-%s-%s-%s", idHex[:8], idHex[8:12], idHex[12:16], idHex[16:20], idHex[20:])
|
|
key := path.Join(p.prefix, id)
|
|
if err := p.store.Put(ctx, key, data, contentType); err != nil {
|
|
return "", errors.New("outbound image: publish object failed")
|
|
}
|
|
return p.publicBaseURL + "/" + id, nil
|
|
}
|
|
|
|
func imageExtension(contentType string) string {
|
|
switch strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) {
|
|
case "image/jpeg", "image/jpg":
|
|
return ".jpg"
|
|
case "image/png":
|
|
return ".png"
|
|
case "image/webp":
|
|
return ".webp"
|
|
case "image/gif":
|
|
return ".gif"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|