google_videos.py 5.7 KB

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