DatabaseBackend.java

   1package eu.siacs.conversations.persistance;
   2
   3import android.content.ContentValues;
   4import android.content.Context;
   5import android.database.Cursor;
   6import android.database.DatabaseUtils;
   7import android.database.sqlite.SQLiteDatabase;
   8import android.database.sqlite.SQLiteOpenHelper;
   9import android.os.Environment;
  10import android.os.SystemClock;
  11import android.util.Base64;
  12import android.util.Log;
  13
  14import com.google.common.base.Stopwatch;
  15
  16import org.json.JSONException;
  17import org.json.JSONObject;
  18import org.whispersystems.libsignal.IdentityKey;
  19import org.whispersystems.libsignal.IdentityKeyPair;
  20import org.whispersystems.libsignal.InvalidKeyException;
  21import org.whispersystems.libsignal.SignalProtocolAddress;
  22import org.whispersystems.libsignal.state.PreKeyRecord;
  23import org.whispersystems.libsignal.state.SessionRecord;
  24import org.whispersystems.libsignal.state.SignedPreKeyRecord;
  25
  26import java.io.ByteArrayInputStream;
  27import java.io.File;
  28import java.io.IOException;
  29import java.security.cert.CertificateEncodingException;
  30import java.security.cert.CertificateException;
  31import java.security.cert.CertificateFactory;
  32import java.security.cert.X509Certificate;
  33import java.util.ArrayList;
  34import java.util.HashMap;
  35import java.util.HashSet;
  36import java.util.List;
  37import java.util.Map;
  38import java.util.Set;
  39import java.util.UUID;
  40import java.util.concurrent.CopyOnWriteArrayList;
  41
  42import eu.siacs.conversations.Config;
  43import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  44import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  45import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
  46import eu.siacs.conversations.entities.Account;
  47import eu.siacs.conversations.entities.Contact;
  48import eu.siacs.conversations.entities.Conversation;
  49import eu.siacs.conversations.entities.Message;
  50import eu.siacs.conversations.entities.PresenceTemplate;
  51import eu.siacs.conversations.entities.Roster;
  52import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  53import eu.siacs.conversations.services.QuickConversationsService;
  54import eu.siacs.conversations.services.ShortcutService;
  55import eu.siacs.conversations.utils.CryptoHelper;
  56import eu.siacs.conversations.utils.CursorUtils;
  57import eu.siacs.conversations.utils.FtsUtils;
  58import eu.siacs.conversations.utils.MimeUtils;
  59import eu.siacs.conversations.utils.Resolver;
  60import eu.siacs.conversations.xmpp.InvalidJid;
  61import eu.siacs.conversations.xmpp.Jid;
  62import eu.siacs.conversations.xmpp.mam.MamReference;
  63
  64public class DatabaseBackend extends SQLiteOpenHelper {
  65
  66    private static final String DATABASE_NAME = "history";
  67    private static final int DATABASE_VERSION = 52;
  68
  69    private static boolean requiresMessageIndexRebuild = false;
  70    private static DatabaseBackend instance = null;
  71    private static final String CREATE_CONTATCS_STATEMENT = "create table "
  72            + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
  73            + Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
  74            + Contact.PRESENCE_NAME + " TEXT,"
  75            + Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
  76            + Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
  77            + Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
  78            + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
  79            + Contact.RTP_CAPABILITY + " TEXT,"
  80            + Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
  81            + Account.TABLENAME + "(" + Account.UUID
  82            + ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
  83            + Contact.JID + ") ON CONFLICT REPLACE);";
  84
  85    private static final String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
  86            + ServiceDiscoveryResult.TABLENAME + "("
  87            + ServiceDiscoveryResult.HASH + " TEXT, "
  88            + ServiceDiscoveryResult.VER + " TEXT, "
  89            + ServiceDiscoveryResult.RESULT + " TEXT, "
  90            + "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
  91            + ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
  92
  93    private static final String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
  94            + PresenceTemplate.TABELNAME + "("
  95            + PresenceTemplate.UUID + " TEXT, "
  96            + PresenceTemplate.LAST_USED + " NUMBER,"
  97            + PresenceTemplate.MESSAGE + " TEXT,"
  98            + PresenceTemplate.STATUS + " TEXT,"
  99            + "UNIQUE(" + PresenceTemplate.MESSAGE + "," + PresenceTemplate.STATUS + ") ON CONFLICT REPLACE);";
 100
 101    private static final String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
 102            + SQLiteAxolotlStore.PREKEY_TABLENAME + "("
 103            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 104            + SQLiteAxolotlStore.ID + " INTEGER, "
 105            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 106            + SQLiteAxolotlStore.ACCOUNT
 107            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 108            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 109            + SQLiteAxolotlStore.ID
 110            + ") ON CONFLICT REPLACE"
 111            + ");";
 112
 113    private static final String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
 114            + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
 115            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 116            + SQLiteAxolotlStore.ID + " INTEGER, "
 117            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 118            + SQLiteAxolotlStore.ACCOUNT
 119            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 120            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 121            + SQLiteAxolotlStore.ID
 122            + ") ON CONFLICT REPLACE" +
 123            ");";
 124
 125    private static final String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
 126            + SQLiteAxolotlStore.SESSION_TABLENAME + "("
 127            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 128            + SQLiteAxolotlStore.NAME + " TEXT, "
 129            + SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
 130            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 131            + SQLiteAxolotlStore.ACCOUNT
 132            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 133            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 134            + SQLiteAxolotlStore.NAME + ", "
 135            + SQLiteAxolotlStore.DEVICE_ID
 136            + ") ON CONFLICT REPLACE"
 137            + ");";
 138
 139    private static final String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
 140            + SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
 141            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 142            + SQLiteAxolotlStore.NAME + " TEXT, "
 143            + SQLiteAxolotlStore.OWN + " INTEGER, "
 144            + SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
 145            + SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
 146            + SQLiteAxolotlStore.TRUST + " TEXT, "
 147            + SQLiteAxolotlStore.ACTIVE + " NUMBER, "
 148            + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
 149            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 150            + SQLiteAxolotlStore.ACCOUNT
 151            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 152            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 153            + SQLiteAxolotlStore.NAME + ", "
 154            + SQLiteAxolotlStore.FINGERPRINT
 155            + ") ON CONFLICT IGNORE"
 156            + ");";
 157
 158    private static final String RESOLVER_RESULTS_TABLENAME = "resolver_results";
 159
 160    private static final String CREATE_RESOLVER_RESULTS_TABLE = "create table " + RESOLVER_RESULTS_TABLENAME + "("
 161            + Resolver.Result.DOMAIN + " TEXT,"
 162            + Resolver.Result.HOSTNAME + " TEXT,"
 163            + Resolver.Result.IP + " BLOB,"
 164            + Resolver.Result.PRIORITY + " NUMBER,"
 165            + Resolver.Result.DIRECT_TLS + " NUMBER,"
 166            + Resolver.Result.AUTHENTICATED + " NUMBER,"
 167            + Resolver.Result.PORT + " NUMBER,"
 168            + "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
 169            + ");";
 170
 171    private static final String CREATE_MESSAGE_TIME_INDEX = "CREATE INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
 172    private static final String CREATE_MESSAGE_CONVERSATION_INDEX = "CREATE INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
 173    private static final String CREATE_MESSAGE_DELETED_INDEX = "CREATE INDEX message_deleted_index ON " + Message.TABLENAME + "(" + Message.DELETED + ")";
 174    private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX = "CREATE INDEX message_file_path_index ON " + Message.TABLENAME + "(" + Message.RELATIVE_FILE_PATH + ")";
 175    private static final String CREATE_MESSAGE_TYPE_INDEX = "CREATE INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
 176
 177    private static final String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING fts4 (uuid,body,notindexed=\"uuid\",content=\"" + Message.TABLENAME + "\",tokenize='unicode61')";
 178    private static final String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index(rowid,uuid,body) VALUES(NEW.rowid,NEW.uuid,NEW.body); END;";
 179    private static final String CREATE_MESSAGE_UPDATE_TRIGGER = "CREATE TRIGGER after_message_update UPDATE OF uuid,body ON " + Message.TABLENAME + " BEGIN UPDATE messages_index SET body=NEW.body,uuid=NEW.uuid WHERE rowid=OLD.rowid; END;";
 180    private static final String CREATE_MESSAGE_DELETE_TRIGGER = "CREATE TRIGGER after_message_delete AFTER DELETE ON " + Message.TABLENAME + " BEGIN DELETE FROM messages_index WHERE rowid=OLD.rowid; END;";
 181    private static final String COPY_PREEXISTING_ENTRIES = "INSERT INTO messages_index(messages_index) VALUES('rebuild');";
 182
 183    private DatabaseBackend(Context context) {
 184        super(context, DATABASE_NAME, null, DATABASE_VERSION);
 185    }
 186
 187    private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
 188        ContentValues values = new ContentValues();
 189        values.put(SQLiteAxolotlStore.TRUST, trust.toString());
 190        values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
 191        return values;
 192    }
 193
 194    public static boolean requiresMessageIndexRebuild() {
 195        return requiresMessageIndexRebuild;
 196    }
 197
 198    public void rebuildMessagesIndex() {
 199        final SQLiteDatabase db = getWritableDatabase();
 200        final Stopwatch stopwatch = Stopwatch.createStarted();
 201        db.execSQL(COPY_PREEXISTING_ENTRIES);
 202        Log.d(Config.LOGTAG,"rebuilt message index in "+ stopwatch.stop().toString());
 203    }
 204
 205    public static synchronized DatabaseBackend getInstance(Context context) {
 206        if (instance == null) {
 207            instance = new DatabaseBackend(context);
 208        }
 209        return instance;
 210    }
 211
 212    @Override
 213    public void onConfigure(SQLiteDatabase db) {
 214        db.execSQL("PRAGMA foreign_keys=ON");
 215        db.rawQuery("PRAGMA secure_delete=ON", null).close();
 216    }
 217
 218    @Override
 219    public void onCreate(SQLiteDatabase db) {
 220        db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID + " TEXT PRIMARY KEY,"
 221                + Account.USERNAME + " TEXT,"
 222                + Account.SERVER + " TEXT,"
 223                + Account.PASSWORD + " TEXT,"
 224                + Account.DISPLAY_NAME + " TEXT, "
 225                + Account.STATUS + " TEXT,"
 226                + Account.STATUS_MESSAGE + " TEXT,"
 227                + Account.ROSTERVERSION + " TEXT,"
 228                + Account.OPTIONS + " NUMBER, "
 229                + Account.AVATAR + " TEXT, "
 230                + Account.KEYS + " TEXT, "
 231                + Account.HOSTNAME + " TEXT, "
 232                + Account.RESOURCE + " TEXT,"
 233                + Account.PINNED_MECHANISM + " TEXT,"
 234                + Account.PINNED_CHANNEL_BINDING + " TEXT,"
 235                + Account.FAST_MECHANISM + " TEXT,"
 236                + Account.FAST_TOKEN + " TEXT,"
 237                + Account.PORT + " NUMBER DEFAULT 5222)");
 238        db.execSQL("create table " + Conversation.TABLENAME + " ("
 239                + Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
 240                + " TEXT, " + Conversation.CONTACT + " TEXT, "
 241                + Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
 242                + " TEXT, " + Conversation.CREATED + " NUMBER, "
 243                + Conversation.STATUS + " NUMBER, " + Conversation.MODE
 244                + " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
 245                + Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
 246                + "(" + Account.UUID + ") ON DELETE CASCADE);");
 247        db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
 248                + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
 249                + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
 250                + " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
 251                + Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
 252                + Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
 253                + Message.RELATIVE_FILE_PATH + " TEXT, "
 254                + Message.SERVER_MSG_ID + " TEXT, "
 255                + Message.FINGERPRINT + " TEXT, "
 256                + Message.CARBON + " INTEGER, "
 257                + Message.EDITED + " TEXT, "
 258                + Message.READ + " NUMBER DEFAULT 1, "
 259                + Message.OOB + " INTEGER, "
 260                + Message.ERROR_MESSAGE + " TEXT,"
 261                + Message.READ_BY_MARKERS + " TEXT,"
 262                + Message.MARKABLE + " NUMBER DEFAULT 0,"
 263                + Message.DELETED + " NUMBER DEFAULT 0,"
 264                + Message.BODY_LANGUAGE + " TEXT,"
 265                + Message.OCCUPANT_ID + " TEXT,"
 266                + Message.REACTIONS + " TEXT,"
 267                + Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
 268                + Message.CONVERSATION + ") REFERENCES "
 269                + Conversation.TABLENAME + "(" + Conversation.UUID
 270                + ") ON DELETE CASCADE);");
 271        db.execSQL(CREATE_MESSAGE_TIME_INDEX);
 272        db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
 273        db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
 274        db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
 275        db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
 276        db.execSQL(CREATE_CONTATCS_STATEMENT);
 277        db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 278        db.execSQL(CREATE_SESSIONS_STATEMENT);
 279        db.execSQL(CREATE_PREKEYS_STATEMENT);
 280        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
 281        db.execSQL(CREATE_IDENTITIES_STATEMENT);
 282        db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 283        db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
 284        db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 285        db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 286        db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 287        db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
 288    }
 289
 290    @Override
 291    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 292        if (oldVersion < 2 && newVersion >= 2) {
 293            db.execSQL("update " + Account.TABLENAME + " set "
 294                    + Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
 295        }
 296        if (oldVersion < 3 && newVersion >= 3) {
 297            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 298                    + Message.TYPE + " NUMBER");
 299        }
 300        if (oldVersion < 5 && newVersion >= 5) {
 301            db.execSQL("DROP TABLE " + Contact.TABLENAME);
 302            db.execSQL(CREATE_CONTATCS_STATEMENT);
 303            db.execSQL("UPDATE " + Account.TABLENAME + " SET "
 304                    + Account.ROSTERVERSION + " = NULL");
 305        }
 306        if (oldVersion < 6 && newVersion >= 6) {
 307            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 308                    + Message.TRUE_COUNTERPART + " TEXT");
 309        }
 310        if (oldVersion < 7 && newVersion >= 7) {
 311            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 312                    + Message.REMOTE_MSG_ID + " TEXT");
 313            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 314                    + Contact.AVATAR + " TEXT");
 315            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
 316                    + Account.AVATAR + " TEXT");
 317        }
 318        if (oldVersion < 8 && newVersion >= 8) {
 319            db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
 320                    + Conversation.ATTRIBUTES + " TEXT");
 321        }
 322        if (oldVersion < 9 && newVersion >= 9) {
 323            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 324                    + Contact.LAST_TIME + " NUMBER");
 325            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 326                    + Contact.LAST_PRESENCE + " TEXT");
 327        }
 328        if (oldVersion < 10 && newVersion >= 10) {
 329            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 330                    + Message.RELATIVE_FILE_PATH + " TEXT");
 331        }
 332        if (oldVersion < 11 && newVersion >= 11) {
 333            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 334                    + Contact.GROUPS + " TEXT");
 335            db.execSQL("delete from " + Contact.TABLENAME);
 336            db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 337        }
 338        if (oldVersion < 12 && newVersion >= 12) {
 339            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 340                    + Message.SERVER_MSG_ID + " TEXT");
 341        }
 342        if (oldVersion < 13 && newVersion >= 13) {
 343            db.execSQL("delete from " + Contact.TABLENAME);
 344            db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 345        }
 346        if (oldVersion < 14 && newVersion >= 14) {
 347            canonicalizeJids(db);
 348        }
 349        if (oldVersion < 15 && newVersion >= 15) {
 350            recreateAxolotlDb(db);
 351            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 352                    + Message.FINGERPRINT + " TEXT");
 353        }
 354        if (oldVersion < 16 && newVersion >= 16) {
 355            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 356                    + Message.CARBON + " INTEGER");
 357        }
 358        if (oldVersion < 19 && newVersion >= 19) {
 359            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
 360        }
 361        if (oldVersion < 20 && newVersion >= 20) {
 362            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
 363            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
 364        }
 365        if (oldVersion < 26 && newVersion >= 26) {
 366            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
 367            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
 368        }
 369        if (oldVersion < 40 && newVersion >= 40) {
 370            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.RESOURCE + " TEXT");
 371        }
 372        /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
 373         * depends on account de-serialization.
 374         */
 375        if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
 376            List<Account> accounts = getAccounts(db);
 377            for (Account account : accounts) {
 378                String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
 379                if (ownDeviceIdString == null) {
 380                    continue;
 381                }
 382                int ownDeviceId = Integer.valueOf(ownDeviceIdString);
 383                SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownDeviceId);
 384                deleteSession(db, account, ownAddress);
 385                IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
 386                if (identityKeyPair != null) {
 387                    String[] selectionArgs = {
 388                            account.getUuid(),
 389                            CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
 390                    };
 391                    ContentValues values = new ContentValues();
 392                    values.put(SQLiteAxolotlStore.TRUSTED, 2);
 393                    db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
 394                            SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 395                                    + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
 396                            selectionArgs);
 397                } else {
 398                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not load own identity key pair");
 399                }
 400            }
 401        }
 402        if (oldVersion < 18 && newVersion >= 18) {
 403            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
 404        }
 405
 406        if (oldVersion < 21 && newVersion >= 21) {
 407            List<Account> accounts = getAccounts(db);
 408            for (Account account : accounts) {
 409                account.unsetPgpSignature();
 410                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 411                        + "=?", new String[]{account.getUuid()});
 412            }
 413        }
 414
 415        if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
 416            db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
 417        }
 418
 419        if (oldVersion < 23 && newVersion >= 23) {
 420            db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 421        }
 422
 423        if (oldVersion < 24 && newVersion >= 24) {
 424            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
 425        }
 426
 427        if (oldVersion < 25 && newVersion >= 25) {
 428            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
 429        }
 430
 431        if (oldVersion < 26 && newVersion >= 26) {
 432            db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 433        }
 434
 435        if (oldVersion < 27 && newVersion >= 27) {
 436            db.execSQL("DELETE FROM " + ServiceDiscoveryResult.TABLENAME);
 437        }
 438
 439        if (oldVersion < 28 && newVersion >= 28) {
 440            canonicalizeJids(db);
 441        }
 442
 443        if (oldVersion < 29 && newVersion >= 29) {
 444            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
 445        }
 446        if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
 447            db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.TRUST + " TEXT");
 448            db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.ACTIVE + " NUMBER");
 449            HashMap<Integer, ContentValues> migration = new HashMap<>();
 450            migration.put(0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 451            migration.put(1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 452            migration.put(2, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
 453            migration.put(3, createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
 454            migration.put(4, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 455            migration.put(5, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 456            migration.put(6, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
 457            migration.put(7, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
 458            migration.put(8, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
 459            for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
 460                String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
 461                String[] where = {String.valueOf(entry.getKey())};
 462                db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, entry.getValue(), whereClause, where);
 463            }
 464
 465        }
 466        if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
 467            db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
 468            ContentValues defaults = new ContentValues();
 469            defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
 470            db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
 471        }
 472        if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
 473            String whereClause = SQLiteAxolotlStore.OWN + "=1";
 474            db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true), whereClause, null);
 475        }
 476
 477        if (oldVersion < 34 && newVersion >= 34) {
 478            db.execSQL(CREATE_MESSAGE_TIME_INDEX);
 479
 480            final File oldPicturesDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Conversations/");
 481            final File oldFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/");
 482            final File newFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Files/");
 483            final File newVideosDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Videos/");
 484            if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
 485                final File newPicturesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Images/");
 486                newPicturesDirectory.getParentFile().mkdirs();
 487                if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
 488                    Log.d(Config.LOGTAG, "moved " + oldPicturesDirectory.getAbsolutePath() + " to " + newPicturesDirectory.getAbsolutePath());
 489                }
 490            }
 491            if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
 492                newFilesDirectory.mkdirs();
 493                newVideosDirectory.mkdirs();
 494                final File[] files = oldFilesDirectory.listFiles();
 495                if (files == null) {
 496                    return;
 497                }
 498                for (File file : files) {
 499                    if (file.getName().equals(".nomedia")) {
 500                        if (file.delete()) {
 501                            Log.d(Config.LOGTAG, "deleted nomedia file in " + oldFilesDirectory.getAbsolutePath());
 502                        }
 503                    } else if (file.isFile()) {
 504                        final String name = file.getName();
 505                        boolean isVideo = false;
 506                        int start = name.lastIndexOf('.') + 1;
 507                        if (start < name.length()) {
 508                            String mime = MimeUtils.guessMimeTypeFromExtension(name.substring(start));
 509                            isVideo = mime != null && mime.startsWith("video/");
 510                        }
 511                        File dst = new File((isVideo ? newVideosDirectory : newFilesDirectory).getAbsolutePath() + "/" + file.getName());
 512                        if (file.renameTo(dst)) {
 513                            Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
 514                        }
 515                    }
 516                }
 517            }
 518        }
 519        if (oldVersion < 35 && newVersion >= 35) {
 520            db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
 521        }
 522        if (oldVersion < 36 && newVersion >= 36) {
 523            List<Account> accounts = getAccounts(db);
 524            for (Account account : accounts) {
 525                account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
 526                account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
 527                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 528                        + "=?", new String[]{account.getUuid()});
 529            }
 530        }
 531
 532        if (oldVersion < 37 && newVersion >= 37) {
 533            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ_BY_MARKERS + " TEXT");
 534        }
 535
 536        if (oldVersion < 38 && newVersion >= 38) {
 537            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0");
 538        }
 539
 540        if (oldVersion < 39 && newVersion >= 39) {
 541            db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
 542        }
 543
 544        if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
 545            List<Account> accounts = getAccounts(db);
 546            for (Account account : accounts) {
 547                account.setOption(Account.OPTION_MAGIC_CREATE, true);
 548                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 549                        + "=?", new String[]{account.getUuid()});
 550            }
 551        }
 552
 553        if (oldVersion < 44 && newVersion >= 44) {
 554            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.DELETED + " NUMBER DEFAULT 0");
 555            db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
 556            db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
 557            db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
 558        }
 559
 560        if (oldVersion < 45 && newVersion >= 45) {
 561            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.BODY_LANGUAGE);
 562        }
 563
 564        if (oldVersion < 46 && newVersion >= 46) {
 565            final long start = SystemClock.elapsedRealtime();
 566            db.rawQuery("PRAGMA secure_delete = FALSE", null).close();
 567            db.execSQL("update " + Message.TABLENAME + " set " + Message.EDITED + "=NULL");
 568            db.rawQuery("PRAGMA secure_delete=ON", null).close();
 569            final long diff = SystemClock.elapsedRealtime() - start;
 570            Log.d(Config.LOGTAG, "deleted old edit information in " + diff + "ms");
 571        }
 572        if (oldVersion < 47 && newVersion >= 47) {
 573            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.PRESENCE_NAME + " TEXT");
 574        }
 575        if (oldVersion < 48 && newVersion >= 48) {
 576            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.RTP_CAPABILITY + " TEXT");
 577        }
 578        if (oldVersion < 49 && newVersion >= 49) {
 579            db.beginTransaction();
 580            db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
 581            db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
 582            db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
 583            db.execSQL("DROP TABLE IF EXISTS messages_index;");
 584            // a hack that should not be necessary, but
 585            // there was at least one occurence when SQLite failed at this
 586            db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
 587            db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
 588            db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
 589            db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
 590            db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 591            db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 592            db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 593            db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
 594            db.setTransactionSuccessful();
 595            db.endTransaction();
 596            requiresMessageIndexRebuild = true;
 597        }
 598        if (oldVersion < 50 && newVersion >= 50) {
 599            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PINNED_MECHANISM + " TEXT");
 600            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PINNED_CHANNEL_BINDING + " TEXT");
 601        }
 602        if (oldVersion < 51 && newVersion >= 51) {
 603            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.FAST_MECHANISM + " TEXT");
 604            db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.FAST_TOKEN + " TEXT");
 605        }
 606        if (oldVersion < 52 && newVersion >= 52) {
 607            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OCCUPANT_ID + " TEXT");
 608            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.REACTIONS + " TEXT");
 609        }
 610    }
 611
 612    private void canonicalizeJids(SQLiteDatabase db) {
 613        // migrate db to new, canonicalized JID domainpart representation
 614
 615        // Conversation table
 616        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 617        while (cursor.moveToNext()) {
 618            String newJid;
 619            try {
 620                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
 621            } catch (IllegalArgumentException ignored) {
 622                Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 623                        + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 624                        + ": " + ignored + ". Skipping...");
 625                continue;
 626            }
 627
 628            final String[] updateArgs = {
 629                    newJid,
 630                    cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 631            };
 632            db.execSQL("update " + Conversation.TABLENAME
 633                    + " set " + Conversation.CONTACTJID + " = ? "
 634                    + " where " + Conversation.UUID + " = ?", updateArgs);
 635        }
 636        cursor.close();
 637
 638        // Contact table
 639        cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 640        while (cursor.moveToNext()) {
 641            String newJid;
 642            try {
 643                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
 644            } catch (final IllegalArgumentException e) {
 645                Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 646                        + cursor.getString(cursor.getColumnIndex(Contact.JID))
 647                        + ":  Skipping...", e);
 648                continue;
 649            }
 650
 651            final String[] updateArgs = {
 652                    newJid,
 653                    cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 654                    cursor.getString(cursor.getColumnIndex(Contact.JID)),
 655            };
 656            db.execSQL("update " + Contact.TABLENAME
 657                    + " set " + Contact.JID + " = ? "
 658                    + " where " + Contact.ACCOUNT + " = ? "
 659                    + " AND " + Contact.JID + " = ?", updateArgs);
 660        }
 661        cursor.close();
 662
 663        // Account table
 664        cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 665        while (cursor.moveToNext()) {
 666            String newServer;
 667            try {
 668                newServer = Jid.of(
 669                        cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 670                        cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 671                        null
 672                ).getDomain().toEscapedString();
 673            } catch (IllegalArgumentException ignored) {
 674                Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 675                        + cursor.getString(cursor.getColumnIndex(Account.SERVER))
 676                        + ": " + ignored + ". Skipping...");
 677                continue;
 678            }
 679
 680            String[] updateArgs = {
 681                    newServer,
 682                    cursor.getString(cursor.getColumnIndex(Account.UUID)),
 683            };
 684            db.execSQL("update " + Account.TABLENAME
 685                    + " set " + Account.SERVER + " = ? "
 686                    + " where " + Account.UUID + " = ?", updateArgs);
 687        }
 688        cursor.close();
 689    }
 690
 691    public void createConversation(Conversation conversation) {
 692        SQLiteDatabase db = this.getWritableDatabase();
 693        db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 694    }
 695
 696    public void createMessage(Message message) {
 697        SQLiteDatabase db = this.getWritableDatabase();
 698        db.insert(Message.TABLENAME, null, message.getContentValues());
 699    }
 700
 701    public void createAccount(Account account) {
 702        SQLiteDatabase db = this.getWritableDatabase();
 703        db.insert(Account.TABLENAME, null, account.getContentValues());
 704    }
 705
 706    public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 707        SQLiteDatabase db = this.getWritableDatabase();
 708        db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 709    }
 710
 711    public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 712        SQLiteDatabase db = this.getReadableDatabase();
 713        String[] selectionArgs = {hash, ver};
 714        Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 715                ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 716                selectionArgs, null, null, null);
 717        if (cursor.getCount() == 0) {
 718            cursor.close();
 719            return null;
 720        }
 721        cursor.moveToFirst();
 722
 723        ServiceDiscoveryResult result = null;
 724        try {
 725            result = new ServiceDiscoveryResult(cursor);
 726        } catch (JSONException e) { /* result is still null */ }
 727
 728        cursor.close();
 729        return result;
 730    }
 731
 732    public void saveResolverResult(String domain, Resolver.Result result) {
 733        SQLiteDatabase db = this.getWritableDatabase();
 734        ContentValues contentValues = result.toContentValues();
 735        contentValues.put(Resolver.Result.DOMAIN, domain);
 736        db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
 737    }
 738
 739    public synchronized Resolver.Result findResolverResult(String domain) {
 740        SQLiteDatabase db = this.getReadableDatabase();
 741        String where = Resolver.Result.DOMAIN + "=?";
 742        String[] whereArgs = {domain};
 743        final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
 744        Resolver.Result result = null;
 745        if (cursor != null) {
 746            try {
 747                if (cursor.moveToFirst()) {
 748                    result = Resolver.Result.fromCursor(cursor);
 749                }
 750            } catch (Exception e) {
 751                Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
 752                return null;
 753            } finally {
 754                cursor.close();
 755            }
 756        }
 757        return result;
 758    }
 759
 760    public void insertPresenceTemplate(PresenceTemplate template) {
 761        SQLiteDatabase db = this.getWritableDatabase();
 762        String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 763        String[] whereToDeleteArgs = {template.getStatusMessage()};
 764        db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 765        db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 766        db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 767    }
 768
 769    public List<PresenceTemplate> getPresenceTemplates() {
 770        ArrayList<PresenceTemplate> templates = new ArrayList<>();
 771        SQLiteDatabase db = this.getReadableDatabase();
 772        Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 773        while (cursor.moveToNext()) {
 774            templates.add(PresenceTemplate.fromCursor(cursor));
 775        }
 776        cursor.close();
 777        return templates;
 778    }
 779
 780    public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 781        CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 782        SQLiteDatabase db = this.getReadableDatabase();
 783        String[] selectionArgs = {Integer.toString(status)};
 784        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 785                + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
 786                + Conversation.CREATED + " desc", selectionArgs);
 787        while (cursor.moveToNext()) {
 788            final Conversation conversation = Conversation.fromCursor(cursor);
 789            if (conversation.getJid() instanceof InvalidJid) {
 790                continue;
 791            }
 792            list.add(conversation);
 793        }
 794        cursor.close();
 795        return list;
 796    }
 797
 798    public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 799        return getMessages(conversations, limit, -1);
 800    }
 801
 802    public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
 803        ArrayList<Message> list = new ArrayList<>();
 804        SQLiteDatabase db = this.getReadableDatabase();
 805        Cursor cursor;
 806        if (timestamp == -1) {
 807            String[] selectionArgs = {conversation.getUuid()};
 808            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 809                    + "=?", selectionArgs, null, null, Message.TIME_SENT
 810                    + " DESC", String.valueOf(limit));
 811        } else {
 812            String[] selectionArgs = {conversation.getUuid(),
 813                    Long.toString(timestamp)};
 814            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 815                            + "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 816                    null, null, Message.TIME_SENT + " DESC",
 817                    String.valueOf(limit));
 818        }
 819        CursorUtils.upgradeCursorWindowSize(cursor);
 820        while (cursor.moveToNext()) {
 821            try {
 822                list.add(0, Message.fromCursor(cursor, conversation));
 823            } catch (Exception e) {
 824                Log.e(Config.LOGTAG, "unable to restore message");
 825            }
 826        }
 827        cursor.close();
 828        return list;
 829    }
 830
 831    public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
 832        final SQLiteDatabase db = this.getReadableDatabase();
 833        final StringBuilder SQL = new StringBuilder();
 834        final String[] selectionArgs;
 835        SQL.append("SELECT " + Message.TABLENAME + ".*," + Conversation.TABLENAME + "." + Conversation.CONTACTJID + "," + Conversation.TABLENAME + "." + Conversation.ACCOUNT + "," + Conversation.TABLENAME + "." + Conversation.MODE + " FROM " + Message.TABLENAME + " JOIN " + Conversation.TABLENAME + " ON " + Message.TABLENAME + "." + Message.CONVERSATION + "=" + Conversation.TABLENAME + "." + Conversation.UUID + " JOIN messages_index ON messages_index.rowid=messages.rowid WHERE " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + "," + Message.ENCRYPTION_PGP + "," + Message.ENCRYPTION_DECRYPTION_FAILED + "," + Message.ENCRYPTION_AXOLOTL_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + "," + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ?");
 836        if (uuid == null) {
 837            selectionArgs = new String[]{FtsUtils.toMatchString(term)};
 838        } else {
 839            selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
 840            SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
 841        }
 842        SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
 843        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
 844        return db.rawQuery(SQL.toString(), selectionArgs);
 845    }
 846
 847    public List<String> markFileAsDeleted(final File file, final boolean internal) {
 848        SQLiteDatabase db = this.getReadableDatabase();
 849        String selection;
 850        String[] selectionArgs;
 851        if (internal) {
 852            final String name = file.getName();
 853            if (name.endsWith(".pgp")) {
 854                selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
 855                selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
 856            } else {
 857                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
 858                selectionArgs = new String[]{file.getAbsolutePath(), name};
 859            }
 860        } else {
 861            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
 862            selectionArgs = new String[]{file.getAbsolutePath()};
 863        }
 864        final List<String> uuids = new ArrayList<>();
 865        Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
 866        while (cursor != null && cursor.moveToNext()) {
 867            uuids.add(cursor.getString(0));
 868        }
 869        if (cursor != null) {
 870            cursor.close();
 871        }
 872        markFileAsDeleted(uuids);
 873        return uuids;
 874    }
 875
 876    public void markFileAsDeleted(List<String> uuids) {
 877        SQLiteDatabase db = this.getReadableDatabase();
 878        final ContentValues contentValues = new ContentValues();
 879        final String where = Message.UUID + "=?";
 880        contentValues.put(Message.DELETED, 1);
 881        db.beginTransaction();
 882        for (String uuid : uuids) {
 883            db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
 884        }
 885        db.setTransactionSuccessful();
 886        db.endTransaction();
 887    }
 888
 889    public void markFilesAsChanged(List<FilePathInfo> files) {
 890        SQLiteDatabase db = this.getReadableDatabase();
 891        final String where = Message.UUID + "=?";
 892        db.beginTransaction();
 893        for (FilePathInfo info : files) {
 894            final ContentValues contentValues = new ContentValues();
 895            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
 896            db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
 897        }
 898        db.setTransactionSuccessful();
 899        db.endTransaction();
 900    }
 901
 902    public List<FilePathInfo> getFilePathInfo() {
 903        final SQLiteDatabase db = this.getReadableDatabase();
 904        final Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID, Message.RELATIVE_FILE_PATH, Message.DELETED}, "type in (1,2,5) and " + Message.RELATIVE_FILE_PATH + " is not null", null, null, null, null);
 905        final List<FilePathInfo> list = new ArrayList<>();
 906        while (cursor != null && cursor.moveToNext()) {
 907            list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
 908        }
 909        if (cursor != null) {
 910            cursor.close();
 911        }
 912        return list;
 913    }
 914
 915    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
 916        SQLiteDatabase db = this.getReadableDatabase();
 917        final String SQL = "select uuid,relativeFilePath from messages where type in (1,2,5) and deleted=0 and " + Message.RELATIVE_FILE_PATH + " is not null and conversationUuid=(select uuid from conversations where accountUuid=? and (contactJid=? or contactJid like ?)) order by timeSent desc";
 918        final String[] args = {account, jid.toString(), jid.toString() + "/%"};
 919        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
 920        List<FilePath> filesPaths = new ArrayList<>();
 921        while (cursor.moveToNext()) {
 922            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
 923        }
 924        cursor.close();
 925        return filesPaths;
 926    }
 927
 928    public static class FilePath {
 929        public final UUID uuid;
 930        public final String path;
 931
 932        private FilePath(String uuid, String path) {
 933            this.uuid = UUID.fromString(uuid);
 934            this.path = path;
 935        }
 936    }
 937
 938    public static class FilePathInfo extends FilePath {
 939        public boolean deleted;
 940
 941        private FilePathInfo(String uuid, String path, boolean deleted) {
 942            super(uuid, path);
 943            this.deleted = deleted;
 944        }
 945
 946        public boolean setDeleted(boolean deleted) {
 947            final boolean changed = deleted != this.deleted;
 948            this.deleted = deleted;
 949            return changed;
 950        }
 951    }
 952
 953    public Conversation findConversation(final Account account, final Jid contactJid) {
 954        SQLiteDatabase db = this.getReadableDatabase();
 955        String[] selectionArgs = {account.getUuid(),
 956                contactJid.asBareJid().toString() + "/%",
 957                contactJid.asBareJid().toString()
 958        };
 959        try(final Cursor cursor = db.query(Conversation.TABLENAME, null,
 960                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 961                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null)) {
 962            if (cursor.getCount() == 0) {
 963                return null;
 964            }
 965            cursor.moveToFirst();
 966            final Conversation conversation = Conversation.fromCursor(cursor);
 967            if (conversation.getJid() instanceof InvalidJid) {
 968                return null;
 969            }
 970            return conversation;
 971        }
 972    }
 973
 974    public void updateConversation(final Conversation conversation) {
 975        final SQLiteDatabase db = this.getWritableDatabase();
 976        final String[] args = {conversation.getUuid()};
 977        db.update(Conversation.TABLENAME, conversation.getContentValues(),
 978                Conversation.UUID + "=?", args);
 979    }
 980
 981    public List<Account> getAccounts() {
 982        SQLiteDatabase db = this.getReadableDatabase();
 983        return getAccounts(db);
 984    }
 985
 986    public List<Jid> getAccountJids(final boolean enabledOnly) {
 987        final SQLiteDatabase db = this.getReadableDatabase();
 988        final List<Jid> jids = new ArrayList<>();
 989        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 990        final String where = enabledOnly ? "not options & (1 <<1)" : null;
 991        try (final Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
 992            while (cursor != null && cursor.moveToNext()) {
 993                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 994            }
 995        } catch (final Exception e) {
 996            return jids;
 997        }
 998        return jids;
 999    }
