Files
TradarrV2/backend/internal/scraper/bloomberg/content.go

94 lines
2.9 KiB
Go

package bloomberg
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"strings"
"time"
)
const maxContentBytes = 2 * 1024 * 1024
const enrichmentTimeout = 100 * time.Second // Node total budget 90s plus transport margin.
func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, password string, articles []scraper.Article) ([]scraper.Article, error) {
out := append([]scraper.Article(nil), articles...)
if len(out) == 0 {
return out, nil
}
ctx, cancel := context.WithTimeout(ctx, enrichmentTimeout)
defer cancel()
urls := make([]string, len(out))
for i, a := range out {
urls[i] = a.URL
}
payload, _ := json.Marshal(struct {
Username string `json:"username"`
Password string `json:"password"`
URLs []string `json:"urls"`
}{username, password, urls})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/enrich", bytes.NewReader(payload))
if err != nil {
return nil, errors.New("bloomberg: enrichment request failed")
}
req.Header.Set("Content-Type", "application/json")
resp, err := b.client.Do(req)
if err != nil {
return nil, scraperFailure(ctx, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bloomberg: enrichment HTTP %d", resp.StatusCode)
}
maximum := min(int64(len(out))*(6*maxContentBytes+8192)+1024, 32*1024*1024)
raw, err := io.ReadAll(io.LimitReader(resp.Body, maximum+1))
if err != nil {
return nil, scraperFailure(ctx, err)
}
if int64(len(raw)) > maximum {
return nil, errors.New("bloomberg: enrichment response too large")
}
var result struct {
Articles []struct {
ContentState string `json:"content_state"`
URL string `json:"url"`
Content string `json:"content"`
ContentTruncated bool `json:"content_truncated"`
PublishedAt json.RawMessage `json:"published_at"`
}
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(raw, &result) != nil || len(result.Articles) != len(out) || (len(result.Error) > 0 && string(result.Error) != "null") {
return nil, errors.New("bloomberg: invalid enrichment response")
}
for i, a := range result.Articles {
if a.URL != out[i].URL {
return nil, errors.New("bloomberg: invalid enrichment association")
}
content := a.Content
truncated := a.ContentTruncated
state := a.ContentState
if state != scraper.ContentComplete || truncated || len(content) > maxContentBytes {
state = scraper.ContentIncomplete
}
if strings.TrimSpace(content) == "" {
state = scraper.ContentUnavailable
}
out[i].ContentState = state
out[i].Content = content
out[i].ContentTruncated = truncated && content != ""
var date string
if json.Unmarshal(a.PublishedAt, &date) == nil {
if parsed, err := time.Parse(time.RFC3339Nano, date); err == nil {
out[i].PublishedAt = &parsed
}
}
}
return out, nil
}