Try different cache locations.

This commit is contained in:
Docile-Alligator 2025-10-06 17:18:09 -04:00
parent 482a2d189d
commit c11b0735b0
9 changed files with 77 additions and 22 deletions

View File

@ -386,10 +386,11 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (getExternalCacheDir() != null) {
File cacheDir = Utils.getCacheDir(ViewImageOrGifActivity.this);
if (cacheDir != null) {
Toast.makeText(ViewImageOrGifActivity.this, R.string.save_image_first, Toast.LENGTH_SHORT).show();
SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, handler, resource,
getExternalCacheDir().getPath(), mImageFileName,
cacheDir.getPath(), mImageFileName,
new SaveBitmapImageToFile.SaveBitmapImageToFileListener() {
@Override
public void saveSuccess(File imageFile) {
@ -432,8 +433,9 @@ public class ViewImageOrGifActivity extends AppCompatActivity implements SetAsWa
@Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
if (getExternalCacheDir() != null) {
SaveGIFToFile.saveGifToFile(mExecutor, handler, resource, getExternalCacheDir().getPath(), mImageFileName,
File cacheDir = Utils.getCacheDir(ViewImageOrGifActivity.this);
if (cacheDir != null) {
SaveGIFToFile.saveGifToFile(mExecutor, handler, resource, cacheDir.getPath(), mImageFileName,
new SaveGIFToFile.SaveGIFToFileListener() {
@Override
public void saveSuccess(File imageFile) {

View File

@ -43,6 +43,7 @@ import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubred
import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData;
import ml.docilealligator.infinityforreddit.utils.CustomThemeSharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
public class BackupSettings {
public static void backupSettings(Context context, Executor executor, Handler handler,
@ -61,7 +62,13 @@ public class BackupSettings {
SharedPreferences postHistorySharedPreferences,
BackupSettingsListener backupSettingsListener) {
executor.execute(() -> {
String backupDir = context.getExternalCacheDir() + "/Backup/" + BuildConfig.VERSION_NAME;
File cacheDir = Utils.getCacheDir(context);
if (cacheDir == null) {
handler.post(() -> backupSettingsListener.failed(context.getText(R.string.restore_settings_failed_cannot_get_cache_dir).toString()));
return;
}
String backupDir = cacheDir + "/Backup/" + BuildConfig.VERSION_NAME;
File backupDirFile = new File(backupDir);
if (new File(backupDir).exists()) {
try {
@ -134,10 +141,10 @@ public class BackupSettings {
String commentFilterUsageJson = new Gson().toJson(commentFilterUsage);
boolean res19 = saveDatabaseTableToFile(commentFilterUsageJson, databaseDirFile.getAbsolutePath(), "/comment_filter_usage.json");
boolean zipRes = zipAndMoveToDestinationDir(context, contentResolver, destinationDirUri);
boolean zipRes = zipAndMoveToDestinationDir(context, cacheDir, contentResolver, destinationDirUri);
try {
FileUtils.deleteDirectory(new File(context.getExternalCacheDir() + "/Backup/"));
FileUtils.deleteDirectory(new File(cacheDir + "/Backup/"));
} catch (IOException e) {
e.printStackTrace();
}
@ -198,18 +205,18 @@ public class BackupSettings {
return true;
}
private static boolean zipAndMoveToDestinationDir(Context context, ContentResolver contentResolver, Uri destinationDirUri) {
private static boolean zipAndMoveToDestinationDir(Context context, File cacheDir, ContentResolver contentResolver, Uri destinationDirUri) {
OutputStream outputStream = null;
boolean result = false;
try {
String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(System.currentTimeMillis()));
String fileName = "Infinity_For_Reddit_Settings_Backup_v" + BuildConfig.VERSION_NAME + "-" + BuildConfig.VERSION_CODE + "-" + time + ".zip";
String filePath = context.getExternalCacheDir() + "/Backup/" + fileName;
String filePath = cacheDir + "/Backup/" + fileName;
ZipFile zip = new ZipFile(filePath, "123321".toCharArray());
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
zip.addFolder(new File(context.getExternalCacheDir() + "/Backup/" + BuildConfig.VERSION_NAME + "/"), zipParameters);
zip.addFolder(new File(cacheDir + "/Backup/" + BuildConfig.VERSION_NAME + "/"), zipParameters);
DocumentFile dir = DocumentFile.fromTreeUri(context, destinationDirUri);
if (dir == null) {

View File

@ -43,6 +43,7 @@ import ml.docilealligator.infinityforreddit.subscribedsubreddit.SubscribedSubred
import ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData;
import ml.docilealligator.infinityforreddit.utils.CustomThemeSharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
public class RestoreSettings {
public static void restoreSettings(Context context, Executor executor, Handler handler,
@ -68,7 +69,12 @@ public class RestoreSettings {
return;
}
String cachePath = context.getExternalCacheDir() + "/Restore/";
File cacheDir = Utils.getCacheDir(context);
if (cacheDir == null) {
handler.post(() -> restoreSettingsListener.failed(context.getString(R.string.restore_settings_failed_cannot_get_cache_dir)));
return;
}
String cachePath = cacheDir + "/Restore/";
if (new File(cachePath).exists()) {
FileUtils.deleteDirectory(new File(cachePath));
}

View File

@ -235,9 +235,10 @@ public class ViewImgurImageFragment extends Fragment {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (activity.getExternalCacheDir() != null) {
File cacheDir = Utils.getCacheDir(activity);
if (cacheDir != null) {
Toast.makeText(activity, R.string.save_image_first, Toast.LENGTH_SHORT).show();
SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, new Handler(), resource, activity.getExternalCacheDir().getPath(),
SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, new Handler(), resource, cacheDir.getPath(),
imgurMedia.getFileName(),
new SaveBitmapImageToFile.SaveBitmapImageToFileListener() {
@Override

View File

@ -405,9 +405,10 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
glide.asBitmap().load(media.hasFallback() ? media.fallbackUrl : media.url).into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (activity.getExternalCacheDir() != null) {
File cacheDir = Utils.getCacheDir(activity);
if (cacheDir != null) {
Toast.makeText(activity, R.string.save_image_first, Toast.LENGTH_SHORT).show();
SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, handler, resource, activity.getExternalCacheDir().getPath(),
SaveBitmapImageToFile.SaveBitmapImageToFile(mExecutor, handler, resource, cacheDir.getPath(),
media.fileName,
new SaveBitmapImageToFile.SaveBitmapImageToFileListener() {
@Override
@ -451,8 +452,9 @@ public class ViewRedditGalleryImageOrGifFragment extends Fragment {
@Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
if (activity.getExternalCacheDir() != null) {
SaveGIFToFile.saveGifToFile(mExecutor, handler, resource, activity.getExternalCacheDir().getPath(), media.fileName,
File cacheDir = Utils.getCacheDir(activity);
if (cacheDir != null) {
SaveGIFToFile.saveGifToFile(mExecutor, handler, resource, cacheDir.getPath(), media.fileName,
new SaveGIFToFile.SaveGIFToFileListener() {
@Override
public void saveSuccess(File imageFile) {

View File

@ -53,6 +53,7 @@ import ml.docilealligator.infinityforreddit.broadcastreceivers.DownloadedMediaDe
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.utils.NotificationUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Response;
@ -181,7 +182,7 @@ public class DownloadRedditVideoService extends JobService {
boolean separateDownloadFolder = sharedPreferences.getBoolean(SharedPreferencesUtils.SEPARATE_FOLDER_FOR_EACH_SUBREDDIT, false);
File externalCacheDirectory = getExternalCacheDir();
File externalCacheDirectory = Utils.getCacheDir(this);
if (externalCacheDirectory != null) {
String destinationFileName = fileNameWithoutExtension + ".mp4";
String finalFileNameWithoutExtension = fileNameWithoutExtension;

View File

@ -16,6 +16,7 @@ import android.os.PersistableBundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
@ -62,6 +63,7 @@ import ml.docilealligator.infinityforreddit.post.SubmitPost;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.JSONUtils;
import ml.docilealligator.infinityforreddit.utils.NotificationUtils;
import ml.docilealligator.infinityforreddit.utils.Utils;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import retrofit2.Response;
@ -291,6 +293,7 @@ public class SubmitPostService extends JobService {
.build();
}
@WorkerThread
private void submitTextOrLinkPost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Retrofit newAuthenticatorOauthRetrofit, Account selectedAccount,
String subredditName, String title, String content, @Nullable String url,
@ -316,6 +319,7 @@ public class SubmitPostService extends JobService {
});
}
@WorkerThread
private void submitCrosspost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Executor executor, Handler handler, Retrofit newAuthenticatorOauthRetrofit,
Account selectedAccount, String subredditName,
@ -340,6 +344,7 @@ public class SubmitPostService extends JobService {
});
}
@WorkerThread
private void submitImagePost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Retrofit newAuthenticatorOauthRetrofit, Account selectedAccount, Uri mediaUri,
String subredditName, String title, String content, Flair flair,
@ -373,6 +378,7 @@ public class SubmitPostService extends JobService {
}
}
@WorkerThread
private void submitVideoPost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Retrofit newAuthenticatorOauthRetrofit, Account selectedAccount, Uri mediaUri,
String subredditName, String title, String content, Flair flair,
@ -380,11 +386,16 @@ public class SubmitPostService extends JobService {
try {
InputStream in = getContentResolver().openInputStream(mediaUri);
String type = getContentResolver().getType(mediaUri);
File cacheDir = Utils.getCacheDir(this);
if (cacheDir == null) {
handler.post(() -> EventBus.getDefault().post(new SubmitVideoOrGifPostEvent(false, false, getString(R.string.submit_video_or_gif_post_failed_cannot_get_cache_directory))));
return;
}
String cacheFilePath;
if (type != null && type.contains("gif")) {
cacheFilePath = getExternalCacheDir() + "/" + mediaUri.getLastPathSegment() + ".gif";
cacheFilePath = cacheDir + "/" + mediaUri.getLastPathSegment() + ".gif";
} else {
cacheFilePath = getExternalCacheDir() + "/" + mediaUri.getLastPathSegment() + ".mp4";
cacheFilePath = cacheDir + "/" + mediaUri.getLastPathSegment() + ".mp4";
}
copyFileToCache(in, cacheFilePath);
@ -431,6 +442,7 @@ public class SubmitPostService extends JobService {
}
}
@WorkerThread
private void submitGalleryPost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Retrofit newAuthenticatorOauthRetrofit, Account selectedAccount, String payload) {
try {
@ -468,6 +480,7 @@ public class SubmitPostService extends JobService {
}
}
@WorkerThread
private void submitPollPost(JobParameters parameters, NotificationManagerCompat manager, int randomNotificationIdOffset,
Retrofit newAuthenticatorOauthRetrofit, Account selectedAccount, String payload) {
try {

View File

@ -41,6 +41,7 @@ import com.google.android.material.textfield.TextInputLayout;
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@ -53,8 +54,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.noties.markwon.core.spans.CustomTypefaceSpan;
import ml.docilealligator.infinityforreddit.thing.MediaMetadata;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.thing.MediaMetadata;
import ml.docilealligator.infinityforreddit.thing.SortType;
import ml.docilealligator.infinityforreddit.thing.UploadedImage;
import retrofit2.Retrofit;
@ -510,4 +511,24 @@ public final class Utils {
public static <T> int fixIndexOutOfBoundsUsingPredetermined(T[] array, int index, int predeterminedIndex) {
return index >= array.length ? predeterminedIndex : index;
}
@Nullable
public static File getCacheDir(Context context) {
File cacheDir = context.getExternalCacheDir();
if (cacheDir != null) {
return cacheDir;
}
cacheDir = context.getCacheDir();
if (cacheDir != null) {
return cacheDir;
}
cacheDir = context.getExternalFilesDir(null);
if (cacheDir != null) {
return cacheDir;
}
return context.getFilesDir();
}
}

View File

@ -53,7 +53,7 @@
<string name="action_download">Download</string>
<string name="action_refresh">Refresh</string>
<string name="action_add_comment">Add a comment</string>
<string name="action_add_comment">Send comment</string>
<string name="action_save_post">Save post</string>
<string name="action_view_crosspost_parent">View crosspost parent</string>
<string name="action_search">Search</string>
@ -250,6 +250,7 @@
<string name="no_camera_available">No camera app available</string>
<string name="error_creating_temp_file">Error creating temp file</string>
<string name="submit_video_or_gif_post_failed_cannot_get_cache_directory">Unable to submit post: cannot access cache directory</string>
<string name="video_is_processing">Video is processing. Please wait.</string>
<string name="image_is_processing">Image is processing. Please wait.</string>
<string name="gif_is_processing">Gif is processing. Please wait.</string>
@ -1232,6 +1233,7 @@
<string name="restore_settings_partially_failed">Some settings may not be restored successfully. Restart the app to see the changes.</string>
<string name="restore_settings_failed_file_corrupted">Cannot restore settings. The file may be corrupted.</string>
<string name="restore_settings_failed_cannot_get_file">Cannot access the file</string>
<string name="restore_settings_failed_cannot_get_cache_dir">Cannot access cache directory</string>
<string name="suicide_prevention_quote">If you are looking for a sign not to kill yourself, this is it.\u2764</string>
<string name="do_not_show_this_again">Don\'t show this again</string>