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