|
| 1 | +import datetime |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | +from django.http import HttpResponse |
| 7 | +from django.urls import reverse |
| 8 | +from django_downloadview import DownloadResponse |
| 9 | + |
| 10 | +from geonode.assets.handlers import asset_handler_registry, AssetHandlerInterface, AssetDownloadHandlerInterface |
| 11 | +from geonode.assets.models import LocalAsset |
| 12 | +from geonode.storage.manager import DefaultStorageManager, StorageManager |
| 13 | +from geonode.utils import build_absolute_uri, mkdtemp |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +_asset_storage_manager = StorageManager( |
| 18 | + concrete_storage_manager=DefaultStorageManager(location=os.path.dirname(settings.ASSETS_ROOT)) |
| 19 | +) |
| 20 | + |
| 21 | + |
| 22 | +class LocalAssetHandler(AssetHandlerInterface): |
| 23 | + @staticmethod |
| 24 | + def handled_asset_class(): |
| 25 | + return LocalAsset |
| 26 | + |
| 27 | + def get_download_handler(self, asset): |
| 28 | + return LocalAssetDownloadHandler() |
| 29 | + |
| 30 | + def get_storage_manager(self, asset): |
| 31 | + return _asset_storage_manager |
| 32 | + |
| 33 | + def _create_asset_dir(self): |
| 34 | + return os.path.normpath( |
| 35 | + mkdtemp(dir=settings.ASSETS_ROOT, prefix=datetime.datetime.now().strftime("%Y%m%d%H%M%S")) |
| 36 | + ) |
| 37 | + |
| 38 | + def create(self, title, description, type, owner, files=None, clone_files=False, *args, **kwargs): |
| 39 | + if not files: |
| 40 | + raise ValueError("File(s) expected") |
| 41 | + |
| 42 | + if clone_files: |
| 43 | + prefix = datetime.datetime.now().strftime("%Y%m%d%H%M%S") |
| 44 | + files = _asset_storage_manager.copy_files_list(files, dir=settings.ASSETS_ROOT, dir_prefix=prefix) |
| 45 | + # TODO: please note the copy_files_list will make flat any directory structure |
| 46 | + |
| 47 | + asset = LocalAsset( |
| 48 | + title=title, |
| 49 | + description=description, |
| 50 | + type=type, |
| 51 | + owner=owner, |
| 52 | + created=datetime.datetime.now(), |
| 53 | + location=files, |
| 54 | + ) |
| 55 | + asset.save() |
| 56 | + return asset |
| 57 | + |
| 58 | + def remove_data(self, asset: LocalAsset): |
| 59 | + """ |
| 60 | + Removes the files related to an Asset. |
| 61 | + Only files within the Assets directory are removed |
| 62 | + """ |
| 63 | + removed_dir = set() |
| 64 | + for file in asset.location: |
| 65 | + is_managed = self._is_file_managed(file) |
| 66 | + if is_managed: |
| 67 | + logger.info(f"Removing asset file {file}") |
| 68 | + _asset_storage_manager.delete(file) |
| 69 | + removed_dir.add(os.path.dirname(file)) |
| 70 | + else: |
| 71 | + logger.info(f"Not removing asset file outside asset directory {file}") |
| 72 | + |
| 73 | + # TODO: in case of subdirs, make sure that all the tree is removed in the proper order |
| 74 | + for dir in removed_dir: |
| 75 | + if not os.path.exists(dir): |
| 76 | + logger.warning(f"Trying to remove not existing asset directory {dir}") |
| 77 | + continue |
| 78 | + if not os.listdir(dir): |
| 79 | + logger.info(f"Removing empty asset directory {dir}") |
| 80 | + os.rmdir(dir) |
| 81 | + |
| 82 | + def replace_data(self, asset: LocalAsset, files: list): |
| 83 | + self.remove_data(asset) |
| 84 | + asset.location = files |
| 85 | + asset.save() |
| 86 | + |
| 87 | + def clone(self, source: LocalAsset) -> LocalAsset: |
| 88 | + # get a new asset instance to be edited and stored back |
| 89 | + asset = LocalAsset.objects.get(pk=source.pk) |
| 90 | + # only copy files if they are managed |
| 91 | + if self._are_files_managed(asset.location): |
| 92 | + asset.location = _asset_storage_manager.copy_files_list( |
| 93 | + asset.location, dir=settings.ASSETS_ROOT, dir_prefix=datetime.datetime.now().strftime("%Y%m%d%H%M%S") |
| 94 | + ) |
| 95 | + # it's a polymorphic object, we need to null both IDs |
| 96 | + # https://django-polymorphic.readthedocs.io/en/stable/advanced.html#copying-polymorphic-objects |
| 97 | + asset.pk = None |
| 98 | + asset.id = None |
| 99 | + asset.save() |
| 100 | + asset.refresh_from_db() |
| 101 | + return asset |
| 102 | + |
| 103 | + def create_download_url(self, asset) -> str: |
| 104 | + return build_absolute_uri(reverse("assets-download", args=(asset.pk,))) |
| 105 | + |
| 106 | + def create_link_url(self, asset) -> str: |
| 107 | + return build_absolute_uri(reverse("assets-link", args=(asset.pk,))) |
| 108 | + |
| 109 | + def _is_file_managed(self, file) -> bool: |
| 110 | + assets_root = os.path.normpath(settings.ASSETS_ROOT) |
| 111 | + return file.startswith(assets_root) |
| 112 | + |
| 113 | + def _are_files_managed(self, files: list) -> bool: |
| 114 | + """ |
| 115 | + :param files: files to be checked |
| 116 | + :return: True if all files are managed, False is no file is managed |
| 117 | + :raise: ValueError if both managed and unmanaged files are in the list |
| 118 | + """ |
| 119 | + managed = unmanaged = None |
| 120 | + for file in files: |
| 121 | + if self._is_file_managed(file): |
| 122 | + managed = True |
| 123 | + else: |
| 124 | + unmanaged = True |
| 125 | + if managed and unmanaged: |
| 126 | + logger.error(f"Both managed and unmanaged files are present: {files}") |
| 127 | + raise ValueError("Both managed and unmanaged files are present") |
| 128 | + |
| 129 | + return bool(managed) |
| 130 | + |
| 131 | + |
| 132 | +class LocalAssetDownloadHandler(AssetDownloadHandlerInterface): |
| 133 | + |
| 134 | + def create_response(self, asset: LocalAsset, attachment: bool = False, basename=None) -> HttpResponse: |
| 135 | + if not asset.location: |
| 136 | + return HttpResponse("Asset does not contain any data", status=500) |
| 137 | + |
| 138 | + if len(asset.location) > 1: |
| 139 | + logger.warning("TODO: Asset contains more than one file. Download needs to be implemented") |
| 140 | + |
| 141 | + file0 = asset.location[0] |
| 142 | + filename = os.path.basename(file0) |
| 143 | + orig_base, ext = os.path.splitext(filename) |
| 144 | + outname = f"{basename or orig_base}{ext}" |
| 145 | + |
| 146 | + if _asset_storage_manager.exists(file0): |
| 147 | + logger.info(f"Returning file {file0} with name {outname}") |
| 148 | + |
| 149 | + return DownloadResponse( |
| 150 | + _asset_storage_manager.open(file0).file, |
| 151 | + basename=f"{outname}", |
| 152 | + attachment=attachment, |
| 153 | + ) |
| 154 | + else: |
| 155 | + logger.warning(f"Internal file {file0} not found for asset {asset.id}") |
| 156 | + return HttpResponse(f"Internal file not found for asset {asset.id}", status=500) |
| 157 | + |
| 158 | + |
| 159 | +asset_handler_registry.register(LocalAssetHandler) |
0 commit comments