wallhaven.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Wallhaven_ is a site created by and for people who like wallpapers.
  3. .. _Wallhaven: https://wallhaven.cc/about#Copyright
  4. """
  5. from datetime import datetime
  6. from urllib.parse import urlencode
  7. from searx.utils import humanize_bytes
  8. about = {
  9. 'website': 'https://wallhaven.cc/',
  10. 'official_api_documentation': 'https://wallhaven.cc/help/api',
  11. 'use_official_api': True,
  12. 'require_api_key': False,
  13. 'results': 'JSON',
  14. }
  15. categories = ['images']
  16. paging = True
  17. base_url = "https://wallhaven.cc"
  18. api_key = ''
  19. """If you own an API key you can add it here, further read `Rate Limiting and
  20. Errors`_.
  21. .. _Rate Limiting and Errors: https://wallhaven.cc/help/api#limits
  22. """
  23. # Possible categories: sfw, sketchy, nsfw
  24. safesearch_map = {0: '111', 1: '110', 2: '100'}
  25. """Turn purities on(1) or off(0) NSFW requires a valid API key.
  26. .. code:: text
  27. 100/110/111 <-- Bits stands for: SFW, Sketchy and NSFW
  28. `What are SFW, Sketchy and NSFW all about?`_:
  29. - SFW = "Safe for work" wallpapers. *Grandma approves.*
  30. - Sketchy = Not quite SFW not quite NSFW. *Grandma might be uncomfortable.*
  31. - NSFW = "Not safe for work". *Grandma isn't sure who you are anymore.*
  32. .. _What are SFW, Sketchy and NSFW all about?:
  33. https://wallhaven.cc/faq#What-are-SFW-Sketchy-and-NSFW-all-about
  34. """
  35. def request(query, params):
  36. args = {
  37. 'q': query,
  38. 'page': params['pageno'],
  39. 'purity': safesearch_map[params['safesearch']],
  40. }
  41. if api_key:
  42. params['headers']['X-API-Key'] = api_key
  43. params['url'] = f"{base_url}/api/v1/search?{urlencode(args)}"
  44. return params
  45. def response(resp):
  46. results = []
  47. json = resp.json()
  48. for result in json['data']:
  49. results.append(
  50. {
  51. 'template': 'images.html',
  52. 'title': '',
  53. 'content': f"{result['category']} / {result['purity']}",
  54. 'url': result['url'],
  55. 'img_src': result['path'],
  56. 'thumbnail_src': result['thumbs']['small'],
  57. 'resolution': result['resolution'].replace('x', ' x '),
  58. 'publishedDate': datetime.strptime(result['created_at'], '%Y-%m-%d %H:%M:%S'),
  59. 'img_format': result['file_type'],
  60. 'filesize': humanize_bytes(result['file_size']),
  61. }
  62. )
  63. return results