57325633b2bce899f02697b2e85a54e928bee298
[redakcja.git] / src / cover / management / commands / refresh_covers.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import urllib2 as urllib
5 from django.core.files.base import ContentFile
6 from django.core.management import BaseCommand
7
8 from cover.models import Image
9 from cover.utils import get_flickr_data, URLOpener, FlickrError
10
11
12 class Command(BaseCommand):
13     def add_arguments(self, parser):
14         parser.add_argument('--from', dest='from_id', type=int, default=1)
15
16     def handle(self, *args, **options):
17         from_id = options.get('from_id', 1)
18         images = Image.objects.filter(id__gte=from_id).exclude(book=None).order_by('id')
19         images = images.filter(source_url__contains='flickr.com').exclude(download_url__endswith='_o.jpg')
20         for image in images:
21             print(image.id)
22             try:
23                 flickr_data = get_flickr_data(image.source_url)
24                 print(flickr_data)
25             except FlickrError as e:
26                 print('Flickr analysis failed: %s' % e)
27             else:
28                 flickr_url = flickr_data['download_url']
29                 if flickr_url != image.download_url:
30                     same_url = Image.objects.filter(download_url=flickr_url)
31                     if same_url:
32                         print('Download url already present in image %s' % same_url.get().id)
33                         continue
34                 try:
35                     t = URLOpener().open(flickr_url).read()
36                 except urllib.URLError:
37                     print('Broken download url')
38                 except IOError:
39                     print('Connection failed')
40                 else:
41                     image.download_url = flickr_url
42                     image.file.save(image.file.name, ContentFile(t))
43                     image.save()