summaryrefslogtreecommitdiff
path: root/searx/engines/wallhaven.py
blob: 4ab83a5624e7ba35ddf4c50c85ffa8c700fd85ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Wallhaven_ is a site created by and for people who like wallpapers.

.. _Wallhaven: https://wallhaven.cc/about#Copyright
"""

from datetime import datetime
from urllib.parse import urlencode

from searx.utils import humanize_bytes

about = {
    'website': 'https://wallhaven.cc/',
    'official_api_documentation': 'https://wallhaven.cc/help/api',
    'use_official_api': True,
    'require_api_key': False,
    'results': 'JSON',
}
categories = ['images']
paging = True

base_url = "https://wallhaven.cc"

api_key = ''
"""If you own an API key you can add it here, further read `Rate Limiting and
Errors`_.

.. _Rate Limiting and Errors: https://wallhaven.cc/help/api#limits

"""

# Possible categories: sfw, sketchy, nsfw
safesearch_map = {0: '111', 1: '110', 2: '100'}
"""Turn purities on(1) or off(0) NSFW requires a valid API key.

.. code:: text

  100/110/111 <-- Bits stands for: SFW, Sketchy and NSFW

`What are SFW, Sketchy and NSFW all about?`_:

- SFW = "Safe for work" wallpapers.  *Grandma approves.*
- Sketchy = Not quite SFW not quite NSFW.  *Grandma might be uncomfortable.*
- NSFW = "Not safe for work". *Grandma isn't sure who you are anymore.*

.. _What are SFW, Sketchy and NSFW all about?:
   https://wallhaven.cc/faq#What-are-SFW-Sketchy-and-NSFW-all-about

"""


def request(query, params):
    args = {
        'q': query,
        'page': params['pageno'],
        'purity': safesearch_map[params['safesearch']],
    }

    if api_key:
        params['headers']['X-API-Key'] = api_key

    params['url'] = f"{base_url}/api/v1/search?{urlencode(args)}"
    return params


def response(resp):
    results = []

    json = resp.json()

    for result in json['data']:

        results.append(
            {
                'template': 'images.html',
                'title': '',
                'content': f"{result['category']} / {result['purity']}",
                'url': result['url'],
                'img_src': result['path'],
                'thumbnail_src': result['thumbs']['small'],
                'resolution': result['resolution'].replace('x', ' x '),
                'publishedDate': datetime.strptime(result['created_at'], '%Y-%m-%d %H:%M:%S'),
                'img_format': result['file_type'],
                'filesize': humanize_bytes(result['file_size']),
            }
        )

    return results