flickr_noapi.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Flickr (Images)
  4. """
  5. from typing import TYPE_CHECKING
  6. import json
  7. from time import time
  8. import re
  9. from urllib.parse import urlencode
  10. from searx.utils import ecma_unescape, html_to_text
  11. if TYPE_CHECKING:
  12. import logging
  13. logger: logging.Logger
  14. # about
  15. about = {
  16. "website": 'https://www.flickr.com',
  17. "wikidata_id": 'Q103204',
  18. "official_api_documentation": 'https://secure.flickr.com/services/api/flickr.photos.search.html',
  19. "use_official_api": False,
  20. "require_api_key": False,
  21. "results": 'HTML',
  22. }
  23. # engine dependent config
  24. categories = ['images']
  25. paging = True
  26. time_range_support = True
  27. safesearch = False
  28. time_range_dict = {
  29. 'day': 60 * 60 * 24,
  30. 'week': 60 * 60 * 24 * 7,
  31. 'month': 60 * 60 * 24 * 7 * 4,
  32. 'year': 60 * 60 * 24 * 7 * 52,
  33. }
  34. image_sizes = ('o', 'k', 'h', 'b', 'c', 'z', 'm', 'n', 't', 'q', 's')
  35. search_url = 'https://www.flickr.com/search?{query}&page={page}'
  36. time_range_url = '&min_upload_date={start}&max_upload_date={end}'
  37. photo_url = 'https://www.flickr.com/photos/{userid}/{photoid}'
  38. modelexport_re = re.compile(r"^\s*modelExport:\s*({.*}),$", re.M)
  39. def build_flickr_url(user_id, photo_id):
  40. return photo_url.format(userid=user_id, photoid=photo_id)
  41. def _get_time_range_url(time_range):
  42. if time_range in time_range_dict:
  43. return time_range_url.format(start=time(), end=str(int(time()) - time_range_dict[time_range]))
  44. return ''
  45. def request(query, params):
  46. params['url'] = search_url.format(query=urlencode({'text': query}), page=params['pageno']) + _get_time_range_url(
  47. params['time_range']
  48. )
  49. return params
  50. def response(resp): # pylint: disable=too-many-branches
  51. results = []
  52. matches = modelexport_re.search(resp.text)
  53. if matches is None:
  54. return results
  55. match = matches.group(1)
  56. model_export = json.loads(match)
  57. if 'legend' not in model_export:
  58. return results
  59. legend = model_export['legend']
  60. # handle empty page
  61. if not legend or not legend[0]:
  62. return results
  63. for x, index in enumerate(legend):
  64. if len(index) != 8:
  65. logger.debug("skip legend enty %s : %s", x, index)
  66. continue
  67. photo = model_export['main'][index[0]][int(index[1])][index[2]][index[3]][index[4]][index[5]][int(index[6])][
  68. index[7]
  69. ]
  70. author = ecma_unescape(photo.get('realname', ''))
  71. source = ecma_unescape(photo.get('username', ''))
  72. if source:
  73. source += ' @ Flickr'
  74. title = ecma_unescape(photo.get('title', ''))
  75. content = html_to_text(ecma_unescape(photo.get('description', '')))
  76. img_src = None
  77. # From the biggest to the lowest format
  78. size_data = None
  79. for image_size in image_sizes:
  80. if image_size in photo['sizes']['data']:
  81. size_data = photo['sizes']['data'][image_size]['data']
  82. break
  83. if not size_data:
  84. logger.debug('cannot find valid image size: {0}'.format(repr(photo['sizes']['data'])))
  85. continue
  86. img_src = size_data['url']
  87. img_format = f"{size_data['width']} x {size_data['height']}"
  88. # For a bigger thumbnail, keep only the url_z, not the url_n
  89. if 'n' in photo['sizes']['data']:
  90. thumbnail_src = photo['sizes']['data']['n']['data']['url']
  91. elif 'z' in photo['sizes']['data']:
  92. thumbnail_src = photo['sizes']['data']['z']['data']['url']
  93. else:
  94. thumbnail_src = img_src
  95. if 'ownerNsid' not in photo:
  96. # should not happen, disowned photo? Show it anyway
  97. url = img_src
  98. else:
  99. url = build_flickr_url(photo['ownerNsid'], photo['id'])
  100. result = {
  101. 'url': url,
  102. 'img_src': img_src,
  103. 'thumbnail_src': thumbnail_src,
  104. 'source': source,
  105. 'img_format': img_format,
  106. 'template': 'images.html',
  107. }
  108. result['author'] = author.encode(errors='ignore').decode()
  109. result['source'] = source.encode(errors='ignore').decode()
  110. result['title'] = title.encode(errors='ignore').decode()
  111. result['content'] = content.encode(errors='ignore').decode()
  112. results.append(result)
  113. return results