Skip to content

Commit

Permalink
DocumentFileExtensions.kt: Use simple string operations to preserve e…
Browse files Browse the repository at this point in the history
…xtension 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 <accounts+github@chiller3.com>
  • Loading branch information
chenxiaolong committed Apr 14, 2023
1 parent 6af5407 commit 67fc1c1
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 67fc1c1

Please sign in to comment.