bing_videos.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing-Videos: description see :py:obj:`searx.engines.bing`.
  4. """
  5. # pylint: disable=invalid-name
  6. from typing import TYPE_CHECKING
  7. import uuid
  8. import json
  9. from urllib.parse import urlencode
  10. from lxml import html
  11. from searx.enginelib.traits import EngineTraits
  12. from searx.engines.bing import (
  13. set_bing_cookies,
  14. _fetch_traits,
  15. )
  16. from searx.engines.bing import send_accept_language_header # pylint: disable=unused-import
  17. if TYPE_CHECKING:
  18. import logging
  19. logger: logging.Logger
  20. traits: EngineTraits
  21. about = {
  22. "website": 'https://www.bing.com/videos',
  23. "wikidata_id": 'Q4914152',
  24. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-video-search-api',
  25. "use_official_api": False,
  26. "require_api_key": False,
  27. "results": 'HTML',
  28. }
  29. # engine dependent config
  30. categories = ['videos', 'web']
  31. paging = True
  32. safesearch = True
  33. time_range_support = True
  34. base_url = 'https://www.bing.com/videos/asyncv2'
  35. """Bing (Videos) async search URL."""
  36. bing_traits_url = 'https://learn.microsoft.com/en-us/bing/search-apis/bing-video-search/reference/market-codes'
  37. """Bing (Video) search API description"""
  38. time_map = {
  39. # fmt: off
  40. 'day': 60 * 24,
  41. 'week': 60 * 24 * 7,
  42. 'month': 60 * 24 * 31,
  43. 'year': 60 * 24 * 365,
  44. # fmt: on
  45. }
  46. def request(query, params):
  47. """Assemble a Bing-Video request."""
  48. engine_region = traits.get_region(params['searxng_locale'], 'en-US')
  49. engine_language = traits.get_language(params['searxng_locale'], 'en')
  50. SID = uuid.uuid1().hex.upper()
  51. set_bing_cookies(params, engine_language, engine_region, SID)
  52. # build URL query
  53. #
  54. # example: https://www.bing.com/videos/asyncv2?q=foo&async=content&first=1&count=35
  55. query_params = {
  56. # fmt: off
  57. 'q': query,
  58. 'async' : 'content',
  59. # to simplify the page count lets use the default of 35 images per page
  60. 'first' : (int(params.get('pageno', 1)) - 1) * 35 + 1,
  61. 'count' : 35,
  62. # fmt: on
  63. }
  64. # time range
  65. #
  66. # example: one week (10080 minutes) '&qft= filterui:videoage-lt10080' '&form=VRFLTR'
  67. if params['time_range']:
  68. query_params['form'] = 'VRFLTR'
  69. query_params['qft'] = ' filterui:videoage-lt%s' % time_map[params['time_range']]
  70. params['url'] = base_url + '?' + urlencode(query_params)
  71. return params
  72. def response(resp):
  73. """Get response from Bing-Video"""
  74. results = []
  75. dom = html.fromstring(resp.text)
  76. for result in dom.xpath('//div[@class="dg_u"]//div[contains(@id, "mc_vtvc_video")]'):
  77. metadata = json.loads(result.xpath('.//div[@class="vrhdata"]/@vrhm')[0])
  78. info = ' - '.join(result.xpath('.//div[@class="mc_vtvc_meta_block"]//span/text()')).strip()
  79. content = '{0} - {1}'.format(metadata['du'], info)
  80. thumbnail = result.xpath('.//div[contains(@class, "mc_vtvc_th")]//img/@src')[0]
  81. results.append(
  82. {
  83. 'url': metadata['murl'],
  84. 'thumbnail': thumbnail,
  85. 'title': metadata.get('vt', ''),
  86. 'content': content,
  87. 'template': 'videos.html',
  88. }
  89. )
  90. return results
  91. def fetch_traits(engine_traits: EngineTraits):
  92. """Fetch languages and regions from Bing-Videos."""
  93. xpath_market_codes = '//table[1]/tbody/tr/td[3]'
  94. # xpath_country_codes = '//table[2]/tbody/tr/td[2]'
  95. xpath_language_codes = '//table[3]/tbody/tr/td[2]'
  96. _fetch_traits(engine_traits, bing_traits_url, xpath_language_codes, xpath_market_codes)