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