google_videos.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This is the implementation of the Google Videos engine.
  3. .. admonition:: Content-Security-Policy (CSP)
  4. This engine needs to allow images from the `data URLs`_ (prefixed with the
  5. ``data:`` scheme)::
  6. Header set Content-Security-Policy "img-src 'self' data: ;"
  7. .. _data URLs:
  8. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  9. """
  10. from __future__ import annotations
  11. from urllib.parse import urlencode, urlparse, parse_qs
  12. from lxml import html
  13. from searx.utils import (
  14. eval_xpath_list,
  15. eval_xpath_getindex,
  16. extract_text,
  17. )
  18. from searx.engines.google import fetch_traits # pylint: disable=unused-import
  19. from searx.engines.google import (
  20. get_google_info,
  21. time_range_dict,
  22. filter_mapping,
  23. suggestion_xpath,
  24. detect_google_sorry,
  25. ui_async,
  26. parse_data_images,
  27. )
  28. from searx.enginelib.traits import EngineTraits
  29. from searx.utils import get_embeded_stream_url
  30. traits: EngineTraits
  31. # about
  32. about = {
  33. "website": 'https://www.google.com',
  34. "wikidata_id": 'Q219885',
  35. "official_api_documentation": 'https://developers.google.com/custom-search',
  36. "use_official_api": False,
  37. "require_api_key": False,
  38. "results": 'HTML',
  39. }
  40. # engine dependent config
  41. categories = ['videos', 'web']
  42. paging = True
  43. max_page = 50
  44. language_support = True
  45. time_range_support = True
  46. safesearch = True
  47. def request(query, params):
  48. """Google-Video search request"""
  49. google_info = get_google_info(params, traits)
  50. start = (params['pageno'] - 1) * 10
  51. query_url = (
  52. 'https://'
  53. + google_info['subdomain']
  54. + '/search'
  55. + "?"
  56. + urlencode(
  57. {
  58. 'q': query,
  59. 'tbm': "vid",
  60. 'start': start,
  61. **google_info['params'],
  62. 'asearch': 'arc',
  63. 'async': ui_async(start),
  64. }
  65. )
  66. )
  67. if params['time_range'] in time_range_dict:
  68. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  69. if 'safesearch' in params:
  70. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  71. params['url'] = query_url
  72. params['cookies'] = google_info['cookies']
  73. params['headers'].update(google_info['headers'])
  74. return params
  75. def response(resp):
  76. """Get response from google's search request"""
  77. results = []
  78. detect_google_sorry(resp)
  79. data_image_map = parse_data_images(resp.text)
  80. # convert the text to dom
  81. dom = html.fromstring(resp.text)
  82. result_divs = eval_xpath_list(dom, '//div[contains(@class, "MjjYud")]')
  83. # parse results
  84. for result in result_divs:
  85. title = extract_text(
  86. eval_xpath_getindex(result, './/h3[contains(@class, "LC20lb")]', 0, default=None), allow_none=True
  87. )
  88. url = eval_xpath_getindex(result, './/a[@jsname="UWckNb"]/@href', 0, default=None)
  89. content = extract_text(
  90. eval_xpath_getindex(result, './/div[contains(@class, "ITZIwc")]', 0, default=None), allow_none=True
  91. )
  92. pub_info = extract_text(
  93. eval_xpath_getindex(result, './/div[contains(@class, "gqF9jc")]', 0, default=None), allow_none=True
  94. )
  95. # Broader XPath to find any <img> element
  96. thumbnail = eval_xpath_getindex(result, './/img/@src', 0, default=None)
  97. duration = extract_text(
  98. eval_xpath_getindex(result, './/span[contains(@class, "k1U36b")]', 0, default=None), allow_none=True
  99. )
  100. video_id = eval_xpath_getindex(result, './/div[@jscontroller="rTuANe"]/@data-vid', 0, default=None)
  101. # Fallback for video_id from URL if not found via XPath
  102. if not video_id and url and 'youtube.com' in url:
  103. parsed_url = urlparse(url)
  104. video_id = parse_qs(parsed_url.query).get('v', [None])[0]
  105. # Handle thumbnail
  106. if thumbnail and thumbnail.startswith('data:image'):
  107. img_id = eval_xpath_getindex(result, './/img/@id', 0, default=None)
  108. if img_id and img_id in data_image_map:
  109. thumbnail = data_image_map[img_id]
  110. else:
  111. thumbnail = None
  112. if not thumbnail and video_id:
  113. thumbnail = f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
  114. # Handle video embed URL
  115. embed_url = None
  116. if video_id:
  117. embed_url = get_embeded_stream_url(f"https://www.youtube.com/watch?v={video_id}")
  118. elif url:
  119. embed_url = get_embeded_stream_url(url)
  120. # Only append results with valid title and url
  121. if title and url:
  122. results.append(
  123. {
  124. 'url': url,
  125. 'title': title,
  126. 'content': content or '',
  127. 'author': pub_info,
  128. 'thumbnail': thumbnail,
  129. 'length': duration,
  130. 'iframe_src': embed_url,
  131. 'template': 'videos.html',
  132. }
  133. )
  134. # parse suggestion
  135. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  136. results.append({'suggestion': extract_text(suggestion)})
  137. return results