package me.teafry.voipmessages; import android.content.Context; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; /** * Chat names and read/unread/archived state, kept in step with the desktop. * Changes here are written to files/state.json; the desktop's "Sync to * Rabbit" reads that, merges it with its own (newest change wins), and leaves * the result in files/state-in.json, applied here on the next start or check. */ final class StateSync { private StateSync() {} /** Write files/state.json; call after any rename or read/unread/archive change. */ static void export(Context c) { try { Store store = Store.get(c); JSONObject state = new JSONObject().put("names", store.namesExport()).put("read", store.readStateExport()); File tmp = new File(c.getFilesDir(), "state.json.tmp"); try (FileOutputStream out = new FileOutputStream(tmp)) { out.write(state.toString().getBytes(StandardCharsets.UTF_8)); } tmp.renameTo(new File(c.getFilesDir(), "state.json")); } catch (Exception ignored) { } } static void importPending(Context c) { File in = new File(c.getFilesDir(), "state-in.json"); if (!in.exists()) return; try { JSONObject state = new JSONObject(new String(Files.readAllBytes(in.toPath()), StandardCharsets.UTF_8)); Store store = Store.get(c); JSONArray names = state.optJSONArray("names"); JSONArray read = state.optJSONArray("read"); if (names != null) store.namesImport(names); if (read != null) store.readStateImport(read); in.delete(); export(c); Notifier.sweep(c); Sync.changed(); } catch (Exception ignored) { } } static void rename(Context c, String did, String contact, String name) { Store.get(c).setName(did, contact, name, System.currentTimeMillis()); export(c); Relay.stateChanged(c); Sync.changed(); } static void markRead(Context c, String did, String contact) { Store.get(c).markRead(did, contact); if (Sim.isSim(did)) Sim.markRead(c, contact); export(c); Relay.stateChanged(c); Notifier.sweep(c); } static void markUnread(Context c, String did, String contact) { Store.get(c).markUnread(did, contact); export(c); Relay.stateChanged(c); } static void setArchived(Context c, String did, String contact, boolean archived) { Store.get(c).setArchived(did, contact, archived); export(c); Relay.stateChanged(c); } }