flickr_noapi.py 4.2 KB

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