oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package websearch
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "net/http"
9 "net/url"
10 "strconv"
11 "strings"
12
13 "amadan.net/oficina/equipo/internal/websource/guard"
14)
15
16// The backends' fixed origins: a key goes to nowhere else.
17const (
18 kagiOrigin = "https://kagi.com"
19 mojeekOrigin = "https://www.mojeek.com"
20 braveOrigin = "https://api.search.brave.com"
21)
22
23// backend is one vendor: its name, its guarded client, and how its
24// request is made and its answer read.
25type backend struct {
26 name string
27 client *guard.Client
28 request func(q string, n int) (*http.Request, error)
29 parse func(status int, body []byte) ([]Result, string)
30}
31
32func (b *backend) Name() string { return b.name }
33
34// Search sends one query and reads its results. A guard refusal is
35// unavailable (a 3xx, never followed, is bad_response); any other error
36// from the guard is the context's final check refusing, and comes back
37// as it is, so the chain stops.
38func (b *backend) Search(ctx context.Context, q string, n int) ([]Result, error) {
39 if n <= 0 || n > MaxResults {
40 n = MaxResults
41 }
42 req, err := b.request(q, n)
43 if err != nil {
44 return nil, &Error{Backend: b.name, Class: ClassBadResponse}
45 }
46 res, err := b.client.Do(ctx, req)
47 if err != nil {
48 var r guard.Refusal
49 if !errors.As(err, &r) {
50 return nil, err
51 }
52 if r.Rule == guard.RuleRedirect {
53 return nil, &Error{Backend: b.name, Class: ClassBadResponse}
54 }
55 return nil, &Error{Backend: b.name, Class: ClassUnavailable, Unsent: !r.Sent}
56 }
57 results, class := b.parse(res.Status, res.Body)
58 if class != "" {
59 return nil, &Error{Backend: b.name, Class: class}
60 }
61 return clean(results, n), nil
62}
63
64// statusClass is a non-200's class: 401 and 403 auth, 402 and 429 limit
65// (out of credit, or too many), 5xx unavailable, else bad_response.
66func statusClass(status int) string {
67 switch {
68 case status == http.StatusOK:
69 return ""
70 case status == http.StatusUnauthorized || status == http.StatusForbidden:
71 return ClassAuth
72 case status == http.StatusPaymentRequired || status == http.StatusTooManyRequests:
73 return ClassLimit
74 case status >= 500:
75 return ClassUnavailable
76 }
77 return ClassBadResponse
78}
79
80// searchClient is a backend's own guarded client: searches' policy, no
81// redirects, the key bound to its origin.
82func searchClient(g guard.Config, cred guard.Credential) (*guard.Client, error) {
83 g.Policy, g.Redirects, g.Credential = guard.PolicySearch, 0, &cred
84 g.Timeouts = guard.Timeouts{}
85 return guard.New(g)
86}
87
88// NewKagi is Kagi's v1 search: POST https://kagi.com/api/v1/search with
89// the key as a bearer and a JSON body of only query and limit.
90func NewKagi(key string, g guard.Config) (Searcher, error) {
91 c, err := searchClient(g, guard.Credential{Origin: kagiOrigin, Header: "Authorization", Value: "Bearer " + key})
92 if err != nil {
93 return nil, err
94 }
95 return &backend{name: Kagi, client: c,
96 request: func(q string, n int) (*http.Request, error) {
97 body, err := json.Marshal(struct {
98 Query string `json:"query"`
99 Limit int `json:"limit"`
100 }{q, n})
101 if err != nil {
102 return nil, err
103 }
104 req, err := http.NewRequest(http.MethodPost, kagiOrigin+"/api/v1/search", bytes.NewReader(body))
105 if err == nil {
106 req.Header.Set("Content-Type", "application/json")
107 }
108 return req, err
109 },
110 parse: func(status int, body []byte) ([]Result, string) {
111 if c := statusClass(status); c != "" {
112 return nil, c
113 }
114 var out struct {
115 Data *struct {
116 Search []struct {
117 URL string `json:"url"`
118 Title string `json:"title"`
119 Snippet string `json:"snippet"`
120 Time string `json:"time"`
121 } `json:"search"`
122 } `json:"data"`
123 Error []json.RawMessage `json:"error"`
124 }
125 if json.Unmarshal(body, &out) != nil || len(out.Error) > 0 || out.Data == nil {
126 return nil, ClassBadResponse
127 }
128 results := make([]Result, 0, len(out.Data.Search))
129 for _, r := range out.Data.Search {
130 results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Snippet, Date: r.Time})
131 }
132 return results, ""
133 }}, nil
134}
135
136// NewMojeek is Mojeek's search (optional fallback): GET
137// https://www.mojeek.com/search with the key as api_key.
138func NewMojeek(key string, g guard.Config) (Searcher, error) {
139 c, err := searchClient(g, guard.Credential{Origin: mojeekOrigin, Param: "api_key", Value: key})
140 if err != nil {
141 return nil, err
142 }
143 return &backend{name: Mojeek, client: c,
144 request: func(q string, n int) (*http.Request, error) {
145 v := url.Values{"q": {q}, "fmt": {"json"}, "t": {strconv.Itoa(n)}, "date": {"1"}}
146 return http.NewRequest(http.MethodGet, mojeekOrigin+"/search?"+v.Encode(), nil)
147 },
148 parse: func(status int, body []byte) ([]Result, string) {
149 if c := statusClass(status); c != "" {
150 return nil, c
151 }
152 var out struct {
153 Response struct {
154 Status string `json:"status"`
155 Results []struct {
156 URL string `json:"url"`
157 Title string `json:"title"`
158 Desc string `json:"desc"`
159 Date any `json:"date"`
160 } `json:"results"`
161 } `json:"response"`
162 }
163 if json.Unmarshal(body, &out) != nil {
164 return nil, ClassBadResponse
165 }
166 if s := out.Response.Status; s != "OK" {
167 if strings.Contains(strings.ToLower(s), "limit") {
168 return nil, ClassLimit
169 }
170 return nil, ClassBadResponse
171 }
172 results := make([]Result, 0, len(out.Response.Results))
173 for _, r := range out.Response.Results {
174 date := ""
175 switch d := r.Date.(type) {
176 case string:
177 date = d
178 case float64:
179 date = strconv.FormatInt(int64(d), 10)
180 }
181 results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Desc, Date: date})
182 }
183 return results, ""
184 }}, nil
185}
186
187// NewBrave is Brave's web search (optional fallback): GET
188// https://api.search.brave.com/res/v1/web/search with the key as
189// X-Subscription-Token.
190func NewBrave(key string, g guard.Config) (Searcher, error) {
191 c, err := searchClient(g, guard.Credential{Origin: braveOrigin, Header: "X-Subscription-Token", Value: key})
192 if err != nil {
193 return nil, err
194 }
195 return &backend{name: Brave, client: c,
196 request: func(q string, n int) (*http.Request, error) {
197 v := url.Values{"q": {q}, "count": {strconv.Itoa(n)}}
198 return http.NewRequest(http.MethodGet, braveOrigin+"/res/v1/web/search?"+v.Encode(), nil)
199 },
200 parse: func(status int, body []byte) ([]Result, string) {
201 if c := statusClass(status); c != "" {
202 return nil, c
203 }
204 var out struct {
205 Web struct {
206 Results []struct {
207 Title string `json:"title"`
208 URL string `json:"url"`
209 Description string `json:"description"`
210 Age string `json:"age"`
211 } `json:"results"`
212 } `json:"web"`
213 }
214 if json.Unmarshal(body, &out) != nil {
215 return nil, ClassBadResponse
216 }
217 results := make([]Result, 0, len(out.Web.Results))
218 for _, r := range out.Web.Results {
219 results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Description, Date: r.Age})
220 }
221 return results, ""
222 }}, nil
223}
224