|
| 1 | +"""Google Books metadata provider.""" |
| 2 | + |
| 3 | +import re |
| 4 | + |
| 5 | +import requests |
| 6 | +from bs4 import BeautifulSoup |
| 7 | +from django.conf import settings |
| 8 | +from django.core.cache import cache |
| 9 | + |
| 10 | +from app import helpers |
| 11 | +from app.models import MediaTypes, Sources |
| 12 | +from app.providers import services |
| 13 | + |
| 14 | +BASE_URL = "https://www.googleapis.com/books/v1/volumes" |
| 15 | +IMAGE_LINK_KEYS = ( |
| 16 | + "extraLarge", |
| 17 | + "large", |
| 18 | + "medium", |
| 19 | + "small", |
| 20 | + "thumbnail", |
| 21 | + "smallThumbnail", |
| 22 | +) |
| 23 | +YEAR_RE = re.compile(r"\b(\d{4})\b") |
| 24 | + |
| 25 | + |
| 26 | +def enabled(): |
| 27 | + """Return whether the instance has a Google Books API key.""" |
| 28 | + return bool(settings.GOOGLE_BOOKS_API_KEY) |
| 29 | + |
| 30 | + |
| 31 | +def handle_error(error): |
| 32 | + """Handle Google Books API errors.""" |
| 33 | + raise services.ProviderAPIError(Sources.GOOGLEBOOKS.value, error) |
| 34 | + |
| 35 | + |
| 36 | +def search(query, page, language=None): |
| 37 | + """Search Google Books volumes.""" |
| 38 | + language_key = language or "all" |
| 39 | + cache_key = ( |
| 40 | + f"search_{Sources.GOOGLEBOOKS.value}_{MediaTypes.BOOK.value}_" |
| 41 | + f"{query}_{language_key}_{page}" |
| 42 | + ) |
| 43 | + data = cache.get(cache_key) |
| 44 | + |
| 45 | + if data is None: |
| 46 | + params = { |
| 47 | + "q": query, |
| 48 | + "startIndex": max(0, (page - 1) * settings.PER_PAGE), |
| 49 | + "maxResults": min(settings.PER_PAGE, 40), |
| 50 | + "printType": "books", |
| 51 | + "key": settings.GOOGLE_BOOKS_API_KEY, |
| 52 | + } |
| 53 | + if language: |
| 54 | + params["langRestrict"] = language |
| 55 | + |
| 56 | + try: |
| 57 | + response = services.api_request( |
| 58 | + Sources.GOOGLEBOOKS.value, |
| 59 | + "GET", |
| 60 | + BASE_URL, |
| 61 | + params=params, |
| 62 | + ) |
| 63 | + except requests.RequestException as error: |
| 64 | + handle_error(error) |
| 65 | + |
| 66 | + results = [ |
| 67 | + result |
| 68 | + for item in response.get("items") or [] |
| 69 | + if (result := _normalize_search_result(item)) is not None |
| 70 | + ] |
| 71 | + data = helpers.format_search_response( |
| 72 | + page, |
| 73 | + settings.PER_PAGE, |
| 74 | + response.get("totalItems") or 0, |
| 75 | + results, |
| 76 | + ) |
| 77 | + cache.set(cache_key, data) |
| 78 | + |
| 79 | + return data |
| 80 | + |
| 81 | + |
| 82 | +def book(media_id): |
| 83 | + """Return normalized metadata for a Google Books volume.""" |
| 84 | + cache_key = f"{Sources.GOOGLEBOOKS.value}_{MediaTypes.BOOK.value}_{media_id}" |
| 85 | + data = cache.get(cache_key) |
| 86 | + |
| 87 | + if data is None: |
| 88 | + try: |
| 89 | + response = services.api_request( |
| 90 | + Sources.GOOGLEBOOKS.value, |
| 91 | + "GET", |
| 92 | + f"{BASE_URL}/{media_id}", |
| 93 | + params={"key": settings.GOOGLE_BOOKS_API_KEY}, |
| 94 | + ) |
| 95 | + except requests.RequestException as error: |
| 96 | + handle_error(error) |
| 97 | + |
| 98 | + data = _normalize_book(response, media_id) |
| 99 | + cache.set(cache_key, data) |
| 100 | + |
| 101 | + return data |
| 102 | + |
| 103 | + |
| 104 | +def _normalize_search_result(item): |
| 105 | + """Convert one Google Books volume into a search result.""" |
| 106 | + volume_info = item.get("volumeInfo") or {} |
| 107 | + media_id = item.get("id") |
| 108 | + title = volume_info.get("title") |
| 109 | + if not media_id or not title: |
| 110 | + return None |
| 111 | + |
| 112 | + return { |
| 113 | + "media_id": media_id, |
| 114 | + "source": Sources.GOOGLEBOOKS.value, |
| 115 | + "media_type": MediaTypes.BOOK.value, |
| 116 | + "title": title, |
| 117 | + "image": _image_url(volume_info.get("imageLinks")), |
| 118 | + "year": _publication_year(volume_info.get("publishedDate")), |
| 119 | + } |
| 120 | + |
| 121 | + |
| 122 | +def _normalize_book(response, media_id): |
| 123 | + """Convert a Google Books volume into Floppy's metadata shape.""" |
| 124 | + volume_info = response.get("volumeInfo") or {} |
| 125 | + title = volume_info.get("title") or "" |
| 126 | + authors = [ |
| 127 | + author |
| 128 | + for author in volume_info.get("authors") or [] |
| 129 | + if isinstance(author, str) and author |
| 130 | + ] |
| 131 | + average_rating = volume_info.get("averageRating") |
| 132 | + try: |
| 133 | + score = float(average_rating) * 2 if average_rating is not None else None |
| 134 | + except (TypeError, ValueError): |
| 135 | + score = None |
| 136 | + |
| 137 | + published_date = volume_info.get("publishedDate") |
| 138 | + source_url = ( |
| 139 | + volume_info.get("canonicalVolumeLink") |
| 140 | + or volume_info.get("infoLink") |
| 141 | + or f"https://books.google.com/books?id={media_id}" |
| 142 | + ) |
| 143 | + language = volume_info.get("language") |
| 144 | + print_type = volume_info.get("printType") |
| 145 | + isbn = [] |
| 146 | + for identifier in volume_info.get("industryIdentifiers") or []: |
| 147 | + if not isinstance(identifier, dict): |
| 148 | + continue |
| 149 | + if identifier.get("type") in {"ISBN_10", "ISBN_13"}: |
| 150 | + value = identifier.get("identifier") |
| 151 | + if value: |
| 152 | + isbn.append(value) |
| 153 | + |
| 154 | + return { |
| 155 | + "media_id": media_id, |
| 156 | + "source": Sources.GOOGLEBOOKS.value, |
| 157 | + "source_url": source_url, |
| 158 | + "media_type": MediaTypes.BOOK.value, |
| 159 | + "title": title, |
| 160 | + "max_progress": volume_info.get("pageCount"), |
| 161 | + "image": _image_url(volume_info.get("imageLinks")), |
| 162 | + "synopsis": _description(volume_info.get("description")), |
| 163 | + "genres": volume_info.get("categories") or [], |
| 164 | + "score": score, |
| 165 | + "score_count": volume_info.get("ratingsCount") or 0, |
| 166 | + "details": { |
| 167 | + "format": print_type.title() if print_type else None, |
| 168 | + "number_of_pages": volume_info.get("pageCount"), |
| 169 | + "publish_date": published_date, |
| 170 | + "author": authors or None, |
| 171 | + "publisher": volume_info.get("publisher"), |
| 172 | + "isbn": isbn, |
| 173 | + "languages": [language] if language else [], |
| 174 | + }, |
| 175 | + "authors_full": [], |
| 176 | + "related": {}, |
| 177 | + } |
| 178 | + |
| 179 | + |
| 180 | +def _image_url(image_links): |
| 181 | + """Choose the highest-resolution available cover image.""" |
| 182 | + if not isinstance(image_links, dict): |
| 183 | + return settings.IMG_NONE |
| 184 | + |
| 185 | + for key in IMAGE_LINK_KEYS: |
| 186 | + image = image_links.get(key) |
| 187 | + if image: |
| 188 | + return str(image).replace("http://", "https://", 1) |
| 189 | + return settings.IMG_NONE |
| 190 | + |
| 191 | + |
| 192 | +def _publication_year(date_value): |
| 193 | + """Extract the first four-digit publication year.""" |
| 194 | + match = YEAR_RE.search(str(date_value or "")) |
| 195 | + return int(match.group(1)) if match else None |
| 196 | + |
| 197 | + |
| 198 | +def _description(description): |
| 199 | + """Strip markup from an optional Google Books description.""" |
| 200 | + if not description: |
| 201 | + return "No synopsis available." |
| 202 | + text = BeautifulSoup(str(description), "html.parser").get_text(separator=" ") |
| 203 | + return " ".join(text.split()) or "No synopsis available." |
0 commit comments