Cache media file size. Reorganize uploading. Remove some unused code.
[wolnelektury.git] / src / catalogue / utils.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import hashlib
5 import os.path
6 import random
7 import re
8 import time
9 from base64 import urlsafe_b64encode
10 from collections import defaultdict
11 from errno import EEXIST, ENOENT
12 from fcntl import flock, LOCK_EX
13 from os import mkdir, path, unlink
14 from urllib.parse import urljoin
15 from zipfile import ZipFile
16
17 from django.apps import apps
18 from django.conf import settings
19 from django.core.files.storage import DefaultStorage
20 from django.http import HttpResponse
21 from django.utils.encoding import force_str
22
23 from reporting.utils import read_chunks
24
25 # Use the system (hardware-based) random number generator if it exists.
26 if hasattr(random, 'SystemRandom'):
27     randrange = random.SystemRandom().randrange
28 else:
29     randrange = random.randrange
30 MAX_SESSION_KEY = 18446744073709551616     # 2 << 63
31
32
33 def get_random_hash(seed):
34     sha_digest = hashlib.sha1((
35         '%s%s%s%s' % (
36             randrange(0, MAX_SESSION_KEY),
37             time.time(),
38             str(seed).encode('utf-8', 'replace'),
39             settings.SECRET_KEY
40         )
41     ).encode('utf-8')).digest()
42     return urlsafe_b64encode(sha_digest).decode('latin1').replace('=', '').replace('_', '-').lower()
43
44
45 def split_tags(*tag_lists):
46     if len(tag_lists) == 1:
47         result = defaultdict(list)
48         for tag in tag_lists[0]:
49             result[tag.category].append(tag)
50     else:
51         result = defaultdict(dict)
52         for tag_list in tag_lists:
53             for tag in tag_list:
54                 try:
55                     result[tag.category][tag.pk].count += tag.count
56                 except KeyError:
57                     result[tag.category][tag.pk] = tag
58         for k, v in result.items():
59             result[k] = sorted(v.values(), key=lambda tag: tag.sort_key)
60     return result
61
62
63 class LockFile(object):
64     """
65     A file lock monitor class; createas an ${objname}.lock
66     file in directory dir, and locks it exclusively.
67     To be used in 'with' construct.
68     """
69     def __init__(self, dir, objname):
70         self.lockname = path.join(dir, objname + ".lock")
71
72     def __enter__(self):
73         self.lock = open(self.lockname, 'w')
74         flock(self.lock, LOCK_EX)
75
76     def __exit__(self, *err):
77         try:
78             unlink(self.lockname)
79         except OSError as oe:
80             if oe.errno != ENOENT:
81                 raise oe
82         self.lock.close()
83
84
85 # @task
86 def create_zip(paths, zip_slug, file_contents=None):
87     """
88     Creates a zip in MEDIA_ROOT/zip directory containing files from path.
89     Resulting archive filename is ${zip_slug}.zip
90     Returns it's path relative to MEDIA_ROOT (no initial slash)
91     """
92     # directory to store zip files
93     zip_path = path.join(settings.MEDIA_ROOT, 'zip')
94
95     try:
96         mkdir(zip_path)
97     except OSError as oe:
98         if oe.errno != EEXIST:
99             raise oe
100     zip_filename = zip_slug + ".zip"
101
102     with LockFile(zip_path, zip_slug):
103         if not path.exists(path.join(zip_path, zip_filename)):
104             zipf = ZipFile(path.join(zip_path, zip_filename), 'w')
105             try:
106                 for arcname, p in paths:
107                     if arcname is None:
108                         arcname = path.basename(p)
109                     zipf.write(p, arcname)
110                 if file_contents:
111                     for arcname, content in file_contents.items():
112                         zipf.writestr(arcname, content)
113             finally:
114                 zipf.close()
115
116         return 'zip/' + zip_filename
117
118
119 def remove_zip(zip_slug):
120     """
121     removes the ${zip_slug}.zip file from zip store.
122     """
123     zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
124     try:
125         unlink(zip_file)
126     except OSError as oe:
127         if oe.errno != ENOENT:
128             raise oe
129
130
131 class AttachmentHttpResponse(HttpResponse):
132     """Response serving a file to be downloaded.
133     """
134     def __init__(self, file_path, file_name, mimetype):
135         super(AttachmentHttpResponse, self).__init__(mimetype=mimetype)
136         self['Content-Disposition'] = 'attachment; filename=%s' % file_name
137         self.file_path = file_path
138         self.file_name = file_name
139
140         with open(DefaultStorage().path(self.file_path)) as f:
141             for chunk in read_chunks(f):
142                 self.write(chunk)
143
144
145 class MultiQuerySet(object):
146     def __init__(self, *args, **kwargs):
147         self.querysets = args
148         self._count = None
149
150     def count(self):
151         if not self._count:
152             self._count = sum(len(qs) for qs in self.querysets)
153         return self._count
154
155     def __len__(self):
156         return self.count()
157
158     def __getitem__(self, item):
159         try:
160             (offset, stop, step) = item.indices(self.count())
161         except AttributeError:
162             # it's not a slice - make it one
163             return self[item:item + 1][0]
164         items = []
165         total_len = stop - offset
166         for qs in self.querysets:
167             if len(qs) < offset:
168                 offset -= len(qs)
169             else:
170                 items += list(qs[offset:stop])
171                 if len(items) >= total_len:
172                     return items
173                 else:
174                     offset = 0
175                     stop = total_len - len(items)
176                     continue
177
178
179 def truncate_html_words(s, num, end_text='...'):
180     """Truncates HTML to a certain number of words (not counting tags and
181     comments). Closes opened tags if they were correctly closed in the given
182     html. Takes an optional argument of what should be used to notify that the
183     string has been truncated, defaulting to ellipsis (...).
184
185     Newlines in the HTML are preserved.
186
187     This is just a version of django.utils.text.truncate_html_words with no space before the end_text.
188     """
189     s = force_str(s)
190     length = int(num)
191     if length <= 0:
192         return ''
193     html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input')
194     # Set up regular expressions
195     re_words = re.compile(r'&.*?;|<.*?>|(\w[\w-]*)', re.U)
196     re_tag = re.compile(r'<(/)?([^ ]+?)(?: (/)| .*?)?>')
197     # Count non-HTML words and keep note of open tags
198     pos = 0
199     end_text_pos = 0
200     words = 0
201     open_tags = []
202     while words <= length:
203         m = re_words.search(s, pos)
204         if not m:
205             # Checked through whole string
206             break
207         pos = m.end(0)
208         if m.group(1):
209             # It's an actual non-HTML word
210             words += 1
211             if words == length:
212                 end_text_pos = pos
213             continue
214         # Check for tag
215         tag = re_tag.match(m.group(0))
216         if not tag or end_text_pos:
217             # Don't worry about non tags or tags after our truncate point
218             continue
219         closing_tag, tagname, self_closing = tag.groups()
220         tagname = tagname.lower()  # Element names are always case-insensitive
221         if self_closing or tagname in html4_singlets:
222             pass
223         elif closing_tag:
224             # Check for match in open tags list
225             try:
226                 i = open_tags.index(tagname)
227             except ValueError:
228                 pass
229             else:
230                 # SGML: An end tag closes, back to the matching start tag,
231                 # all unclosed intervening start tags with omitted end tags
232                 open_tags = open_tags[i+1:]
233         else:
234             # Add it to the start of the open tags list
235             open_tags.insert(0, tagname)
236     if words <= length:
237         # Don't try to close tags if we don't need to truncate
238         return s
239     out = s[:end_text_pos]
240     if end_text:
241         out += end_text
242     # Close any tags still open
243     for tag in open_tags:
244         out += '</%s>' % tag
245     # Return string
246     return out
247
248
249 def customizations_hash(customizations):
250     customizations.sort()
251     return hash(tuple(customizations))
252
253
254 def get_customized_pdf_path(book, customizations):
255     """
256     Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
257     """
258     h = customizations_hash(customizations)
259     return 'book/%s/%s-custom-%s.pdf' % (book.slug, book.slug, h)
260
261
262 def clear_custom_pdf(book):
263     """
264     Returns a list of paths to generated customized pdf of a book
265     """
266     from waiter.utils import clear_cache
267     clear_cache('book/%s' % book.slug)
268
269
270 class AppSettings(object):
271     """Allows specyfying custom settings for an app, with default values.
272
273     Just subclass, set some properties and instantiate with a prefix.
274     Getting a SETTING from an instance will check for prefix_SETTING
275     in project settings if set, else take the default. The value will be
276     then filtered through _more_SETTING method, if there is one.
277
278     """
279     def __init__(self, prefix):
280         self._prefix = prefix
281
282     def __getattribute__(self, name):
283         if name.startswith('_'):
284             return object.__getattribute__(self, name)
285         value = getattr(settings, "%s_%s" % (self._prefix, name), object.__getattribute__(self, name))
286         more = "_more_%s" % name
287         if hasattr(self, more):
288             value = getattr(self, more)(value)
289         return value
290
291
292 def delete_from_cache_by_language(cache, key_template):
293     cache.delete_many([key_template % lc for lc, ln in settings.LANGUAGES])
294
295
296 def gallery_path(slug):
297     return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, slug) + '/'
298
299
300 def gallery_url(slug):
301     return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, slug)
302
303
304 def absolute_url(url):
305     Site = apps.get_model('sites', 'Site')
306     site = Site.objects.get_current()
307     base_url = '%s://%s' % (
308         'https' if settings.SESSION_COOKIE_SECURE else 'http',
309         site.domain
310     )
311     return urljoin(base_url, url)
312
313
314 def set_file_permissions(self, fieldfile):
315     if fieldfile.instance.preview:
316         fieldfile.set_readable(False)
317
318
319 CHUNK_SIZE = 1024 * 1024  # 1 MB
320
321 def iter_file(field_file, chunk_size=CHUNK_SIZE):
322     storage = field_file.storage
323     if hasattr(storage, "bucket"):
324         # If through S3Storage, chunk directly from
325         # boto interface to avoid loading the whole thing.
326         key = storage._normalize_name(field_file.name)
327         body = storage.bucket.Object(key).get()["Body"]
328         try:
329             yield from body.iter_chunks(chunk_size)
330         finally:
331             body.close()
332     else:
333         with field_file.open("rb") as f:
334             yield from f.chunks(chunk_size)