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.Collections;
  32import java.util.HashMap;
  33import java.util.HashSet;
  34import java.util.Iterator;
  35import java.util.List;
  36import java.util.Map;
  37import java.util.Set;
  38import java.util.UUID;
  39import java.util.concurrent.CopyOnWriteArrayList;
  40
  41import org.json.JSONException;
  42
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  45import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  46import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
  47import eu.siacs.conversations.entities.Account;
  48import eu.siacs.conversations.entities.Contact;
  49import eu.siacs.conversations.entities.Conversation;
  50import eu.siacs.conversations.entities.Message;
  51import eu.siacs.conversations.entities.PresenceTemplate;
  52import eu.siacs.conversations.entities.Roster;
  53import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  54import eu.siacs.conversations.services.QuickConversationsService;
  55import eu.siacs.conversations.services.ShortcutService;
  56import eu.siacs.conversations.utils.CryptoHelper;
  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.mam.MamReference;
  62import rocks.xmpp.addr.Jid;
  63
  64public class DatabaseBackend extends SQLiteOpenHelper {
  65
  66    private static final String DATABASE_NAME = "history";
  67    private static final int DATABASE_VERSION = 44;
  68    private static DatabaseBackend instance = null;
  69    private static String CREATE_CONTATCS_STATEMENT = "create table "
  70            + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
  71            + Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
  72            + Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
  73            + Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
  74            + Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
  75            + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
  76            + Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
  77            + Account.TABLENAME + "(" + Account.UUID
  78            + ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
  79            + Contact.JID + ") ON CONFLICT REPLACE);";
  80
  81    private static String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
  82            + ServiceDiscoveryResult.TABLENAME + "("
  83            + ServiceDiscoveryResult.HASH + " TEXT, "
  84            + ServiceDiscoveryResult.VER + " TEXT, "
  85            + ServiceDiscoveryResult.RESULT + " TEXT, "
  86            + "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
  87            + ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
  88
  89    private static String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
  90            + PresenceTemplate.TABELNAME + "("
  91            + PresenceTemplate.UUID + " TEXT, "
  92            + PresenceTemplate.LAST_USED + " NUMBER,"
  93            + PresenceTemplate.MESSAGE + " TEXT,"
  94            + PresenceTemplate.STATUS + " TEXT,"
  95            + "UNIQUE(" + PresenceTemplate.MESSAGE + "," + PresenceTemplate.STATUS + ") ON CONFLICT REPLACE);";
  96
  97    private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
  98            + SQLiteAxolotlStore.PREKEY_TABLENAME + "("
  99            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 100            + SQLiteAxolotlStore.ID + " INTEGER, "
 101            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 102            + SQLiteAxolotlStore.ACCOUNT
 103            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 104            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 105            + SQLiteAxolotlStore.ID
 106            + ") ON CONFLICT REPLACE"
 107            + ");";
 108
 109    private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
 110            + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
 111            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 112            + SQLiteAxolotlStore.ID + " INTEGER, "
 113            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 114            + SQLiteAxolotlStore.ACCOUNT
 115            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 116            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 117            + SQLiteAxolotlStore.ID
 118            + ") ON CONFLICT REPLACE" +
 119            ");";
 120
 121    private static String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
 122            + SQLiteAxolotlStore.SESSION_TABLENAME + "("
 123            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 124            + SQLiteAxolotlStore.NAME + " TEXT, "
 125            + SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
 126            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 127            + SQLiteAxolotlStore.ACCOUNT
 128            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 129            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 130            + SQLiteAxolotlStore.NAME + ", "
 131            + SQLiteAxolotlStore.DEVICE_ID
 132            + ") ON CONFLICT REPLACE"
 133            + ");";
 134
 135    private static String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
 136            + SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
 137            + SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 138            + SQLiteAxolotlStore.NAME + " TEXT, "
 139            + SQLiteAxolotlStore.OWN + " INTEGER, "
 140            + SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
 141            + SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
 142            + SQLiteAxolotlStore.TRUST + " TEXT, "
 143            + SQLiteAxolotlStore.ACTIVE + " NUMBER, "
 144            + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
 145            + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 146            + SQLiteAxolotlStore.ACCOUNT
 147            + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 148            + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 149            + SQLiteAxolotlStore.NAME + ", "
 150            + SQLiteAxolotlStore.FINGERPRINT
 151            + ") ON CONFLICT IGNORE"
 152            + ");";
 153
 154    private static String RESOLVER_RESULTS_TABLENAME = "resolver_results";
 155
 156    private static String CREATE_RESOLVER_RESULTS_TABLE = "create table " + RESOLVER_RESULTS_TABLENAME + "("
 157            + Resolver.Result.DOMAIN + " TEXT,"
 158            + Resolver.Result.HOSTNAME + " TEXT,"
 159            + Resolver.Result.IP + " BLOB,"
 160            + Resolver.Result.PRIORITY + " NUMBER,"
 161            + Resolver.Result.DIRECT_TLS + " NUMBER,"
 162            + Resolver.Result.AUTHENTICATED + " NUMBER,"
 163            + Resolver.Result.PORT + " NUMBER,"
 164            + "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
 165            + ");";
 166
 167    private static String CREATE_MESSAGE_TIME_INDEX = "create INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
 168    private static String CREATE_MESSAGE_CONVERSATION_INDEX = "create INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
 169    private static String CREATE_MESSAGE_DELETED_INDEX = "create index message_deleted_index ON " + Message.TABLENAME + "(" + Message.DELETED + ")";
 170    private static String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX = "create INDEX message_file_path_index ON " + Message.TABLENAME + "(" + Message.RELATIVE_FILE_PATH + ")";
 171    private static String CREATE_MESSAGE_TYPE_INDEX = "create INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
 172
 173    private static String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING FTS4(uuid TEXT PRIMARY KEY, body TEXT)";
 174    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;";
 175    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;";
 176    private static String COPY_PREEXISTING_ENTRIES = "INSERT into messages_index(uuid,body) select uuid,body FROM " + Message.TABLENAME + ";";
 177
 178    private DatabaseBackend(Context context) {
 179        super(context, DATABASE_NAME, null, DATABASE_VERSION);
 180    }
 181
 182    private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
 183        ContentValues values = new ContentValues();
 184        values.put(SQLiteAxolotlStore.TRUST, trust.toString());
 185        values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
 186        return values;
 187    }
 188
 189    public static synchronized DatabaseBackend getInstance(Context context) {
 190        if (instance == null) {
 191            instance = new DatabaseBackend(context);
 192        }
 193        return instance;
 194    }
 195
 196    @Override
 197    public void onConfigure(SQLiteDatabase db) {
 198        db.execSQL("PRAGMA foreign_keys=ON");
 199        db.rawQuery("PRAGMA secure_delete=ON", null);
 200    }
 201
 202    @Override
 203    public void onCreate(SQLiteDatabase db) {
 204        db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID + " TEXT PRIMARY KEY,"
 205                + Account.USERNAME + " TEXT,"
 206                + Account.SERVER + " TEXT,"
 207                + Account.PASSWORD + " TEXT,"
 208                + Account.DISPLAY_NAME + " TEXT, "
 209                + Account.STATUS + " TEXT,"
 210                + Account.STATUS_MESSAGE + " TEXT,"
 211                + Account.ROSTERVERSION + " TEXT,"
 212                + Account.OPTIONS + " NUMBER, "
 213                + Account.AVATAR + " TEXT, "
 214                + Account.KEYS + " TEXT, "
 215                + Account.HOSTNAME + " TEXT, "
 216                + Account.RESOURCE + " TEXT,"
 217                + Account.PORT + " NUMBER DEFAULT 5222)");
 218        db.execSQL("create table " + Conversation.TABLENAME + " ("
 219                + Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
 220                + " TEXT, " + Conversation.CONTACT + " TEXT, "
 221                + Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
 222                + " TEXT, " + Conversation.CREATED + " NUMBER, "
 223                + Conversation.STATUS + " NUMBER, " + Conversation.MODE
 224                + " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
 225                + Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
 226                + "(" + Account.UUID + ") ON DELETE CASCADE);");
 227        db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
 228                + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
 229                + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
 230                + " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
 231                + Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
 232                + Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
 233                + Message.RELATIVE_FILE_PATH + " TEXT, "
 234                + Message.SERVER_MSG_ID + " TEXT, "
 235                + Message.FINGERPRINT + " TEXT, "
 236                + Message.CARBON + " INTEGER, "
 237                + Message.EDITED + " TEXT, "
 238                + Message.READ + " NUMBER DEFAULT 1, "
 239                + Message.OOB + " INTEGER, "
 240                + Message.ERROR_MESSAGE + " TEXT,"
 241                + Message.READ_BY_MARKERS + " TEXT,"
 242                + Message.MARKABLE + " NUMBER DEFAULT 0,"
 243                + Message.DELETED + " NUMBER DEFAULT 0,"
 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
 547    private void canonicalizeJids(SQLiteDatabase db) {
 548        // migrate db to new, canonicalized JID domainpart representation
 549
 550        // Conversation table
 551        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 552        while (cursor.moveToNext()) {
 553            String newJid;
 554            try {
 555                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
 556            } catch (IllegalArgumentException ignored) {
 557                Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 558                        + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 559                        + ": " + ignored + ". Skipping...");
 560                continue;
 561            }
 562
 563            String updateArgs[] = {
 564                    newJid,
 565                    cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 566            };
 567            db.execSQL("update " + Conversation.TABLENAME
 568                    + " set " + Conversation.CONTACTJID + " = ? "
 569                    + " where " + Conversation.UUID + " = ?", updateArgs);
 570        }
 571        cursor.close();
 572
 573        // Contact table
 574        cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 575        while (cursor.moveToNext()) {
 576            String newJid;
 577            try {
 578                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
 579            } catch (IllegalArgumentException ignored) {
 580                Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 581                        + cursor.getString(cursor.getColumnIndex(Contact.JID))
 582                        + ": " + ignored + ". Skipping...");
 583                continue;
 584            }
 585
 586            String updateArgs[] = {
 587                    newJid,
 588                    cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 589                    cursor.getString(cursor.getColumnIndex(Contact.JID)),
 590            };
 591            db.execSQL("update " + Contact.TABLENAME
 592                    + " set " + Contact.JID + " = ? "
 593                    + " where " + Contact.ACCOUNT + " = ? "
 594                    + " AND " + Contact.JID + " = ?", updateArgs);
 595        }
 596        cursor.close();
 597
 598        // Account table
 599        cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 600        while (cursor.moveToNext()) {
 601            String newServer;
 602            try {
 603                newServer = Jid.of(
 604                        cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 605                        cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 606                        null
 607                ).getDomain();
 608            } catch (IllegalArgumentException ignored) {
 609                Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 610                        + cursor.getString(cursor.getColumnIndex(Account.SERVER))
 611                        + ": " + ignored + ". Skipping...");
 612                continue;
 613            }
 614
 615            String updateArgs[] = {
 616                    newServer,
 617                    cursor.getString(cursor.getColumnIndex(Account.UUID)),
 618            };
 619            db.execSQL("update " + Account.TABLENAME
 620                    + " set " + Account.SERVER + " = ? "
 621                    + " where " + Account.UUID + " = ?", updateArgs);
 622        }
 623        cursor.close();
 624    }
 625
 626    public void createConversation(Conversation conversation) {
 627        SQLiteDatabase db = this.getWritableDatabase();
 628        db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 629    }
 630
 631    public void createMessage(Message message) {
 632        SQLiteDatabase db = this.getWritableDatabase();
 633        db.insert(Message.TABLENAME, null, message.getContentValues());
 634    }
 635
 636    public void createAccount(Account account) {
 637        SQLiteDatabase db = this.getWritableDatabase();
 638        db.insert(Account.TABLENAME, null, account.getContentValues());
 639    }
 640
 641    public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 642        SQLiteDatabase db = this.getWritableDatabase();
 643        db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 644    }
 645
 646    public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 647        SQLiteDatabase db = this.getReadableDatabase();
 648        String[] selectionArgs = {hash, ver};
 649        Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 650                ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 651                selectionArgs, null, null, null);
 652        if (cursor.getCount() == 0) {
 653            cursor.close();
 654            return null;
 655        }
 656        cursor.moveToFirst();
 657
 658        ServiceDiscoveryResult result = null;
 659        try {
 660            result = new ServiceDiscoveryResult(cursor);
 661        } catch (JSONException e) { /* result is still null */ }
 662
 663        cursor.close();
 664        return result;
 665    }
 666
 667    public void saveResolverResult(String domain, Resolver.Result result) {
 668        SQLiteDatabase db = this.getWritableDatabase();
 669        ContentValues contentValues = result.toContentValues();
 670        contentValues.put(Resolver.Result.DOMAIN, domain);
 671        db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
 672    }
 673
 674    public synchronized Resolver.Result findResolverResult(String domain) {
 675        SQLiteDatabase db = this.getReadableDatabase();
 676        String where = Resolver.Result.DOMAIN + "=?";
 677        String[] whereArgs = {domain};
 678        final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
 679        Resolver.Result result = null;
 680        if (cursor != null) {
 681            try {
 682                if (cursor.moveToFirst()) {
 683                    result = Resolver.Result.fromCursor(cursor);
 684                }
 685            } catch (Exception e) {
 686                Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
 687                return null;
 688            } finally {
 689                cursor.close();
 690            }
 691        }
 692        return result;
 693    }
 694
 695    public void insertPresenceTemplate(PresenceTemplate template) {
 696        SQLiteDatabase db = this.getWritableDatabase();
 697        String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 698        String[] whereToDeleteArgs = {template.getStatusMessage()};
 699        db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 700        db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 701        db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 702    }
 703
 704    public List<PresenceTemplate> getPresenceTemplates() {
 705        ArrayList<PresenceTemplate> templates = new ArrayList<>();
 706        SQLiteDatabase db = this.getReadableDatabase();
 707        Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 708        while (cursor.moveToNext()) {
 709            templates.add(PresenceTemplate.fromCursor(cursor));
 710        }
 711        cursor.close();
 712        return templates;
 713    }
 714
 715    public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 716        CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 717        SQLiteDatabase db = this.getReadableDatabase();
 718        String[] selectionArgs = {Integer.toString(status)};
 719        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 720                + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
 721                + Conversation.CREATED + " desc", selectionArgs);
 722        while (cursor.moveToNext()) {
 723            final Conversation conversation = Conversation.fromCursor(cursor);
 724            if (conversation.getJid() instanceof InvalidJid) {
 725                continue;
 726            }
 727            list.add(conversation);
 728        }
 729        cursor.close();
 730        return list;
 731    }
 732
 733    public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 734        return getMessages(conversations, limit, -1);
 735    }
 736
 737    public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
 738        ArrayList<Message> list = new ArrayList<>();
 739        SQLiteDatabase db = this.getReadableDatabase();
 740        Cursor cursor;
 741        if (timestamp == -1) {
 742            String[] selectionArgs = {conversation.getUuid()};
 743            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 744                    + "=?", selectionArgs, null, null, Message.TIME_SENT
 745                    + " DESC", String.valueOf(limit));
 746        } else {
 747            String[] selectionArgs = {conversation.getUuid(),
 748                    Long.toString(timestamp)};
 749            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 750                            + "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 751                    null, null, Message.TIME_SENT + " DESC",
 752                    String.valueOf(limit));
 753        }
 754        if (cursor.getCount() > 0) {
 755            cursor.moveToLast();
 756            do {
 757                Message message = Message.fromCursor(cursor, conversation);
 758                if (message != null) {
 759                    list.add(message);
 760                }
 761            } while (cursor.moveToPrevious());
 762        }
 763        cursor.close();
 764        return list;
 765    }
 766
 767    public Cursor getMessageSearchCursor(List<String> term) {
 768        SQLiteDatabase db = this.getReadableDatabase();
 769        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;
 770        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
 771        return db.rawQuery(SQL, new String[]{FtsUtils.toMatchString(term)});
 772    }
 773
 774    public Iterable<Message> getMessagesIterable(final Conversation conversation) {
 775        return () -> {
 776            class MessageIterator implements Iterator<Message> {
 777                private SQLiteDatabase db = getReadableDatabase();
 778                private String[] selectionArgs = {conversation.getUuid()};
 779                private Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 780                        + "=?", selectionArgs, null, null, Message.TIME_SENT
 781                        + " ASC", null);
 782
 783                private MessageIterator() {
 784                    cursor.moveToFirst();
 785                }
 786
 787                @Override
 788                public boolean hasNext() {
 789                    return !cursor.isAfterLast();
 790                }
 791
 792                @Override
 793                public Message next() {
 794                    Message message = Message.fromCursor(cursor, conversation);
 795                    cursor.moveToNext();
 796                    return message;
 797                }
 798
 799                @Override
 800                public void remove() {
 801                    throw new UnsupportedOperationException();
 802                }
 803            }
 804            return new MessageIterator();
 805        };
 806    }
 807
 808    public List<String> markFileAsDeleted(final File file, final boolean internal) {
 809        SQLiteDatabase db = this.getReadableDatabase();
 810        String selection;
 811        String[] selectionArgs;
 812        if (internal) {
 813            final String name = file.getName();
 814            if (name.endsWith(".pgp")) {
 815                selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
 816                selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
 817            } else {
 818                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
 819                selectionArgs = new String[]{file.getAbsolutePath(), name};
 820            }
 821        } else {
 822            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
 823            selectionArgs = new String[]{file.getAbsolutePath()};
 824        }
 825        final List<String> uuids = new ArrayList<>();
 826        Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
 827        while (cursor != null && cursor.moveToNext()) {
 828            uuids.add(cursor.getString(0));
 829        }
 830        if (cursor != null) {
 831            cursor.close();
 832        }
 833        markFileAsDeleted(uuids);
 834        return uuids;
 835    }
 836
 837    public void markFileAsDeleted(List<String> uuids) {
 838        SQLiteDatabase db = this.getReadableDatabase();
 839        final ContentValues contentValues = new ContentValues();
 840        final String where = Message.UUID + "=?";
 841        contentValues.put(Message.DELETED, 1);
 842        db.beginTransaction();
 843        for (String uuid : uuids) {
 844            db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
 845        }
 846        db.setTransactionSuccessful();
 847        db.endTransaction();
 848    }
 849
 850    public void markFilesAsChanged(List<FilePathInfo> files) {
 851        SQLiteDatabase db = this.getReadableDatabase();
 852        final String where = Message.UUID + "=?";
 853        db.beginTransaction();
 854        for (FilePathInfo info : files) {
 855            final ContentValues contentValues = new ContentValues();
 856            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
 857            db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
 858        }
 859        db.setTransactionSuccessful();
 860        db.endTransaction();
 861    }
 862
 863    public List<FilePathInfo> getFilePathInfo() {
 864        final SQLiteDatabase db = this.getReadableDatabase();
 865        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);
 866        final List<FilePathInfo> list = new ArrayList<>();
 867        while (cursor != null && cursor.moveToNext()) {
 868            list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
 869        }
 870        if (cursor != null) {
 871            cursor.close();
 872        }
 873        return list;
 874    }
 875
 876    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
 877        SQLiteDatabase db = this.getReadableDatabase();
 878        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";
 879        final String[] args = {account, jid.toEscapedString(), jid.toEscapedString() + "/%"};
 880        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + String.valueOf(limit) : ""), args);
 881        List<FilePath> filesPaths = new ArrayList<>();
 882        while (cursor.moveToNext()) {
 883            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
 884        }
 885        cursor.close();
 886        return filesPaths;
 887    }
 888
 889    public static class FilePath {
 890        public final UUID uuid;
 891        public final String path;
 892
 893        private FilePath(String uuid, String path) {
 894            this.uuid = UUID.fromString(uuid);
 895            this.path = path;
 896        }
 897    }
 898
 899    public static class FilePathInfo extends FilePath {
 900        public boolean deleted;
 901
 902        private FilePathInfo(String uuid, String path, boolean deleted) {
 903            super(uuid,path);
 904            this.deleted = deleted;
 905        }
 906
 907        public boolean setDeleted(boolean deleted) {
 908            final boolean changed = deleted != this.deleted;
 909            this.deleted = deleted;
 910            return changed;
 911        }
 912    }
 913
 914    public Conversation findConversation(final Account account, final Jid contactJid) {
 915        SQLiteDatabase db = this.getReadableDatabase();
 916        String[] selectionArgs = {account.getUuid(),
 917                contactJid.asBareJid().toString() + "/%",
 918                contactJid.asBareJid().toString()
 919        };
 920        Cursor cursor = db.query(Conversation.TABLENAME, null,
 921                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 922                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 923        if (cursor.getCount() == 0) {
 924            cursor.close();
 925            return null;
 926        }
 927        cursor.moveToFirst();
 928        Conversation conversation = Conversation.fromCursor(cursor);
 929        cursor.close();
 930        if (conversation.getJid() instanceof InvalidJid) {
 931            return null;
 932        }
 933        return conversation;
 934    }
 935
 936    public void updateConversation(final Conversation conversation) {
 937        final SQLiteDatabase db = this.getWritableDatabase();
 938        final String[] args = {conversation.getUuid()};
 939        db.update(Conversation.TABLENAME, conversation.getContentValues(),
 940                Conversation.UUID + "=?", args);
 941    }
 942
 943    public List<Account> getAccounts() {
 944        SQLiteDatabase db = this.getReadableDatabase();
 945        return getAccounts(db);
 946    }
 947
 948    public List<Jid> getAccountJids(final boolean enabledOnly) {
 949        SQLiteDatabase db = this.getReadableDatabase();
 950        final List<Jid> jids = new ArrayList<>();
 951        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 952        String where = enabledOnly ? "not options & (1 <<1)" : null;
 953        Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
 954        try {
 955            while (cursor.moveToNext()) {
 956                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 957            }
 958            return jids;
 959        } catch (Exception e) {
 960            return jids;
 961        } finally {
 962            if (cursor != null) {
 963                cursor.close();
 964            }
 965        }
 966    }
 967
 968    private List<Account> getAccounts(SQLiteDatabase db) {
 969        List<Account> list = new ArrayList<>();
 970        Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 971                null, null);
 972        while (cursor.moveToNext()) {
 973            list.add(Account.fromCursor(cursor));
 974        }
 975        cursor.close();
 976        return list;
 977    }
 978
 979    public boolean updateAccount(Account account) {
 980        SQLiteDatabase db = this.getWritableDatabase();
 981        String[] args = {account.getUuid()};
 982        final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 983        return rows == 1;
 984    }
 985
 986    public boolean deleteAccount(Account account) {
 987        SQLiteDatabase db = this.getWritableDatabase();
 988        String[] args = {account.getUuid()};
 989        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 990        return rows == 1;
 991    }
 992
 993    public boolean updateMessage(Message message, boolean includeBody) {
 994        SQLiteDatabase db = this.getWritableDatabase();
 995        String[] args = {message.getUuid()};
 996        ContentValues contentValues = message.getContentValues();
 997        contentValues.remove(Message.UUID);
 998        if (!includeBody) {
 999            contentValues.remove(Message.BODY);
1000        }
1001        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
1002    }
1003
1004    public boolean updateMessage(Message message, String uuid) {
1005        SQLiteDatabase db = this.getWritableDatabase();
1006        String[] args = {uuid};
1007        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
1008    }
1009
1010    public void readRoster(Roster roster) {
1011        SQLiteDatabase db = this.getReadableDatabase();
1012        Cursor cursor;
1013        String args[] = {roster.getAccount().getUuid()};
1014        cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
1015        while (cursor.moveToNext()) {
1016            roster.initContact(Contact.fromCursor(cursor));
1017        }
1018        cursor.close();
1019    }
1020
1021    public void writeRoster(final Roster roster) {
1022        long start = SystemClock.elapsedRealtime();
1023        final Account account = roster.getAccount();
1024        final SQLiteDatabase db = this.getWritableDatabase();
1025        db.beginTransaction();
1026        for (Contact contact : roster.getContacts()) {
1027            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.getAvatarFilename() != null || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1028                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1029            } else {
1030                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1031                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1032                db.delete(Contact.TABLENAME, where, whereArgs);
1033            }
1034        }
1035        db.setTransactionSuccessful();
1036        db.endTransaction();
1037        account.setRosterVersion(roster.getVersion());
1038        updateAccount(account);
1039        long duration = SystemClock.elapsedRealtime() - start;
1040        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1041    }
1042
1043    public void deleteMessagesInConversation(Conversation conversation) {
1044        long start = SystemClock.elapsedRealtime();
1045        final SQLiteDatabase db = this.getWritableDatabase();
1046        db.beginTransaction();
1047        String[] args = {conversation.getUuid()};
1048        db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
1049        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1050        db.setTransactionSuccessful();
1051        db.endTransaction();
1052        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1053    }
1054
1055    public void expireOldMessages(long timestamp) {
1056        final String[] args = {String.valueOf(timestamp)};
1057        SQLiteDatabase db = this.getReadableDatabase();
1058        db.beginTransaction();
1059        db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
1060        db.delete(Message.TABLENAME, "timeSent<?", args);
1061        db.setTransactionSuccessful();
1062        db.endTransaction();
1063    }
1064
1065    public MamReference getLastMessageReceived(Account account) {
1066        Cursor cursor = null;
1067        try {
1068            SQLiteDatabase db = this.getReadableDatabase();
1069            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";
1070            String[] args = {account.getUuid()};
1071            cursor = db.rawQuery(sql, args);
1072            if (cursor.getCount() == 0) {
1073                return null;
1074            } else {
1075                cursor.moveToFirst();
1076                return new MamReference(cursor.getLong(0), cursor.getString(1));
1077            }
1078        } catch (Exception e) {
1079            return null;
1080        } finally {
1081            if (cursor != null) {
1082                cursor.close();
1083            }
1084        }
1085    }
1086
1087    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1088        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";
1089        String[] args = {account.getUuid(), fingerprint};
1090        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1091        long time;
1092        if (cursor.moveToFirst()) {
1093            time = cursor.getLong(0);
1094        } else {
1095            time = 0;
1096        }
1097        cursor.close();
1098        return time;
1099    }
1100
1101    public MamReference getLastClearDate(Account account) {
1102        SQLiteDatabase db = this.getReadableDatabase();
1103        String[] columns = {Conversation.ATTRIBUTES};
1104        String selection = Conversation.ACCOUNT + "=?";
1105        String[] args = {account.getUuid()};
1106        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1107        MamReference maxClearDate = new MamReference(0);
1108        while (cursor.moveToNext()) {
1109            try {
1110                final JSONObject o = new JSONObject(cursor.getString(0));
1111                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1112            } catch (Exception e) {
1113                //ignored
1114            }
1115        }
1116        cursor.close();
1117        return maxClearDate;
1118    }
1119
1120    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1121        final SQLiteDatabase db = this.getReadableDatabase();
1122        String[] selectionArgs = {account.getUuid(),
1123                contact.getName(),
1124                Integer.toString(contact.getDeviceId())};
1125        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1126                null,
1127                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1128                        + SQLiteAxolotlStore.NAME + " = ? AND "
1129                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1130                selectionArgs,
1131                null, null, null);
1132    }
1133
1134    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1135        SessionRecord session = null;
1136        Cursor cursor = getCursorForSession(account, contact);
1137        if (cursor.getCount() != 0) {
1138            cursor.moveToFirst();
1139            try {
1140                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1141            } catch (IOException e) {
1142                cursor.close();
1143                throw new AssertionError(e);
1144            }
1145        }
1146        cursor.close();
1147        return session;
1148    }
1149
1150    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1151        final SQLiteDatabase db = this.getReadableDatabase();
1152        return getSubDeviceSessions(db, account, contact);
1153    }
1154
1155    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1156        List<Integer> devices = new ArrayList<>();
1157        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1158        String[] selectionArgs = {account.getUuid(),
1159                contact.getName()};
1160        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1161                columns,
1162                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1163                        + SQLiteAxolotlStore.NAME + " = ?",
1164                selectionArgs,
1165                null, null, null);
1166
1167        while (cursor.moveToNext()) {
1168            devices.add(cursor.getInt(
1169                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1170        }
1171
1172        cursor.close();
1173        return devices;
1174    }
1175
1176    public List<String> getKnownSignalAddresses(Account account) {
1177        List<String> addresses = new ArrayList<>();
1178        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1179        String[] selectionArgs = {account.getUuid()};
1180        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1181                colums,
1182                SQLiteAxolotlStore.ACCOUNT + " = ?",
1183                selectionArgs,
1184                null, null, null
1185        );
1186        while (cursor.moveToNext()) {
1187            addresses.add(cursor.getString(0));
1188        }
1189        cursor.close();
1190        return addresses;
1191    }
1192
1193    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1194        Cursor cursor = getCursorForSession(account, contact);
1195        int count = cursor.getCount();
1196        cursor.close();
1197        return count != 0;
1198    }
1199
1200    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1201        SQLiteDatabase db = this.getWritableDatabase();
1202        ContentValues values = new ContentValues();
1203        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1204        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1205        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1206        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1207        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1208    }
1209
1210    public void deleteSession(Account account, SignalProtocolAddress contact) {
1211        SQLiteDatabase db = this.getWritableDatabase();
1212        deleteSession(db, account, contact);
1213    }
1214
1215    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1216        String[] args = {account.getUuid(),
1217                contact.getName(),
1218                Integer.toString(contact.getDeviceId())};
1219        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1220                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1221                        + SQLiteAxolotlStore.NAME + " = ? AND "
1222                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1223                args);
1224    }
1225
1226    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1227        SQLiteDatabase db = this.getWritableDatabase();
1228        String[] args = {account.getUuid(), contact.getName()};
1229        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1230                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1231                        + SQLiteAxolotlStore.NAME + " = ?",
1232                args);
1233    }
1234
1235    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1236        SQLiteDatabase db = this.getReadableDatabase();
1237        String[] columns = {SQLiteAxolotlStore.KEY};
1238        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1239        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1240                columns,
1241                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1242                        + SQLiteAxolotlStore.ID + "=?",
1243                selectionArgs,
1244                null, null, null);
1245
1246        return cursor;
1247    }
1248
1249    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1250        PreKeyRecord record = null;
1251        Cursor cursor = getCursorForPreKey(account, preKeyId);
1252        if (cursor.getCount() != 0) {
1253            cursor.moveToFirst();
1254            try {
1255                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1256            } catch (IOException e) {
1257                throw new AssertionError(e);
1258            }
1259        }
1260        cursor.close();
1261        return record;
1262    }
1263
1264    public boolean containsPreKey(Account account, int preKeyId) {
1265        Cursor cursor = getCursorForPreKey(account, preKeyId);
1266        int count = cursor.getCount();
1267        cursor.close();
1268        return count != 0;
1269    }
1270
1271    public void storePreKey(Account account, PreKeyRecord record) {
1272        SQLiteDatabase db = this.getWritableDatabase();
1273        ContentValues values = new ContentValues();
1274        values.put(SQLiteAxolotlStore.ID, record.getId());
1275        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1276        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1277        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1278    }
1279
1280    public int deletePreKey(Account account, int preKeyId) {
1281        SQLiteDatabase db = this.getWritableDatabase();
1282        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1283        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1284                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1285                        + SQLiteAxolotlStore.ID + "=?",
1286                args);
1287    }
1288
1289    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1290        SQLiteDatabase db = this.getReadableDatabase();
1291        String[] columns = {SQLiteAxolotlStore.KEY};
1292        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1293        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1294                columns,
1295                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1296                selectionArgs,
1297                null, null, null);
1298
1299        return cursor;
1300    }
1301
1302    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1303        SignedPreKeyRecord record = null;
1304        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1305        if (cursor.getCount() != 0) {
1306            cursor.moveToFirst();
1307            try {
1308                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1309            } catch (IOException e) {
1310                throw new AssertionError(e);
1311            }
1312        }
1313        cursor.close();
1314        return record;
1315    }
1316
1317    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1318        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1319        SQLiteDatabase db = this.getReadableDatabase();
1320        String[] columns = {SQLiteAxolotlStore.KEY};
1321        String[] selectionArgs = {account.getUuid()};
1322        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1323                columns,
1324                SQLiteAxolotlStore.ACCOUNT + "=?",
1325                selectionArgs,
1326                null, null, null);
1327
1328        while (cursor.moveToNext()) {
1329            try {
1330                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1331            } catch (IOException ignored) {
1332            }
1333        }
1334        cursor.close();
1335        return prekeys;
1336    }
1337
1338    public int getSignedPreKeysCount(Account account) {
1339        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1340        String[] selectionArgs = {account.getUuid()};
1341        SQLiteDatabase db = this.getReadableDatabase();
1342        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1343                columns,
1344                SQLiteAxolotlStore.ACCOUNT + "=?",
1345                selectionArgs,
1346                null, null, null);
1347        final int count;
1348        if (cursor.moveToFirst()) {
1349            count = cursor.getInt(0);
1350        } else {
1351            count = 0;
1352        }
1353        cursor.close();
1354        return count;
1355    }
1356
1357    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1358        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1359        int count = cursor.getCount();
1360        cursor.close();
1361        return count != 0;
1362    }
1363
1364    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1365        SQLiteDatabase db = this.getWritableDatabase();
1366        ContentValues values = new ContentValues();
1367        values.put(SQLiteAxolotlStore.ID, record.getId());
1368        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1369        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1370        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1371    }
1372
1373    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1374        SQLiteDatabase db = this.getWritableDatabase();
1375        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1376        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1377                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1378                        + SQLiteAxolotlStore.ID + "=?",
1379                args);
1380    }
1381
1382    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1383        final SQLiteDatabase db = this.getReadableDatabase();
1384        return getIdentityKeyCursor(db, account, name, own);
1385    }
1386
1387    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1388        return getIdentityKeyCursor(db, account, name, own, null);
1389    }
1390
1391    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1392        final SQLiteDatabase db = this.getReadableDatabase();
1393        return getIdentityKeyCursor(db, account, fingerprint);
1394    }
1395
1396    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1397        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1398    }
1399
1400    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1401        String[] columns = {SQLiteAxolotlStore.TRUST,
1402                SQLiteAxolotlStore.ACTIVE,
1403                SQLiteAxolotlStore.LAST_ACTIVATION,
1404                SQLiteAxolotlStore.KEY};
1405        ArrayList<String> selectionArgs = new ArrayList<>(4);
1406        selectionArgs.add(account.getUuid());
1407        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1408        if (name != null) {
1409            selectionArgs.add(name);
1410            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1411        }
1412        if (fingerprint != null) {
1413            selectionArgs.add(fingerprint);
1414            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1415        }
1416        if (own != null) {
1417            selectionArgs.add(own ? "1" : "0");
1418            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1419        }
1420        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1421                columns,
1422                selectionString,
1423                selectionArgs.toArray(new String[selectionArgs.size()]),
1424                null, null, null);
1425
1426        return cursor;
1427    }
1428
1429    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1430        SQLiteDatabase db = getReadableDatabase();
1431        return loadOwnIdentityKeyPair(db, account);
1432    }
1433
1434    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1435        String name = account.getJid().asBareJid().toString();
1436        IdentityKeyPair identityKeyPair = null;
1437        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1438        if (cursor.getCount() != 0) {
1439            cursor.moveToFirst();
1440            try {
1441                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1442            } catch (InvalidKeyException e) {
1443                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1444            }
1445        }
1446        cursor.close();
1447
1448        return identityKeyPair;
1449    }
1450
1451    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1452        return loadIdentityKeys(account, name, null);
1453    }
1454
1455    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1456        Set<IdentityKey> identityKeys = new HashSet<>();
1457        Cursor cursor = getIdentityKeyCursor(account, name, false);
1458
1459        while (cursor.moveToNext()) {
1460            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1461                continue;
1462            }
1463            try {
1464                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1465                if (key != null) {
1466                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1467                } else {
1468                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1469                }
1470            } catch (InvalidKeyException e) {
1471                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1472            }
1473        }
1474        cursor.close();
1475
1476        return identityKeys;
1477    }
1478
1479    public long numTrustedKeys(Account account, String name) {
1480        SQLiteDatabase db = getReadableDatabase();
1481        String[] args = {
1482                account.getUuid(),
1483                name,
1484                FingerprintStatus.Trust.TRUSTED.toString(),
1485                FingerprintStatus.Trust.VERIFIED.toString(),
1486                FingerprintStatus.Trust.VERIFIED_X509.toString()
1487        };
1488        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1489                SQLiteAxolotlStore.ACCOUNT + " = ?"
1490                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1491                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1492                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1493                args
1494        );
1495    }
1496
1497    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1498        SQLiteDatabase db = this.getWritableDatabase();
1499        ContentValues values = new ContentValues();
1500        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1501        values.put(SQLiteAxolotlStore.NAME, name);
1502        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1503        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1504        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1505        values.putAll(status.toContentValues());
1506        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1507        String[] whereArgs = {account.getUuid(), name, fingerprint};
1508        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1509        if (rows == 0) {
1510            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1511        }
1512    }
1513
1514    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1515        SQLiteDatabase db = this.getWritableDatabase();
1516        ContentValues values = new ContentValues();
1517        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1518        values.put(SQLiteAxolotlStore.NAME, name);
1519        values.put(SQLiteAxolotlStore.OWN, 0);
1520        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1521        values.putAll(status.toContentValues());
1522        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1523    }
1524
1525    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1526        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1527        final FingerprintStatus status;
1528        if (cursor.getCount() > 0) {
1529            cursor.moveToFirst();
1530            status = FingerprintStatus.fromCursor(cursor);
1531        } else {
1532            status = null;
1533        }
1534        cursor.close();
1535        return status;
1536    }
1537
1538    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1539        SQLiteDatabase db = this.getWritableDatabase();
1540        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1541    }
1542
1543    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1544        String[] selectionArgs = {
1545                account.getUuid(),
1546                fingerprint
1547        };
1548        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1549                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1550                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1551                selectionArgs);
1552        return rows == 1;
1553    }
1554
1555    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1556        SQLiteDatabase db = this.getWritableDatabase();
1557        String[] selectionArgs = {
1558                account.getUuid(),
1559                fingerprint
1560        };
1561        try {
1562            ContentValues values = new ContentValues();
1563            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1564            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1565                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1566                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1567                    selectionArgs) == 1;
1568        } catch (CertificateEncodingException e) {
1569            Log.d(Config.LOGTAG, "could not encode certificate");
1570            return false;
1571        }
1572    }
1573
1574    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1575        SQLiteDatabase db = this.getReadableDatabase();
1576        String[] selectionArgs = {
1577                account.getUuid(),
1578                fingerprint
1579        };
1580        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1581        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1582        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1583        if (cursor.getCount() < 1) {
1584            return null;
1585        } else {
1586            cursor.moveToFirst();
1587            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1588            cursor.close();
1589            if (certificate == null || certificate.length == 0) {
1590                return null;
1591            }
1592            try {
1593                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1594                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1595            } catch (CertificateException e) {
1596                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1597                return null;
1598            }
1599        }
1600    }
1601
1602    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1603        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1604    }
1605
1606    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1607        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1608    }
1609
1610
1611    private void recreateAxolotlDb(SQLiteDatabase db) {
1612        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1613        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1614        db.execSQL(CREATE_SESSIONS_STATEMENT);
1615        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1616        db.execSQL(CREATE_PREKEYS_STATEMENT);
1617        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1618        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1619        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1620        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1621    }
1622
1623    public void wipeAxolotlDb(Account account) {
1624        String accountName = account.getUuid();
1625        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1626        SQLiteDatabase db = this.getWritableDatabase();
1627        String[] deleteArgs = {
1628                accountName
1629        };
1630        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1631                SQLiteAxolotlStore.ACCOUNT + " = ?",
1632                deleteArgs);
1633        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1634                SQLiteAxolotlStore.ACCOUNT + " = ?",
1635                deleteArgs);
1636        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1637                SQLiteAxolotlStore.ACCOUNT + " = ?",
1638                deleteArgs);
1639        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1640                SQLiteAxolotlStore.ACCOUNT + " = ?",
1641                deleteArgs);
1642    }
1643
1644    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1645        SQLiteDatabase db = this.getReadableDatabase();
1646        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;";
1647        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1648        Cursor cursor = db.rawQuery(SQL, whereArgs);
1649        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1650        while (cursor.moveToNext()) {
1651            try {
1652                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1653            } catch (Exception e) {
1654                Log.d(Config.LOGTAG, e.getMessage());
1655            }
1656        }
1657        cursor.close();
1658        return contacts;
1659    }
1660}