34b1e7054c4a330069313209fe7d5cab561e5bc0
[wolnelektury.git] / src / catalogue / management / commands / report_dead_links.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from __future__ import print_function, unicode_literals
6
7 from django.core.management.base import BaseCommand
8
9
10 class Command(BaseCommand):
11     help = 'Checks for dead links.'
12
13     def handle(self, **options):
14         from catalogue.models import Book
15         from picture.models import Picture
16         from urllib2 import urlopen, HTTPError, URLError
17         from django.core.urlresolvers import reverse
18         from django.contrib.sites.models import Site
19         from django.contrib.sites.shortcuts import get_current_site
20
21         domain = get_current_site(None).domain
22
23         fields = [
24             (Book, [
25                 ('gazeta_link', lambda b: b.gazeta_link),
26                 ('wiki_link', lambda b: b.wiki_link),
27                 ('źródło', lambda b: b.extra_info.get('source_url')),
28                 ], 'admin:catalogue_book_change'
29             ),
30             (Picture, [
31                 ('gazeta_link', lambda p: p.culturepl_link),
32                 ('wiki_link', lambda p: p.wiki_link),
33                 ('źródło', lambda p: p.extra_info.get('source_url')),
34                 ], 'admin:pictures_picture_change'
35             )
36         ]
37
38         for model, model_fields, admin_name in fields:
39             for obj in model.objects.all():
40                 clean = True
41                 for name, get in model_fields:
42                     url = get(obj)
43                     if url:
44                         try:
45                             urlopen(url)
46                         except (HTTPError, URLError, ValueError), e:
47                             if clean:
48                                 clean = False
49                                 print(unicode(obj).encode('utf-8'))
50                                 print(('Na stronie: https://%s%s' % (domain, obj.get_absolute_url())).encode('utf-8'))
51                                 print(('Administracja: https://%s%s' % (domain, reverse(admin_name, args=[obj.pk]))).encode('utf-8'))
52                                 if obj.extra_info.get('about'):
53                                     print(('Redakcja: %s' % (obj.extra_info.get('about'),)).encode('utf-8'))
54                             print(('    %s (%s): %s' % (name, getattr(e, 'code', 'błąd'), url)).encode('utf-8'))
55                 if not clean:
56                     print()