From 999b802f7d7b21b67991396404430a3c5abc9ffb Mon Sep 17 00:00:00 2001 From: cwilvx Date: Wed, 8 May 2024 11:15:02 +0300 Subject: [PATCH] guess audio mimetypes --- app/api/send_file.py | 9 +++------ app/utils/files.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 app/utils/files.py diff --git a/app/api/send_file.py b/app/api/send_file.py index 5c804079..74d1b88d 100644 --- a/app/api/send_file.py +++ b/app/api/send_file.py @@ -11,6 +11,7 @@ from app.api.apischemas import TrackHashSchema from app.lib.trackslib import get_silence_paddings from app.store.tracks import TrackStore +from app.utils.files import guess_mime_type bp_tag = Tag(name="File", description="Audio files") api = APIBlueprint("track", __name__, url_prefix="/file", abp_tags=[bp_tag]) @@ -33,10 +34,6 @@ def send_track_file(path: TrackHashSchema, query: SendTrackFileQuery): filepath = query.filepath msg = {"msg": "File Not Found"} - def get_mime(filename: str) -> str: - ext = filename.rsplit(".", maxsplit=1)[-1] - return f"audio/{ext}" - # If filepath is provided, try to send that if filepath is not None: try: @@ -47,7 +44,7 @@ def send_track_file(path: TrackHashSchema, query: SendTrackFileQuery): track_exists = track is not None and os.path.exists(track.filepath) if track_exists: - audio_type = get_mime(filepath) + audio_type = guess_mime_type(filepath) return send_file_as_chunks(track.filepath, audio_type) # Else, find file by trackhash @@ -57,7 +54,7 @@ def send_track_file(path: TrackHashSchema, query: SendTrackFileQuery): if track is None: return msg, 404 - audio_type = get_mime(track.filepath) + audio_type = guess_mime_type(track.filepath) try: return send_file_as_chunks(track.filepath, audio_type) diff --git a/app/utils/files.py b/app/utils/files.py new file mode 100644 index 00000000..382ac423 --- /dev/null +++ b/app/utils/files.py @@ -0,0 +1,21 @@ +import mimetypes + + +def get_mime_from_ext(filename: str): + """ + Constructs a mime type from a file extension. + """ + ext = filename.rsplit(".", maxsplit=1)[-1] + return f"audio/{ext}" + + +def guess_mime_type(filename: str): + """ + Guess the mime type of a file. + """ + type = mimetypes.guess_type(filename)[0] + + if type is None: + return get_mime_from_ext(filename) + + return type