diff options
| -rw-r--r-- | Makefile | 4 | ||||
| -rw-r--r-- | docs/admin/installation-apache.rst | 15 | ||||
| -rw-r--r-- | docs/admin/installation-nginx.rst | 10 | ||||
| -rw-r--r-- | docs/admin/morty.rst | 15 | ||||
| -rw-r--r-- | requirements.txt | 2 | ||||
| -rw-r--r-- | searx/engines/google.py | 15 | ||||
| -rw-r--r-- | searx/engines/google_images.py | 12 | ||||
| -rw-r--r-- | searx/engines/google_news.py | 220 | ||||
| -rw-r--r-- | searx/search/checker/__main__.py | 1 | ||||
| -rw-r--r-- | searx/search/checker/impl.py | 15 | ||||
| -rw-r--r-- | searx/search/processors/online.py | 6 | ||||
| -rw-r--r-- | searx/settings.yml | 12 | ||||
| -rwxr-xr-x | utils/lxc.sh | 1 | ||||
| -rwxr-xr-x | utils/searx.sh | 6 |
14 files changed, 229 insertions, 105 deletions
@@ -177,7 +177,9 @@ PYLINT_FILES=\ searx/testing.py \ searx/engines/gigablast.py \ searx/engines/deviantart.py \ - searx/engines/digg.py + searx/engines/digg.py \ + searx/engines/google.py \ + searx/engines/google_news.py test.pylint: pyenvinstall $(call cmd,pylint,$(PYLINT_FILES)) diff --git a/docs/admin/installation-apache.rst b/docs/admin/installation-apache.rst index 217e57718..311b5c250 100644 --- a/docs/admin/installation-apache.rst +++ b/docs/admin/installation-apache.rst @@ -180,10 +180,6 @@ modules and create a `Location`_ configuration for the searx site. In most distributions you have to un-comment the lines in the main configuration file, except in :ref:`The Debian Layout`. -To pass the HTTP HOST header -With ProxyPreserveHost_ the incoming Host HTTP request header is passed to the -proxied host. - .. tabs:: .. group-tab:: Ubuntu / debian @@ -231,6 +227,11 @@ proxied host. LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so +With ProxyPreserveHost_ the incoming Host HTTP request header is passed to the +proxied host. + +.. _apache searx via filtron plus morty: + .. tabs:: .. group-tab:: searx via filtron plus morty @@ -285,15 +286,15 @@ proxied host. </Location> - Note that reverse proxy advised to be used in case of single-user or - low-traffic instances. For a fully result proxification add :ref:`morty's - <searx morty>` **public URL** to your :origin:`searx/settings.yml`: + For a fully result proxification add :ref:`morty's <searx morty>` **public + URL** to your :origin:`searx/settings.yml`: .. code:: yaml result_proxy: # replace example.org with your server's public name url : https://example.org/morty + key : !!binary "insert_your_morty_proxy_key_here" server: image_proxy : True diff --git a/docs/admin/installation-nginx.rst b/docs/admin/installation-nginx.rst index 589c40ada..430ebbcce 100644 --- a/docs/admin/installation-nginx.rst +++ b/docs/admin/installation-nginx.rst @@ -163,6 +163,8 @@ Started wiki`_ is always a good resource *to keep in the pocket*. Create configuration at ``/etc/nginx/conf.d/searx`` and place a symlink to sites-enabled: +.. _nginx searx via filtron plus morty: + .. tabs:: .. group-tab:: searx via filtron plus morty @@ -210,21 +212,21 @@ Started wiki`_ is always a good resource *to keep in the pocket*. proxy_set_header X-Scheme $scheme; } - Note that reverse proxy advised to be used in case of single-user or - low-traffic instances. For a fully result proxification add :ref:`morty's - <searx morty>` **public URL** to your :origin:`searx/settings.yml`: + For a fully result proxification add :ref:`morty's <searx morty>` **public + URL** to your :origin:`searx/settings.yml`: .. code:: yaml result_proxy: # replace example.org with your server's public name url : https://example.org/morty + key : !!binary "insert_your_morty_proxy_key_here" server: image_proxy : True - .. group-tab:: proxy or uWSGI + .. group-tab:: proxy or uWSGI Be warned, with this setup, your instance isn't :ref:`protected <searx filtron>`. Nevertheless it is good enough for intranet usage and it is a diff --git a/docs/admin/morty.rst b/docs/admin/morty.rst index 2858fde3c..5468c9c13 100644 --- a/docs/admin/morty.rst +++ b/docs/admin/morty.rst @@ -16,15 +16,22 @@ By default searx can only act as an image proxy for result images, but it is possible to proxify all the result URLs with an external service, morty_. To use this feature, morty has to be installed and activated in searx's -``settings.yml``. - -Add the following snippet to your ``settings.yml`` and restart searx: +``settings.yml``. Add the following snippet to your ``settings.yml`` and +restart searx: .. code:: yaml result_proxy: url : http://127.0.0.1:3000/ - key : your_morty_proxy_key + key : !!binary "insert_your_morty_proxy_key_here" + +Note that the example above (``http://127.0.0.1:3000``) is only for single-user +instances without a HTTP proxy. If your morty service is public, the url is the +address of the reverse proxy (e.g ``https://example.org/morty``). + +For more information about *result proxy* have a look at *"searx via filtron +plus morty"* in the :ref:`nginx <nginx searx via filtron plus morty>` and +:ref:`apache <apache searx via filtron plus morty>` sections. ``url`` Is the address of the running morty service. diff --git a/requirements.txt b/requirements.txt index 776bbc20b..a8d9b3f20 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,4 +9,4 @@ pygments==2.1.3 python-dateutil==2.8.1 pyyaml==5.3.1 requests[socks]==2.25.1 -pycld3==0.20 +langdetect==1.0.8 diff --git a/searx/engines/google.py b/searx/engines/google.py index 4198de640..fe9cd63e0 100644 --- a/searx/engines/google.py +++ b/searx/engines/google.py @@ -155,6 +155,11 @@ def get_lang_country(params, lang_list, custom_aliases): return language, country, lang_country +def detect_google_sorry(resp): + resp_url = urlparse(resp.url) + if resp_url.netloc == 'sorry.google.com' or resp_url.path.startswith('/sorry'): + raise SearxEngineCaptchaException() + def request(query, params): """Google search request""" @@ -200,16 +205,10 @@ def request(query, params): def response(resp): """Get response from google's search request""" - results = [] - # detect google sorry - resp_url = urlparse(resp.url) - if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect': - raise SearxEngineCaptchaException() - - if resp_url.path.startswith('/sorry'): - raise SearxEngineCaptchaException() + detect_google_sorry(resp) + results = [] # which subdomain ? # subdomain = resp.search_params.get('google_subdomain') diff --git a/searx/engines/google_images.py b/searx/engines/google_images.py index 8c2cb9d2a..612682c44 100644 --- a/searx/engines/google_images.py +++ b/searx/engines/google_images.py @@ -12,10 +12,9 @@ Definitions`_. Header set Content-Security-Policy "img-src 'self' data: ;" """ -from urllib.parse import urlencode, urlparse, unquote +from urllib.parse import urlencode, unquote from lxml import html from searx import logger -from searx.exceptions import SearxEngineCaptchaException from searx.utils import extract_text, eval_xpath from searx.engines.google import _fetch_supported_languages, supported_languages_url # NOQA # pylint: disable=unused-import @@ -23,6 +22,7 @@ from searx.engines.google import ( get_lang_country, google_domains, time_range_dict, + detect_google_sorry, ) logger = logger.getChild('google images') @@ -123,13 +123,7 @@ def response(resp): """Get response from google's search request""" results = [] - # detect google sorry - resp_url = urlparse(resp.url) - if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect': - raise SearxEngineCaptchaException() - - if resp_url.path.startswith('/sorry'): - raise SearxEngineCaptchaException() + detect_google_sorry(resp) # which subdomain ? # subdomain = resp.search_params.get('google_subdomain') diff --git a/searx/engines/google_news.py b/searx/engines/google_news.py index 63fef6696..e83b2ba48 100644 --- a/searx/engines/google_news.py +++ b/searx/engines/google_news.py @@ -1,12 +1,45 @@ # SPDX-License-Identifier: AGPL-3.0-or-later -""" - Google (News) +"""Google (News) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. Not all parameters can be appied, e.g. num_ (the number of +search results to return) is ignored. + +.. _Query Parameter Definitions: + https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions + +.. _num: https://developers.google.com/custom-search/docs/xml_results#numsp + """ +# pylint: disable=invalid-name, missing-function-docstring + +import binascii +import re from urllib.parse import urlencode +from base64 import b64decode from lxml import html -from searx.utils import match_language -from searx.engines.google import _fetch_supported_languages, supported_languages_url # NOQA # pylint: disable=unused-import + +from searx import logger +from searx.utils import ( + eval_xpath, + eval_xpath_list, + eval_xpath_getindex, + extract_text, +) + +# pylint: disable=unused-import +from searx.engines.google import ( + supported_languages_url, + _fetch_supported_languages, + detect_google_sorry, +) +# pylint: enable=unused-import + +from searx.engines.google import ( + get_lang_country, + filter_mapping, +) # about about = { @@ -18,72 +51,147 @@ about = { "results": 'HTML', } -# search-url +logger = logger.getChild('google news') + +# compared to other google engines google-news has a different time range +# support. The time range is included in the search term. +time_range_dict = { + 'day': 'when:1d', + 'week': 'when:7d', + 'month': 'when:1m', + 'year': 'when:1y', +} + +# engine dependent config + categories = ['news'] -paging = True +paging = False language_support = True -safesearch = True +use_locale_domain = True time_range_support = True -number_of_results = 10 - -search_url = 'https://www.google.com/search'\ - '?{query}'\ - '&tbm=nws'\ - '&gws_rd=cr'\ - '&{search_options}' -time_range_attr = "qdr:{range}" -time_range_dict = {'day': 'd', - 'week': 'w', - 'month': 'm', - 'year': 'y'} - +safesearch = True # not really, but it is not generated by google -# do search-request def request(query, params): - - search_options = { - 'start': (params['pageno'] - 1) * number_of_results - } - - if params['time_range'] in time_range_dict: - search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']]) - - if safesearch and params['safesearch']: - search_options['safe'] = 'on' - - params['url'] = search_url.format(query=urlencode({'q': query}), - search_options=urlencode(search_options)) - - if params['language'] != 'all': - language = match_language(params['language'], supported_languages, language_aliases).split('-')[0] - if language: - params['url'] += '&hl=' + language + """Google-News search request""" + + language, country, lang_country = get_lang_country( + # pylint: disable=undefined-variable + params, supported_languages, language_aliases + ) + subdomain = 'news.google.com' + + if params['time_range']: # in time_range_dict: + query += ' ' + time_range_dict[params['time_range']] + + query_url = 'https://'+ subdomain + '/search' + "?" + urlencode({ + 'q': query, + 'hl': language, + 'lr': "lang_" + language, + 'ie': "utf8", + 'oe': "utf8", + 'ceid' : "%s:%s" % (country, language), + 'gl' : country, + }) + + if params['safesearch']: + query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]}) + + params['url'] = query_url + logger.debug("query_url --> %s", query_url) + + # en-US,en;q=0.8,en;q=0.5 + params['headers']['Accept-Language'] = ( + lang_country + ',' + language + ';q=0.8,' + language + ';q=0.5' + ) + logger.debug("HTTP header Accept-Language --> %s", + params['headers']['Accept-Language']) + params['headers']['Accept'] = ( + 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' + ) + + # hl=en redirect to hl=en-US / en-CA ... + params['soft_max_redirects'] = 1 + + #params['google_subdomain'] = subdomain return params -# get response from search-request def response(resp): + """Get response from google's search request""" results = [] + detect_google_sorry(resp) + + # which subdomain ? + # subdomain = resp.search_params.get('google_subdomain') + + # convert the text to dom dom = html.fromstring(resp.text) - # parse results - for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'): - try: - r = { - 'url': result.xpath('.//a[@class="l lLrAF"]')[0].attrib.get("href"), - 'title': ''.join(result.xpath('.//a[@class="l lLrAF"]//text()')), - 'content': ''.join(result.xpath('.//div[@class="st"]//text()')), - } - except: - continue - - imgs = result.xpath('.//img/@src') - if len(imgs) and not imgs[0].startswith('data'): - r['img_src'] = imgs[0] - - results.append(r) + for result in eval_xpath_list(dom, '//div[@class="xrnccd"]'): + + # The first <a> tag in the <article> contains the link to the + # article The href attribute of the <a> is a google internal link, + # we can't use. The real link is hidden in the jslog attribute: + # + # <a ... + # jslog="95014; 4:https://www.cnn.com/.../index.html; track:click" + # href="./articles/CAIiENu3nGS...?hl=en-US&gl=US&ceid=US%3Aen" + # ... /> + + jslog = eval_xpath_getindex(result, './article/a/@jslog', 0) + url = re.findall('http[^;]*', jslog) + if url: + url = url[0] + else: + # The real URL is base64 encoded in the json attribute: + # jslog="95014; 5:W251bGwsbnVsbCxudW...giXQ==; track:click" + jslog = jslog.split(";")[1].split(':')[1].strip() + try: + padding = (4 -(len(jslog) % 4)) * "=" + jslog = b64decode(jslog + padding) + except binascii.Error: + # URL cant be read, skip this result + continue + + # now we have : b'[null, ... null,"https://www.cnn.com/.../index.html"]' + url = re.findall('http[^;"]*', str(jslog))[0] + + # the first <h3> tag in the <article> contains the title of the link + title = extract_text(eval_xpath(result, './article/h3[1]')) + + # the first <div> tag in the <article> contains the content of the link + content = extract_text(eval_xpath(result, './article/div[1]')) + + # the second <div> tag contains origin publisher and the publishing date + + pub_date = extract_text(eval_xpath(result, './article/div[2]//time')) + pub_origin = extract_text(eval_xpath(result, './article/div[2]//a')) + + pub_info = [] + if pub_origin: + pub_info.append(pub_origin) + if pub_date: + # The pub_date is mostly a string like 'yesertday', not a real + # timezone date or time. Therefore we can't use publishedDate. + pub_info.append(pub_date) + pub_info = ', '.join(pub_info) + if pub_info: + content = pub_info + ': ' + content + + # The image URL is located in a preceding sibling <img> tag, e.g.: + # "https://lh3.googleusercontent.com/DjhQh7DMszk.....z=-p-h100-w100" + # These URL are long but not personalized (double checked via tor). + + img_src = extract_text(result.xpath('preceding-sibling::a/figure/img/@src')) + + results.append({ + 'url': url, + 'title': title, + 'content': content, + 'img_src': img_src, + }) # return results return results diff --git a/searx/search/checker/__main__.py b/searx/search/checker/__main__.py index 75b37e6c5..0d7d1b8ed 100644 --- a/searx/search/checker/__main__.py +++ b/searx/search/checker/__main__.py @@ -74,6 +74,7 @@ def run(engine_name_list, verbose): stdout.write(f' {"found languages":15}: {" ".join(sorted(list(checker.test_results.languages)))}\n') for test_name, logs in checker.test_results.logs.items(): for log in logs: + log = map(lambda l: l if isinstance(l, str) else repr(l), log) stdout.write(f' {test_name:15}: {RED}{" ".join(log)}{RESET_SEQ}\n') diff --git a/searx/search/checker/impl.py b/searx/search/checker/impl.py index 244536f1b..25887b0f4 100644 --- a/searx/search/checker/impl.py +++ b/searx/search/checker/impl.py @@ -9,7 +9,8 @@ from time import time from urllib.parse import urlparse import re -import cld3 +from langdetect import detect_langs +from langdetect.lang_detect_exception import LangDetectException import requests.exceptions from searx import poolrequests, logger @@ -181,10 +182,14 @@ class ResultContainerTests: self.test_results.add_error(self.test_name, message, *args, '(' + sqstr + ')') def _add_language(self, text: str) -> typing.Optional[str]: - r = cld3.get_language(str(text)) # pylint: disable=E1101 - if r is not None and r.probability >= 0.98 and r.is_reliable: - self.languages.add(r.language) - self.test_results.add_language(r.language) + try: + r = detect_langs(str(text)) # pylint: disable=E1101 + except LangDetectException: + return None + + if len(r) > 0 and r[0].prob > 0.95: + self.languages.add(r[0].lang) + self.test_results.add_language(r[0].lang) return None def _check_result(self, result): diff --git a/searx/search/processors/online.py b/searx/search/processors/online.py index 0ceb0adf2..d79edd542 100644 --- a/searx/search/processors/online.py +++ b/searx/search/processors/online.py @@ -239,14 +239,14 @@ class OnlineProcessor(EngineProcessor): 'test': ['unique_results'] } - if getattr(self.engine, 'lang', False): + if getattr(self.engine, 'supported_languages', []): tests['lang_fr'] = { 'matrix': {'query': 'paris', 'lang': 'fr'}, - 'result_container': ['not_empty', ('has_lang', 'fr')], + 'result_container': ['not_empty', ('has_language', 'fr')], } tests['lang_en'] = { 'matrix': {'query': 'paris', 'lang': 'en'}, - 'result_container': ['not_empty', ('has_lang', 'en')], + 'result_container': ['not_empty', ('has_language', 'en')], } if getattr(self.engine, 'safesearch', False): diff --git a/searx/settings.yml b/searx/settings.yml index 767bf6d82..d7149ad7c 100644 --- a/searx/settings.yml +++ b/searx/settings.yml @@ -105,11 +105,17 @@ outgoing: # communication with search engines checker: # disable checker when in debug mode off_when_debug: True + # scheduling: interval or int # use "scheduling: False" to disable scheduling - scheduling: - start_after: [300, 1800] # delay to start the first run of the checker - every: [86400, 90000] # how often the checker runs + # to activate the scheduler: + # * uncomment "scheduling" section + # * add "cache2 = name=searxcache,items=2000,blocks=2000,blocksize=4096,bitmap=1" to your uwsgi.ini + + # scheduling: + # start_after: [300, 1800] # delay to start the first run of the checker + # every: [86400, 90000] # how often the checker runs + # additional tests: only for the YAML anchors (see the engines section) additional_tests: rosebud: &test_rosebud diff --git a/utils/lxc.sh b/utils/lxc.sh index 39701ef04..bad5c10c8 100755 --- a/utils/lxc.sh +++ b/utils/lxc.sh @@ -39,6 +39,7 @@ $ubu1904_boilerplate echo 'Set disable_coredump false' >> /etc/sudo.conf " +# shellcheck disable=SC2034 ubu2010_boilerplate="$ubu1904_boilerplate" # shellcheck disable=SC2034 diff --git a/utils/searx.sh b/utils/searx.sh index f85935fa2..a33642ee4 100755 --- a/utils/searx.sh +++ b/utils/searx.sh @@ -46,7 +46,6 @@ SEARX_PACKAGES_debian="\ python3-dev python3-babel python3-venv uwsgi uwsgi-plugin-python3 git build-essential libxslt-dev zlib1g-dev libffi-dev libssl-dev -libprotobuf-dev protobuf-compiler shellcheck" BUILD_PACKAGES_debian="\ @@ -59,7 +58,6 @@ SEARX_PACKAGES_arch="\ python python-pip python-lxml python-babel uwsgi uwsgi-plugin-python git base-devel libxml2 -protobuf shellcheck" BUILD_PACKAGES_arch="\ @@ -71,7 +69,7 @@ SEARX_PACKAGES_fedora="\ python python-pip python-lxml python-babel uwsgi uwsgi-plugin-python3 git @development-tools libxml2 -ShellCheck protobuf-compiler protobuf-devel" +ShellCheck" BUILD_PACKAGES_fedora="\ firefox graphviz graphviz-gd ImageMagick librsvg2-tools @@ -84,7 +82,7 @@ SEARX_PACKAGES_centos="\ python36 python36-pip python36-lxml python-babel uwsgi uwsgi-plugin-python3 git @development-tools libxml2 -ShellCheck protobuf-compiler protobuf-devel" +ShellCheck" BUILD_PACKAGES_centos="\ firefox graphviz graphviz-gd ImageMagick librsvg2-tools |