fix mime type detection in urls that have query params or an anchor

This commit is contained in:
Daniel Gultsch 2021-10-14 17:30:55 +02:00
parent 6d2e406ee5
commit 3706981645

View file

@ -21,6 +21,8 @@ import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -274,6 +276,8 @@ public final class MimeUtils {
add("image/ico", "ico");
add("image/ief", "ief");
add("image/heic", "heic");
add("image/heif", "heif");
add("image/avif", "avif");
// add ".jpg" first so it will be the default for guessExtensionFromMimeType
add("image/jpeg", "jpg");
add("image/jpeg", "jpeg");
@ -587,22 +591,33 @@ public final class MimeUtils {
}
public static String extractRelevantExtension(final String path, final boolean ignoreCryptoExtension) {
if (path == null || path.isEmpty()) {
if (Strings.isNullOrEmpty(path)) {
return null;
}
String filename = path.substring(path.lastIndexOf('/') + 1).toLowerCase();
int dotPosition = filename.lastIndexOf(".");
final String filenameQueryAnchor = path.substring(path.lastIndexOf('/') + 1);
final String filenameQuery = cutBefore(filenameQueryAnchor, '#');
final String filename = cutBefore(filenameQuery, '?');
final int dotPosition = filename.lastIndexOf('.');
if (dotPosition != -1) {
String extension = filename.substring(dotPosition + 1);
// we want the real file extension, not the crypto one
if (ignoreCryptoExtension && Transferable.VALID_CRYPTO_EXTENSIONS.contains(extension)) {
return extractRelevantExtension(filename.substring(0, dotPosition));
} else {
return extension;
}
if (dotPosition == -1) {
return null;
}
final String extension = filename.substring(dotPosition + 1);
// we want the real file extension, not the crypto one
if (ignoreCryptoExtension && Transferable.VALID_CRYPTO_EXTENSIONS.contains(extension)) {
return extractRelevantExtension(filename.substring(0, dotPosition));
} else {
return extension;
}
}
private static String cutBefore(final String input, final char c) {
final int position = input.indexOf(c);
if (position > 0) {
return input.substring(0, position);
} else {
return input;
}
return null;
}
}