From 9398560306f5609bcf1d3fdda6511cdb3b67d3f3 Mon Sep 17 00:00:00 2001 From: Anton Khirnov Date: Wed, 24 Nov 2021 15:36:28 +0100 Subject: helper: move guess_mimetype into its own file --- alot/utils/magic.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 alot/utils/magic.py (limited to 'alot/utils/magic.py') diff --git a/alot/utils/magic.py b/alot/utils/magic.py new file mode 100644 index 00000000..b6bbcfb2 --- /dev/null +++ b/alot/utils/magic.py @@ -0,0 +1,44 @@ +# This file is released under the GNU GPL, version 3 or a later revision. +# For further details see the COPYING file + +import re + +import magic + + +def guess_mimetype(blob): + """ + uses file magic to determine the mime-type of the given data blob. + + :param blob: file content as read by file.read() + :type blob: data + :returns: mime-type, falls back to 'application/octet-stream' + :rtype: str + """ + mimetype = 'application/octet-stream' + # this is a bit of a hack to support different versions of python magic. + # Hopefully at some point this will no longer be necessary + # + # the version with open() is the bindings shipped with the file source from + # http://darwinsys.com/file/ - this is what is used by the python-magic + # package on Debian/Ubuntu. However, it is not available on pypi/via pip. + # + # the version with from_buffer() is available at + # https://github.com/ahupp/python-magic and directly installable via pip. + # + # for more detail see https://github.com/pazz/alot/pull/588 + if hasattr(magic, 'open'): + m = magic.open(magic.MAGIC_MIME_TYPE) + m.load() + magictype = m.buffer(blob) + elif hasattr(magic, 'from_buffer'): + # cf. issue #841 + magictype = magic.from_buffer(blob, mime=True) or magictype + else: + raise Exception('Unknown magic API') + + # libmagic does not always return proper mimetype strings, cf. issue #459 + if re.match(r'\w+\/\w+', magictype): + mimetype = magictype + return mimetype + -- cgit v1.2.3