google_videos.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 appied.
  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 lxml import html
  18. from searx import logger
  19. from searx.utils import (
  20. eval_xpath,
  21. eval_xpath_list,
  22. eval_xpath_getindex,
  23. extract_text,
  24. )
  25. from searx.engines.google import (
  26. get_lang_info,
  27. time_range_dict,
  28. filter_mapping,
  29. results_xpath,
  30. g_section_with_header,
  31. title_xpath,
  32. href_xpath,
  33. content_xpath,
  34. suggestion_xpath,
  35. spelling_suggestion_xpath,
  36. detect_google_sorry,
  37. )
  38. # pylint: disable=unused-import
  39. from searx.engines.google import (
  40. supported_languages_url
  41. , _fetch_supported_languages
  42. )
  43. # pylint: enable=unused-import
  44. # about
  45. about = {
  46. "website": 'https://www.google.com',
  47. "wikidata_id": 'Q219885',
  48. "official_api_documentation": 'https://developers.google.com/custom-search',
  49. "use_official_api": False,
  50. "require_api_key": False,
  51. "results": 'HTML',
  52. }
  53. logger = logger.getChild('google video')
  54. # engine dependent config
  55. categories = ['videos']
  56. paging = False
  57. language_support = True
  58. use_locale_domain = True
  59. time_range_support = True
  60. safesearch = True
  61. RE_CACHE = {}
  62. def _re(regexpr):
  63. """returns compiled regular expression"""
  64. RE_CACHE[regexpr] = RE_CACHE.get(regexpr, re.compile(regexpr))
  65. return RE_CACHE[regexpr]
  66. def scrap_out_thumbs(dom):
  67. """Scrap out thumbnail data from <script> tags.
  68. """
  69. ret_val = dict()
  70. thumb_name = 'vidthumb'
  71. for script in eval_xpath_list(dom, '//script[contains(., "_setImagesSrc")]'):
  72. _script = script.text
  73. # var s='data:image/jpeg;base64, ...'
  74. _imgdata = _re("s='([^']*)").findall( _script)
  75. if not _imgdata:
  76. continue
  77. # var ii=['vidthumb4','vidthumb7']
  78. for _vidthumb in _re(r"(%s\d+)" % thumb_name).findall(_script):
  79. # At least the equal sign in the URL needs to be decoded
  80. ret_val[_vidthumb] = _imgdata[0].replace(r"\x3d", "=")
  81. # {google.ldidly=-1;google.ldi={"vidthumb8":"https://...
  82. for script in eval_xpath_list(dom, '//script[contains(., "google.ldi={")]'):
  83. _script = script.text
  84. for key_val in _re(r'"%s\d+\":\"[^\"]*"' % thumb_name).findall( _script) :
  85. match = _re(r'"(%s\d+)":"(.*)"' % thumb_name).search(key_val)
  86. if match:
  87. # At least the equal sign in the URL needs to be decoded
  88. ret_val[match.group(1)] = match.group(2).replace(r"\u003d", "=")
  89. logger.debug("found %s imgdata for: %s", thumb_name, ret_val.keys())
  90. return ret_val
  91. def request(query, params):
  92. """Google-Video search request"""
  93. lang_info = get_lang_info(
  94. # pylint: disable=undefined-variable
  95. params, supported_languages, language_aliases
  96. )
  97. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  98. 'q': query,
  99. 'tbm': "vid",
  100. 'hl': lang_info['hl'],
  101. 'lr': lang_info['lr'],
  102. 'ie': "utf8",
  103. 'oe': "utf8",
  104. })
  105. if params['time_range'] in time_range_dict:
  106. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  107. if params['safesearch']:
  108. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  109. logger.debug("query_url --> %s", query_url)
  110. params['url'] = query_url
  111. logger.debug("HTTP header Accept-Language --> %s", lang_info['Accept-Language'])
  112. params['headers']['Accept-Language'] = lang_info['Accept-Language']
  113. params['headers']['Accept'] = (
  114. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  115. )
  116. return params
  117. def response(resp):
  118. """Get response from google's search request"""
  119. results = []
  120. detect_google_sorry(resp)
  121. # convert the text to dom
  122. dom = html.fromstring(resp.text)
  123. vidthumb_imgdata = scrap_out_thumbs(dom)
  124. # parse results
  125. for result in eval_xpath_list(dom, results_xpath):
  126. # google *sections*
  127. if extract_text(eval_xpath(result, g_section_with_header)):
  128. logger.debug("ingoring <g-section-with-header>")
  129. continue
  130. title = extract_text(eval_xpath_getindex(result, title_xpath, 0))
  131. url = eval_xpath_getindex(result, href_xpath, 0)
  132. c_node = eval_xpath_getindex(result, content_xpath, 0)
  133. # <img id="vidthumb1" ...>
  134. img_id = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@id', 0, default=None)
  135. if img_id is None:
  136. continue
  137. img_src = vidthumb_imgdata.get(img_id, None)
  138. if not img_src:
  139. logger.error("no vidthumb imgdata for: %s" % img_id)
  140. img_src = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@src', 0)
  141. length = extract_text(eval_xpath(c_node, './/div[1]//a/div[3]'))
  142. content = extract_text(eval_xpath(c_node, './/div[2]/span'))
  143. pub_info = extract_text(eval_xpath(c_node, './/div[2]/div'))
  144. results.append({
  145. 'url': url,
  146. 'title': title,
  147. 'content': content,
  148. 'length': length,
  149. 'author': pub_info,
  150. 'thumbnail': img_src,
  151. 'template': 'videos.html',
  152. })
  153. # parse suggestion
  154. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  155. # append suggestion
  156. results.append({'suggestion': extract_text(suggestion)})
  157. for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
  158. results.append({'correction': extract_text(correction)})
  159. return results