pixabay.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Pixabay provides royalty-free media (images, videos)"""
  3. from datetime import timedelta
  4. from urllib.parse import quote_plus, urlencode
  5. from dateutil import parser
  6. from searx.utils import gen_useragent
  7. # about
  8. about = {
  9. "website": 'https://pixabay.com',
  10. "wikidata_id": 'Q1746538',
  11. "official_api_documentation": 'https://pixabay.com/api/docs/',
  12. "use_official_api": False,
  13. "require_api_key": False,
  14. "results": 'JSON',
  15. }
  16. base_url = 'https://pixabay.com'
  17. categories = ['images']
  18. pixabay_type = "images" # alternative: 'videos'
  19. paging = True
  20. safesearch = True
  21. time_range_support = True
  22. safesearch_map = {0: 'off', 1: '1', 2: '1'}
  23. time_range_map = {'day': '1d', 'week': '1w', 'month': '1m', 'year': '1y'}
  24. # using http2 returns forbidden errors
  25. enable_http2 = False
  26. def request(query, params):
  27. args = {
  28. 'pagi': params['pageno'],
  29. }
  30. if params['time_range']:
  31. args['date'] = time_range_map[params['time_range']]
  32. params['url'] = f"{base_url}/{pixabay_type}/search/{quote_plus(query)}/?{urlencode(args)}"
  33. params['headers'] = {
  34. 'User-Agent': gen_useragent() + " Pixabay",
  35. 'Accept': 'application/json',
  36. 'x-bootstrap-cache-miss': '1',
  37. 'x-fetch-bootstrap': '1',
  38. }
  39. params['cookies']['g_rated'] = safesearch_map[params['safesearch']]
  40. # prevent automatic redirects to first page on pagination
  41. params['allow_redirects'] = False
  42. return params
  43. def _image_result(result):
  44. return {
  45. 'template': 'images.html',
  46. 'url': base_url + result["href"],
  47. # images are sorted in ascending quality
  48. 'thumbnail_src': list(result['sources'].values())[0],
  49. 'img_src': list(result['sources'].values())[-1],
  50. 'title': result.get('name'),
  51. 'content': result.get('description', ''),
  52. }
  53. def _video_result(result):
  54. return {
  55. 'template': 'videos.html',
  56. 'url': base_url + result["href"],
  57. # images are sorted in ascending quality
  58. 'thumbnail': result['sources'].get('thumbnail'),
  59. 'iframe_src': result['sources'].get('embed'),
  60. 'title': result.get('name'),
  61. 'content': result.get('description', ''),
  62. 'length': timedelta(seconds=result['duration']),
  63. 'publishedDate': parser.parse(result['uploadDate']),
  64. }
  65. def response(resp):
  66. results = []
  67. # if there are no results on this page, we get a redirect
  68. # to the first page
  69. if resp.status_code == 302:
  70. return results
  71. json_data = resp.json()
  72. for result in json_data.get('page', {}).get('results', []):
  73. if result['mediaType'] in ('photo', 'illustration', 'vector'):
  74. results.append(_image_result(result))
  75. elif result['mediaType'] == 'video':
  76. results.append(_video_result(result))
  77. return results