wallhaven.py 2.3 KB

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