flickr-noapi.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. url = build_flickr_url(photo['owner']['id'], photo['id'])
  53. title = photo['title']
  54. content = '<span class="photo-author">' +\
  55. photo['owner']['username'] +\
  56. '</span><br />'
  57. if 'description' in photo:
  58. content = content +\
  59. '<span class="description">' +\
  60. photo['description'] +\
  61. '</span>'
  62. # append result
  63. results.append({'url': url,
  64. 'title': title,
  65. 'img_src': img_src,
  66. 'content': content,
  67. 'template': 'images.html'})
  68. return results