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.
7 from cPickle import load, dump
8 from optparse import make_option
10 from django.core.management.base import BaseCommand
11 from django.core.management.color import color_style
14 from catalogue.models import Book, Tag
17 class Command(BaseCommand):
18 option_list = BaseCommand.option_list + (
19 make_option('-t', '--tags', dest='tags', metavar='SLUG,...',
20 help='Use only books tagged with this tags'),
21 make_option('-i', '--include', dest='include', metavar='SLUG,...',
22 help='Include specific books by slug'),
23 make_option('-e', '--exclude', dest='exclude', metavar='SLUG,...',
24 help='Exclude specific books by slug')
26 help = 'Prepare ZIP package with files of given type.'
27 args = '[%s] output_path.zip' % '|'.join(ftypes)
29 def handle(self, ftype, path, **options):
30 self.style = color_style()
31 verbose = int(options.get('verbosity'))
32 tags = options.get('tags')
33 include = options.get('include')
34 exclude = options.get('exclude')
36 if ftype in Book.formats:
37 field = "%s_file" % ftype
39 print self.style.ERROR('Unknown file type.')
45 books += list(Book.objects.filter(slug__in=include.split(',')).only('slug', field))
48 books += list(Book.tagged.with_all(Tag.objects.filter(slug__in=tags.split(','))).only('slug', field))
50 books = list(Book.objects.all().only('slug', field))
53 books = [book for book in books if book.slug not in exclude.split(',')]
55 archive = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED)
57 processed = skipped = 0
60 print 'Parsing', book.slug
61 content = getattr(book, field)
64 print self.style.NOTICE('%s has no %s file' % (book.slug, ftype))
67 archive.write(content.path, str('%s.%s' % (book.slug, ftype)))
73 print self.style.ERROR("No books with %s files found" % ftype)
75 print self.style.ERROR("No books found")
79 print "%d processed, %d skipped" % (processed, skipped)
80 print "Results written to %s" % path