google_videos.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This is the implementation of the google videos engine.
  4. .. admonition:: Content-Security-Policy (CSP)
  5. This engine needs to allow images from the `data URLs`_ (prefixed with the
  6. ``data:`` scheme)::
  7. Header set Content-Security-Policy "img-src 'self' data: ;"
  8. .. _data URLs:
  9. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  10. """
  11. # pylint: disable=invalid-name
  12. import re
  13. from urllib.parse import urlencode
  14. from lxml import html
  15. from searx.utils import (
  16. eval_xpath,
  17. eval_xpath_list,
  18. eval_xpath_getindex,
  19. extract_text,
  20. )
  21. from searx.engines.google import (
  22. get_lang_info,
  23. time_range_dict,
  24. filter_mapping,
  25. g_section_with_header,
  26. title_xpath,
  27. suggestion_xpath,
  28. detect_google_sorry,
  29. )
  30. # pylint: disable=unused-import
  31. from searx.engines.google import supported_languages_url, _fetch_supported_languages
  32. # pylint: enable=unused-import
  33. # about
  34. about = {
  35. "website": 'https://www.google.com',
  36. "wikidata_id": 'Q219885',
  37. "official_api_documentation": 'https://developers.google.com/custom-search',
  38. "use_official_api": False,
  39. "require_api_key": False,
  40. "results": 'HTML',
  41. }
  42. # engine dependent config
  43. categories = ['videos', 'web']
  44. paging = False
  45. language_support = True
  46. use_locale_domain = True
  47. time_range_support = True
  48. safesearch = True
  49. send_accept_language_header = True
  50. RE_CACHE = {}
  51. def _re(regexpr):
  52. """returns compiled regular expression"""
  53. RE_CACHE[regexpr] = RE_CACHE.get(regexpr, re.compile(regexpr))
  54. return RE_CACHE[regexpr]
  55. def scrap_out_thumbs_src(dom):
  56. ret_val = {}
  57. thumb_name = 'dimg_'
  58. for script in eval_xpath_list(dom, '//script[contains(., "google.ldi={")]'):
  59. _script = script.text
  60. # "dimg_35":"https://i.ytimg.c....",
  61. _dimurl = _re("s='([^']*)").findall(_script)
  62. for k, v in _re('(' + thumb_name + '[0-9]*)":"(http[^"]*)').findall(_script):
  63. v = v.replace(r'\u003d', '=')
  64. v = v.replace(r'\u0026', '&')
  65. ret_val[k] = v
  66. logger.debug("found %s imgdata for: %s", thumb_name, ret_val.keys())
  67. return ret_val
  68. def scrap_out_thumbs(dom):
  69. """Scrap out thumbnail data from <script> tags."""
  70. ret_val = {}
  71. thumb_name = 'dimg_'
  72. for script in eval_xpath_list(dom, '//script[contains(., "_setImagesSrc")]'):
  73. _script = script.text
  74. # var s='data:image/jpeg;base64, ...'
  75. _imgdata = _re("s='([^']*)").findall(_script)
  76. if not _imgdata:
  77. continue
  78. # var ii=['dimg_17']
  79. for _vidthumb in _re(r"(%s\d+)" % thumb_name).findall(_script):
  80. # At least the equal sign in the URL needs to be decoded
  81. ret_val[_vidthumb] = _imgdata[0].replace(r"\x3d", "=")
  82. logger.debug("found %s imgdata for: %s", thumb_name, ret_val.keys())
  83. return ret_val
  84. def request(query, params):
  85. """Google-Video search request"""
  86. lang_info = get_lang_info(params, supported_languages, language_aliases, False)
  87. query_url = (
  88. 'https://'
  89. + lang_info['subdomain']
  90. + '/search'
  91. + "?"
  92. + urlencode({'q': query, 'tbm': "vid", **lang_info['params'], 'ie': "utf8", 'oe': "utf8"})
  93. )
  94. if params['time_range'] in time_range_dict:
  95. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  96. if params['safesearch']:
  97. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  98. params['url'] = query_url
  99. params['cookies']['CONSENT'] = "YES+"
  100. params['headers'].update(lang_info['headers'])
  101. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  102. return params
  103. def response(resp):
  104. """Get response from google's search request"""
  105. results = []
  106. detect_google_sorry(resp)
  107. # convert the text to dom
  108. dom = html.fromstring(resp.text)
  109. vidthumb_imgdata = scrap_out_thumbs(dom)
  110. thumbs_src = scrap_out_thumbs_src(dom)
  111. logger.debug(str(thumbs_src))
  112. # parse results
  113. for result in eval_xpath_list(dom, '//div[contains(@class, "g ")]'):
  114. # ignore google *sections*
  115. if extract_text(eval_xpath(result, g_section_with_header)):
  116. logger.debug("ingoring <g-section-with-header>")
  117. continue
  118. # ingnore articles without an image id / e.g. news articles
  119. img_id = eval_xpath_getindex(result, './/g-img/img/@id', 0, default=None)
  120. if img_id is None:
  121. logger.error("no img_id found in item %s (news article?)", len(results) + 1)
  122. continue
  123. img_src = vidthumb_imgdata.get(img_id, None)
  124. if not img_src:
  125. img_src = thumbs_src.get(img_id, "")
  126. title = extract_text(eval_xpath_getindex(result, title_xpath, 0))
  127. url = eval_xpath_getindex(result, './/div[@class="dXiKIc"]//a/@href', 0)
  128. length = extract_text(eval_xpath(result, './/div[contains(@class, "P7xzyf")]/span/span'))
  129. c_node = eval_xpath_getindex(result, './/div[@class="Uroaid"]', 0)
  130. content = extract_text(c_node)
  131. pub_info = extract_text(eval_xpath(result, './/div[@class="Zg1NU"]'))
  132. results.append(
  133. {
  134. 'url': url,
  135. 'title': title,
  136. 'content': content,
  137. 'length': length,
  138. 'author': pub_info,
  139. 'thumbnail': img_src,
  140. 'template': 'videos.html',
  141. }
  142. )
  143. # parse suggestion
  144. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  145. # append suggestion
  146. results.append({'suggestion': extract_text(suggestion)})
  147. return results