1
0
mirror of https://codeberg.org/Freeyourgadget/Gadgetbridge synced 2024-12-26 02:25:50 +01:00

Made UriHelper a bit more failure resistant

This commit is contained in:
TaaviE 2020-07-28 01:16:17 +03:00
parent 1c2cd99efd
commit 709fb0a82b

View File

@ -22,15 +22,18 @@ import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class UriHelper {
@NonNull
private final Uri uri;
@ -41,6 +44,8 @@ public class UriHelper {
@Nullable
private File file;
private static final Logger LOG = LoggerFactory.getLogger(UriHelper.class);
private UriHelper(@NonNull Uri uri, @NonNull Context context) {
this.uri = uri;
this.context = context;
@ -118,17 +123,36 @@ public class UriHelper {
}
private void resolveMetadata() throws IOException {
if (uri == null) {
throw new IOException("URI was null, can't query metadata");
}
String uriScheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(uriScheme)) {
Cursor cursor = context.getContentResolver().query(
if (uriScheme == null) {
throw new IOException("URI scheme was null, can't query metadata");
}
switch (uriScheme) {
case ContentResolver.SCHEME_CONTENT:
Cursor cursor;
try {
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(
uri,
new String[]{
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.SIZE
}, null, null, null);
} catch (IllegalStateException e) {
LOG.error(e.toString());
throw new IOException("IllegalStateException when trying to query metadata for: " + uri);
}
if (cursor == null) {
throw new IOException("Unable to query metadata for: " + uri);
}
try {
if (cursor.moveToFirst()) {
int name_index = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
@ -155,17 +179,19 @@ public class UriHelper {
} finally {
cursor.close();
}
} else if (ContentResolver.SCHEME_FILE.equals(uriScheme)) {
break;
case ContentResolver.SCHEME_FILE:
file = new File(uri.getPath());
if (!file.exists()) {
throw new FileNotFoundException("Does not exist: " + file);
}
fileName = file.getName();
fileSize = file.length();
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uriScheme)) {
break;
case ContentResolver.SCHEME_ANDROID_RESOURCE:
// we could actually read it, but I don't see how we can determine the file size
throw new IOException("Unsupported scheme for uri: " + uri);
} else {
default:
throw new IOException("Unsupported scheme for uri: " + uri);
}
}