# -*- coding: utf-8 -*- from __future__ import unicode_literals # Erik Stein , 2016 import os import warnings from django.core.files.storage import FileSystemStorage from django.conf import settings from django.utils._os import safe_join from django.utils.deconstruct import deconstructible from django.utils.encoding import filepath_to_uri from django.utils.six.moves.urllib.parse import urljoin __all__ = ('MediaAssetStorage',) ORIGINAL_FILE_PREFIX = 'original' CACHED_VARIANT_PREFIX = 'cache' MANUAL_VARIANT_PREFIX = 'manual' """ Storage setup: //original/filename.ext /cache//. /manual//. TODO Add snapshot (versioning) to path after asset_uuid. """ class BaseVariantSubStorage(FileSystemStorage): def delete(self, parent_storage, name): """ Deletes the whole storage path """ raise NotImplemented @deconstructible class MediaAssetStorage(FileSystemStorage): """ Standard media assets filesystem storage """ def __init__(self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None): if location is None: location = getattr(settings, 'MEDIA_ASSETS_ROOT', settings.MEDIA_ROOT) if base_url is None: base_url = getattr(settings, 'MEDIA_ASSETS_URL', settings.MEDIA_URL) if not base_url.endswith('/'): base_url += '/' super(MediaAssetStorage, self).__init__(self) def delete(self, name): super(MediaAssetStorage, self).delete(name) # FIXME Delete all cached files, too warnings.warn("Cached files for asset \"%s\" are not deleted." % name) def path(self, name): """ `name` must already contain the whole asset filesystem path. """ return safe_join(self.location, ORIGINAL_FILE_PREFIX, name) def size(self, name): return os.path.getsize(self.path(name)) def url(self, name): if self.base_url is None: raise ValueError("This file is not accessible via a URL.") return urljoin(self.base_url, ORIGINAL_FILE_PREFIX, filepath_to_uri(name))