From 0e293f1b7edc40be2aa24ef1522194fcf0229a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Kersten=20=28jke=29?= Date: Mon, 22 Mar 2021 16:31:41 +0000 Subject: [PATCH] [FIX] tools: properly guess image/svg+xml mimetype with magic lib MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Magic return image/svg instead of image/svg+xml if file starts with Signed-off-by: Quentin Smetz (qsm) --- odoo/tools/mimetypes.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/odoo/tools/mimetypes.py b/odoo/tools/mimetypes.py index 017b34faf11..3c30b3ace83 100644 --- a/odoo/tools/mimetypes.py +++ b/odoo/tools/mimetypes.py @@ -5,6 +5,7 @@ Mimetypes-related utilities # TODO: reexport stdlib mimetypes? """ import collections +import functools import io import logging import re @@ -133,7 +134,7 @@ _mime_mappings = ( # zip, but will include jar, odt, ods, odp, docx, xlsx, pptx, apk _Entry('application/zip', [b'PK\x03\x04'], [_check_ooxml, _check_open_container_format]), ) -def guess_mimetype(bin_data, default='application/octet-stream'): +def _odoo_guess_mimetype(bin_data, default='application/octet-stream'): """ Attempts to guess the mime type of the provided binary data, similar to but significantly more limited than libmagic @@ -166,17 +167,28 @@ try: import magic except ImportError: magic = None -else: - # There are 2 python libs named 'magic' with incompatible api. +if magic: + # There are 2 python libs named 'magic' with incompatible api. # magic from pypi https://pypi.python.org/pypi/python-magic/ - if hasattr(magic,'from_buffer'): - guess_mimetype = lambda bin_data, default=None: magic.from_buffer(bin_data, mime=True) + if hasattr(magic, 'from_buffer'): + _guesser = functools.partial(magic.from_buffer, mime=True) # magic from file(1) https://packages.debian.org/squeeze/python-magic - elif hasattr(magic,'open'): + elif hasattr(magic, 'open'): ms = magic.open(magic.MAGIC_MIME_TYPE) ms.load() - guess_mimetype = lambda bin_data, default=None: ms.buffer(bin_data) + _guesser = ms.buffer + + def guess_mimetype(bin_data, default=None): + mimetype = _guesser(bin_data) + # upgrade incorrect mimetype to official one, fixed upstream + # https://github.com/file/file/commit/1a08bb5c235700ba623ffa6f3c95938fe295b262 + if mimetype == 'image/svg': + return 'image/svg+xml' + return mimetype +else: + guess_mimetype = _odoo_guess_mimetype + def neuter_mimetype(mimetype, user): wrong_type = 'ht' in mimetype or 'xml' in mimetype or 'svg' in mimetype