Cache media file size. Reorganize uploading. Remove some unused code.
[wolnelektury.git] / src / catalogue / utils.py
index 267d6be..2469d6c 100644 (file)
@@ -17,7 +17,6 @@ from zipfile import ZipFile
 from django.apps import apps
 from django.conf import settings
 from django.core.files.storage import DefaultStorage
 from django.apps import apps
 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.utils.encoding import force_str
 
 from django.http import HttpResponse
 from django.utils.encoding import force_str
 
@@ -61,19 +60,6 @@ def split_tags(*tag_lists):
     return result
 
 
     return result
 
 
-class ExistingFile(UploadedFile):
-
-    def __init__(self, path, *args, **kwargs):
-        self.path = path
-        super(ExistingFile, self).__init__(*args, **kwargs)
-
-    def temporary_file_path(self):
-        return self.path
-
-    def close(self):
-        pass
-
-
 class LockFile(object):
     """
     A file lock monitor class; createas an ${objname}.lock
 class LockFile(object):
     """
     A file lock monitor class; createas an ${objname}.lock
@@ -325,12 +311,24 @@ def absolute_url(url):
     return urljoin(base_url, url)
 
 
     return urljoin(base_url, url)
 
 
-def get_mp3_length(path):
-    from mutagen.mp3 import MP3
-    return int(MP3(path).info.length)
-
-
 def set_file_permissions(self, fieldfile):
     if fieldfile.instance.preview:
         fieldfile.set_readable(False)
 
 def set_file_permissions(self, fieldfile):
     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)