summaryrefslogtreecommitdiff
path: root/searx/engines/seekr.py
blob: 967eef86db2b755777045e0a9226d7f405684344 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# SPDX-License-Identifier: AGPL-3.0-or-later
"""seekr.com Seeker Score

Seekr is a privately held search and content evaluation engine that prioritizes
credibility over popularity.

Configuration
=============

The engine has the following additional settings:

- :py:obj:`seekr_category`
- :py:obj:`api_key`

This implementation is used by seekr engines in the :ref:`settings.yml
<settings engine>`:

.. code:: yaml

  - name: seekr news
    seekr_category: news
    ...
  - name: seekr images
    seekr_category: images
    ...
  - name: seekr videos
    seekr_category: videos
    ...

Known Quirks
============

The implementation to support :py:obj:`paging <searx.enginelib.Engine.paging>`
is based on the *nextpage* method of Seekr's REST API.  This feature is *next
page driven* and plays well with the :ref:`infinite_scroll <settings ui>`
setting in SearXNG but it does not really fit into SearXNG's UI to select a page
by number.

Implementations
===============

"""

from datetime import datetime
from json import loads
from urllib.parse import urlencode
from flask_babel import gettext

about = {
    "website": 'https://seekr.com/',
    "official_api_documentation": None,
    "use_official_api": False,
    "require_api_key": True,
    "results": 'JSON',
    "language": 'en',
}

base_url = "https://api.seekr.com"
paging = True

api_key = "srh1-22fb-sekr"
"""API key / reversed engineered / is still the same one since 2022."""

seekr_category: str = 'unset'
"""Search category, any of ``news``, ``videos`` or ``images``."""


def init(engine_settings):

    # global paging
    if engine_settings['seekr_category'] not in ['news', 'videos', 'images']:
        raise ValueError(f"Unsupported seekr category: {engine_settings['seekr_category']}")


def request(query, params):

    if not query:
        return None

    args = {
        'query': query,
        'apiKey': api_key,
    }

    api_url = base_url + '/engine'
    if seekr_category == 'news':
        api_url += '/v2/newssearch'

    elif seekr_category == 'images':
        api_url += '/imagetab'

    elif seekr_category == 'videos':
        api_url += '/videotab'

    params['url'] = f"{api_url}?{urlencode(args)}"
    if params['pageno'] > 1:
        nextpage = params['engine_data'].get('nextpage')
        if nextpage:
            params['url'] = nextpage

    return params


def _images_response(json):

    search_results = json.get('expertResponses')
    if search_results:
        search_results = search_results[0].get('advice')
    else:  # response from a 'nextResultSet'
        search_results = json.get('advice')

    results = []
    if not search_results:
        return results

    for result in search_results['results']:
        summary = loads(result['summary'])
        results.append(
            {
                'template': 'images.html',
                'url': summary['refererurl'],
                'title': result['title'],
                'img_src': result['url'],
                'resolution': f"{summary['width']}x{summary['height']}",
                'thumbnail_src': 'https://media.seekr.com/engine/rp/' + summary['tg'] + '/?src= ' + result['thumbnail'],
            }
        )

    if search_results.get('nextResultSet'):
        results.append(
            {
                "engine_data": search_results.get('nextResultSet'),
                "key": "nextpage",
            }
        )
    return results


def _videos_response(json):

    search_results = json.get('expertResponses')
    if search_results:
        search_results = search_results[0].get('advice')
    else:  # response from a 'nextResultSet'
        search_results = json.get('advice')

    results = []
    if not search_results:
        return results

    for result in search_results['results']:
        summary = loads(result['summary'])
        results.append(
            {
                'template': 'videos.html',
                'url': result['url'],
                'title': result['title'],
                'thumbnail': 'https://media.seekr.com/engine/rp/' + summary['tg'] + '/?src= ' + result['thumbnail'],
            }
        )

    if search_results.get('nextResultSet'):
        results.append(
            {
                "engine_data": search_results.get('nextResultSet'),
                "key": "nextpage",
            }
        )
    return results


def _news_response(json):

    search_results = json.get('expertResponses')
    if search_results:
        search_results = search_results[0]['advice']['categorySearchResult']['searchResult']
    else:  # response from a 'nextResultSet'
        search_results = json.get('advice')

    results = []
    if not search_results:
        return results

    for result in search_results['results']:

        results.append(
            {
                'url': result['url'],
                'title': result['title'],
                'content': result['summary'] or result["topCategory"] or result["displayUrl"] or '',
                'thumbnail': result.get('thumbnail', ''),
                'publishedDate': datetime.strptime(result['pubDate'][:19], '%Y-%m-%d %H:%M:%S'),
                'metadata': gettext("Language") + ': ' + result.get('language', ''),
            }
        )

    if search_results.get('nextResultSet'):
        results.append(
            {
                "engine_data": search_results.get('nextResultSet'),
                "key": "nextpage",
            }
        )
    return results


def response(resp):
    json = resp.json()

    if seekr_category == "videos":
        return _videos_response(json)
    if seekr_category == "images":
        return _images_response(json)
    if seekr_category == "news":
        return _news_response(json)

    raise ValueError(f"Unsupported seekr category: {seekr_category}")