package org.thoughtcrime.securesms.util; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.database.NoExternalStorageException; import org.whispersystems.libsignal.util.ByteUtil; import java.io.File; import java.security.SecureRandom; import java.util.Arrays; import java.util.Calendar; import java.util.Locale; public class BackupUtil { private static final String TAG = BackupUtil.class.getSimpleName(); public static @NonNull String getLastBackupTime(@NonNull Context context, @NonNull Locale locale) { try { BackupInfo backup = getLatestBackup(context); if (backup == null) return context.getString(R.string.BackupUtil_never); else return DateUtils.getExtendedRelativeTimeSpanString(context, locale, backup.getTimestamp()); } catch (NoExternalStorageException e) { Log.w(TAG, e); return context.getString(R.string.BackupUtil_unknown); } } public static @Nullable BackupInfo getLatestBackup(@NonNull Context context) throws NoExternalStorageException { File backupDirectory = StorageUtil.getBackupDirectory(context); File[] backups = backupDirectory.listFiles(); BackupInfo latestBackup = null; for (File backup : backups) { long backupTimestamp = getBackupTimestamp(backup); if (latestBackup == null || (backupTimestamp != -1 && backupTimestamp > latestBackup.getTimestamp())) { latestBackup = new BackupInfo(backupTimestamp, backup.length(), backup); } } return latestBackup; } @SuppressWarnings("ResultOfMethodCallIgnored") public static void deleteAllBackups(@NonNull Context context) { try { File backupDirectory = StorageUtil.getBackupDirectory(context); File[] backups = backupDirectory.listFiles(); for (File backup : backups) { if (backup.isFile()) backup.delete(); } } catch (NoExternalStorageException e) { Log.w(TAG, e); } } public static void deleteOldBackups(@NonNull Context context) { try { File backupDirectory = StorageUtil.getBackupDirectory(context); File[] backups = backupDirectory.listFiles(); if (backups != null && backups.length > 5) { Arrays.sort(backups, (left, right) -> { long leftTimestamp = getBackupTimestamp(left); long rightTimestamp = getBackupTimestamp(right); if (leftTimestamp == -1 && rightTimestamp == -1) return 0; else if (leftTimestamp == -1) return 1; else if (rightTimestamp == -1) return -1; return (int)(rightTimestamp - leftTimestamp); }); for (int i=5;i