540304dcfa72376363d5700531dc3bed0c33aa4d
[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 from optparse import make_option
8
9 from django.core.files.base import ContentFile
10 from django.core.management import BaseCommand
11
12 from cover.models import Image
13 from cover.utils import get_flickr_data, URLOpener, FlickrError
14
15
16 class Command(BaseCommand):
17     option_list = BaseCommand.option_list + (
18         make_option('--from', dest='from_id', type=int, default=1),
19     )
20
21     def handle(self, *args, **options):
22         from_id = options.get('from_id', 1)
23         for image in Image.objects.filter(id__gte=from_id).exclude(book=None).order_by('id'):
24             print image.id
25             if image.source_url and 'flickr.com' in image.source_url:
26                 try:
27                     flickr_data = get_flickr_data(image.source_url)
28                     print flickr_data
29                 except FlickrError as e:
30                     print 'Flickr analysis failed: %s' % e
31                 else:
32                     flickr_url = flickr_data['download_url']
33                     if flickr_url != image.download_url:
34                         same_url = Image.objects.filter(download_url=flickr_url)
35                         if same_url:
36                             print 'Download url already present in image %s' % same_url.get().id
37                             continue
38                     try:
39                         t = URLOpener().open(flickr_data['download_url']).read()
40                     except urllib.URLError:
41                         print 'Broken download url'
42                     except IOError:
43                         print 'Connection failed'
44                     else:
45                         image.download_url = flickr_data['download_url']
46                         image.file.save(image.file.name, ContentFile(t))
47                         image.save()