From 0d0741285c1d858531f97d1e50d542845a35e6da Mon Sep 17 00:00:00 2001 From: David Manthey Date: Wed, 24 Aug 2022 16:29:03 -0400 Subject: [PATCH] Improve mimetypes on upload. --- CHANGELOG.md | 1 + girder/girder_large_image/__init__.py | 31 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 480d1eb4b..3aa762b2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Improvements - Add a general filter control to item lists ([938](../../pull/938), [941](../../pull/941)) - Item list modal dialogs are wider ([939](../../pull/939)) +- Improve mimetypes on upload to Girder ([943](../../pull/943)) ### Bug Fixes - Fix iterating tiles where the overlap larger than the tile size ([940](../../pull/940)) diff --git a/girder/girder_large_image/__init__.py b/girder/girder_large_image/__init__.py index af8009581..defe371f6 100644 --- a/girder/girder_large_image/__init__.py +++ b/girder/girder_large_image/__init__.py @@ -57,6 +57,9 @@ pass +mimetypes = None + + # Girder 3 is pinned to use pymongo < 4; its warnings aren't relevant until # that changes. warnings.filterwarnings('ignore', category=UserWarning, module='pymongo') @@ -217,6 +220,33 @@ def handleRemoveFile(event): ImageItem().delete(item, [fileObj['_id']]) +def handleFinalizeUploadBefore(event): + """ + When a file is uploaded, mark its mime type based on its extension if we + would otherwise just mark it as generic application/octet-stream. + """ + fileObj = event.info['file'] + if fileObj.get('mimeType', None) in {None, 'application/octet-stream'}: + global mimetypes + + if not mimetypes: + import mimetypes + + if not mimetypes.inited: + mimetypes.init() + # Augment the standard mimetypes with some additional values + for mimeType, ext, std in [ + ('text/yaml', '.yaml', True), + ('text/yaml', '.yml', False), + ]: + if ext not in mimetypes.types_map: + mimetypes.add_type(mimeType, ext, std) + + alt = mimetypes.guess_type(fileObj.get('name', ''))[0] + if alt is not None: + fileObj['mimeType'] = alt + + # Validators @setting_utilities.validator({ @@ -356,3 +386,4 @@ def load(self, info): events.bind('model.item.remove', 'large_image.removeThumbnails', removeThumbnails) events.bind('server_fuse.unmount', 'large_image', large_image.cache_util.cachesClear) events.bind('model.file.remove', 'large_image', handleRemoveFile) + events.bind('model.file.finalizeUpload.before', 'large_image', handleFinalizeUploadBefore)