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 data for Lesmianator.'
27 ftypes = ['xml', 'txt', 'html', 'epub', 'pdf']
28 args = '[%s] output_path.zip' % '|'.join(ftypes)
30 def handle(self, ftype, path, **options):
31 self.style = color_style()
32 verbose = int(options.get('verbosity'))
33 tags = options.get('tags')
34 include = options.get('include')
35 exclude = options.get('exclude')
37 if ftype in self.ftypes:
38 field = "%s_file" % ftype
40 print self.style.ERROR('Unknown file type.')
46 books += list(Book.objects.filter(slug__in=include.split(',')).only('slug', field))
49 books += list(Book.tagged.with_all(Tag.objects.filter(slug__in=tags.split(','))).only('slug', field))
51 books = list(Book.objects.all().only('slug', field))
54 books = [book for book in books if book.slug not in exclude.split(',')]
56 archive = zipfile.ZipFile(path, 'w')
58 processed = skipped = 0
61 print 'Parsing', book.slug
62 content = getattr(book, field)
65 print self.style.NOTICE('%s has no %s file' % (book.slug, ftype))
68 archive.write(content.path, str('%s.%s' % (book.slug, ftype)))
74 print self.style.ERROR("No books with %s files found" % ftype)
76 print self.style.ERROR("No books found")
80 print "%d processed, %d skipped" % (processed, skipped)
81 print "Results written to %s" % path