e392ae2da81e103149865fb7e79c16a1ad24957a
[wolnelektury.git] / apps / catalogue / tasks.py
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.
4 #
5 from datetime import datetime
6 from traceback import print_exc
7 from celery.task import task
8 from django.conf import settings
9 from wolnelektury.utils import localtime_to_utc
10 from waiter.models import WaitedFile
11
12
13 # TODO: move to model?
14 def touch_tag(tag):
15     update_dict = {
16         'changed_at': localtime_to_utc(datetime.now()),
17     }
18
19     type(tag).objects.filter(pk=tag.pk).update(**update_dict)
20
21
22 @task
23 def index_book(book_id, book_info=None, **kwargs):
24     from catalogue.models import Book
25     try:
26         return Book.objects.get(id=book_id).search_index(book_info, **kwargs)
27     except Exception, e:
28         print "Exception during index: %s" % e
29         print_exc()
30         raise e
31
32
33 @task(ignore_result=True, rate_limit=settings.CATALOGUE_CUSTOMPDF_RATE_LIMIT)
34 def build_custom_pdf(book_id, customizations, file_name, waiter_id=None):
35     """Builds a custom PDF file."""
36     try:
37         from django.core.files import File
38         from django.core.files.storage import DefaultStorage
39         from catalogue.models import Book
40
41         print "will gen %s" % DefaultStorage().path(file_name)
42         if not DefaultStorage().exists(file_name):
43             kwargs = {
44                 'cover': True,
45             }
46             if 'no-cover' in customizations:
47                 kwargs['cover'] = False
48                 customizations.remove('no-cover')
49             pdf = Book.objects.get(pk=book_id).wldocument().as_pdf(
50                     customizations=customizations,
51                     morefloats=settings.LIBRARIAN_PDF_MOREFLOATS,
52                     **kwargs)
53             DefaultStorage().save(file_name, File(open(pdf.get_filename())))
54     finally:
55         if waiter_id is not None:
56             WaitedFile.objects.filter(pk=waiter_id).delete()