Skip to content

Commit

Permalink
Fix loss of filename extension due to DocumentFile.renameTo()
Browse files Browse the repository at this point in the history
When DocumentFile.renameTo() is called on a SAF URI, the file extension
is preserved, but this is not the case for file URIs. This commit
introduces an extension method .renameToPreserveExt() that behaves the
same regardless of URI.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
  • Loading branch information
chenxiaolong committed Feb 24, 2023
1 parent 92887ac commit 379010a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions app/src/main/java/com/chiller3/bcr/DocumentFileExtensions.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.chiller3.bcr

import android.content.ContentResolver
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 @@ -98,3 +100,27 @@ fun DocumentFile.findFileFast(displayName: String): DocumentFile? {

return null
}

/**
* Like [DocumentFile.renameTo], but preserves the extension for file URIs.
*
* This fixes [DocumentFile.renameTo]'s behavior so it is the same for both SAF and file URIs.
*/
fun DocumentFile.renameToPreserveExt(displayName: String): Boolean {
val newName = when (uri.scheme) {
ContentResolver.SCHEME_FILE -> {
buildString {
append(displayName)

val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(type)
if (ext != null) {
append('.')
append(ext)
}
}
}
else -> displayName
}

return renameTo(newName)
}
4 changes: 2 additions & 2 deletions app/src/main/java/com/chiller3/bcr/RecorderThread.kt
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ class RecorderThread(
if (finalFilename != initialFilename) {
Log.i(tag, "Renaming ${redactor.redact(initialFilename)} to ${redactor.redact(finalFilename)}")

if (outputFile.renameTo(finalFilename)) {
if (outputFile.renameToPreserveExt(finalFilename)) {
resultUri = outputFile.uri
} else {
Log.w(tag, "Failed to rename to final filename: ${redactor.redact(finalFilename)}")
Expand Down Expand Up @@ -381,7 +381,7 @@ class RecorderThread(
if (finalLogcatFilename != logcatFilename) {
Log.i(tag, "Renaming ${redactor.redact(logcatFilename)} to ${redactor.redact(finalLogcatFilename)}")

if (!logcatFile.renameTo(finalLogcatFilename)) {
if (!logcatFile.renameToPreserveExt(finalLogcatFilename)) {
Log.w(tag, "Failed to rename to final filename: ${redactor.redact(finalLogcatFilename)}")
}
}
Expand Down

0 comments on commit 379010a

Please sign in to comment.