Customized pdf basically works.
[wolnelektury.git] / apps / catalogue / utils.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 __future__ import with_statement
6
7 import random
8 import time
9 from base64 import urlsafe_b64encode
10
11 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
12 from django.core.files.uploadedfile import UploadedFile
13 from django.utils.hashcompat import sha_constructor
14 from django.conf import settings
15 from celery.task import task
16 from os import mkdir, path, unlink
17 from errno import EEXIST, ENOENT
18 from fcntl import flock, LOCK_EX
19 from zipfile import ZipFile
20
21 from librarian import DocProvider
22 from reporting.utils import read_chunks
23 from celery.task import task
24 import catalogue.models
25
26 # Use the system (hardware-based) random number generator if it exists.
27 if hasattr(random, 'SystemRandom'):
28     randrange = random.SystemRandom().randrange
29 else:
30     randrange = random.randrange
31 MAX_SESSION_KEY = 18446744073709551616L     # 2 << 63
32
33
34 def get_random_hash(seed):
35     sha_digest = sha_constructor('%s%s%s%s' %
36         (randrange(0, MAX_SESSION_KEY), time.time(), unicode(seed).encode('utf-8', 'replace'),
37         settings.SECRET_KEY)).digest()
38     return urlsafe_b64encode(sha_digest).replace('=', '').replace('_', '-').lower()
39
40
41 def split_tags(tags):
42     result = {}
43     for tag in tags:
44         result.setdefault(tag.category, []).append(tag)
45     return result
46
47
48 class ExistingFile(UploadedFile):
49
50     def __init__(self, path, *args, **kwargs):
51         self.path = path
52         return super(ExistingFile, self).__init__(*args, **kwargs)
53
54     def temporary_file_path(self):
55         return self.path
56
57     def close(self):
58         pass
59
60
61 class ORMDocProvider(DocProvider):
62     """Used for getting books' children."""
63
64     def __init__(self, book):
65         self.book = book
66
67     def by_slug(self, slug):
68         if slug == self.book.slug:
69             return self.book.xml_file
70         else:
71             return type(self.book).objects.get(slug=slug).xml_file
72
73
74 class LockFile(object):
75     """
76     A file lock monitor class; createas an ${objname}.lock
77     file in directory dir, and locks it exclusively.
78     To be used in 'with' construct.
79     """
80     def __init__(self, dir, objname):
81         self.lockname = path.join(dir, objname + ".lock")
82
83     def __enter__(self):
84         self.lock = open(self.lockname, 'w')
85         flock(self.lock, LOCK_EX)
86
87     def __exit__(self, *err):
88         try:
89             unlink(self.lockname)
90         except OSError as oe:
91             if oe.errno != oe.EEXIST:
92                 raise oe
93         self.lock.close()
94
95
96 @task
97 def create_zip(paths, zip_slug):
98     """
99     Creates a zip in MEDIA_ROOT/zip directory containing files from path.
100     Resulting archive filename is ${zip_slug}.zip
101     Returns it's path relative to MEDIA_ROOT (no initial slash)
102     """
103     # directory to store zip files
104     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
105
106     try:
107         mkdir(zip_path)
108     except OSError as oe:
109         if oe.errno != EEXIST:
110             raise oe
111     zip_filename = zip_slug + ".zip"
112
113     with LockFile(zip_path, zip_slug):
114         if not path.exists(path.join(zip_path, zip_filename)):
115             zipf = ZipFile(path.join(zip_path, zip_filename), 'w')
116             try:
117                 for arcname, p in paths:
118                     if arcname is None:
119                         arcname = path.basename(p)
120                     zipf.write(p, arcname)
121             finally:
122                 zipf.close()
123
124         return 'zip/' + zip_filename
125
126
127 def remove_zip(zip_slug):
128     """
129     removes the ${zip_slug}.zip file from zip store.
130     """
131     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
132     try:
133         unlink(zip_file)
134     except OSError as oe:
135         if oe.errno != ENOENT:
136             raise oe
137
138
139 class AttachmentHttpResponse(HttpResponse):
140     """Response serving a file to be downloaded.
141     """
142     def __init__ (self, file_path, file_name, mimetype):
143         super(AttachmentHttpResponse, self).__init__(mimetype=mimetype)
144         self['Content-Disposition'] = 'attachment; filename=%s' % file_name
145         self.file_path = file_path
146         self.file_name = file_name
147
148         with open(self.file_path) as f:
149             for chunk in read_chunks(f):
150                 self.write(chunk)
151
152 @task
153 def create_custom_pdf(book_id, customizations, file_name):
154     book = catalogue.models.Book.objects.get(id=book_id)
155     if not path.exists(file_name):
156         book.build_pdf(customizations=customizations, file_name=file_name)