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.core.files.uploadedfile import UploadedFile
12 from django.utils.hashcompat import sha_constructor
13 from django.conf import settings
14 from celery.task import task
15 from os import mkdir, path, unlink
16 from errno import EEXIST, ENOENT
17 from fcntl import flock, LOCK_EX
18 from zipfile import ZipFile
20 from librarian import DocProvider
23 # Use the system (hardware-based) random number generator if it exists.
24 if hasattr(random, 'SystemRandom'):
25 randrange = random.SystemRandom().randrange
27 randrange = random.randrange
28 MAX_SESSION_KEY = 18446744073709551616L # 2 << 63
31 def get_random_hash(seed):
32 sha_digest = sha_constructor('%s%s%s%s' %
33 (randrange(0, MAX_SESSION_KEY), time.time(), unicode(seed).encode('utf-8', 'replace'),
34 settings.SECRET_KEY)).digest()
35 return urlsafe_b64encode(sha_digest).replace('=', '').replace('_', '-').lower()
41 result.setdefault(tag.category, []).append(tag)
45 class ExistingFile(UploadedFile):
47 def __init__(self, path, *args, **kwargs):
49 return super(ExistingFile, self).__init__(*args, **kwargs)
51 def temporary_file_path(self):
58 class BookImportDocProvider(DocProvider):
59 """Used for joined EPUB and PDF files."""
61 def __init__(self, book):
64 def by_slug(self, slug):
65 if slug == self.book.slug:
66 return self.book.xml_file
68 return type(self.book).objects.get(slug=slug).xml_file
71 class LockFile(object):
73 A file lock monitor class; createas an ${objname}.lock
74 file in directory dir, and locks it exclusively.
75 To be used in 'with' construct.
77 def __init__(self, dir, objname):
78 self.lockname = path.join(dir, objname + ".lock")
81 self.lock = open(self.lockname, 'w')
82 flock(self.lock, LOCK_EX)
84 def __exit__(self, *err):
88 if oe.errno != oe.EEXIST:
93 def create_zip(paths, zip_slug):
95 Creates a zip in MEDIA_ROOT/zip directory containing files from path.
96 Resulting archive filename is ${zip_slug}.zip
97 Returns it's path relative to MEDIA_ROOT (no initial slash)
99 # directory to store zip files
100 zip_path = path.join(settings.MEDIA_ROOT, 'zip')
104 except OSError as oe:
105 if oe.errno != EEXIST:
107 zip_filename = zip_slug + ".zip"
109 with LockFile(zip_path, zip_slug):
110 if not path.exists(path.join(zip_path, zip_filename)):
111 zipf = ZipFile(path.join(zip_path, zip_filename), 'w')
114 zipf.write(p, path.basename(p))
118 return 'zip/' + zip_filename
121 def remove_zip(zip_slug):
123 removes the ${zip_slug}.zip file from zip store.
125 zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
128 except OSError as oe:
129 if oe.errno != ENOENT:
134 def create_zip_task(*args):
135 return create_zip(*args)