google_videos.py 5.7 KB

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