Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for puremagic #150

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions mautrix/util/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,40 @@

import functools

import magic

try:
_from_buffer = functools.partial(magic.from_buffer, mime=True)
_from_filename = functools.partial(magic.from_file, mime=True)
except AttributeError:
_from_buffer = lambda data: magic.detect_from_content(data).mime_type
_from_filename = lambda file: magic.detect_from_filename(file).mime_type
from puremagic.main import PureMagicWithConfidence as _PureMagicResult
import puremagic

_blacklist = {".koz"}

def _cleanup_result(results: list[_PureMagicResult]) -> str:
for res in results:
if not res.mime_type or res.extension in _blacklist:
continue
return res.mime_type
return "application/octet-stream"

def _from_buffer(data: bytes) -> str:
try:
return _cleanup_result(puremagic.magic_string(data))
except puremagic.PureError:
return "application/octet-stream"

def _from_filename(filename: str) -> str:
try:
return _cleanup_result(puremagic.magic_file(filename))
except puremagic.PureError:
return "application/octet-stream"

except ImportError:
import magic

try:
_from_buffer = functools.partial(magic.from_buffer, mime=True)
_from_filename = functools.partial(magic.from_file, mime=True)
except AttributeError:
_from_buffer = lambda data: magic.detect_from_content(data).mime_type
_from_filename = lambda file: magic.detect_from_filename(file).mime_type


def mimetype(data: bytes | bytearray | str) -> str:
Expand Down
2 changes: 1 addition & 1 deletion optional-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
python-magic
puremagic
ruamel.yaml
SQLAlchemy<2
commonmark
Expand Down