summaryrefslogtreecommitdiff
path: root/alot/utils/magic.py
diff options
context:
space:
mode:
Diffstat (limited to 'alot/utils/magic.py')
-rw-r--r--alot/utils/magic.py44
1 files changed, 44 insertions, 0 deletions
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
+