google_videos.py 5.5 KB

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