diff --git a/app/src/main/java/eu/faircode/email/MessageClassifier.java b/app/src/main/java/eu/faircode/email/MessageClassifier.java index b7705d4488..5fbda0cb13 100644 --- a/app/src/main/java/eu/faircode/email/MessageClassifier.java +++ b/app/src/main/java/eu/faircode/email/MessageClassifier.java @@ -25,6 +25,7 @@ import android.os.Build; import android.text.TextUtils; import android.util.JsonReader; import android.util.JsonWriter; +import android.util.MalformedJsonException; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; @@ -390,6 +391,17 @@ public class MessageClassifier { long start = new Date().getTime(); File file = getFile(context); + if (file.exists()) + try { + File backup = getBackupFile(context); + Log.i("Classifier backup " + backup); + backup.delete(); + file.renameTo(backup); + } catch (Throwable ex) { + Log.w(ex); + } + + Log.i("Classifier save " + file); try (JsonWriter writer = new JsonWriter(new BufferedWriter(new FileWriter(file)))) { writer.beginObject(); @@ -467,9 +479,31 @@ public class MessageClassifier { return; clear(context); - - long start = new Date().getTime(); File file = getFile(context); + try { + _load(file); + } catch (MalformedJsonException ex) { + Log.w(ex); + clear(context); + File backup = getBackupFile(context); + if (backup.exists()) + try { + _load(backup); + } catch (Throwable ex1) { + Log.e(ex1); + backup.delete(); + clear(context); + } + } catch (Throwable ex) { + Log.e(ex); + file.delete(); + clear(context); + } + } + + private static synchronized void _load(File file) throws IOException { + Log.i("Classifier read " + file); + long start = new Date().getTime(); if (file.exists()) try (JsonReader reader = new JsonReader(new BufferedReader(new FileReader(file)))) { reader.beginObject(); @@ -599,10 +633,6 @@ public class MessageClassifier { break; } reader.endObject(); - } catch (Throwable ex) { - Log.e(ex); - file.delete(); - clear(context); } loaded = true; @@ -654,6 +684,10 @@ public class MessageClassifier { return new File(context.getFilesDir(), "classifier.json"); } + static File getBackupFile(@NonNull Context context) { + return new File(context.getFilesDir(), "classifier.backup"); + } + private static class State { private final List words = new ArrayList<>(); private final Map classStats = new HashMap<>();