From 689ec6d7866924a2fc545ff26beeef5939b8e21b Mon Sep 17 00:00:00 2001 From: Andrew Gunnerson Date: Thu, 13 Apr 2023 21:56:47 -0400 Subject: [PATCH] DocumentFileExtensions.kt: Use simple string operations to preserve extension when renaming MimeTypeMap's getExtensionFromMimeType() and getMimeTypeFromExtension() are not consistent with each other. Querying the extension for `audio/mp4` returns `m4a` as expected, but querying the MIME type for `m4a` returns `audio/mpeg`, which is associated with the `mp3` extension. Due to this, whenever an output file needed to be renamed, files that originally had the `m4a` extension would get changed to `mp3`. This commit fixes the issue by removing the whole extension -> MIME type -> extension round trip when renaming files. Instead, it just appends everything after the last dot from the original filename when renaming. Fixes: #292 Signed-off-by: Andrew Gunnerson --- .../main/java/com/chiller3/bcr/DocumentFileExtensions.kt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt b/app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt index b7b07a5e3..694a3f569 100644 --- a/app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt +++ b/app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt @@ -5,7 +5,6 @@ import android.content.Context import android.net.Uri import android.provider.DocumentsContract import android.util.Log -import android.webkit.MimeTypeMap import androidx.documentfile.provider.DocumentFile private const val TAG = "DocumentFileExtensions" @@ -112,8 +111,12 @@ fun DocumentFile.renameToPreserveExt(displayName: String): Boolean { buildString { append(displayName) - val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(type) - if (ext != null) { + // This intentionally just does simple string operations because MimeTypeMap's + // getExtensionFromMimeType() and getMimeTypeFromExtension() are not consistent with + // each other. Eg. audio/mp4 -> m4a -> audio/mpeg -> mp3. + + val ext = name!!.substringAfterLast('.', "") + if (ext.isNotEmpty()) { append('.') append(ext) }