package websearch import ( "bytes" "context" "encoding/json" "errors" "net/http" "net/url" "strconv" "strings" "amadan.net/oficina/equipo/internal/websource/guard" ) // The backends' fixed origins: a key goes to nowhere else. const ( kagiOrigin = "https://kagi.com" mojeekOrigin = "https://www.mojeek.com" braveOrigin = "https://api.search.brave.com" ) // backend is one vendor: its name, its guarded client, and how its // request is made and its answer read. type backend struct { name string client *guard.Client request func(q string, n int) (*http.Request, error) parse func(status int, body []byte) ([]Result, string) } func (b *backend) Name() string { return b.name } // Search sends one query and reads its results. A guard refusal is // unavailable (a 3xx, never followed, is bad_response); any other error // from the guard is the context's final check refusing, and comes back // as it is, so the chain stops. func (b *backend) Search(ctx context.Context, q string, n int) ([]Result, error) { if n <= 0 || n > MaxResults { n = MaxResults } req, err := b.request(q, n) if err != nil { return nil, &Error{Backend: b.name, Class: ClassBadResponse} } res, err := b.client.Do(ctx, req) if err != nil { var r guard.Refusal if !errors.As(err, &r) { return nil, err } if r.Rule == guard.RuleRedirect { return nil, &Error{Backend: b.name, Class: ClassBadResponse} } return nil, &Error{Backend: b.name, Class: ClassUnavailable, Unsent: !r.Sent} } results, class := b.parse(res.Status, res.Body) if class != "" { return nil, &Error{Backend: b.name, Class: class} } return clean(results, n), nil } // statusClass is a non-200's class: 401 and 403 auth, 402 and 429 limit // (out of credit, or too many), 5xx unavailable, else bad_response. func statusClass(status int) string { switch { case status == http.StatusOK: return "" case status == http.StatusUnauthorized || status == http.StatusForbidden: return ClassAuth case status == http.StatusPaymentRequired || status == http.StatusTooManyRequests: return ClassLimit case status >= 500: return ClassUnavailable } return ClassBadResponse } // searchClient is a backend's own guarded client: searches' policy, no // redirects, the key bound to its origin. func searchClient(g guard.Config, cred guard.Credential) (*guard.Client, error) { g.Policy, g.Redirects, g.Credential = guard.PolicySearch, 0, &cred g.Timeouts = guard.Timeouts{} return guard.New(g) } // NewKagi is Kagi's v1 search: POST https://kagi.com/api/v1/search with // the key as a bearer and a JSON body of only query and limit. func NewKagi(key string, g guard.Config) (Searcher, error) { c, err := searchClient(g, guard.Credential{Origin: kagiOrigin, Header: "Authorization", Value: "Bearer " + key}) if err != nil { return nil, err } return &backend{name: Kagi, client: c, request: func(q string, n int) (*http.Request, error) { body, err := json.Marshal(struct { Query string `json:"query"` Limit int `json:"limit"` }{q, n}) if err != nil { return nil, err } req, err := http.NewRequest(http.MethodPost, kagiOrigin+"/api/v1/search", bytes.NewReader(body)) if err == nil { req.Header.Set("Content-Type", "application/json") } return req, err }, parse: func(status int, body []byte) ([]Result, string) { if c := statusClass(status); c != "" { return nil, c } var out struct { Data *struct { Search []struct { URL string `json:"url"` Title string `json:"title"` Snippet string `json:"snippet"` Time string `json:"time"` } `json:"search"` } `json:"data"` Error []json.RawMessage `json:"error"` } if json.Unmarshal(body, &out) != nil || len(out.Error) > 0 || out.Data == nil { return nil, ClassBadResponse } results := make([]Result, 0, len(out.Data.Search)) for _, r := range out.Data.Search { results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Snippet, Date: r.Time}) } return results, "" }}, nil } // NewMojeek is Mojeek's search (optional fallback): GET // https://www.mojeek.com/search with the key as api_key. func NewMojeek(key string, g guard.Config) (Searcher, error) { c, err := searchClient(g, guard.Credential{Origin: mojeekOrigin, Param: "api_key", Value: key}) if err != nil { return nil, err } return &backend{name: Mojeek, client: c, request: func(q string, n int) (*http.Request, error) { v := url.Values{"q": {q}, "fmt": {"json"}, "t": {strconv.Itoa(n)}, "date": {"1"}} return http.NewRequest(http.MethodGet, mojeekOrigin+"/search?"+v.Encode(), nil) }, parse: func(status int, body []byte) ([]Result, string) { if c := statusClass(status); c != "" { return nil, c } var out struct { Response struct { Status string `json:"status"` Results []struct { URL string `json:"url"` Title string `json:"title"` Desc string `json:"desc"` Date any `json:"date"` } `json:"results"` } `json:"response"` } if json.Unmarshal(body, &out) != nil { return nil, ClassBadResponse } if s := out.Response.Status; s != "OK" { if strings.Contains(strings.ToLower(s), "limit") { return nil, ClassLimit } return nil, ClassBadResponse } results := make([]Result, 0, len(out.Response.Results)) for _, r := range out.Response.Results { date := "" switch d := r.Date.(type) { case string: date = d case float64: date = strconv.FormatInt(int64(d), 10) } results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Desc, Date: date}) } return results, "" }}, nil } // NewBrave is Brave's web search (optional fallback): GET // https://api.search.brave.com/res/v1/web/search with the key as // X-Subscription-Token. func NewBrave(key string, g guard.Config) (Searcher, error) { c, err := searchClient(g, guard.Credential{Origin: braveOrigin, Header: "X-Subscription-Token", Value: key}) if err != nil { return nil, err } return &backend{name: Brave, client: c, request: func(q string, n int) (*http.Request, error) { v := url.Values{"q": {q}, "count": {strconv.Itoa(n)}} return http.NewRequest(http.MethodGet, braveOrigin+"/res/v1/web/search?"+v.Encode(), nil) }, parse: func(status int, body []byte) ([]Result, string) { if c := statusClass(status); c != "" { return nil, c } var out struct { Web struct { Results []struct { Title string `json:"title"` URL string `json:"url"` Description string `json:"description"` Age string `json:"age"` } `json:"results"` } `json:"web"` } if json.Unmarshal(body, &out) != nil { return nil, ClassBadResponse } results := make([]Result, 0, len(out.Web.Results)) for _, r := range out.Web.Results { results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Description, Date: r.Age}) } return results, "" }}, nil }