zip package for epub/pdf/audiobooks
[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.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
17 from fcntl import flock, LOCK_EX
18 from zipfile import ZipFile
19
20 from librarian import DocProvider
21
22
23 # Use the system (hardware-based) random number generator if it exists.
24 if hasattr(random, 'SystemRandom'):
25     randrange = random.SystemRandom().randrange
26 else:
27     randrange = random.randrange
28 MAX_SESSION_KEY = 18446744073709551616L     # 2 << 63
29
30
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()
36
37
38 def split_tags(tags):
39     result = {}
40     for tag in tags:
41         result.setdefault(tag.category, []).append(tag)
42     return result
43
44
45 class ExistingFile(UploadedFile):
46
47     def __init__(self, path, *args, **kwargs):
48         self.path = path
49         return super(ExistingFile, self).__init__(*args, **kwargs)
50
51     def temporary_file_path(self):
52         return self.path
53
54     def close(self):
55         pass
56
57
58 class BookImportDocProvider(DocProvider):
59     """Used for joined EPUB and PDF files."""
60
61     def __init__(self, book):
62         self.book = book
63
64     def by_slug(self, slug):
65         if slug == self.book.slug:
66             return self.book.xml_file
67         else:
68             return type(self.book).objects.get(slug=slug).xml_file
69
70
71 class LockFile(object):
72     def __init__(self, dir, objname):
73         self.lockname = path.join(dir, objname + ".lock")
74
75     def __entry__(self):
76         self.lock = open(self.lockname, 'w')
77         flock(self.lock, LOCK_EX)
78
79     def __exit__(self, *err):
80         self.lock.close()
81         unlink(self.lockname)
82
83
84 def create_zip(paths, zip_slug):
85     # directory to store zip files
86     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
87
88     try:
89         mkdir(zip_path)
90     except OSError as oe:
91         if oe.errno != EEXIST:
92             raise oe
93     zip_filename = zip_slug + ".zip"
94
95     with LockFile(zip_path, zip_slug):
96         if not path.exists(path.join(zip_path, zip_filename)):
97             with ZipFile(path.join(zip_path, zip_filename), 'w') as zipf:
98                 for p in paths:
99                     zipf.write(p, path.basename(p))
100
101         return 'zip/' + zip_filename
102
103
104 def remove_zip(zip_slug):
105     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
106     try:
107         unlink(zip_file)
108     except OSError as oe:
109         if oe.errno != EEXIST:
110             raise oe
111
112
113 @task
114 def create_zip_task(*args):
115     return create_zip(*args)