google_videos.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Google (Viedo)
  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, urlparse
  18. from lxml import html
  19. from searx import logger
  20. from searx.exceptions import SearxEngineCaptchaException
  21. from searx.utils import (
  22. eval_xpath,
  23. eval_xpath_list,
  24. extract_text,
  25. )
  26. from searx.engines.google import (
  27. get_lang_country,
  28. google_domains,
  29. time_range_dict,
  30. filter_mapping,
  31. results_xpath,
  32. g_section_with_header,
  33. title_xpath,
  34. href_xpath,
  35. content_xpath,
  36. suggestion_xpath,
  37. spelling_suggestion_xpath
  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. "template": 'video.html',
  54. "parse": ('url', 'title', 'content', 'thumbnail')
  55. }
  56. logger = logger.getChild('google video')
  57. # engine dependent config
  58. categories = ['videos']
  59. paging = False
  60. language_support = True
  61. use_locale_domain = True
  62. time_range_support = True
  63. safesearch = True
  64. RE_CACHE = {}
  65. def _re(regexpr):
  66. """returns compiled regular expression"""
  67. RE_CACHE[regexpr] = RE_CACHE.get(regexpr, re.compile(regexpr))
  68. return RE_CACHE[regexpr]
  69. def scrap_out_thumbs(dom):
  70. """Scrap out thumbnail data from <script> tags.
  71. """
  72. ret_val = dict()
  73. thumb_name = 'vidthumb'
  74. for script in eval_xpath(dom, '//script[contains(., "_setImagesSrc")]'):
  75. _script = script.text
  76. # var s='data:image/jpeg;base64, ...'
  77. _imgdata = _re("s='([^']*)").findall( _script)
  78. if not _imgdata:
  79. continue
  80. # var ii=['vidthumb4','vidthumb7']
  81. for _vidthumb in _re(r"(%s\d+)" % thumb_name).findall(_script):
  82. # At least the equal sign in the URL needs to be decoded
  83. ret_val[_vidthumb] = _imgdata[0].replace(r"\x3d", "=")
  84. # {google.ldidly=-1;google.ldi={"vidthumb8":"https://...
  85. for script in eval_xpath(dom, '//script[contains(., "google.ldi={")]'):
  86. _script = script.text
  87. for key_val in _re(r'"%s\d+\":\"[^\"]*"' % thumb_name).findall( _script) :
  88. match = _re(r'"(%s\d+)":"(.*)"' % thumb_name).search(key_val)
  89. if match:
  90. # At least the equal sign in the URL needs to be decoded
  91. ret_val[match.group(1)] = match.group(2).replace(r"\u003d", "=")
  92. logger.debug("found %s imgdata for: %s", thumb_name, ret_val.keys())
  93. return ret_val
  94. def request(query, params):
  95. """Google-Video search request"""
  96. language, country, lang_country = get_lang_country(
  97. # pylint: disable=undefined-variable
  98. params, supported_languages, language_aliases
  99. )
  100. subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
  101. query_url = 'https://'+ subdomain + '/search' + "?" + urlencode({
  102. 'q': query,
  103. 'tbm': "vid",
  104. 'hl': lang_country,
  105. 'lr': "lang_" + language,
  106. 'ie': "utf8",
  107. 'oe': "utf8",
  108. })
  109. if params['time_range'] in time_range_dict:
  110. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  111. if params['safesearch']:
  112. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  113. params['url'] = query_url
  114. logger.debug("query_url --> %s", query_url)
  115. # en-US,en;q=0.8,en;q=0.5
  116. params['headers']['Accept-Language'] = (
  117. "%s,%s;q=0.8,%s;q=0.5" % (lang_country, language, language))
  118. logger.debug(
  119. "HTTP Accept-Language --> %s", params['headers']['Accept-Language'])
  120. params['headers']['Accept'] = (
  121. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  122. )
  123. #params['google_subdomain'] = subdomain
  124. return params
  125. def response(resp):
  126. """Get response from google's search request"""
  127. results = []
  128. # detect google sorry
  129. resp_url = urlparse(resp.url)
  130. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  131. raise SearxEngineCaptchaException()
  132. if resp_url.path.startswith('/sorry'):
  133. raise SearxEngineCaptchaException()
  134. # which subdomain ?
  135. # subdomain = resp.search_params.get('google_subdomain')
  136. # convert the text to dom
  137. dom = html.fromstring(resp.text)
  138. vidthumb_imgdata = scrap_out_thumbs(dom)
  139. # parse results
  140. for result in eval_xpath_list(dom, results_xpath):
  141. # google *sections*
  142. if extract_text(eval_xpath(result, g_section_with_header)):
  143. logger.debug("ingoring <g-section-with-header>")
  144. continue
  145. title = extract_text(eval_xpath(result, title_xpath)[0])
  146. url = eval_xpath(result, href_xpath)[0]
  147. c_node = eval_xpath(result, content_xpath)[0]
  148. # <img id="vidthumb1" ...>
  149. img_id = eval_xpath(c_node, './div[1]//a/g-img/img/@id')
  150. if not img_id:
  151. continue
  152. img_id = img_id[0]
  153. img_src = vidthumb_imgdata.get(img_id, None)
  154. if not img_src:
  155. logger.error("no vidthumb imgdata for: %s" % img_id)
  156. img_src = eval_xpath(c_node, './div[1]//a/g-img/img/@src')[0]
  157. duration = extract_text(eval_xpath(c_node, './div[1]//a/span'))
  158. content = extract_text(eval_xpath(c_node, './div[2]/span'))
  159. pub_info = extract_text(eval_xpath(c_node, './div[2]/div'))
  160. if len(duration) > 3:
  161. content = duration + " - " + content
  162. if pub_info:
  163. content = content + " (%s)" % pub_info
  164. results.append({
  165. 'url': url,
  166. 'title': title,
  167. 'content': content,
  168. 'thumbnail': img_src,
  169. 'template': 'videos.html',
  170. })
  171. # parse suggestion
  172. for suggestion in eval_xpath(dom, suggestion_xpath):
  173. # append suggestion
  174. results.append({'suggestion': extract_text(suggestion)})
  175. for correction in eval_xpath(dom, spelling_suggestion_xpath):
  176. results.append({'correction': extract_text(correction)})
  177. return results