882ac62433
- outboundimage: re-encode large PNG/JPEG screenshots as downscaled JPEG (1600px long edge, q82, transparency flattened onto white) before upload; undecodable, small, GIF/WebP payloads are published untouched - outboundimage: StableHashPublisher skips the upload when the content-addressed object already exists (ObjectStater); OSS store implements it via IsObjectExist - cmd/dobotai: DOBOTAI_OUTBOUND_IMAGE_REWRITE_TIMEOUT default 60s -> 180s; DOBOTAI_OUTBOUND_IMAGE_COMPRESS (on by default, off restores raw bytes)
202 lines
7.0 KiB
Go
202 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk"
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/outboundimage"
|
|
)
|
|
|
|
const (
|
|
outboundImageMaxCountDefault = 12
|
|
outboundImageMaxBytes = 10 << 20
|
|
outboundImagePrefix = "dobotai/im-images"
|
|
outboundImageRoute = "/dingtalk/i/"
|
|
// outboundImageRewriteTimeoutDefault is the budget for one answer's image
|
|
// rewrite. Manual screenshots are multi-megabyte uploads and the container's
|
|
// uplink is the real ceiling (measured ~0.6MB/s), so long answers need a
|
|
// budget with headroom: the historical 15s delivery timeout truncated them.
|
|
outboundImageRewriteTimeoutDefault = 180 * time.Second
|
|
)
|
|
|
|
// outboundImageMaxCount resolves how many images one answer may rewrite.
|
|
// DOBOTAI_OUTBOUND_IMAGE_MAX_COUNT overrides the default; invalid values fall back.
|
|
func outboundImageMaxCount() int {
|
|
raw := strings.TrimSpace(os.Getenv("DOBOTAI_OUTBOUND_IMAGE_MAX_COUNT"))
|
|
if raw == "" {
|
|
return outboundImageMaxCountDefault
|
|
}
|
|
n, err := strconv.Atoi(raw)
|
|
if err != nil || n < 1 {
|
|
log.Printf("outbound image: invalid DOBOTAI_OUTBOUND_IMAGE_MAX_COUNT=%q; using default %d", raw, outboundImageMaxCountDefault)
|
|
return outboundImageMaxCountDefault
|
|
}
|
|
return n
|
|
}
|
|
|
|
// outboundImageRewriteTimeout resolves the budget for the image rewrite stage.
|
|
// DOBOTAI_OUTBOUND_IMAGE_REWRITE_TIMEOUT accepts a Go duration ("90s", "2m");
|
|
// invalid or non-positive values fall back to the default.
|
|
func outboundImageRewriteTimeout() time.Duration {
|
|
raw := strings.TrimSpace(os.Getenv("DOBOTAI_OUTBOUND_IMAGE_REWRITE_TIMEOUT"))
|
|
if raw == "" {
|
|
return outboundImageRewriteTimeoutDefault
|
|
}
|
|
duration, err := time.ParseDuration(raw)
|
|
if err != nil || duration <= 0 {
|
|
log.Printf("outbound image: invalid DOBOTAI_OUTBOUND_IMAGE_REWRITE_TIMEOUT=%q; using default %s", raw, outboundImageRewriteTimeoutDefault)
|
|
return outboundImageRewriteTimeoutDefault
|
|
}
|
|
return duration
|
|
}
|
|
|
|
// outboundImageCompressionEnabled reports whether published screenshots are
|
|
// re-encoded as smaller JPEGs before upload. It is on by default because the
|
|
// container uplink, not the rewrite code, caps how many images fit in the
|
|
// delivery budget; DOBOTAI_OUTBOUND_IMAGE_COMPRESS=off restores the original
|
|
// bytes exactly as fetched.
|
|
func outboundImageCompressionEnabled() bool {
|
|
switch strings.ToLower(strings.TrimSpace(os.Getenv("DOBOTAI_OUTBOUND_IMAGE_COMPRESS"))) {
|
|
case "off", "0", "false", "no":
|
|
log.Printf("outbound image: compression disabled by configuration")
|
|
return false
|
|
default:
|
|
return true
|
|
}
|
|
}
|
|
|
|
type outboundImageConfig struct {
|
|
WeKnoraBaseURL string
|
|
WeKnoraAPIKey string
|
|
Endpoint string
|
|
Region string
|
|
AccessKeyID string
|
|
AccessKeySecret string
|
|
Bucket string
|
|
PublicBaseURL string
|
|
}
|
|
|
|
type outboundImageRuntime struct {
|
|
rewriter dingtalk.OutboundContentRewriter
|
|
publisher *outboundimage.StableHashPublisher
|
|
handler http.Handler
|
|
// rewriteTimeout is the budget the channel gives the image rewrite stage.
|
|
rewriteTimeout time.Duration
|
|
// publicURLPrefix is the prefix of every published image URL, used by the
|
|
// DingTalk card image uploader to recognise (and refetch) our own images.
|
|
publicURLPrefix string
|
|
}
|
|
|
|
func buildOutboundImageRuntime(cfg outboundImageConfig) (outboundImageRuntime, error) {
|
|
ossValues := []string{cfg.Endpoint, cfg.Region, cfg.AccessKeyID, cfg.AccessKeySecret, cfg.Bucket, cfg.PublicBaseURL}
|
|
enabled := false
|
|
for _, value := range ossValues {
|
|
if strings.TrimSpace(value) != "" {
|
|
enabled = true
|
|
break
|
|
}
|
|
}
|
|
if !enabled {
|
|
return outboundImageRuntime{}, nil
|
|
}
|
|
for _, value := range append([]string{cfg.WeKnoraBaseURL, cfg.WeKnoraAPIKey}, ossValues...) {
|
|
if strings.TrimSpace(value) == "" {
|
|
return outboundImageRuntime{}, errors.New("outbound image: complete WeKnora, OSS, and public URL configuration is required")
|
|
}
|
|
}
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
transport.Proxy = nil
|
|
fetcher, err := outboundimage.NewWeKnoraFetcher(
|
|
cfg.WeKnoraBaseURL,
|
|
cfg.WeKnoraAPIKey,
|
|
&http.Client{Timeout: 30 * time.Second, Transport: transport},
|
|
outboundImageMaxBytes,
|
|
)
|
|
if err != nil {
|
|
return outboundImageRuntime{}, err
|
|
}
|
|
store, err := outboundimage.NewAliyunOSSStore(
|
|
cfg.Endpoint,
|
|
cfg.Region,
|
|
cfg.AccessKeyID,
|
|
cfg.AccessKeySecret,
|
|
cfg.Bucket,
|
|
)
|
|
if err != nil {
|
|
return outboundImageRuntime{}, err
|
|
}
|
|
publisher, err := outboundimage.NewStableHashPublisher(store, outboundImagePrefix, cfg.PublicBaseURL)
|
|
if err != nil {
|
|
return outboundImageRuntime{}, err
|
|
}
|
|
handler, err := outboundimage.NewStableImageHandler(store, outboundImagePrefix, outboundImageRoute, outboundImageMaxBytes)
|
|
if err != nil {
|
|
return outboundImageRuntime{}, err
|
|
}
|
|
return outboundImageRuntime{
|
|
rewriter: outboundimage.NewRewriter(fetcher, publisher, outboundImageMaxCount(), outboundimage.WithImageCompression(outboundImageCompressionEnabled())),
|
|
publisher: publisher,
|
|
handler: handler,
|
|
rewriteTimeout: outboundImageRewriteTimeout(),
|
|
publicURLPrefix: strings.TrimRight(cfg.PublicBaseURL, "/") + "/",
|
|
}, nil
|
|
}
|
|
|
|
func buildOutboundImageRewriter(cfg outboundImageConfig) (dingtalk.OutboundContentRewriter, error) {
|
|
runtime, err := buildOutboundImageRuntime(cfg)
|
|
return runtime.rewriter, err
|
|
}
|
|
|
|
// buildCardImageMedia wires the DingTalk media-id rewriter used for AI card
|
|
// bodies. It returns nil when the feature is switched off or not configured, so
|
|
// a disabled uploader simply keeps external image URLs in place.
|
|
func buildCardImageMedia(publicImagePrefix, clientID, clientSecret, listenAddr string) dingtalk.CardImageMediaRewriter {
|
|
switch strings.ToLower(strings.TrimSpace(os.Getenv("DINGTALK_CARD_IMAGE_MEDIA"))) {
|
|
case "off", "0", "false", "no":
|
|
log.Printf("DingTalk card image media ids disabled by configuration")
|
|
return nil
|
|
}
|
|
resolver, err := dingtalk.NewCardImageMediaRewriter(dingtalk.CardImageMediaOptions{
|
|
ClientID: clientID,
|
|
ClientSecret: clientSecret,
|
|
ImageURLPrefix: publicImagePrefix,
|
|
FetchURLPrefix: cardImageFetchPrefix(listenAddr),
|
|
})
|
|
if err != nil {
|
|
log.Printf("DingTalk card image media ids disabled: %v", err)
|
|
return nil
|
|
}
|
|
if resolver == nil {
|
|
return nil
|
|
}
|
|
log.Printf("DingTalk card images will be delivered through DingTalk media ids")
|
|
return resolver
|
|
}
|
|
|
|
// cardImageFetchPrefix derives the prefix used to download our own published
|
|
// images before uploading them to DingTalk. An explicit
|
|
// DINGTALK_CARD_IMAGE_FETCH_BASE_URL (host only, without the image route) wins;
|
|
// otherwise the local listen port is reused so the fetch stays on loopback.
|
|
func cardImageFetchPrefix(listenAddr string) string {
|
|
base := strings.TrimSpace(os.Getenv("DINGTALK_CARD_IMAGE_FETCH_BASE_URL"))
|
|
if base == "" {
|
|
addr := strings.TrimSpace(listenAddr)
|
|
if addr == "" {
|
|
return ""
|
|
}
|
|
_, port, err := net.SplitHostPort(addr)
|
|
if err != nil || port == "" {
|
|
return ""
|
|
}
|
|
base = "http://127.0.0.1:" + port
|
|
}
|
|
return strings.TrimRight(base, "/") + outboundImageRoute
|
|
}
|