1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
 
   2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   5 from django.core.management.base import BaseCommand
 
   6 from django.core.management.color import color_style
 
   7 from catalogue.models import Book, Tag
 
  10 class Command(BaseCommand):
 
  11     help = 'Prepare ZIP package with files of given type.'
 
  13     def add_arguments(self, parser):
 
  15                 '-t', '--tags', dest='tags', metavar='SLUG,...',
 
  16                 help='Use only books tagged with this tags')
 
  18                 '-i', '--include', dest='include', metavar='SLUG,...',
 
  19                 help='Include specific books by slug')
 
  21                 '-e', '--exclude', dest='exclude', metavar='SLUG,...',
 
  22                 help='Exclude specific books by slug')
 
  23         parser.add_argument('ftype', metavar='|'.join(Book.formats))
 
  24         parser.add_argument('path', metavar='output_path.zip')
 
  26     def handle(self, **options):
 
  27         self.style = color_style()
 
  28         ftype = options['ftype']
 
  29         path = options['path']
 
  30         verbose = int(options.get('verbosity'))
 
  31         tags = options.get('tags')
 
  32         include = options.get('include')
 
  33         exclude = options.get('exclude')
 
  35         if ftype in Book.formats:
 
  36             field = "%s_file" % ftype
 
  38             print(self.style.ERROR('Unknown file type.'))
 
  44             books += list(Book.objects.filter(slug__in=include.split(',')).only('slug', field))
 
  47             books += list(Book.tagged.with_all(Tag.objects.filter(slug__in=tags.split(','))).only('slug', field))
 
  49             books = list(Book.objects.all().only('slug', field))
 
  52             books = [book for book in books if book.slug not in exclude.split(',')]
 
  54         archive = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED)
 
  56         processed = skipped = 0
 
  59                 print('Parsing', book.slug)
 
  60             content = getattr(book, field)
 
  63                     print(self.style.NOTICE('%s has no %s file' % (book.slug, ftype)))
 
  66             archive.write(content.path, str('%s.%s' % (book.slug, ftype)))
 
  72                 print(self.style.ERROR("No books with %s files found" % ftype))
 
  74                 print(self.style.ERROR("No books found"))
 
  78             print("%d processed, %d skipped" % (processed, skipped))
 
  79             print("Results written to %s" % path)