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.
5 from __future__ import with_statement
9 from base64 import urlsafe_b64encode
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
21 from librarian import DocProvider
22 from reporting.utils import read_chunks
23 from celery.task import task
24 import catalogue.models
26 # Use the system (hardware-based) random number generator if it exists.
27 if hasattr(random, 'SystemRandom'):
28 randrange = random.SystemRandom().randrange
30 randrange = random.randrange
31 MAX_SESSION_KEY = 18446744073709551616L # 2 << 63
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()
44 result.setdefault(tag.category, []).append(tag)
48 class ExistingFile(UploadedFile):
50 def __init__(self, path, *args, **kwargs):
52 return super(ExistingFile, self).__init__(*args, **kwargs)
54 def temporary_file_path(self):
61 class ORMDocProvider(DocProvider):
62 """Used for getting books' children."""
64 def __init__(self, book):
67 def by_slug(self, slug):
68 if slug == self.book.slug:
69 return self.book.xml_file
71 return type(self.book).objects.get(slug=slug).xml_file
74 class LockFile(object):
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.
80 def __init__(self, dir, objname):
81 self.lockname = path.join(dir, objname + ".lock")
84 self.lock = open(self.lockname, 'w')
85 flock(self.lock, LOCK_EX)
87 def __exit__(self, *err):
91 if oe.errno != oe.EEXIST:
97 def create_zip(paths, zip_slug):
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)
103 # directory to store zip files
104 zip_path = path.join(settings.MEDIA_ROOT, 'zip')
108 except OSError as oe:
109 if oe.errno != EEXIST:
111 zip_filename = zip_slug + ".zip"
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')
117 for arcname, p in paths:
119 arcname = path.basename(p)
120 zipf.write(p, arcname)
124 return 'zip/' + zip_filename
127 def remove_zip(zip_slug):
129 removes the ${zip_slug}.zip file from zip store.
131 zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
134 except OSError as oe:
135 if oe.errno != ENOENT:
139 class AttachmentHttpResponse(HttpResponse):
140 """Response serving a file to be downloaded.
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
148 with open(self.file_path) as f:
149 for chunk in read_chunks(f):
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)