google_videos.py 5.8 KB

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