zipfile does not support __exit__
[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, ENOENT
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     """
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.
76     """
77     def __init__(self, dir, objname):
78         self.lockname = path.join(dir, objname + ".lock")
79
80     def __enter__(self):
81         self.lock = open(self.lockname, 'w')
82         flock(self.lock, LOCK_EX)
83
84     def __exit__(self, *err):
85         try:
86             unlink(self.lockname)
87         except OSError as oe:
88             if oe.errno != oe.EEXIST:
89                 raise oe
90         self.lock.close()
91
92
93 def create_zip(paths, zip_slug):
94     """
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)
98     """
99     # directory to store zip files
100     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
101
102     try:
103         mkdir(zip_path)
104     except OSError as oe:
105         if oe.errno != EEXIST:
106             raise oe
107     zip_filename = zip_slug + ".zip"
108
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')
112             try:
113                 for p in paths:
114                     zipf.write(p, path.basename(p))
115             finally:
116                 zipf.close()
117
118         return 'zip/' + zip_filename
119
120
121 def remove_zip(zip_slug):
122     """
123     removes the ${zip_slug}.zip file from zip store.
124     """
125     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
126     try:
127         unlink(zip_file)
128     except OSError as oe:
129         if oe.errno != ENOENT:
130             raise oe
131
132
133 @task
134 def create_zip_task(*args):
135     return create_zip(*args)