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.
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
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
23 from reporting.utils import read_chunks
25 # Use the system (hardware-based) random number generator if it exists.
26 if hasattr(random, 'SystemRandom'):
27 randrange = random.SystemRandom().randrange
29 randrange = random.randrange
30 MAX_SESSION_KEY = 18446744073709551616 # 2 << 63
33 def get_random_hash(seed):
34 sha_digest = hashlib.sha1((
36 randrange(0, MAX_SESSION_KEY),
38 str(seed).encode('utf-8', 'replace'),
41 ).encode('utf-8')).digest()
42 return urlsafe_b64encode(sha_digest).decode('latin1').replace('=', '').replace('_', '-').lower()
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)
51 result = defaultdict(dict)
52 for tag_list in tag_lists:
55 result[tag.category][tag.pk].count += tag.count
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)
63 class LockFile(object):
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.
69 def __init__(self, dir, objname):
70 self.lockname = path.join(dir, objname + ".lock")
73 self.lock = open(self.lockname, 'w')
74 flock(self.lock, LOCK_EX)
76 def __exit__(self, *err):
80 if oe.errno != ENOENT:
86 def create_zip(paths, zip_slug, file_contents=None):
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)
92 # directory to store zip files
93 zip_path = path.join(settings.MEDIA_ROOT, 'zip')
98 if oe.errno != EEXIST:
100 zip_filename = zip_slug + ".zip"
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')
106 for arcname, p in paths:
108 arcname = path.basename(p)
109 zipf.write(p, arcname)
111 for arcname, content in file_contents.items():
112 zipf.writestr(arcname, content)
116 return 'zip/' + zip_filename
119 def remove_zip(zip_slug):
121 removes the ${zip_slug}.zip file from zip store.
123 zip_file = path.join(settings.MEDIA_ROOT, 'zip', zip_slug + '.zip')
126 except OSError as oe:
127 if oe.errno != ENOENT:
131 class AttachmentHttpResponse(HttpResponse):
132 """Response serving a file to be downloaded.
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
140 with open(DefaultStorage().path(self.file_path)) as f:
141 for chunk in read_chunks(f):
145 class MultiQuerySet(object):
146 def __init__(self, *args, **kwargs):
147 self.querysets = args
152 self._count = sum(len(qs) for qs in self.querysets)
158 def __getitem__(self, item):
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]
165 total_len = stop - offset
166 for qs in self.querysets:
170 items += list(qs[offset:stop])
171 if len(items) >= total_len:
175 stop = total_len - len(items)
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 (...).
185 Newlines in the HTML are preserved.
187 This is just a version of django.utils.text.truncate_html_words with no space before the end_text.
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
202 while words <= length:
203 m = re_words.search(s, pos)
205 # Checked through whole string
209 # It's an actual non-HTML word
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
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:
224 # Check for match in open tags list
226 i = open_tags.index(tagname)
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:]
234 # Add it to the start of the open tags list
235 open_tags.insert(0, tagname)
237 # Don't try to close tags if we don't need to truncate
239 out = s[:end_text_pos]
242 # Close any tags still open
243 for tag in open_tags:
249 def customizations_hash(customizations):
250 customizations.sort()
251 return hash(tuple(customizations))
254 def get_customized_pdf_path(book, customizations):
256 Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
258 h = customizations_hash(customizations)
259 return 'book/%s/%s-custom-%s.pdf' % (book.slug, book.slug, h)
262 def clear_custom_pdf(book):
264 Returns a list of paths to generated customized pdf of a book
266 from waiter.utils import clear_cache
267 clear_cache('book/%s' % book.slug)
270 class AppSettings(object):
271 """Allows specyfying custom settings for an app, with default values.
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.
279 def __init__(self, prefix):
280 self._prefix = prefix
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)
292 def delete_from_cache_by_language(cache, key_template):
293 cache.delete_many([key_template % lc for lc, ln in settings.LANGUAGES])
296 def gallery_path(slug):
297 return os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, slug) + '/'
300 def gallery_url(slug):
301 return '%s%s%s/' % (settings.MEDIA_URL, settings.IMAGE_DIR, slug)
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',
311 return urljoin(base_url, url)
314 def set_file_permissions(self, fieldfile):
315 if fieldfile.instance.preview:
316 fieldfile.set_readable(False)
319 CHUNK_SIZE = 1024 * 1024 # 1 MB
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"]
329 yield from body.iter_chunks(chunk_size)
333 with field_file.open("rb") as f:
334 yield from f.chunks(chunk_size)