openlibrary.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Open library (books)
  3. """
  4. from urllib.parse import urlencode
  5. import re
  6. from dateutil import parser
  7. about = {
  8. 'website': 'https://openlibrary.org',
  9. 'wikidata_id': 'Q1201876',
  10. 'require_api_key': False,
  11. 'use_official_api': False,
  12. 'official_api_documentation': 'https://openlibrary.org/developers/api',
  13. }
  14. paging = True
  15. categories = []
  16. base_url = "https://openlibrary.org"
  17. results_per_page = 10
  18. def request(query, params):
  19. args = {
  20. 'q': query,
  21. 'page': params['pageno'],
  22. 'limit': results_per_page,
  23. }
  24. params['url'] = f"{base_url}/search.json?{urlencode(args)}"
  25. return params
  26. def _parse_date(date):
  27. try:
  28. return parser.parse(date)
  29. except parser.ParserError:
  30. return None
  31. def response(resp):
  32. results = []
  33. for item in resp.json().get("docs", []):
  34. cover = None
  35. if 'lending_identifier_s' in item:
  36. cover = f"https://archive.org/services/img/{item['lending_identifier_s']}"
  37. published = item.get('publish_date')
  38. if published:
  39. published_dates = [date for date in map(_parse_date, published) if date]
  40. if published_dates:
  41. published = min(published_dates)
  42. if not published:
  43. published = parser.parse(str(item.get('first_published_year')))
  44. result = {
  45. 'template': 'paper.html',
  46. 'url': f"{base_url}{item['key']}",
  47. 'title': item['title'],
  48. 'content': re.sub(r"\{|\}", "", item['first_sentence'][0]) if item.get('first_sentence') else '',
  49. 'isbn': item.get('isbn', [])[:5],
  50. 'authors': item.get('author_name', []),
  51. 'thumbnail': cover,
  52. 'publishedDate': published,
  53. 'tags': item.get('subject', [])[:10] + item.get('place', [])[:10],
  54. }
  55. results.append(result)
  56. return results