0fdeaf81089225885ff77f62c8afa192ff6bffd4
[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.core.files.base import File
14 from django.core.files.storage import DefaultStorage
15 from django.utils.hashcompat import sha_constructor
16 from django.conf import settings
17 from celery.task import task
18 from os import mkdir, path, unlink
19 from errno import EEXIST, ENOENT
20 from fcntl import flock, LOCK_EX
21 from zipfile import ZipFile
22 from traceback import print_exc
23
24 from reporting.utils import read_chunks
25 from celery.task import task
26 import catalogue.models
27
28 # Use the system (hardware-based) random number generator if it exists.
29 if hasattr(random, 'SystemRandom'):
30     randrange = random.SystemRandom().randrange
31 else:
32     randrange = random.randrange
33 MAX_SESSION_KEY = 18446744073709551616L     # 2 << 63
34
35
36 def get_random_hash(seed):
37     sha_digest = sha_constructor('%s%s%s%s' %
38         (randrange(0, MAX_SESSION_KEY), time.time(), unicode(seed).encode('utf-8', 'replace'),
39         settings.SECRET_KEY)).digest()
40     return urlsafe_b64encode(sha_digest).replace('=', '').replace('_', '-').lower()
41
42
43 def split_tags(tags):
44     result = {}
45     for tag in tags:
46         result.setdefault(tag.category, []).append(tag)
47     return result
48
49
50 class ExistingFile(UploadedFile):
51
52     def __init__(self, path, *args, **kwargs):
53         self.path = path
54         return super(ExistingFile, self).__init__(*args, **kwargs)
55
56     def temporary_file_path(self):
57         return self.path
58
59     def close(self):
60         pass
61
62
63 class LockFile(object):
64     """
65     A file lock monitor class; createas an ${objname}.lock
66     file in directory dir, and locks it exclusively.
67     To be used in 'with' construct.
68     """
69     def __init__(self, dir, objname):
70         self.lockname = path.join(dir, objname + ".lock")
71
72     def __enter__(self):
73         self.lock = open(self.lockname, 'w')
74         flock(self.lock, LOCK_EX)
75
76     def __exit__(self, *err):
77         try:
78             unlink(self.lockname)
79         except OSError as oe:
80             if oe.errno != oe.EEXIST:
81                 raise oe
82         self.lock.close()
83
84
85 @task
86 def create_zip(paths, zip_slug):
87     """
88     Creates a zip in MEDIA_ROOT/zip directory containing files from path.
89     Resulting archive filename is ${zip_slug}.zip
90     Returns it's path relative to MEDIA_ROOT (no initial slash)
91     """
92     # directory to store zip files
93     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
94
95     try:
96         mkdir(zip_path)
97     except OSError as oe:
98         if oe.errno != EEXIST:
99             raise oe
100     zip_filename = zip_slug + ".zip"
101
102     with LockFile(zip_path, zip_slug):
103         if not path.exists(path.join(zip_path, zip_filename)):
104             zipf = ZipFile(path.join(zip_path, zip_filename), 'w')
105             try:
106                 for arcname, p in paths:
107                     if arcname is None:
108                         arcname = path.basename(p)
109                     zipf.write(p, arcname)
110             finally:
111                 zipf.close()
112
113         return 'zip/' + zip_filename
114
115
116 def remove_zip(zip_slug):
117     """
118     removes the ${zip_slug}.zip file from zip store.
119     """
120     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
121     try:
122         unlink(zip_file)
123     except OSError as oe:
124         if oe.errno != ENOENT:
125             raise oe
126
127
128 class AttachmentHttpResponse(HttpResponse):
129     """Response serving a file to be downloaded.
130     """
131     def __init__ (self, file_path, file_name, mimetype):
132         super(AttachmentHttpResponse, self).__init__(mimetype=mimetype)
133         self['Content-Disposition'] = 'attachment; filename=%s' % file_name
134         self.file_path = file_path
135         self.file_name = file_name
136
137         with open(DefaultStorage().path(self.file_path)) as f:
138             for chunk in read_chunks(f):
139                 self.write(chunk)
140
141 @task
142 def async_build_pdf(book_id, customizations, file_name):
143     """
144     A celery task to generate pdf files.
145     Accepts the same args as Book.build_pdf, but with book id as first parameter
146     instead of Book instance
147     """
148     try:
149         book = catalogue.models.Book.objects.get(id=book_id)
150         print "will gen %s" % DefaultStorage().path(file_name)
151         if not DefaultStorage().exists(file_name):
152             book.build_pdf(customizations=customizations, file_name=file_name)
153         print "done."
154     except Exception, e:
155         print "Error during pdf creation: %s" % e
156         print_exc
157         raise e
158
159
160 class MultiQuerySet(object):
161     def __init__(self, *args, **kwargs):
162         self.querysets = args
163         self._count = None
164     
165     def count(self):
166         if not self._count:
167             self._count = sum(len(qs) for qs in self.querysets)
168         return self._count
169     
170     def __len__(self):
171         return self.count()
172         
173     def __getitem__(self, item):
174         try:
175             indices = (offset, stop, step) = item.indices(self.count())
176         except AttributeError:
177             # it's not a slice - make it one
178             return self[item : item + 1][0]
179         items = []
180         total_len = stop - offset
181         for qs in self.querysets:
182             if len(qs) < offset:
183                 offset -= len(qs)
184             else:
185                 items += list(qs[offset:stop])
186                 if len(items) >= total_len:
187                     return items
188                 else:
189                     offset = 0
190                     stop = total_len - len(items)
191                     continue