check regex match before access in flickr module
[mygpo.git] / mygpo / data / flickr.py
blob9506b005079d55805b274e285546508523d52f2b
2 # This file is part of gpodder.net.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
19 import re
20 import urllib
22 from django.conf import settings
24 from mygpo.core.json import json
27 def get_photo_sizes(photo_id):
28 api_key = settings.FLICKR_API_KEY
29 request = 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=%s&photo_id=%s&format=json' % (api_key, photo_id)
31 resp = urllib.urlopen(request).read()
33 extract_re = '^jsonFlickrApi\((.*)\)$'
34 m = re.match(extract_re, resp)
35 if not m:
36 return []
38 resp_obj = json.loads(m.group(1))
40 try:
41 return resp_obj['sizes']['size']
42 except KeyError:
43 return []
46 def get_photo_id(url):
47 photo_id_re = 'http://.*flickr.com/[^/]+/([^_]+)_.*'
48 return re.match(photo_id_re, url).group(1)
51 def is_flickr_image(url):
52 return re.search('flickr\.com.*\.(jpg|jpeg|png|gif)', url)
54 def get_display_photo(url, label='Medium'):
55 photo_id = get_photo_id(url)
56 sizes = get_photo_sizes(photo_id)
57 for s in sizes:
58 if s['label'] == label:
59 return s['source']
61 return url