try to guess mime type via extension in display name

This commit is contained in:
Daniel Gultsch 2020-07-21 10:19:21 +02:00
parent 28856aaf9f
commit 16300727d1
1 changed files with 30 additions and 9 deletions

View File

@ -16,7 +16,9 @@
package eu.siacs.conversations.utils; package eu.siacs.conversations.utils;
import android.content.Context; import android.content.Context;
import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log; import android.util.Log;
import java.io.File; import java.io.File;
@ -538,19 +540,21 @@ public final class MimeUtils {
String mimeType; String mimeType;
try { try {
mimeType = context.getContentResolver().getType(uri); mimeType = context.getContentResolver().getType(uri);
} catch (Throwable throwable) { } catch (final Throwable throwable) {
mimeType = null; mimeType = null;
} }
// try the extension // try the extension
if ((mimeType == null || mimeType.equals("application/octet-stream")) && uri.getPath() != null) { if (mimeType == null || mimeType.equals("application/octet-stream")) {
String path = uri.getPath(); final String path = uri.getPath();
int start = path.lastIndexOf('.') + 1; if (path != null) {
if (start < path.length()) { mimeType = guessFromPath(path);
final String guess = MimeUtils.guessMimeTypeFromExtension(path.substring(start));
if (guess != null) {
mimeType = guess;
} }
} }
if (mimeType == null && "content".equals(uri.getScheme())) {
final String name = getDisplayName(context, uri);
if (name != null) {
mimeType = guessFromPath(name);
}
} }
// sometimes this works (as with the commit content api) // sometimes this works (as with the commit content api)
if (mimeType == null) { if (mimeType == null) {
@ -559,6 +563,23 @@ public final class MimeUtils {
return mimeType; return mimeType;
} }
private static String getDisplayName(final Context context, final Uri uri) {
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
return null;
}
private static String guessFromPath(final String path) {
final int start = path.lastIndexOf('.') + 1;
if (start < path.length()) {
return MimeUtils.guessMimeTypeFromExtension(path.substring(start));
}
return null;
}
public static String extractRelevantExtension(URL url) { public static String extractRelevantExtension(URL url) {
String path = url.getPath(); String path = url.getPath();
return extractRelevantExtension(path, true); return extractRelevantExtension(path, true);