Files
dobotai-platform/internal/outboundimage/weknora_fetcher.go
T

81 lines
2.7 KiB
Go

package outboundimage
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type WeKnoraFetcher struct {
baseURL *url.URL
apiKey string
client *http.Client
maxBytes int64
}
func NewWeKnoraFetcher(baseURL, apiKey string, client *http.Client, maxBytes int64) (*WeKnoraFetcher, error) {
parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return nil, errors.New("outbound image: invalid WeKnora base URL")
}
if strings.TrimSpace(apiKey) == "" {
return nil, errors.New("outbound image: WeKnora API key is required")
}
if maxBytes <= 0 {
return nil, errors.New("outbound image: positive max bytes is required")
}
if client == nil {
client = &http.Client{Timeout: 30 * time.Second}
}
return &WeKnoraFetcher{baseURL: parsed, apiKey: apiKey, client: client, maxBytes: maxBytes}, nil
}
func (f *WeKnoraFetcher) Fetch(ctx context.Context, reference string) ([]byte, string, error) {
if !strings.HasPrefix(reference, "resource://") || !resourceMarkdownImageRE.MatchString("![]("+reference+")") {
return nil, "", errors.New("outbound image: unsupported resource reference")
}
u := *f.baseURL
u.Path = "/files"
u.RawPath = ""
query := u.Query()
query.Set("file_path", reference)
u.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, "", errors.New("outbound image: create WeKnora request failed")
}
req.Header.Set("X-API-Key", f.apiKey)
resp, err := f.client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("outbound image: WeKnora request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return nil, "", fmt.Errorf("outbound image: WeKnora HTTP %d", resp.StatusCode)
}
contentType := strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])
if !strings.HasPrefix(contentType, "image/") {
return nil, "", errors.New("outbound image: WeKnora response is not an image")
}
if length := strings.TrimSpace(resp.Header.Get("Content-Length")); length != "" {
if n, convErr := strconv.ParseInt(length, 10, 64); convErr == nil && n > f.maxBytes {
return nil, "", errors.New("outbound image: WeKnora image exceeds size limit")
}
}
data, err := io.ReadAll(io.LimitReader(resp.Body, f.maxBytes+1))
if err != nil {
return nil, "", errors.New("outbound image: read WeKnora response failed")
}
if int64(len(data)) == 0 || int64(len(data)) > f.maxBytes {
return nil, "", errors.New("outbound image: WeKnora image exceeds size limit")
}
return data, contentType, nil
}