Merge pull request #793 from gpodder/remove-advertise
[mygpo.git] / mygpo / data / flickr.py
blob1e05e3ae3df9d475866c66285663ae5f7855aa36
1 import json
2 import re
3 import requests
5 from django.conf import settings
7 import logging
9 logger = logging.getLogger(__name__)
12 GET_SIZES_TEMPLATE = "https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key={api_key}&photo_id={photo_id}&format=json&nojsoncallback=1"
15 def get_photo_sizes(photo_id):
16 """Returns available sizes for the photo with the given ID
18 Returns a list of dicts containing the following keys
19 * source
20 * url
21 * media
22 * height
23 * width
24 * label
25 """
27 api_key = settings.FLICKR_API_KEY
28 url = GET_SIZES_TEMPLATE.format(api_key=api_key, photo_id=photo_id)
30 try:
31 resp = requests.get(url)
32 except requests.exceptions.RequestException as e:
33 logger.warning("Retrieving Flickr photo sizes failed: %s", str(e))
34 return []
36 try:
37 resp_obj = resp.json()
38 except json.JSONDecodeError as jde:
39 return []
41 try:
42 return resp_obj["sizes"]["size"]
43 except KeyError:
44 return []
47 def get_photo_id(url):
48 """Returns the Photo ID for a Photo URL
50 >>> get_photo_id('https://farm9.staticflickr.com/8747/12346789012_bf1e234567_b.jpg')
51 '12346789012'
53 >>> get_photo_id('https://www.flickr.com/photos/someuser/12345678901/')
54 '12345678901'
56 """
58 photo_id_re = [
59 "http://.*flickr.com/[^/]+/([^_]+)_.*",
60 "https://.*staticflickr.com/[^/]+/([^_]+)_.*",
61 "https?://.*flickr.com/photos/[^/]+/([^/]+).*",
64 for regex in photo_id_re:
65 match = re.match(regex, url)
66 if match:
67 return match.group(1)
70 def is_flickr_image(url):
71 """Returns True if the URL represents a Flickr images
73 >>> is_flickr_image('https://farm9.staticflickr.com/8747/12346789012_bf1e234567_b.jpg')
74 True
76 >>> is_flickr_image('http://www.example.com/podcast.mp3')
77 False
79 >>> is_flickr_image(None)
80 False
81 """
83 if url is None:
84 return False
85 return bool(re.search(r"flickr\.com.*\.(jpg|jpeg|png|gif)", url))
88 def get_display_photo(url, label="Medium"):
89 photo_id = get_photo_id(url)
90 sizes = get_photo_sizes(photo_id)
91 for s in sizes:
92 if s["label"] == label:
93 return s["source"]
95 return url