Basic eink version.
[wolnelektury.git] / src / catalogue / tasks.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 traceback import print_exc
5 from celery.task import task
6 from celery.utils.log import get_task_logger
7 from django.conf import settings
8 from django.utils import timezone
9
10 from catalogue.utils import absolute_url, gallery_url
11 from waiter.models import WaitedFile
12
13 task_logger = get_task_logger(__name__)
14
15
16 # TODO: move to model?
17 def touch_tag(tag):
18     update_dict = {
19         'changed_at': timezone.now(),
20     }
21
22     type(tag).objects.filter(pk=tag.pk).update(**update_dict)
23
24
25 @task
26 def index_book(book_id, book_info=None, **kwargs):
27     from catalogue.models import Book
28     try:
29         return Book.objects.get(id=book_id).search_index(book_info, **kwargs)
30     except Exception as e:
31         print("Exception during index: %s" % e)
32         print_exc()
33         raise e
34
35
36 @task(ignore_result=True, rate_limit=settings.CATALOGUE_CUSTOMPDF_RATE_LIMIT)
37 def build_custom_pdf(book_id, customizations, file_name, waiter_id=None):
38     """Builds a custom PDF file."""
39     try:
40         from django.core.files import File
41         from django.core.files.storage import DefaultStorage
42         from catalogue.models import Book
43
44         task_logger.info(DefaultStorage().path(file_name))
45         if not DefaultStorage().exists(file_name):
46             kwargs = {
47                 'cover': True,
48             }
49             if 'nocover' in customizations:
50                 kwargs['cover'] = False
51                 customizations.remove('nocover')
52             wldoc = Book.objects.get(pk=book_id).wldocument()
53             pdf = wldoc.as_pdf(
54                 customizations=customizations,
55                 morefloats=settings.LIBRARIAN_PDF_MOREFLOATS,
56                 base_url=absolute_url(gallery_url(wldoc.book_info.url.slug)),
57                 **kwargs)
58             DefaultStorage().save(file_name, File(open(pdf.get_filename(), 'rb')))
59     finally:
60         if waiter_id is not None:
61             WaitedFile.objects.filter(pk=waiter_id).delete()
62
63
64 @task(ignore_result=True)
65 def update_counters():
66     from .helpers import update_counters
67     update_counters()
68
69
70 @task(ignore_result=True)
71 def update_references(book_id):
72     from catalogue.models import Book
73     Book.objects.get(id=book_id).update_references()
74