refreshing flickr cover images + some cleanup
[redakcja.git] / apps / cover / management / commands / refresh_covers.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import urllib2 as urllib
7
8 from django.core.files.base import ContentFile
9 from django.core.management.base import NoArgsCommand
10
11 from cover.models import Image
12 from cover.utils import get_flickr_data, URLOpener, FlickrError
13
14
15 class Command(NoArgsCommand):
16     def handle_noargs(self, **options):
17         for image in Image.objects.exclude(book=None).order_by('id'):
18             print image.id
19             if 'flickr.com' in image.source_url:
20                 try:
21                     flickr_data = get_flickr_data(image.source_url)
22                 except FlickrError as e:
23                     print 'Flickr analysis failed: %s' % e
24                 else:
25                     try:
26                         t = URLOpener().open(image.download_url).read()
27                     except urllib.URLError:
28                         print 'Broken download url'
29                     except IOError:
30                         print 'Connection failed'
31                     else:
32                         image.download_url = flickr_data['download_url']
33                         image.file.save(image.file.name, ContentFile(t))
34                         image.save()