| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | type SearchHit struct { |
| 14 | OLKey string `json:"key"` |
| 15 | Title string `json:"title"` |
| 16 | Authors string `json:"author_name"` |
| 17 | ISBN *string `json:"isbn,omitempty"` // canonical ISBN-13 |
| 18 | CoverURL *string `json:"cover_url,omitempty"` |
| 19 | } |
| 20 | |
| 21 | type olResponse struct { |
| 22 | Docs []olDoc `json:"docs"` |
| 23 | } |
| 24 | |
| 25 | type olDoc struct { |
| 26 | OLKey string `json:"key"` |
| 27 | Title string `json:"title"` |
| 28 | Authors []string `json:"author_name"` |
| 29 | ISBN []string `json:"isbn"` |
| 30 | CoverID int64 `json:"cover_i"` |
| 31 | } |
| 32 | |
| 33 | func openLibrarySearch(ctx context.Context, query string) ([]SearchHit, error) { |
| 34 | trimmed := strings.TrimSpace(query) |
| 35 | if trimmed == "" { |
| 36 | return nil, nil |
| 37 | } |
| 38 | queries := url.Values{ |
| 39 | "limit": {"10"}, |
| 40 | "fields": {"key,title,author_name,isbn,cover_i"}, |
| 41 | } |
| 42 | q := trimmed |
| 43 | if isISBNQuery(trimmed) { |
| 44 | q = strings.ToUpper(stripISBNSep(trimmed)) |
| 45 | queries.Add("isbn", q) |
| 46 | } else { |
| 47 | queries.Add("q", q) |
| 48 | } |
| 49 | u := "https://openlibrary.org/search.json?" + queries.Encode() |
| 50 | |
| 51 | client := &http.Client{Timeout: 8 * time.Second} |
| 52 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | req.Header.Set("User-Agent", "andromeda-library/0.1") |
| 57 | resp, err := client.Do(req) |
| 58 | if err != nil { |
| 59 | return nil, fmt.Errorf("request: %w", err) |
| 60 | } |
| 61 | defer resp.Body.Close() |
| 62 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 63 | return nil, fmt.Errorf("openlibrary status %s", resp.Status) |
| 64 | } |
| 65 | var data olResponse |
| 66 | if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { |
| 67 | return nil, fmt.Errorf("parse: %w", err) |
| 68 | } |
| 69 | |
| 70 | hits := make([]SearchHit, 0, len(data.Docs)) |
| 71 | for _, d := range data.Docs { |
| 72 | title := d.Title |
| 73 | if title == "" { |
| 74 | title = "Untitled" |
| 75 | } |
| 76 | hit := SearchHit{ |
| 77 | OLKey: d.OLKey, |
| 78 | Title: title, |
| 79 | Authors: strings.Join(d.Authors, ", "), |
| 80 | } |
| 81 | if isbn := pickISBN(d.ISBN); isbn != "" { |
| 82 | hit.ISBN = &isbn |
| 83 | } |
| 84 | if d.CoverID != 0 { |
| 85 | cover := fmt.Sprintf("https://covers.openlibrary.org/b/id/%d-L.jpg", d.CoverID) |
| 86 | hit.CoverURL = &cover |
| 87 | } |
| 88 | hits = append(hits, hit) |
| 89 | } |
| 90 | return hits, nil |
| 91 | } |
| 92 | |
| 93 | func isISBNChars(s string) bool { |
| 94 | for _, c := range s { |
| 95 | if (c < '0' || c > '9') && c != 'X' && c != 'x' { |
| 96 | return false |
| 97 | } |
| 98 | } |
| 99 | return true |
| 100 | } |
| 101 | |
| 102 | func isISBNQuery(s string) bool { |
| 103 | n := stripISBNSep(s) |
| 104 | return (len(n) == 10 || len(n) == 13) && isISBNChars(n) |
| 105 | } |
| 106 | |
| 107 | func stripISBNSep(s string) string { |
| 108 | return strings.Map(func(r rune) rune { |
| 109 | if r == '-' || r == ' ' { |
| 110 | return -1 |
| 111 | } |
| 112 | return r |
| 113 | }, s) |
| 114 | } |
| 115 | |
| 116 | // pickISBN normalizes to ISBN-13 and returns one canonical value. |
| 117 | func pickISBN(raw []string) string { |
| 118 | seen := map[string]struct{}{} |
| 119 | var firstValid string |
| 120 | for _, r := range raw { |
| 121 | n := strings.ToUpper(stripISBNSep(r)) |
| 122 | if len(n) == 10 { |
| 123 | if !validISBN10(n) { |
| 124 | continue |
| 125 | } |
| 126 | n, _ = isbn10to13(n) |
| 127 | } |
| 128 | if len(n) != 13 || !validISBN13(n) { |
| 129 | continue |
| 130 | } |
| 131 | if _, dup := seen[n]; dup { |
| 132 | continue |
| 133 | } |
| 134 | seen[n] = struct{}{} |
| 135 | if firstValid == "" { |
| 136 | firstValid = n |
| 137 | } |
| 138 | } |
| 139 | return firstValid |
| 140 | } |
| 141 | |
| 142 | func validISBN13(s string) bool { |
| 143 | sum := 0 |
| 144 | for i, c := range s { |
| 145 | d := int(c - '0') |
| 146 | if d < 0 || d > 9 { |
| 147 | return false |
| 148 | } |
| 149 | if i%2 == 1 { |
| 150 | d *= 3 |
| 151 | } |
| 152 | sum += d |
| 153 | } |
| 154 | return sum%10 == 0 |
| 155 | } |
| 156 | |
| 157 | func validISBN10(s string) bool { |
| 158 | sum := 0 |
| 159 | for i, c := range s { |
| 160 | d := 10 |
| 161 | if c != 'X' { |
| 162 | d = int(c - '0') |
| 163 | if d < 0 || d > 9 { |
| 164 | return false |
| 165 | } |
| 166 | } else if i != 9 { |
| 167 | return false |
| 168 | } |
| 169 | sum += d * (10 - i) |
| 170 | } |
| 171 | return sum%11 == 0 |
| 172 | } |
| 173 | |
| 174 | func isbn10to13(s string) (string, bool) { |
| 175 | if len(s) != 10 { |
| 176 | return "", false |
| 177 | } |
| 178 | base := "978" + s[:9] |
| 179 | sum := 0 |
| 180 | for i, c := range base { |
| 181 | d := int(c - '0') |
| 182 | if d < 0 || d > 9 { |
| 183 | return "", false |
| 184 | } |
| 185 | if i%2 == 1 { |
| 186 | d *= 3 |
| 187 | } |
| 188 | sum += d |
| 189 | } |
| 190 | return base + string(rune('0'+(10-sum%10)%10)), true |
| 191 | } |