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