package main import ( "errors" "net/http" "strings" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/outboundimage" ) const ( outboundImageMaxCount = 5 outboundImageMaxBytes = 10 << 20 outboundImagePrefix = "dobotai/im-images" outboundImageRoute = "/dingtalk/i/" ) 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 } 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), publisher: publisher, handler: handler, }, nil } func buildOutboundImageRewriter(cfg outboundImageConfig) (dingtalk.OutboundContentRewriter, error) { runtime, err := buildOutboundImageRuntime(cfg) return runtime.rewriter, err }