1000
1001    private List<Account> getAccounts(SQLiteDatabase db) {
1002        final List<Account> list = new ArrayList<>();
1003        try (final Cursor cursor =
1004                db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1005            while (cursor != null && cursor.moveToNext()) {
1006                list.add(Account.fromCursor(cursor));
1007            }
1008        }
1009        return list;
1010    }
1011
1012    public boolean updateAccount(Account account) {
1013        final var db = this.getWritableDatabase();
1014        final String[] args = {account.getUuid()};
1015        final int rows =
1016                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1017        return rows == 1;
1018    }
1019
1020    public boolean deleteAccount(final Account account) {
1021        final var db = this.getWritableDatabase();
1022        final String[] args = {account.getUuid()};
1023        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1024        return rows == 1;
1025    }
1026
1027    public boolean updateMessage(final Message message, final boolean includeBody) {
1028        final var db = this.getWritableDatabase();
1029        final String[] args = {message.getUuid()};
1030        final var contentValues = message.getContentValues();
1031        contentValues.remove(Message.UUID);
1032        if (!includeBody) {
1033            contentValues.remove(Message.BODY);
1034        }
1035        final int rows = db.update(Message.TABLENAME, contentValues, Message.UUID + "=?", args);
1036        return rows == 1;
1037    }
1038
1039    public boolean updateMessage(final Message message, final String uuid) {
1040        final var db = this.getWritableDatabase();
1041        final String[] args = {uuid};
1042        final int rows =
1043                db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args);
1044        return rows == 1;
1045    }
1046
1047    public void readRoster(Roster roster) {
1048        final SQLiteDatabase db = this.getReadableDatabase();
1049        final String[] args = {roster.getAccount().getUuid()};
1050        try (final Cursor cursor =
1051                db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1052            while (cursor.moveToNext()) {
1053                roster.initContact(Contact.fromCursor(cursor));
1054            }
1055        }
1056    }
1057
1058    public void writeRoster(final Roster roster) {
1059        long start = SystemClock.elapsedRealtime();
1060        final Account account = roster.getAccount();
1061        final SQLiteDatabase db = this.getWritableDatabase();
1062        db.beginTransaction();
1063        for (Contact contact : roster.getContacts()) {
1064            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1065                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1066            } else {
1067                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1068                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1069                db.delete(Contact.TABLENAME, where, whereArgs);
1070            }
1071        }
1072        db.setTransactionSuccessful();
1073        db.endTransaction();
1074        account.setRosterVersion(roster.getVersion());
1075        updateAccount(account);
1076        long duration = SystemClock.elapsedRealtime() - start;
1077        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1078    }
1079
1080    public void deleteMessagesInConversation(Conversation conversation) {
1081        long start = SystemClock.elapsedRealtime();
1082        final SQLiteDatabase db = this.getWritableDatabase();
1083        db.beginTransaction();
1084        final String[] args = {conversation.getUuid()};
1085        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1086        db.setTransactionSuccessful();
1087        db.endTransaction();
1088        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1089    }
1090
1091    public void expireOldMessages(long timestamp) {
1092        final String[] args = {String.valueOf(timestamp)};
1093        SQLiteDatabase db = this.getReadableDatabase();
1094        db.beginTransaction();
1095        db.delete(Message.TABLENAME, "timeSent<?", args);
1096        db.setTransactionSuccessful();
1097        db.endTransaction();
1098    }
1099
1100    public MamReference getLastMessageReceived(Account account) {
1101        Cursor cursor = null;
1102        try {
1103            SQLiteDatabase db = this.getReadableDatabase();
1104            String sql = "select messages.timeSent,messages.serverMsgId from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and (messages.status=0 or messages.carbon=1 or messages.serverMsgId not null) and (conversations.mode=0 or (messages.serverMsgId not null and messages.type=4)) order by messages.timesent desc limit 1";
1105            String[] args = {account.getUuid()};
1106            cursor = db.rawQuery(sql, args);
1107            if (cursor.getCount() == 0) {
1108                return null;
1109            } else {
1110                cursor.moveToFirst();
1111                return new MamReference(cursor.getLong(0), cursor.getString(1));
1112            }
1113        } catch (Exception e) {
1114            return null;
1115        } finally {
1116            if (cursor != null) {
1117                cursor.close();
1118            }
1119        }
1120    }
1121
1122    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1123        String SQL = "select messages.timeSent from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and messages.axolotl_fingerprint=? order by messages.timesent desc limit 1";
1124        String[] args = {account.getUuid(), fingerprint};
1125        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1126        long time;
1127        if (cursor.moveToFirst()) {
1128            time = cursor.getLong(0);
1129        } else {
1130            time = 0;
1131        }
1132        cursor.close();
1133        return time;
1134    }
1135
1136    public MamReference getLastClearDate(Account account) {
1137        SQLiteDatabase db = this.getReadableDatabase();
1138        String[] columns = {Conversation.ATTRIBUTES};
1139        String selection = Conversation.ACCOUNT + "=?";
1140        String[] args = {account.getUuid()};
1141        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1142        MamReference maxClearDate = new MamReference(0);
1143        while (cursor.moveToNext()) {
1144            try {
1145                final JSONObject o = new JSONObject(cursor.getString(0));
1146                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1147            } catch (Exception e) {
1148                //ignored
1149            }
1150        }
1151        cursor.close();
1152        return maxClearDate;
1153    }
1154
1155    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1156        final SQLiteDatabase db = this.getReadableDatabase();
1157        String[] selectionArgs = {account.getUuid(),
1158                contact.getName(),
1159                Integer.toString(contact.getDeviceId())};
1160        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1161                null,
1162                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1163                        + SQLiteAxolotlStore.NAME + " = ? AND "
1164                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1165                selectionArgs,
1166                null, null, null);
1167    }
1168
1169    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1170        SessionRecord session = null;
1171        Cursor cursor = getCursorForSession(account, contact);
1172        if (cursor.getCount() != 0) {
1173            cursor.moveToFirst();
1174            try {
1175                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1176            } catch (IOException e) {
1177                cursor.close();
1178                throw new AssertionError(e);
1179            }
1180        }
1181        cursor.close();
1182        return session;
1183    }
1184
1185    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1186        final SQLiteDatabase db = this.getReadableDatabase();
1187        return getSubDeviceSessions(db, account, contact);
1188    }
1189
1190    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1191        List<Integer> devices = new ArrayList<>();
1192        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1193        String[] selectionArgs = {account.getUuid(),
1194                contact.getName()};
1195        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1196                columns,
1197                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1198                        + SQLiteAxolotlStore.NAME + " = ?",
1199                selectionArgs,
1200                null, null, null);
1201
1202        while (cursor.moveToNext()) {
1203            devices.add(cursor.getInt(
1204                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1205        }
1206
1207        cursor.close();
1208        return devices;
1209    }
1210
1211    public List<String> getKnownSignalAddresses(Account account) {
1212        List<String> addresses = new ArrayList<>();
1213        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1214        String[] selectionArgs = {account.getUuid()};
1215        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1216                colums,
1217                SQLiteAxolotlStore.ACCOUNT + " = ?",
1218                selectionArgs,
1219                null, null, null
1220        );
1221        while (cursor.moveToNext()) {
1222            addresses.add(cursor.getString(0));
1223        }
1224        cursor.close();
1225        return addresses;
1226    }
1227
1228    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1229        Cursor cursor = getCursorForSession(account, contact);
1230        int count = cursor.getCount();
1231        cursor.close();
1232        return count != 0;
1233    }
1234
1235    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1236        SQLiteDatabase db = this.getWritableDatabase();
1237        ContentValues values = new ContentValues();
1238        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1239        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1240        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1241        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1242        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1243    }
1244
1245    public void deleteSession(Account account, SignalProtocolAddress contact) {
1246        SQLiteDatabase db = this.getWritableDatabase();
1247        deleteSession(db, account, contact);
1248    }
1249
1250    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1251        String[] args = {account.getUuid(),
1252                contact.getName(),
1253                Integer.toString(contact.getDeviceId())};
1254        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1255                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1256                        + SQLiteAxolotlStore.NAME + " = ? AND "
1257                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1258                args);
1259    }
1260
1261    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1262        SQLiteDatabase db = this.getWritableDatabase();
1263        String[] args = {account.getUuid(), contact.getName()};
1264        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1265                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1266                        + SQLiteAxolotlStore.NAME + " = ?",
1267                args);
1268    }
1269
1270    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1271        SQLiteDatabase db = this.getReadableDatabase();
1272        String[] columns = {SQLiteAxolotlStore.KEY};
1273        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1274        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1275                columns,
1276                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1277                        + SQLiteAxolotlStore.ID + "=?",
1278                selectionArgs,
1279                null, null, null);
1280
1281        return cursor;
1282    }
1283
1284    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1285        PreKeyRecord record = null;
1286        Cursor cursor = getCursorForPreKey(account, preKeyId);
1287        if (cursor.getCount() != 0) {
1288            cursor.moveToFirst();
1289            try {
1290                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1291            } catch (IOException e) {
1292                throw new AssertionError(e);
1293            }
1294        }
1295        cursor.close();
1296        return record;
1297    }
1298
1299    public boolean containsPreKey(Account account, int preKeyId) {
1300        Cursor cursor = getCursorForPreKey(account, preKeyId);
1301        int count = cursor.getCount();
1302        cursor.close();
1303        return count != 0;
1304    }
1305
1306    public void storePreKey(Account account, PreKeyRecord record) {
1307        SQLiteDatabase db = this.getWritableDatabase();
1308        ContentValues values = new ContentValues();
1309        values.put(SQLiteAxolotlStore.ID, record.getId());
1310        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1311        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1312        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1313    }
1314
1315    public int deletePreKey(Account account, int preKeyId) {
1316        SQLiteDatabase db = this.getWritableDatabase();
1317        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1318        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1319                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1320                        + SQLiteAxolotlStore.ID + "=?",
1321                args);
1322    }
1323
1324    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1325        SQLiteDatabase db = this.getReadableDatabase();
1326        String[] columns = {SQLiteAxolotlStore.KEY};
1327        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1328        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1329                columns,
1330                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1331                selectionArgs,
1332                null, null, null);
1333
1334        return cursor;
1335    }
1336
1337    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1338        SignedPreKeyRecord record = null;
1339        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1340        if (cursor.getCount() != 0) {
1341            cursor.moveToFirst();
1342            try {
1343                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1344            } catch (IOException e) {
1345                throw new AssertionError(e);
1346            }
1347        }
1348        cursor.close();
1349        return record;
1350    }
1351
1352    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1353        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1354        SQLiteDatabase db = this.getReadableDatabase();
1355        String[] columns = {SQLiteAxolotlStore.KEY};
1356        String[] selectionArgs = {account.getUuid()};
1357        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1358                columns,
1359                SQLiteAxolotlStore.ACCOUNT + "=?",
1360                selectionArgs,
1361                null, null, null);
1362
1363        while (cursor.moveToNext()) {
1364            try {
1365                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1366            } catch (IOException ignored) {
1367            }
1368        }
1369        cursor.close();
1370        return prekeys;
1371    }
1372
1373    public int getSignedPreKeysCount(Account account) {
1374        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1375        String[] selectionArgs = {account.getUuid()};
1376        SQLiteDatabase db = this.getReadableDatabase();
1377        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1378                columns,
1379                SQLiteAxolotlStore.ACCOUNT + "=?",
1380                selectionArgs,
1381                null, null, null);
1382        final int count;
1383        if (cursor.moveToFirst()) {
1384            count = cursor.getInt(0);
1385        } else {
1386            count = 0;
1387        }
1388        cursor.close();
1389        return count;
1390    }
1391
1392    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1393        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1394        int count = cursor.getCount();
1395        cursor.close();
1396        return count != 0;
1397    }
1398
1399    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1400        SQLiteDatabase db = this.getWritableDatabase();
1401        ContentValues values = new ContentValues();
1402        values.put(SQLiteAxolotlStore.ID, record.getId());
1403        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1404        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1405        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1406    }
1407
1408    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1409        SQLiteDatabase db = this.getWritableDatabase();
1410        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1411        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1412                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1413                        + SQLiteAxolotlStore.ID + "=?",
1414                args);
1415    }
1416
1417    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1418        final SQLiteDatabase db = this.getReadableDatabase();
1419        return getIdentityKeyCursor(db, account, name, own);
1420    }
1421
1422    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1423        return getIdentityKeyCursor(db, account, name, own, null);
1424    }
1425
1426    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1427        final SQLiteDatabase db = this.getReadableDatabase();
1428        return getIdentityKeyCursor(db, account, fingerprint);
1429    }
1430
1431    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1432        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1433    }
1434
1435    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1436        String[] columns = {SQLiteAxolotlStore.TRUST,
1437                SQLiteAxolotlStore.ACTIVE,
1438                SQLiteAxolotlStore.LAST_ACTIVATION,
1439                SQLiteAxolotlStore.KEY};
1440        ArrayList<String> selectionArgs = new ArrayList<>(4);
1441        selectionArgs.add(account.getUuid());
1442        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1443        if (name != null) {
1444            selectionArgs.add(name);
1445            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1446        }
1447        if (fingerprint != null) {
1448            selectionArgs.add(fingerprint);
1449            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1450        }
1451        if (own != null) {
1452            selectionArgs.add(own ? "1" : "0");
1453            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1454        }
1455        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1456                columns,
1457                selectionString,
1458                selectionArgs.toArray(new String[selectionArgs.size()]),
1459                null, null, null);
1460
1461        return cursor;
1462    }
1463
1464    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1465        SQLiteDatabase db = getReadableDatabase();
1466        return loadOwnIdentityKeyPair(db, account);
1467    }
1468
1469    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1470        String name = account.getJid().asBareJid().toString();
1471        IdentityKeyPair identityKeyPair = null;
1472        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1473        if (cursor.getCount() != 0) {
1474            cursor.moveToFirst();
1475            try {
1476                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1477            } catch (InvalidKeyException e) {
1478                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1479            }
1480        }
1481        cursor.close();
1482
1483        return identityKeyPair;
1484    }
1485
1486    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1487        return loadIdentityKeys(account, name, null);
1488    }
1489
1490    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1491        Set<IdentityKey> identityKeys = new HashSet<>();
1492        Cursor cursor = getIdentityKeyCursor(account, name, false);
1493
1494        while (cursor.moveToNext()) {
1495            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1496                continue;
1497            }
1498            try {
1499                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1500                if (key != null) {
1501                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1502                } else {
1503                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1504                }
1505            } catch (InvalidKeyException e) {
1506                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1507            }
1508        }
1509        cursor.close();
1510
1511        return identityKeys;
1512    }
1513
1514    public long numTrustedKeys(Account account, String name) {
1515        SQLiteDatabase db = getReadableDatabase();
1516        String[] args = {
1517                account.getUuid(),
1518                name,
1519                FingerprintStatus.Trust.TRUSTED.toString(),
1520                FingerprintStatus.Trust.VERIFIED.toString(),
1521                FingerprintStatus.Trust.VERIFIED_X509.toString()
1522        };
1523        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1524                SQLiteAxolotlStore.ACCOUNT + " = ?"
1525                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1526                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1527                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1528                args
1529        );
1530    }
1531
1532    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1533        SQLiteDatabase db = this.getWritableDatabase();
1534        ContentValues values = new ContentValues();
1535        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1536        values.put(SQLiteAxolotlStore.NAME, name);
1537        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1538        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1539        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1540        values.putAll(status.toContentValues());
1541        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1542        String[] whereArgs = {account.getUuid(), name, fingerprint};
1543        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1544        if (rows == 0) {
1545            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1546        }
1547    }
1548
1549    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1550        SQLiteDatabase db = this.getWritableDatabase();
1551        ContentValues values = new ContentValues();
1552        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1553        values.put(SQLiteAxolotlStore.NAME, name);
1554        values.put(SQLiteAxolotlStore.OWN, 0);
1555        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1556        values.putAll(status.toContentValues());
1557        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1558    }
1559
1560    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1561        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1562        final FingerprintStatus status;
1563        if (cursor.getCount() > 0) {
1564            cursor.moveToFirst();
1565            status = FingerprintStatus.fromCursor(cursor);
1566        } else {
1567            status = null;
1568        }
1569        cursor.close();
1570        return status;
1571    }
1572
1573    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1574        SQLiteDatabase db = this.getWritableDatabase();
1575        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1576    }
1577
1578    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1579        String[] selectionArgs = {
1580                account.getUuid(),
1581                fingerprint
1582        };
1583        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1584                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1585                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1586                selectionArgs);
1587        return rows == 1;
1588    }
1589
1590    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1591        SQLiteDatabase db = this.getWritableDatabase();
1592        String[] selectionArgs = {
1593                account.getUuid(),
1594                fingerprint
1595        };
1596        try {
1597            ContentValues values = new ContentValues();
1598            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1599            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1600                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1601                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1602                    selectionArgs) == 1;
1603        } catch (CertificateEncodingException e) {
1604            Log.d(Config.LOGTAG, "could not encode certificate");
1605            return false;
1606        }
1607    }
1608
1609    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1610        SQLiteDatabase db = this.getReadableDatabase();
1611        String[] selectionArgs = {
1612                account.getUuid(),
1613                fingerprint
1614        };
1615        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1616        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1617        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1618        if (cursor.getCount() < 1) {
1619            return null;
1620        } else {
1621            cursor.moveToFirst();
1622            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1623            cursor.close();
1624            if (certificate == null || certificate.length == 0) {
1625                return null;
1626            }
1627            try {
1628                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1629                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1630            } catch (CertificateException e) {
1631                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1632                return null;
1633            }
1634        }
1635    }
1636
1637    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1638        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1639    }
1640
1641    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1642        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1643    }
1644
1645
1646    private void recreateAxolotlDb(SQLiteDatabase db) {
1647        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1648        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1649        db.execSQL(CREATE_SESSIONS_STATEMENT);
1650        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1651        db.execSQL(CREATE_PREKEYS_STATEMENT);
1652        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1653        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1654        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1655        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1656    }
1657
1658    public void wipeAxolotlDb(Account account) {
1659        String accountName = account.getUuid();
1660        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1661        SQLiteDatabase db = this.getWritableDatabase();
1662        String[] deleteArgs = {
1663                accountName
1664        };
1665        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1666                SQLiteAxolotlStore.ACCOUNT + " = ?",
1667                deleteArgs);
1668        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1669                SQLiteAxolotlStore.ACCOUNT + " = ?",
1670                deleteArgs);
1671        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1672                SQLiteAxolotlStore.ACCOUNT + " = ?",
1673                deleteArgs);
1674        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1675                SQLiteAxolotlStore.ACCOUNT + " = ?",
1676                deleteArgs);
1677    }
1678
1679    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1680        SQLiteDatabase db = this.getReadableDatabase();
1681        final String SQL = "select " + Conversation.TABLENAME + "." + Conversation.ACCOUNT + "," + Conversation.TABLENAME + "." + Conversation.CONTACTJID + " from " + Conversation.TABLENAME + " join " + Message.TABLENAME + " on conversations.uuid=messages.conversationUuid where messages.status!=0 and carbon==0  and conversations.mode=0 and messages.timeSent>=? group by conversations.uuid order by count(body) desc limit 4;";
1682        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1683        Cursor cursor = db.rawQuery(SQL, whereArgs);
1684        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1685        while (cursor.moveToNext()) {
1686            try {
1687                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1688            } catch (Exception e) {
1689                Log.d(Config.LOGTAG, e.getMessage());
1690            }
1691        }
1692        cursor.close();
1693        return contacts;
1694    }
1695}