google_videos.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Google (Video)
  3. For detailed description of the *REST-full* API see: `Query Parameter
  4. Definitions`_. Not all parameters can be applied.
  5. .. _admonition:: Content-Security-Policy (CSP)
  6. This engine needs to allow images from the `data URLs`_ (prefixed with the
  7. ``data:` scheme).::
  8. Header set Content-Security-Policy "img-src 'self' data: ;"
  9. .. _Query Parameter Definitions:
  10. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  11. .. _data URLs:
  12. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  13. """
  14. # pylint: disable=invalid-name, missing-function-docstring
  15. import re
  16. from urllib.parse import urlencode
  17. from random import random
  18. from lxml import html
  19. from searx import logger
  20. from searx.utils import (
  21. eval_xpath,
  22. eval_xpath_list,
  23. eval_xpath_getindex,
  24. extract_text,
  25. )
  26. from searx.engines.google import (
  27. get_lang_info,
  28. time_range_dict,
  29. filter_mapping,
  30. results_xpath,
  31. g_section_with_header,
  32. title_xpath,
  33. href_xpath,
  34. content_xpath,
  35. suggestion_xpath,
  36. spelling_suggestion_xpath,
  37. detect_google_sorry,
  38. )
  39. # pylint: disable=unused-import
  40. from searx.engines.google import (
  41. supported_languages_url
  42. , _fetch_supported_languages
  43. )
  44. # pylint: enable=unused-import
  45. # about
  46. about = {
  47. "website": 'https://www.google.com',
  48. "wikidata_id": 'Q219885',
  49. "official_api_documentation": 'https://developers.google.com/custom-search',
  50. "use_official_api": False,
  51. "require_api_key": False,
  52. "results": 'HTML',
  53. }
  54. logger = logger.getChild('google video')
  55. # engine dependent config
  56. categories = ['videos']
  57. paging = False
  58. language_support = True
  59. use_locale_domain = True
  60. time_range_support = True
  61. safesearch = True
  62. RE_CACHE = {}
  63. def _re(regexpr):
  64. """returns compiled regular expression"""
  65. RE_CACHE[regexpr] = RE_CACHE.get(regexpr, re.compile(regexpr))
  66. return RE_CACHE[regexpr]
  67. def scrap_out_thumbs(dom):
  68. """Scrap out thumbnail data from <script> tags.
  69. """
  70. ret_val = {}
  71. thumb_name = 'vidthumb'
  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=['vidthumb4','vidthumb7']
  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. # {google.ldidly=-1;google.ldi={"vidthumb8":"https://...
  83. for script in eval_xpath_list(dom, '//script[contains(., "google.ldi={")]'):
  84. _script = script.text
  85. for key_val in _re(r'"%s\d+\":\"[^\"]*"' % thumb_name).findall( _script) :
  86. match = _re(r'"(%s\d+)":"(.*)"' % thumb_name).search(key_val)
  87. if match:
  88. # At least the equal sign in the URL needs to be decoded
  89. ret_val[match.group(1)] = match.group(2).replace(r"\u003d", "=")
  90. logger.debug("found %s imgdata for: %s", thumb_name, ret_val.keys())
  91. return ret_val
  92. def request(query, params):
  93. """Google-Video search request"""
  94. lang_info = get_lang_info(
  95. # pylint: disable=undefined-variable
  96. params, supported_languages, language_aliases, False
  97. )
  98. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  99. 'q': query,
  100. 'tbm': "vid",
  101. **lang_info['params'],
  102. 'ucbcb': 1,
  103. 'ie': "utf8",
  104. 'oe': "utf8",
  105. })
  106. if params['time_range'] in time_range_dict:
  107. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  108. if params['safesearch']:
  109. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  110. logger.debug("query_url --> %s", query_url)
  111. params['url'] = query_url
  112. logger.debug("HTTP header Accept-Language --> %s", lang_info.get('Accept-Language'))
  113. params['cookies']['CONSENT'] = "PENDING+" + str(random()*100)
  114. params['headers'].update(lang_info['headers'])
  115. params['headers']['Accept'] = (
  116. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  117. )
  118. return params
  119. def response(resp):
  120. """Get response from google's search request"""
  121. results = []
  122. detect_google_sorry(resp)
  123. # convert the text to dom
  124. dom = html.fromstring(resp.text)
  125. vidthumb_imgdata = scrap_out_thumbs(dom)
  126. # parse results
  127. for result in eval_xpath_list(dom, results_xpath):
  128. # google *sections*
  129. if extract_text(eval_xpath(result, g_section_with_header)):
  130. logger.debug("ignoring <g-section-with-header>")
  131. continue
  132. title = extract_text(eval_xpath_getindex(result, title_xpath, 0))
  133. url = eval_xpath_getindex(result, href_xpath, 0)
  134. c_node = eval_xpath_getindex(result, content_xpath, 0)
  135. # <img id="vidthumb1" ...>
  136. img_id = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@id', 0, default=None)
  137. if img_id is None:
  138. continue
  139. img_src = vidthumb_imgdata.get(img_id, None)
  140. if not img_src:
  141. logger.error("no vidthumb imgdata for: %s" % img_id)
  142. img_src = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@src', 0)
  143. length = extract_text(eval_xpath(c_node, './/div[1]//a/div[3]'))
  144. content = extract_text(eval_xpath(c_node, './/div[2]/span'))
  145. pub_info = extract_text(eval_xpath(c_node, './/div[2]/div'))
  146. results.append({
  147. 'url': url,
  148. 'title': title,
  149. 'content': content,
  150. 'length': length,
  151. 'author': pub_info,
  152. 'thumbnail': img_src,
  153. 'template': 'videos.html',
  154. })
  155. # parse suggestion
  156. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  157. # append suggestion
  158. results.append({'suggestion': extract_text(suggestion)})
  159. for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
  160. results.append({'correction': extract_text(correction)})
  161. return results