flickr-noapi.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env python
  2. # Flickr (Images)
  3. #
  4. # @website https://www.flickr.com
  5. # @provide-api yes (https://secure.flickr.com/services/api/flickr.photos.search.html)
  6. #
  7. # @using-api no
  8. # @results HTML
  9. # @stable no
  10. # @parse url, title, thumbnail, img_src
  11. from urllib import urlencode
  12. from json import loads
  13. import re
  14. categories = ['images']
  15. url = 'https://secure.flickr.com/'
  16. search_url = url+'search/?{query}&page={page}'
  17. photo_url = 'https://www.flickr.com/photos/{userid}/{photoid}'
  18. regex = re.compile(r"\"search-photos-models\",\"photos\":(.*}),\"totalItems\":", re.DOTALL)
  19. image_sizes = ('o', 'k', 'h', 'b', 'c', 'z', 'n', 'm', 't', 'q', 's')
  20. paging = True
  21. def build_flickr_url(user_id, photo_id):
  22. return photo_url.format(userid=user_id, photoid=photo_id)
  23. def request(query, params):
  24. params['url'] = search_url.format(query=urlencode({'text': query}),
  25. page=params['pageno'])
  26. return params
  27. def response(resp):
  28. results = []
  29. matches = regex.search(resp.text)
  30. if matches is None:
  31. return results
  32. match = matches.group(1)
  33. search_results = loads(match)
  34. if '_data' not in search_results:
  35. return []
  36. photos = search_results['_data']
  37. for photo in photos:
  38. # In paged configuration, the first pages' photos
  39. # are represented by a None object
  40. if photo is None:
  41. continue
  42. img_src = None
  43. # From the biggest to the lowest format
  44. for image_size in image_sizes:
  45. if image_size in photo['sizes']:
  46. img_src = photo['sizes'][image_size]['displayUrl']
  47. break
  48. if not img_src:
  49. continue
  50. if 'id' not in photo['owner']:
  51. continue
  52. # For a bigger thumbnail, keep only the url_z, not the url_n
  53. if 'n' in photo['sizes']:
  54. thumbnail_src = photo['sizes']['n']['displayUrl']
  55. elif 'z' in photo['sizes']:
  56. thumbnail_src = photo['sizes']['z']['displayUrl']
  57. else:
  58. thumbnail_src = img_src
  59. url = build_flickr_url(photo['owner']['id'], photo['id'])
  60. title = photo.get('title', '')
  61. content = '<span class="photo-author">' +\
  62. photo['owner']['username'] +\
  63. '</span><br />'
  64. if 'description' in photo:
  65. content = content +\
  66. '<span class="description">' +\
  67. photo['description'] +\
  68. '</span>'
  69. # append result
  70. results.append({'url': url,
  71. 'title': title,
  72. 'img_src': img_src,
  73. 'thumbnail_src': thumbnail_src,
  74. 'content': content,
  75. 'template': 'images.html'})
  76. return results