26e1cf65a4581691b189b7a4f300a8c8917e434e
[wolnelektury.git] / src / catalogue / management / commands / build_stale.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from time import time
5 from django.conf import settings
6 from django.core.management.base import BaseCommand
7
8 from catalogue.fields import EbookField
9 from catalogue.models import Book
10
11
12 class Command(BaseCommand):
13     help = 'Schedule regenerating stale ebook files.'
14
15     def add_arguments(self, parser):
16         parser.add_argument(
17             '-l', '--limit', type=int,
18             help='Limit number of files to build'
19         )
20         parser.add_argument(
21             '-t', '--time', type=int, metavar='SECONDS',
22             help='Limit timenumber of files to build'
23         )
24
25     def handle(self, **options):
26         t = time()
27         counter = 0
28         tasks = []
29         while True:
30             if options['time'] is not None and time() - t > options['time']:
31                 break
32             if options['limit'] is not None and counter >= options['limit']:
33                 break
34             if not tasks:
35                 tasks = EbookField.find_all_stale(Book, options['limit'] or 100)
36             if not tasks:
37                 break
38             field_name, book = tasks.pop(0)
39             print(field_name, book)
40             counter += 1
41             try:
42                 getattr(book, field_name).build()
43             except Exception as e:
44                 print('ERROR', e)