initial
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
// Websuche über die Brave Search API, liefert je Fundstelle Titel, URL und Kurzbeschreibung.
|
||||
|
||||
package brave
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.karlbreuer.com/karl/research/pkg/settings"
|
||||
)
|
||||
|
||||
const searchURL = "https://api.search.brave.com/res/v1/web/search"
|
||||
|
||||
// Abstand zwischen zwei Anfragen, Brave erlaubt eine pro Sekunde
|
||||
const minInterval = 1200 * time.Millisecond
|
||||
|
||||
// gilt je Anfrage, die Wartezeit in der Queue zählt nicht mit
|
||||
const searchTimeout = 30 * time.Second
|
||||
|
||||
// Versuche pro Suche, wiederholt wird nur bei Ratelimit
|
||||
const maxTries = 3
|
||||
|
||||
// kein eigenes Timeout, die Laufzeit bestimmt der Context
|
||||
var searchClient = &http.Client{}
|
||||
|
||||
// Result ist eine Fundstelle der Websuche.
|
||||
type Result struct {
|
||||
URL string
|
||||
Title string
|
||||
Description string // kurzer Textausschnitt der Seite
|
||||
}
|
||||
|
||||
// Error ist eine Fehlerantwort von Brave.
|
||||
type Error struct {
|
||||
Status int
|
||||
Code string // z.B. RATE_LIMITED, QUOTA_LIMITED
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Code != "" {
|
||||
return fmt.Sprintf("HTTP %d %s: %s", e.Status, e.Code, e.Message)
|
||||
}
|
||||
return fmt.Sprintf("HTTP %d: %s", e.Status, e.Message)
|
||||
}
|
||||
|
||||
// Kontingent aufgebraucht kommt auch als 429, da hilft Warten nicht
|
||||
func rateLimited(err error) bool {
|
||||
var be *Error
|
||||
return errors.As(err, &be) && be.Status == http.StatusTooManyRequests && be.Code != "QUOTA_LIMITED"
|
||||
}
|
||||
|
||||
type errRespT struct {
|
||||
Error struct {
|
||||
Detail string `json:"detail"`
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type searchRespT struct {
|
||||
Web struct {
|
||||
Results []struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
} `json:"results"`
|
||||
} `json:"web"`
|
||||
}
|
||||
|
||||
var (
|
||||
// Platz 1 in der Queue, wartende Sender kommen in Reihenfolge ihrer Ankunft dran
|
||||
slot = make(chan struct{}, 1)
|
||||
// frühester Start der nächsten Anfrage, nur mit belegtem slot anfassen
|
||||
nextStart time.Time
|
||||
)
|
||||
|
||||
// wait reiht den Aufrufer ein und gibt ihn frühestens minInterval nach dem Vorgänger frei.
|
||||
func wait() {
|
||||
slot <- struct{}{}
|
||||
time.Sleep(time.Until(nextStart))
|
||||
nextStart = time.Now().Add(minInterval)
|
||||
<-slot
|
||||
}
|
||||
|
||||
// Search sucht nach query und liefert die Fundstellen in der Reihenfolge von Brave.
|
||||
// Brave nimmt pro Anfrage nur einen Suchtext an, mehrere Suchen laufen über mehrere Aufrufe.
|
||||
// Alle Aufrufe im Prozess teilen sich eine Queue, Search ist aus mehreren Goroutinen nutzbar.
|
||||
// Keine Treffer sind kein Fehler, dann ist das Ergebnis leer.
|
||||
func Search(query string) ([]Result, error) {
|
||||
apiKey := settings.Get().BRAVE_KEY
|
||||
if apiKey == "" {
|
||||
return nil, errors.New("BRAVE_KEY nicht gesetzt")
|
||||
}
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return nil, errors.New("leere suchanfrage")
|
||||
}
|
||||
|
||||
var err error
|
||||
for range maxTries {
|
||||
wait()
|
||||
var res []Result
|
||||
if res, err = searchOnce(apiKey, query); err == nil {
|
||||
return res, nil
|
||||
}
|
||||
if !rateLimited(err) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func searchOnce(apiKey, query string) ([]Result, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), searchTimeout)
|
||||
defer cancel()
|
||||
|
||||
params := url.Values{}
|
||||
params.Set("q", query)
|
||||
// nur Webtreffer, ohne Hervorhebungen im Text
|
||||
params.Set("result_filter", "web")
|
||||
params.Set("text_decorations", "false")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL+"?"+params.Encode(), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request bauen: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-Subscription-Token", apiKey)
|
||||
|
||||
resp, err := searchClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request senden: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
out, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("body lesen: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
e := &Error{Status: resp.StatusCode, Message: strings.TrimSpace(string(out))}
|
||||
var parsed errRespT
|
||||
if json.Unmarshal(out, &parsed) == nil {
|
||||
e.Code = parsed.Error.Code
|
||||
if parsed.Error.Detail != "" {
|
||||
e.Message = parsed.Error.Detail
|
||||
}
|
||||
}
|
||||
return nil, e
|
||||
}
|
||||
|
||||
var parsed searchRespT
|
||||
if err := json.Unmarshal(out, &parsed); err != nil {
|
||||
return nil, fmt.Errorf("antwort unmarshal: %w; rohausgabe: %s", err, string(out))
|
||||
}
|
||||
res := make([]Result, 0, len(parsed.Web.Results))
|
||||
for _, r := range parsed.Web.Results {
|
||||
// Titel und Beschreibung können HTML Entities enthalten
|
||||
res = append(res, Result{r.URL, html.UnescapeString(r.Title), html.UnescapeString(r.Description)})
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
Reference in New Issue
Block a user