chore(library): added specific query if isbn 5cb1fd08
Steve · 2026-10-26 07:00 1 file(s) · +138 −140
apps/library/openlibrary.go +138 −140
11 11
)
12 12
13 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"`
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 19
}
20 20
21 21
type olResponse struct {
22 -
    Docs []olDoc `json:"docs"`
22 +
	Docs []olDoc `json:"docs"`
23 23
}
24 24
25 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"`
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 31
}
32 32
33 33
func openLibrarySearch(ctx context.Context, query string) ([]SearchHit, error) {
34 -
    trimmed := strings.TrimSpace(query)
35 -
    if trimmed == "" {
36 -
        return nil, nil
37 -
    }
38 -
    q := trimmed
39 -
    if isISBNQuery(trimmed) {
40 -
        // Open Library normalizes both ISBN-10 and ISBN-13 here; just uppercase.
41 -
        q = "isbn:" + strings.ToUpper(stripISBNSep(trimmed))
42 -
    }
43 -
    u := "https://openlibrary.org/search.json?" + url.Values{
44 -
        "q":      {q},
45 -
        "limit":  {"10"},
46 -
        // Explicit fields: since Jan 2025 the default field set is reduced,
47 -
        // so you must ask for what you use.
48 -
        "fields": {"key,title,author_name,isbn,cover_i"},
49 -
    }.Encode()
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 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") // no API key needed
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 -
    }
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 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
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 91
}
92 -
93 92
94 93
func isISBNChars(s string) bool {
95 94
	for _, c := range s {
101 100
}
102 101
103 102
func isISBNQuery(s string) bool {
104 -
    n := stripISBNSep(s)
105 -
    return (len(n) == 10 || len(n) == 13) && isISBNChars(n)
103 +
	n := stripISBNSep(s)
104 +
	return (len(n) == 10 || len(n) == 13) && isISBNChars(n)
106 105
}
107 106
108 107
func stripISBNSep(s string) string {
109 -
    return strings.Map(func(r rune) rune {
110 -
        if r == '-' || r == ' ' {
111 -
            return -1
112 -
        }
113 -
        return r
114 -
    }, s)
108 +
	return strings.Map(func(r rune) rune {
109 +
		if r == '-' || r == ' ' {
110 +
			return -1
111 +
		}
112 +
		return r
113 +
	}, s)
115 114
}
116 115
117 116
// pickISBN normalizes to ISBN-13 and returns one canonical value.
118 117
func pickISBN(raw []string) string {
119 -
    seen := map[string]struct{}{}
120 -
    var firstValid string
121 -
    for _, r := range raw {
122 -
        n := strings.ToUpper(stripISBNSep(r))
123 -
        if len(n) == 10 {
124 -
            if !validISBN10(n) {
125 -
                continue
126 -
            }
127 -
            n, _ = isbn10to13(n)
128 -
        }
129 -
        if len(n) != 13 || !validISBN13(n) {
130 -
            continue
131 -
        }
132 -
        if _, dup := seen[n]; dup {
133 -
            continue
134 -
        }
135 -
        seen[n] = struct{}{}
136 -
        if firstValid == "" {
137 -
            firstValid = n
138 -
        }
139 -
    }
140 -
    return firstValid
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
141 140
}
142 141
143 142
func validISBN13(s string) bool {
144 -
    sum := 0
145 -
    for i, c := range s {
146 -
        d := int(c - '0')
147 -
        if d < 0 || d > 9 {
148 -
            return false
149 -
        }
150 -
        if i%2 == 1 {
151 -
            d *= 3
152 -
        }
153 -
        sum += d
154 -
    }
155 -
    return sum%10 == 0
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
156 155
}
157 156
158 157
func validISBN10(s string) bool {
159 -
    sum := 0
160 -
    for i, c := range s {
161 -
        d := 10
162 -
        if c != 'X' {
163 -
            d = int(c - '0')
164 -
            if d < 0 || d > 9 {
165 -
                return false
166 -
            }
167 -
        } else if i != 9 {
168 -
            return false // X only valid as check digit
169 -
        }
170 -
        sum += d * (10 - i)
171 -
    }
172 -
    return sum%11 == 0
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
173 172
}
174 173
175 174
func isbn10to13(s string) (string, bool) {
176 -
    if len(s) != 10 {
177 -
        return "", false
178 -
    }
179 -
    base := "978" + s[:9]
180 -
    sum := 0
181 -
    for i, c := range base {
182 -
        d := int(c - '0')
183 -
        if d < 0 || d > 9 {
184 -
            return "", false
185 -
        }
186 -
        if i%2 == 1 {
187 -
            d *= 3
188 -
        }
189 -
        sum += d
190 -
    }
191 -
    return base + string(rune('0'+(10-sum%10)%10)), true
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
192 191
}
193 -