Tidying up all the covers craziness and storages.
[wolnelektury.git] / src / catalogue / utils.py
index 9461243..e6e567b 100644 (file)
@@ -1,5 +1,5 @@
-# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
 import hashlib
 import os.path
 #
 import hashlib
 import os.path
@@ -19,7 +19,7 @@ from django.conf import settings
 from django.core.files.storage import DefaultStorage
 from django.core.files.uploadedfile import UploadedFile
 from django.http import HttpResponse
 from django.core.files.storage import DefaultStorage
 from django.core.files.uploadedfile import UploadedFile
 from django.http import HttpResponse
-from django.utils.encoding import force_text
+from django.utils.encoding import force_str
 
 from reporting.utils import read_chunks
 
 
 from reporting.utils import read_chunks
 
@@ -200,7 +200,7 @@ def truncate_html_words(s, num, end_text='...'):
 
     This is just a version of django.utils.text.truncate_html_words with no space before the end_text.
     """
 
     This is just a version of django.utils.text.truncate_html_words with no space before the end_text.
     """
-    s = force_text(s)
+    s = force_str(s)
     length = int(num)
     if length <= 0:
         return ''
     length = int(num)
     if length <= 0:
         return ''
@@ -334,3 +334,20 @@ def set_file_permissions(self, fieldfile):
     if fieldfile.instance.preview:
         fieldfile.set_readable(False)
 
     if fieldfile.instance.preview:
         fieldfile.set_readable(False)
 
+
+CHUNK_SIZE = 1024 * 1024  # 1 MB
+
+def iter_file(field_file, chunk_size=CHUNK_SIZE):
+    storage = field_file.storage
+    if hasattr(storage, "bucket"):
+        # If through S3Storage, chunk directly from
+        # boto interface to avoid loading the whole thing.
+        key = storage._normalize_name(field_file.name)
+        body = storage.bucket.Object(key).get()["Body"]
+        try:
+            yield from body.iter_chunks(chunk_size)
+        finally:
+            body.close()
+    else:
+        with field_file.open("rb") as f:
+            yield from f.chunks(chunk_size)