diff --git a/internal/search/service.go b/internal/search/service.go index 39e4faa..927a0ff 100644 --- a/internal/search/service.go +++ b/internal/search/service.go @@ -66,7 +66,10 @@ func (serv *Service) searchBooks(query string) []Result { // Use the general `q` search rather than `title`: it matches across all // fields including translated/edition titles (e.g. "Policán" -> Dog Man), // whereas `title` only matches a work's primary (usually English) title. - reqURL := "https://openlibrary.org/search.json?limit=5&fields=title,author_name,cover_i,key,first_publish_year&q=" + url.QueryEscape(query) + // Request `editions` too: it returns the specific edition that matched the + // query, so we can show the user's-language title ("Policán 3") and cover + // instead of the work's primary (English) title. + reqURL := "https://openlibrary.org/search.json?limit=5&fields=title,author_name,cover_i,key,first_publish_year,editions&q=" + url.QueryEscape(query) var payload struct { Docs []struct { @@ -75,6 +78,12 @@ func (serv *Service) searchBooks(query string) []Result { CoverI int `json:"cover_i"` Key string `json:"key"` FirstPublishYear int `json:"first_publish_year"` + Editions struct { + Docs []struct { + Title string `json:"title"` + CoverI int `json:"cover_i"` + } `json:"docs"` + } `json:"editions"` } `json:"docs"` } if err := getJSON(reqURL, &payload); err != nil { @@ -83,9 +92,23 @@ func (serv *Service) searchBooks(query string) []Result { results := make([]Result, 0, len(payload.Docs)) for _, doc := range payload.Docs { + // Prefer the matched edition's title/cover (in the searched language) + // over the work's primary (usually English) ones. + title := doc.Title + coverID := doc.CoverI + if len(doc.Editions.Docs) > 0 { + ed := doc.Editions.Docs[0] + if ed.Title != "" { + title = ed.Title + } + if ed.CoverI != 0 { + coverID = ed.CoverI + } + } + pic := "" - if doc.CoverI != 0 { - pic = fmt.Sprintf("https://covers.openlibrary.org/b/id/%d-M.jpg", doc.CoverI) + if coverID != 0 { + pic = fmt.Sprintf("https://covers.openlibrary.org/b/id/%d-M.jpg", coverID) } desc := strings.Join(doc.AuthorName, ", ") if doc.FirstPublishYear != 0 { @@ -96,7 +119,7 @@ func (serv *Service) searchBooks(query string) []Result { } results = append(results, Result{ Category: "book", - Name: doc.Title, + Name: title, URL: "https://openlibrary.org" + doc.Key, PicURL: pic, Description: desc,