chore(library): initial work to migrate from google books api to open library f13f9d48
Steve · 2026-10-25 21:06 12 file(s) · +549 −155
TODO.md (deleted) +0 −0

Binary file — no preview.

apps/library/TODO.md (added) +14 −0
1 +
- [x] Update `db.go` to include the following:
2 +
  - [x] `ol_key`:  `docs[i].key`
3 +
  - [x] db migration
4 +
- [/] Refactor
5 +
  - [x] `db.go`
6 +
  - [x] `db_test.go`
7 +
  - [x] `google_books.go` - > `openlibrary.go`
8 +
    - [x] See if we can get what we need from the [fields](https://github.com/internetarchive/openlibrary/blob/b4afa14b0981ae1785c26c71908af99b879fa975/openlibrary/plugins/worksearch/schemes/works.py#L38-L91)
9 +
  - [x] `handlers_web.go`
10 +
  - [x] `templates/admin.html`
11 +
  - [x] `main.go`
12 +
  - [ ] `docker-compose.yml`
13 +
  - [x] `app.go`
14 +
  - [ ] `README.md`
apps/library/app.go +0 −1
32 32
	Templates      *template.Template
33 33
	Sessions       *auth.Store
34 34
	AdminPassword  string
35 -
	GoogleBooksKey string
36 35
	CookieSecure   bool
37 36
	BaseURL        string
38 37
	DisplayMode    DisplayMode
apps/library/db.go +17 −7
11 11
CREATE TABLE IF NOT EXISTS books (
12 12
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
13 13
    google_id     TEXT UNIQUE,
14 +
		ol_key        TEXT,
14 15
    title         TEXT NOT NULL,
15 16
    authors       TEXT NOT NULL,
16 17
    isbn          TEXT,
31 32
type Book struct {
32 33
	ID        int64   `json:"id"`
33 34
	GoogleID  *string `json:"google_id,omitempty"`
35 +
	OLKey     *string `json:"key,omitempty"`
34 36
	Title     string  `json:"title"`
35 37
	Authors   string  `json:"authors"`
36 38
	ISBN      *string `json:"isbn,omitempty"`
43 45
44 46
type NewBook struct {
45 47
	GoogleID *string
48 +
	OLKey    *string
46 49
	Title    string
47 50
	Authors  string
48 51
	ISBN     *string
61 64
	return CategoryLabels{Reading: "Reading", Read: "Read", Want: "Want to Read"}
62 65
}
63 66
64 -
const selectCols = `id, google_id, title, authors, isbn, cover_url, notes, status, added_at, updated_at`
67 +
const selectCols = `id, google_id, ol_key, title, authors, isbn, cover_url, notes, status, added_at, updated_at`
65 68
66 69
func scanBook(s interface{ Scan(...any) error }) (*Book, error) {
67 70
	var b Book
68 -
	var gid, isbn, cover, notes sql.NullString
69 -
	err := s.Scan(&b.ID, &gid, &b.Title, &b.Authors, &isbn, &cover, &notes, &b.Status, &b.AddedAt, &b.UpdatedAt)
71 +
	var gid, olKey, isbn, cover, notes sql.NullString
72 +
	err := s.Scan(&b.ID, &gid, &olKey, &b.Title, &b.Authors, &isbn, &cover, &notes, &b.Status, &b.AddedAt, &b.UpdatedAt)
70 73
	if errors.Is(err, sql.ErrNoRows) {
71 74
		return nil, nil
72 75
	}
77 80
		v := gid.String
78 81
		b.GoogleID = &v
79 82
	}
83 +
	if olKey.Valid {
84 +
		v := olKey.String
85 +
		b.OLKey = &v
86 +
	}
80 87
	if isbn.Valid {
81 88
		v := isbn.String
82 89
		b.ISBN = &v
121 128
122 129
func insertBook(db *sql.DB, b NewBook) (int64, error) {
123 130
	now := time.Now().UTC().Unix()
124 -
	var gid, isbn, cover, notes any
131 +
	var gid, olKey, isbn, cover, notes any
125 132
	if b.GoogleID != nil && *b.GoogleID != "" {
126 133
		gid = *b.GoogleID
134 +
	}
135 +
	if b.OLKey != nil && *b.OLKey != "" {
136 +
		olKey = *b.OLKey
127 137
	}
128 138
	if b.ISBN != nil && *b.ISBN != "" {
129 139
		isbn = *b.ISBN
135 145
		notes = *b.Notes
136 146
	}
137 147
	res, err := db.Exec(
138 -
		`INSERT INTO books (google_id, title, authors, isbn, cover_url, notes, status, added_at, updated_at)
139 -
		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
148 +
		`INSERT INTO books (google_id, ol_key, title, authors, isbn, cover_url, notes, status, added_at, updated_at)
149 +
		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
140 150
		 ON CONFLICT(google_id) DO UPDATE SET status = excluded.status, updated_at = excluded.updated_at`,
141 -
		gid, b.Title, b.Authors, isbn, cover, notes, b.Status, now, now,
151 +
		gid, olKey, b.Title, b.Authors, isbn, cover, notes, b.Status, now, now,
142 152
	)
143 153
	if err != nil {
144 154
		return 0, err
apps/library/db_test.go +0 −3
69 69
		t.Fatalf("labels %#v", labels)
70 70
	}
71 71
72 -
	if got := pickISBN([]identifier{{Kind: "ISBN_10", Identifier: "ten"}, {Kind: "ISBN_13", Identifier: "thirteen"}}); got != "thirteen" {
73 -
		t.Fatalf("isbn %q", got)
74 -
	}
75 72
	if !isISBNChars("123456789X") || isISBNChars("123ABC") {
76 73
		t.Fatal("isbn char validation failed")
77 74
	}
apps/library/docker-compose.yml +0 −1
10 10
      - PORT=${PORT:-3000}
11 11
      - LIBRARY_DB_PATH=/data/library-go.sqlite
12 12
      - ADMIN_PASSWORD=${ADMIN_PASSWORD:-changeme}
13 -
      - GOOGLE_BOOKS_API_KEY=${GOOGLE_BOOKS_API_KEY:-}
14 13
      - BASE_URL=${BASE_URL:-http://localhost:${PORT:-3000}}
15 14
      - LIBRARY_DISPLAY_MODE=${LIBRARY_DISPLAY_MODE:-inline}
16 15
      - COOKIE_SECURE=${COOKIE_SECURE:-false}
apps/library/google_books.go (deleted) +0 −136
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 -
	GoogleID string  `json:"google_id"`
15 -
	Title    string  `json:"title"`
16 -
	Authors  string  `json:"authors"`
17 -
	ISBN     *string `json:"isbn,omitempty"`
18 -
	CoverURL *string `json:"cover_url,omitempty"`
19 -
}
20 -
21 -
type volumesResponse struct {
22 -
	Items []volume `json:"items"`
23 -
}
24 -
25 -
type volume struct {
26 -
	ID         string     `json:"id"`
27 -
	VolumeInfo volumeInfo `json:"volumeInfo"`
28 -
}
29 -
30 -
type volumeInfo struct {
31 -
	Title       string       `json:"title"`
32 -
	Authors     []string     `json:"authors"`
33 -
	Identifiers []identifier `json:"industryIdentifiers"`
34 -
	ImageLinks  *imageLinks  `json:"imageLinks"`
35 -
}
36 -
37 -
type identifier struct {
38 -
	Kind       string `json:"type"`
39 -
	Identifier string `json:"identifier"`
40 -
}
41 -
42 -
type imageLinks struct {
43 -
	Thumbnail      string `json:"thumbnail"`
44 -
	SmallThumbnail string `json:"smallThumbnail"`
45 -
}
46 -
47 -
func googleBooksSearch(ctx context.Context, query, apiKey string) ([]SearchHit, error) {
48 -
	trimmed := strings.TrimSpace(query)
49 -
	if trimmed == "" {
50 -
		return nil, nil
51 -
	}
52 -
	normalized := strings.Map(func(r rune) rune {
53 -
		if r == ' ' || r == '\t' || r == '\n' || r == '-' {
54 -
			return -1
55 -
		}
56 -
		return r
57 -
	}, trimmed)
58 -
	isISBN := (len(normalized) == 10 || len(normalized) == 13) && isISBNChars(normalized)
59 -
	q := trimmed
60 -
	if isISBN {
61 -
		q = "isbn:" + strings.ToUpper(normalized)
62 -
	}
63 -
	u := "https://www.googleapis.com/books/v1/volumes?q=" + url.QueryEscape(q) + "&maxResults=10&printType=books"
64 -
	if apiKey != "" {
65 -
		u += "&key=" + url.QueryEscape(apiKey)
66 -
	}
67 -
68 -
	client := &http.Client{Timeout: 8 * time.Second}
69 -
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
70 -
	if err != nil {
71 -
		return nil, err
72 -
	}
73 -
	req.Header.Set("User-Agent", "andromeda-library/0.1")
74 -
	resp, err := client.Do(req)
75 -
	if err != nil {
76 -
		return nil, fmt.Errorf("request: %w", err)
77 -
	}
78 -
	defer resp.Body.Close()
79 -
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
80 -
		return nil, fmt.Errorf("google books status %s", resp.Status)
81 -
	}
82 -
	var data volumesResponse
83 -
	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
84 -
		return nil, fmt.Errorf("parse: %w", err)
85 -
	}
86 -
	hits := make([]SearchHit, 0, len(data.Items))
87 -
	for _, v := range data.Items {
88 -
		title := v.VolumeInfo.Title
89 -
		if title == "" {
90 -
			title = "Untitled"
91 -
		}
92 -
		hit := SearchHit{
93 -
			GoogleID: v.ID,
94 -
			Title:    title,
95 -
			Authors:  strings.Join(v.VolumeInfo.Authors, ", "),
96 -
		}
97 -
		if isbn := pickISBN(v.VolumeInfo.Identifiers); isbn != "" {
98 -
			hit.ISBN = &isbn
99 -
		}
100 -
		if v.VolumeInfo.ImageLinks != nil {
101 -
			cover := v.VolumeInfo.ImageLinks.Thumbnail
102 -
			if cover == "" {
103 -
				cover = v.VolumeInfo.ImageLinks.SmallThumbnail
104 -
			}
105 -
			if cover != "" {
106 -
				cover = strings.Replace(cover, "http://", "https://", 1)
107 -
				hit.CoverURL = &cover
108 -
			}
109 -
		}
110 -
		hits = append(hits, hit)
111 -
	}
112 -
	return hits, nil
113 -
}
114 -
115 -
func pickISBN(ids []identifier) string {
116 -
	for _, i := range ids {
117 -
		if i.Kind == "ISBN_13" {
118 -
			return i.Identifier
119 -
		}
120 -
	}
121 -
	for _, i := range ids {
122 -
		if i.Kind == "ISBN_10" {
123 -
			return i.Identifier
124 -
		}
125 -
	}
126 -
	return ""
127 -
}
128 -
129 -
func isISBNChars(s string) bool {
130 -
	for _, c := range s {
131 -
		if (c < '0' || c > '9') && c != 'X' && c != 'x' {
132 -
			return false
133 -
		}
134 -
	}
135 -
	return true
136 -
}
apps/library/handlers_web.go +4 −4
176 176
}
177 177
178 178
func (a *App) adminSearch(w http.ResponseWriter, r *http.Request) {
179 -
	hits, err := googleBooksSearch(r.Context(), r.URL.Query().Get("q"), a.GoogleBooksKey)
179 +
	hits, err := openLibrarySearch(r.Context(), r.URL.Query().Get("q"))
180 180
	if err != nil {
181 -
		a.Log.Warn("google books search failed", "err", err)
181 +
		a.Log.Warn("Open Library search failed", "err", err)
182 182
		web.WriteError(w, http.StatusBadGateway, err.Error())
183 183
		return
184 184
	}
199 199
		return
200 200
	}
201 201
	b := NewBook{Title: r.FormValue("title"), Authors: r.FormValue("authors"), Status: status}
202 -
	if v := strings.TrimSpace(r.FormValue("google_id")); v != "" {
203 -
		b.GoogleID = &v
202 +
	if v := strings.TrimSpace(r.FormValue("key")); v != "" {
203 +
		b.OLKey = &v
204 204
	}
205 205
	if v := strings.TrimSpace(r.FormValue("isbn")); v != "" {
206 206
		b.ISBN = &v
apps/library/main.go +1 −1
21 21
	if err != nil {
22 22
		log.Fatal(err)
23 23
	}
24 +
	db.Exec(`ALTER TABLE books ADD COLUMN ol_key TEXT`)
24 25
	defer db.Close()
25 26
26 27
	sessions := &auth.Store{DB: db, CookieName: "session", CookieSecure: config.GetenvBool("COOKIE_SECURE", false)}
36 37
		Templates:      tmpl,
37 38
		Sessions:       sessions,
38 39
		AdminPassword:  os.Getenv("ADMIN_PASSWORD"),
39 -
		GoogleBooksKey: os.Getenv("GOOGLE_BOOKS_API_KEY"),
40 40
		CookieSecure:   sessions.CookieSecure,
41 41
		BaseURL:        config.Getenv("BASE_URL", "http://localhost:3000"),
42 42
		DisplayMode:    parseDisplayMode(config.Getenv("LIBRARY_DISPLAY_MODE", "inline")),
apps/library/openlibrary-res.json (added) +318 −0
1 +
{
2 +
  "numFound": 355,
3 +
  "start": 0,
4 +
  "numFoundExact": true,
5 +
  "num_found": 355,
6 +
  "documentation_url": "https://openlibrary.org/dev/docs/api/search",
7 +
  "q": "gene wolfe",
8 +
  "offset": null,
9 +
  "docs": [
10 +
    {
11 +
      "author_name": [
12 +
        "Gene Wolfe"
13 +
      ],
14 +
      "isbn": [
15 +
        "9780671540661",
16 +
        "9780671828257",
17 +
        "8325001089",
18 +
        "2207256340",
19 +
        "9029043415",
20 +
        "9780671253257",
21 +
        "9788445070963",
22 +
        "0099263203",
23 +
        "9789029043410",
24 +
        "0575114150",
25 +
        "9782207256350",
26 +
        "0671828258",
27 +
        "9789731022208",
28 +
        "2207256359",
29 +
        "1857988868",
30 +
        "9786057762368",
31 +
        "9731022201",
32 +
        "9789505470563",
33 +
        "0671450700",
34 +
        "9782207303214",
35 +
        "0671540661",
36 +
        "9781857988864",
37 +
        "9788325001087",
38 +
        "9782207256343",
39 +
        "8445070967",
40 +
        "9505470568",
41 +
        "0671253255",
42 +
        "9780575114159",
43 +
        "9780099263203",
44 +
        "0671463985",
45 +
        "9780671450700",
46 +
        "6057762363",
47 +
        "9780671463984",
48 +
        "2207303217",
49 +
        "0099678802",
50 +
        "9780099678809"
51 +
      ],
52 +
      "key": "/works/OL14871979W",
53 +
      "title": "The Shadow of the Torturer"
54 +
    },
55 +
    {
56 +
      "author_name": [
57 +
        "Gene Wolfe"
58 +
      ],
59 +
      "isbn": [
60 +
        "9780099679202",
61 +
        "9782207303450",
62 +
        "9780671416164",
63 +
        "9788325001223",
64 +
        "0099274701",
65 +
        "0671413708",
66 +
        "0671474251",
67 +
        "0671416162",
68 +
        "9789731022239",
69 +
        "9780575114166",
70 +
        "9780283988028",
71 +
        "2207303454",
72 +
        "8445072137",
73 +
        "9788445071427",
74 +
        "8445071424",
75 +
        "9780671474256",
76 +
        "9781522689621",
77 +
        "9780671413705",
78 +
        "0283988029",
79 +
        "0575114169",
80 +
        "9731022236",
81 +
        "9788445072134",
82 +
        "0099679205",
83 +
        "8325001224",
84 +
        "1522689621",
85 +
        "9780099274704"
86 +
      ],
87 +
      "key": "/works/OL14871970W",
88 +
      "title": "The claw of the conciliator"
89 +
    },
90 +
    {
91 +
      "author_name": [
92 +
        "Gene Wolfe"
93 +
      ],
94 +
      "isbn": [
95 +
        "0671435957",
96 +
        "0575114177",
97 +
        "9780099295402",
98 +
        "0099295407",
99 +
        "9780671454500",
100 +
        "0671631934",
101 +
        "8445071432",
102 +
        "0283988606",
103 +
        "9780575114173",
104 +
        "2207303616",
105 +
        "9788445071434",
106 +
        "0671499459",
107 +
        "9780283988608",
108 +
        "9780671631932",
109 +
        "9780671499457",
110 +
        "9780671435950",
111 +
        "9782207303610",
112 +
        "0671454501"
113 +
      ],
114 +
      "key": "/works/OL14871972W",
115 +
      "title": "The Sword of the Lictor"
116 +
    },
117 +
    {
118 +
      "author_name": [
119 +
        "Gene Wolfe"
120 +
      ],
121 +
      "isbn": [
122 +
        "0575114185",
123 +
        "8842910104",
124 +
        "8324575081",
125 +
        "0283989432",
126 +
        "9788842910107",
127 +
        "2207303756",
128 +
        "9780283989438",
129 +
        "9782207303757",
130 +
        "8445071440",
131 +
        "9780575114180",
132 +
        "9788445071441",
133 +
        "2070429180",
134 +
        "9780671496661",
135 +
        "0671496662",
136 +
        "9782070429189",
137 +
        "0099320606",
138 +
        "0671452517",
139 +
        "9788324575084",
140 +
        "9780671452513",
141 +
        "9780099320609"
142 +
      ],
143 +
      "key": "/works/OL14871898W",
144 +
      "title": "The Citadel of the Autarch"
145 +
    },
146 +
    {
147 +
      "author_name": [
148 +
        "Gene Wolfe"
149 +
      ],
150 +
      "isbn": [
151 +
        "0312863942",
152 +
        "9780312863944",
153 +
        "9781429966344",
154 +
        "9788445071458",
155 +
        "9780575041165",
156 +
        "9780812558173",
157 +
        "9789721029644",
158 +
        "9721029645",
159 +
        "9780708882689",
160 +
        "9782207304884",
161 +
        "2207304884",
162 +
        "031293033X",
163 +
        "9780312930332",
164 +
        "9782207304891",
165 +
        "0708882684",
166 +
        "1429966343",
167 +
        "2207304892",
168 +
        "8445071459",
169 +
        "0812558170",
170 +
        "0575041161"
171 +
      ],
172 +
      "key": "/works/OL14871974W",
173 +
      "title": "The Urth of the new sun"
174 +
    },
175 +
    {
176 +
      "author_name": [
177 +
        "Gene Wolfe"
178 +
      ],
179 +
      "isbn": [
180 +
        "9781568658070",
181 +
        "2354089163",
182 +
        "1568658079",
183 +
        "9782354089160"
184 +
      ],
185 +
      "key": "/works/OL14871946W",
186 +
      "title": "Book of the New Sun"
187 +
    },
188 +
    {
189 +
      "author_name": [
190 +
        "Gene Wolfe"
191 +
      ],
192 +
      "isbn": [
193 +
        "9782253119272",
194 +
        "0099300303",
195 +
        "225311927X",
196 +
        "2354089244",
197 +
        "1250861004",
198 +
        "9781250840103",
199 +
        "9780575094222",
200 +
        "0812516249",
201 +
        "9780684128306",
202 +
        "9780312890209",
203 +
        "9780099300304",
204 +
        "3453045149",
205 +
        "9788445072479",
206 +
        "8445072471",
207 +
        "0575015977",
208 +
        "9781250861009",
209 +
        "9783453045149",
210 +
        "3910914063",
211 +
        "1250840104",
212 +
        "9783910914063",
213 +
        "9782221105849",
214 +
        "2221105842",
215 +
        "9780441235018",
216 +
        "3453303059",
217 +
        "0312890206",
218 +
        "0575094222",
219 +
        "0441235018",
220 +
        "1857988175",
221 +
        "0575114142",
222 +
        "9780812516241",
223 +
        "9780704311763",
224 +
        "0704311763",
225 +
        "9782354089245",
226 +
        "0684128306",
227 +
        "9780575114142",
228 +
        "9781857988178",
229 +
        "9783453303058",
230 +
        "9781466801134",
231 +
        "9780575015975",
232 +
        "1466801131"
233 +
      ],
234 +
      "key": "/works/OL14871904W",
235 +
      "title": "The Fifth Head Of Cerberus"
236 +
    },
237 +
    {
238 +
      "author_name": [
239 +
        "Gene Wolfe"
240 +
      ],
241 +
      "isbn": [
242 +
        "9780283987380",
243 +
        "1429966270",
244 +
        "9781857989779",
245 +
        "1250827043",
246 +
        "1407234684",
247 +
        "1857989775",
248 +
        "9781429966276",
249 +
        "9780283990298",
250 +
        "9780283988028",
251 +
        "1250781256",
252 +
        "0283990295",
253 +
        "0312890176",
254 +
        "0283987383",
255 +
        "9781407234687",
256 +
        "0283988029",
257 +
        "9780312890179",
258 +
        "9780575116733",
259 +
        "0575116730",
260 +
        "9781250781253",
261 +
        "9781250827043"
262 +
      ],
263 +
      "key": "/works/OL14871933W",
264 +
      "title": "Shadow & Claw"
265 +
    },
266 +
    {
267 +
      "author_name": [
268 +
        "Gene Wolfe"
269 +
      ],
270 +
      "isbn": [
271 +
        "9781429966313",
272 +
        "1429966319",
273 +
        "9780312890186",
274 +
        "1857987004",
275 +
        "3910914640",
276 +
        "1250781248",
277 +
        "1250827035",
278 +
        "9781250781246",
279 +
        "0312890186",
280 +
        "0312890184",
281 +
        "9781250827036",
282 +
        "9783910914643",
283 +
        "9781473212008",
284 +
        "1473212006",
285 +
        "9781857987003"
286 +
      ],
287 +
      "key": "/works/OL14871968W",
288 +
      "title": "Sword & citadel"
289 +
    },
290 +
    {
291 +
      "author_name": [
292 +
        "Gene Wolfe"
293 +
      ],
294 +
      "isbn": [
295 +
        "9780812558166",
296 +
        "2207304604",
297 +
        "9788385432777",
298 +
        "8385432779",
299 +
        "9781565440166",
300 +
        "9781466828513",
301 +
        "9780708882252",
302 +
        "1565440161",
303 +
        "0312937342",
304 +
        "9780812558159",
305 +
        "9780312937348",
306 +
        "0812558162",
307 +
        "0708882250",
308 +
        "146682851X",
309 +
        "9780575039285",
310 +
        "0812558154",
311 +
        "9782207304600",
312 +
        "0575039280"
313 +
      ],
314 +
      "key": "/works/OL14871980W",
315 +
      "title": "Soldier of the Mist"
316 +
    }
317 +
  ]
318 +
}
apps/library/openlibrary.go (added) +193 −0
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 +
    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()
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 +
    }
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 +
94 +
func isISBNChars(s string) bool {
95 +
	for _, c := range s {
96 +
		if (c < '0' || c > '9') && c != 'X' && c != 'x' {
97 +
			return false
98 +
		}
99 +
	}
100 +
	return true
101 +
}
102 +
103 +
func isISBNQuery(s string) bool {
104 +
    n := stripISBNSep(s)
105 +
    return (len(n) == 10 || len(n) == 13) && isISBNChars(n)
106 +
}
107 +
108 +
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)
115 +
}
116 +
117 +
// pickISBN normalizes to ISBN-13 and returns one canonical value.
118 +
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
141 +
}
142 +
143 +
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
156 +
}
157 +
158 +
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
173 +
}
174 +
175 +
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
192 +
}
193 +
apps/library/templates/admin.html +2 −2
43 43
    </section>
44 44
45 45
    <section class="admin-form">
46 -
      <h3>Search Books (Google)</h3>
46 +
      <h3>Search Books (Open Library)</h3>
47 47
      <div class="search-row">
48 48
        <input type="text" id="book-query" placeholder="title, author, isbn" />
49 49
        <button type="button" id="search-btn" onclick="searchBooks()">Search</button>
239 239
          el.value = value || '';
240 240
          return el;
241 241
        };
242 -
        info.appendChild(hidden('google_id', hit.google_id));
242 +
        info.appendChild(hidden('key', hit.key));
243 243
        info.appendChild(hidden('title', hit.title));
244 244
        info.appendChild(hidden('authors', hit.authors));
245 245
        info.appendChild(hidden('isbn', hit.isbn));