remove USE_CELERY option, use built-in CELERY_ALWAYS_EAGER instead
[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 ORMDocProvider(DocProvider):
59     """Used for getting books' children."""
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 @task
94 def create_zip(paths, zip_slug):
95     """
96     Creates a zip in MEDIA_ROOT/zip directory containing files from path.
97     Resulting archive filename is ${zip_slug}.zip
98     Returns it's path relative to MEDIA_ROOT (no initial slash)
99     """
100     # directory to store zip files
101     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
102
103     try:
104         mkdir(zip_path)
105     except OSError as oe:
106         if oe.errno != EEXIST:
107             raise oe
108     zip_filename = zip_slug + ".zip"
109
110     with LockFile(zip_path, zip_slug):
111         if not path.exists(path.join(zip_path, zip_filename)):
112             zipf = ZipFile(path.join(zip_path, zip_filename), 'w')
113             try:
114                 for p in paths:
115                     zipf.write(p, path.basename(p))
116             finally:
117                 zipf.close()
118
119         return 'zip/' + zip_filename
120
121
122 def remove_zip(zip_slug):
123     """
124     removes the ${zip_slug}.zip file from zip store.
125     """
126     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
127     try:
128         unlink(zip_file)
129     except OSError as oe:
130         if oe.errno != ENOENT:
131             raise oe