google_videos.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Google (Video)
  4. For detailed description of the *REST-full* API see: `Query Parameter
  5. Definitions`_. Not all parameters can be appied.
  6. .. _admonition:: Content-Security-Policy (CSP)
  7. This engine needs to allow images from the `data URLs`_ (prefixed with the
  8. ``data:` scheme).::
  9. Header set Content-Security-Policy "img-src 'self' data: ;"
  10. .. _Query Parameter Definitions:
  11. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  12. .. _data URLs:
  13. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  14. """
  15. # pylint: disable=invalid-name, missing-function-docstring
  16. import re
  17. from urllib.parse import urlencode
  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 = dict()
  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
  97. )
  98. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  99. 'q': query,
  100. 'tbm': "vid",
  101. 'hl': lang_info['hl'],
  102. 'lr': lang_info['lr'],
  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['Accept-Language'])
  113. params['headers']['Accept-Language'] = lang_info['Accept-Language']
  114. params['headers']['Accept'] = (
  115. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  116. )
  117. return params
  118. def response(resp):
  119. """Get response from google's search request"""
  120. results = []
  121. detect_google_sorry(resp)
  122. # convert the text to dom
  123. dom = html.fromstring(resp.text)
  124. vidthumb_imgdata = scrap_out_thumbs(dom)
  125. # parse results
  126. for result in eval_xpath_list(dom, results_xpath):
  127. # google *sections*
  128. if extract_text(eval_xpath(result, g_section_with_header)):
  129. logger.debug("ingoring <g-section-with-header>")
  130. continue
  131. title = extract_text(eval_xpath_getindex(result, title_xpath, 0))
  132. url = eval_xpath_getindex(result, href_xpath, 0)
  133. c_node = eval_xpath_getindex(result, content_xpath, 0)
  134. # <img id="vidthumb1" ...>
  135. img_id = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@id', 0, default=None)
  136. if img_id is None:
  137. continue
  138. img_src = vidthumb_imgdata.get(img_id, None)
  139. if not img_src:
  140. logger.error("no vidthumb imgdata for: %s" % img_id)
  141. img_src = eval_xpath_getindex(c_node, './div[1]//a/g-img/img/@src', 0)
  142. length = extract_text(eval_xpath(c_node, './/div[1]//a/div[3]'))
  143. content = extract_text(eval_xpath(c_node, './/div[2]/span'))
  144. pub_info = extract_text(eval_xpath(c_node, './/div[2]/div'))
  145. results.append({
  146. 'url': url,
  147. 'title': title,
  148. 'content': content,
  149. 'length': length,
  150. 'author': pub_info,
  151. 'thumbnail': img_src,
  152. 'template': 'videos.html',
  153. })
  154. # parse suggestion
  155. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  156. # append suggestion
  157. results.append({'suggestion': extract_text(suggestion)})
  158. for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
  159. results.append({'correction': extract_text(correction)})
  160. return results