# -*- 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__ = ('ProtectedMediaAssetStorage',) """ Storage setup: //original/filename.ext /cache//. /manual//. TODO Add snapshot (versioning) to path after asset_uuid. """ FILENAME_MAX_LENGTH = getattr(settings, 'ASSETKIT_FILENAME_MAX_LENGTH', 255) ORIGINAL_FILE_PREFIX = 'original' CACHED_VARIANT_PREFIX = 'cache' MANUAL_VARIANT_PREFIX = 'manual' PROTECTED_MEDIA_ROOT = os.path.join(os.path.dirname(settings.MEDIA_ROOT), 'protected') PROTECTED_MEDIA_URL = '/protected/' class BaseVariantSubStorage(FileSystemStorage): def delete(self, parent_storage, name): """ Deletes the whole storage path """ raise NotImplemented @deconstructible class ProtectedMediaAssetStorage(FileSystemStorage): """ Standard media assets filesystem storage """ def __init__(self, location=None, base_url=None, **kwargs): if location is None: location = getattr(settings, 'PROTECTED_MEDIA_ROOT', PROTECTED_MEDIA_ROOT) if base_url is None: base_url = getattr(settings, 'PROTECTED_MEDIA_URL', PROTECTED_MEDIA_URL) if not base_url.endswith('/'): base_url += '/' super(ProtectedMediaAssetStorage, self).__init__(location=location, base_url=base_url, **kwargs) def delete(self, name): super(ProtectedMediaAssetStorage, 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, name) def size(self, name): return os.path.getsize(self.path(name)) def url(self, name): return urljoin(self.base_url, filepath_to_uri(name))