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