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)";
 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)";
 819                selectionArgs = new String[]{file.getAbsolutePath(), name};
 820            }
 821        } else {
 822            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2)";
 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 List<FilePath> getAllNonDeletedFilePath() {
 851        final SQLiteDatabase db = this.getReadableDatabase();
 852        final Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID, Message.RELATIVE_FILE_PATH}, "type in (1,2) and deleted=0 and "+Message.RELATIVE_FILE_PATH+" is not null", null, null, null, null);
 853        final List<FilePath> list = new ArrayList<>();
 854        while (cursor != null && cursor.moveToNext()) {
 855            list.add(new FilePath(cursor.getString(0), cursor.getString(1)));
 856        }
 857        if (cursor != null) {
 858            cursor.close();
 859        }
 860        return list;
 861    }
 862
 863    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
 864        SQLiteDatabase db = this.getReadableDatabase();
 865        final String SQL = "select uuid,relativeFilePath from messages where type in (1,2) 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";
 866        final String[] args = {account, jid.toEscapedString(), jid.toEscapedString() + "/%"};
 867        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + String.valueOf(limit) : ""), args);
 868        List<FilePath> filesPaths = new ArrayList<>();
 869        while (cursor.moveToNext()) {
 870            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
 871        }
 872        cursor.close();
 873        return filesPaths;
 874    }
 875
 876    public static class FilePath {
 877        public final UUID uuid;
 878        public final String path;
 879
 880        private FilePath(String uuid, String path) {
 881            this.uuid = UUID.fromString(uuid);
 882            this.path = path;
 883        }
 884    }
 885
 886    public Conversation findConversation(final Account account, final Jid contactJid) {
 887        SQLiteDatabase db = this.getReadableDatabase();
 888        String[] selectionArgs = {account.getUuid(),
 889                contactJid.asBareJid().toString() + "/%",
 890                contactJid.asBareJid().toString()
 891        };
 892        Cursor cursor = db.query(Conversation.TABLENAME, null,
 893                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 894                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 895        if (cursor.getCount() == 0) {
 896            cursor.close();
 897            return null;
 898        }
 899        cursor.moveToFirst();
 900        Conversation conversation = Conversation.fromCursor(cursor);
 901        cursor.close();
 902        if (conversation.getJid() instanceof InvalidJid) {
 903            return null;
 904        }
 905        return conversation;
 906    }
 907
 908    public void updateConversation(final Conversation conversation) {
 909        final SQLiteDatabase db = this.getWritableDatabase();
 910        final String[] args = {conversation.getUuid()};
 911        db.update(Conversation.TABLENAME, conversation.getContentValues(),
 912                Conversation.UUID + "=?", args);
 913    }
 914
 915    public List<Account> getAccounts() {
 916        SQLiteDatabase db = this.getReadableDatabase();
 917        return getAccounts(db);
 918    }
 919
 920    public List<Jid> getAccountJids(final boolean enabledOnly) {
 921        SQLiteDatabase db = this.getReadableDatabase();
 922        final List<Jid> jids = new ArrayList<>();
 923        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 924        String where = enabledOnly ? "not options & (1 <<1)" : null;
 925        Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
 926        try {
 927            while (cursor.moveToNext()) {
 928                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 929            }
 930            return jids;
 931        } catch (Exception e) {
 932            return jids;
 933        } finally {
 934            if (cursor != null) {
 935                cursor.close();
 936            }
 937        }
 938    }
 939
 940    private List<Account> getAccounts(SQLiteDatabase db) {
 941        List<Account> list = new ArrayList<>();
 942        Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 943                null, null);
 944        while (cursor.moveToNext()) {
 945            list.add(Account.fromCursor(cursor));
 946        }
 947        cursor.close();
 948        return list;
 949    }
 950
 951    public boolean updateAccount(Account account) {
 952        SQLiteDatabase db = this.getWritableDatabase();
 953        String[] args = {account.getUuid()};
 954        final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 955        return rows == 1;
 956    }
 957
 958    public boolean deleteAccount(Account account) {
 959        SQLiteDatabase db = this.getWritableDatabase();
 960        String[] args = {account.getUuid()};
 961        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 962        return rows == 1;
 963    }
 964
 965    public boolean updateMessage(Message message, boolean includeBody) {
 966        SQLiteDatabase db = this.getWritableDatabase();
 967        String[] args = {message.getUuid()};
 968        ContentValues contentValues = message.getContentValues();
 969        contentValues.remove(Message.UUID);
 970        if (!includeBody) {
 971            contentValues.remove(Message.BODY);
 972        }
 973        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
 974    }
 975
 976    public boolean updateMessage(Message message, String uuid) {
 977        SQLiteDatabase db = this.getWritableDatabase();
 978        String[] args = {uuid};
 979        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
 980    }
 981
 982    public void readRoster(Roster roster) {
 983        SQLiteDatabase db = this.getReadableDatabase();
 984        Cursor cursor;
 985        String args[] = {roster.getAccount().getUuid()};
 986        cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 987        while (cursor.moveToNext()) {
 988            roster.initContact(Contact.fromCursor(cursor));
 989        }
 990        cursor.close();
 991    }
 992
 993    public void writeRoster(final Roster roster) {
 994        long start = SystemClock.elapsedRealtime();
 995        final Account account = roster.getAccount();
 996        final SQLiteDatabase db = this.getWritableDatabase();
 997        db.beginTransaction();
 998        for (Contact contact : roster.getContacts()) {
 999            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.getAvatarFilename() != null || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1000                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1001            } else {
1002                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1003                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1004                db.delete(Contact.TABLENAME, where, whereArgs);
1005            }
1006        }
1007        db.setTransactionSuccessful();
1008        db.endTransaction();
1009        account.setRosterVersion(roster.getVersion());
1010        updateAccount(account);
1011        long duration = SystemClock.elapsedRealtime() - start;
1012        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1013    }
1014
1015    public void deleteMessagesInConversation(Conversation conversation) {
1016        long start = SystemClock.elapsedRealtime();
1017        final SQLiteDatabase db = this.getWritableDatabase();
1018        db.beginTransaction();
1019        String[] args = {conversation.getUuid()};
1020        db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
1021        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1022        db.setTransactionSuccessful();
1023        db.endTransaction();
1024        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1025    }
1026
1027    public void expireOldMessages(long timestamp) {
1028        final String[] args = {String.valueOf(timestamp)};
1029        SQLiteDatabase db = this.getReadableDatabase();
1030        db.beginTransaction();
1031        db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
1032        db.delete(Message.TABLENAME, "timeSent<?", args);
1033        db.setTransactionSuccessful();
1034        db.endTransaction();
1035    }
1036
1037    public MamReference getLastMessageReceived(Account account) {
1038        Cursor cursor = null;
1039        try {
1040            SQLiteDatabase db = this.getReadableDatabase();
1041            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";
1042            String[] args = {account.getUuid()};
1043            cursor = db.rawQuery(sql, args);
1044            if (cursor.getCount() == 0) {
1045                return null;
1046            } else {
1047                cursor.moveToFirst();
1048                return new MamReference(cursor.getLong(0), cursor.getString(1));
1049            }
1050        } catch (Exception e) {
1051            return null;
1052        } finally {
1053            if (cursor != null) {
1054                cursor.close();
1055            }
1056        }
1057    }
1058
1059    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1060        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";
1061        String[] args = {account.getUuid(), fingerprint};
1062        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1063        long time;
1064        if (cursor.moveToFirst()) {
1065            time = cursor.getLong(0);
1066        } else {
1067            time = 0;
1068        }
1069        cursor.close();
1070        return time;
1071    }
1072
1073    public MamReference getLastClearDate(Account account) {
1074        SQLiteDatabase db = this.getReadableDatabase();
1075        String[] columns = {Conversation.ATTRIBUTES};
1076        String selection = Conversation.ACCOUNT + "=?";
1077        String[] args = {account.getUuid()};
1078        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1079        MamReference maxClearDate = new MamReference(0);
1080        while (cursor.moveToNext()) {
1081            try {
1082                final JSONObject o = new JSONObject(cursor.getString(0));
1083                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1084            } catch (Exception e) {
1085                //ignored
1086            }
1087        }
1088        cursor.close();
1089        return maxClearDate;
1090    }
1091
1092    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1093        final SQLiteDatabase db = this.getReadableDatabase();
1094        String[] selectionArgs = {account.getUuid(),
1095                contact.getName(),
1096                Integer.toString(contact.getDeviceId())};
1097        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1098                null,
1099                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1100                        + SQLiteAxolotlStore.NAME + " = ? AND "
1101                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1102                selectionArgs,
1103                null, null, null);
1104    }
1105
1106    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1107        SessionRecord session = null;
1108        Cursor cursor = getCursorForSession(account, contact);
1109        if (cursor.getCount() != 0) {
1110            cursor.moveToFirst();
1111            try {
1112                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1113            } catch (IOException e) {
1114                cursor.close();
1115                throw new AssertionError(e);
1116            }
1117        }
1118        cursor.close();
1119        return session;
1120    }
1121
1122    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1123        final SQLiteDatabase db = this.getReadableDatabase();
1124        return getSubDeviceSessions(db, account, contact);
1125    }
1126
1127    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1128        List<Integer> devices = new ArrayList<>();
1129        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1130        String[] selectionArgs = {account.getUuid(),
1131                contact.getName()};
1132        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1133                columns,
1134                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1135                        + SQLiteAxolotlStore.NAME + " = ?",
1136                selectionArgs,
1137                null, null, null);
1138
1139        while (cursor.moveToNext()) {
1140            devices.add(cursor.getInt(
1141                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1142        }
1143
1144        cursor.close();
1145        return devices;
1146    }
1147
1148    public List<String> getKnownSignalAddresses(Account account) {
1149        List<String> addresses = new ArrayList<>();
1150        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1151        String[] selectionArgs = {account.getUuid()};
1152        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1153                colums,
1154                SQLiteAxolotlStore.ACCOUNT + " = ?",
1155                selectionArgs,
1156                null, null, null
1157        );
1158        while (cursor.moveToNext()) {
1159            addresses.add(cursor.getString(0));
1160        }
1161        cursor.close();
1162        return addresses;
1163    }
1164
1165    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1166        Cursor cursor = getCursorForSession(account, contact);
1167        int count = cursor.getCount();
1168        cursor.close();
1169        return count != 0;
1170    }
1171
1172    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1173        SQLiteDatabase db = this.getWritableDatabase();
1174        ContentValues values = new ContentValues();
1175        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1176        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1177        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1178        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1179        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1180    }
1181
1182    public void deleteSession(Account account, SignalProtocolAddress contact) {
1183        SQLiteDatabase db = this.getWritableDatabase();
1184        deleteSession(db, account, contact);
1185    }
1186
1187    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1188        String[] args = {account.getUuid(),
1189                contact.getName(),
1190                Integer.toString(contact.getDeviceId())};
1191        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1192                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1193                        + SQLiteAxolotlStore.NAME + " = ? AND "
1194                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1195                args);
1196    }
1197
1198    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1199        SQLiteDatabase db = this.getWritableDatabase();
1200        String[] args = {account.getUuid(), contact.getName()};
1201        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1202                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1203                        + SQLiteAxolotlStore.NAME + " = ?",
1204                args);
1205    }
1206
1207    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1208        SQLiteDatabase db = this.getReadableDatabase();
1209        String[] columns = {SQLiteAxolotlStore.KEY};
1210        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1211        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1212                columns,
1213                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1214                        + SQLiteAxolotlStore.ID + "=?",
1215                selectionArgs,
1216                null, null, null);
1217
1218        return cursor;
1219    }
1220
1221    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1222        PreKeyRecord record = null;
1223        Cursor cursor = getCursorForPreKey(account, preKeyId);
1224        if (cursor.getCount() != 0) {
1225            cursor.moveToFirst();
1226            try {
1227                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1228            } catch (IOException e) {
1229                throw new AssertionError(e);
1230            }
1231        }
1232        cursor.close();
1233        return record;
1234    }
1235
1236    public boolean containsPreKey(Account account, int preKeyId) {
1237        Cursor cursor = getCursorForPreKey(account, preKeyId);
1238        int count = cursor.getCount();
1239        cursor.close();
1240        return count != 0;
1241    }
1242
1243    public void storePreKey(Account account, PreKeyRecord record) {
1244        SQLiteDatabase db = this.getWritableDatabase();
1245        ContentValues values = new ContentValues();
1246        values.put(SQLiteAxolotlStore.ID, record.getId());
1247        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1248        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1249        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1250    }
1251
1252    public int deletePreKey(Account account, int preKeyId) {
1253        SQLiteDatabase db = this.getWritableDatabase();
1254        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1255        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1256                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1257                        + SQLiteAxolotlStore.ID + "=?",
1258                args);
1259    }
1260
1261    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1262        SQLiteDatabase db = this.getReadableDatabase();
1263        String[] columns = {SQLiteAxolotlStore.KEY};
1264        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1265        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1266                columns,
1267                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1268                selectionArgs,
1269                null, null, null);
1270
1271        return cursor;
1272    }
1273
1274    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1275        SignedPreKeyRecord record = null;
1276        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1277        if (cursor.getCount() != 0) {
1278            cursor.moveToFirst();
1279            try {
1280                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1281            } catch (IOException e) {
1282                throw new AssertionError(e);
1283            }
1284        }
1285        cursor.close();
1286        return record;
1287    }
1288
1289    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1290        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1291        SQLiteDatabase db = this.getReadableDatabase();
1292        String[] columns = {SQLiteAxolotlStore.KEY};
1293        String[] selectionArgs = {account.getUuid()};
1294        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1295                columns,
1296                SQLiteAxolotlStore.ACCOUNT + "=?",
1297                selectionArgs,
1298                null, null, null);
1299
1300        while (cursor.moveToNext()) {
1301            try {
1302                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1303            } catch (IOException ignored) {
1304            }
1305        }
1306        cursor.close();
1307        return prekeys;
1308    }
1309
1310    public int getSignedPreKeysCount(Account account) {
1311        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1312        String[] selectionArgs = {account.getUuid()};
1313        SQLiteDatabase db = this.getReadableDatabase();
1314        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1315                columns,
1316                SQLiteAxolotlStore.ACCOUNT + "=?",
1317                selectionArgs,
1318                null, null, null);
1319        final int count;
1320        if (cursor.moveToFirst()) {
1321            count = cursor.getInt(0);
1322        } else {
1323            count = 0;
1324        }
1325        cursor.close();
1326        return count;
1327    }
1328
1329    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1330        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1331        int count = cursor.getCount();
1332        cursor.close();
1333        return count != 0;
1334    }
1335
1336    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1337        SQLiteDatabase db = this.getWritableDatabase();
1338        ContentValues values = new ContentValues();
1339        values.put(SQLiteAxolotlStore.ID, record.getId());
1340        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1341        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1342        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1343    }
1344
1345    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1346        SQLiteDatabase db = this.getWritableDatabase();
1347        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1348        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1349                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1350                        + SQLiteAxolotlStore.ID + "=?",
1351                args);
1352    }
1353
1354    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1355        final SQLiteDatabase db = this.getReadableDatabase();
1356        return getIdentityKeyCursor(db, account, name, own);
1357    }
1358
1359    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1360        return getIdentityKeyCursor(db, account, name, own, null);
1361    }
1362
1363    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1364        final SQLiteDatabase db = this.getReadableDatabase();
1365        return getIdentityKeyCursor(db, account, fingerprint);
1366    }
1367
1368    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1369        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1370    }
1371
1372    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1373        String[] columns = {SQLiteAxolotlStore.TRUST,
1374                SQLiteAxolotlStore.ACTIVE,
1375                SQLiteAxolotlStore.LAST_ACTIVATION,
1376                SQLiteAxolotlStore.KEY};
1377        ArrayList<String> selectionArgs = new ArrayList<>(4);
1378        selectionArgs.add(account.getUuid());
1379        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1380        if (name != null) {
1381            selectionArgs.add(name);
1382            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1383        }
1384        if (fingerprint != null) {
1385            selectionArgs.add(fingerprint);
1386            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1387        }
1388        if (own != null) {
1389            selectionArgs.add(own ? "1" : "0");
1390            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1391        }
1392        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1393                columns,
1394                selectionString,
1395                selectionArgs.toArray(new String[selectionArgs.size()]),
1396                null, null, null);
1397
1398        return cursor;
1399    }
1400
1401    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1402        SQLiteDatabase db = getReadableDatabase();
1403        return loadOwnIdentityKeyPair(db, account);
1404    }
1405
1406    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1407        String name = account.getJid().asBareJid().toString();
1408        IdentityKeyPair identityKeyPair = null;
1409        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1410        if (cursor.getCount() != 0) {
1411            cursor.moveToFirst();
1412            try {
1413                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1414            } catch (InvalidKeyException e) {
1415                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1416            }
1417        }
1418        cursor.close();
1419
1420        return identityKeyPair;
1421    }
1422
1423    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1424        return loadIdentityKeys(account, name, null);
1425    }
1426
1427    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1428        Set<IdentityKey> identityKeys = new HashSet<>();
1429        Cursor cursor = getIdentityKeyCursor(account, name, false);
1430
1431        while (cursor.moveToNext()) {
1432            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1433                continue;
1434            }
1435            try {
1436                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1437                if (key != null) {
1438                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1439                } else {
1440                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1441                }
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 identityKeys;
1449    }
1450
1451    public long numTrustedKeys(Account account, String name) {
1452        SQLiteDatabase db = getReadableDatabase();
1453        String[] args = {
1454                account.getUuid(),
1455                name,
1456                FingerprintStatus.Trust.TRUSTED.toString(),
1457                FingerprintStatus.Trust.VERIFIED.toString(),
1458                FingerprintStatus.Trust.VERIFIED_X509.toString()
1459        };
1460        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1461                SQLiteAxolotlStore.ACCOUNT + " = ?"
1462                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1463                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1464                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1465                args
1466        );
1467    }
1468
1469    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1470        SQLiteDatabase db = this.getWritableDatabase();
1471        ContentValues values = new ContentValues();
1472        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1473        values.put(SQLiteAxolotlStore.NAME, name);
1474        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1475        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1476        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1477        values.putAll(status.toContentValues());
1478        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1479        String[] whereArgs = {account.getUuid(), name, fingerprint};
1480        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1481        if (rows == 0) {
1482            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1483        }
1484    }
1485
1486    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1487        SQLiteDatabase db = this.getWritableDatabase();
1488        ContentValues values = new ContentValues();
1489        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1490        values.put(SQLiteAxolotlStore.NAME, name);
1491        values.put(SQLiteAxolotlStore.OWN, 0);
1492        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1493        values.putAll(status.toContentValues());
1494        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1495    }
1496
1497    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1498        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1499        final FingerprintStatus status;
1500        if (cursor.getCount() > 0) {
1501            cursor.moveToFirst();
1502            status = FingerprintStatus.fromCursor(cursor);
1503        } else {
1504            status = null;
1505        }
1506        cursor.close();
1507        return status;
1508    }
1509
1510    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1511        SQLiteDatabase db = this.getWritableDatabase();
1512        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1513    }
1514
1515    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1516        String[] selectionArgs = {
1517                account.getUuid(),
1518                fingerprint
1519        };
1520        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1521                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1522                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1523                selectionArgs);
1524        return rows == 1;
1525    }
1526
1527    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1528        SQLiteDatabase db = this.getWritableDatabase();
1529        String[] selectionArgs = {
1530                account.getUuid(),
1531                fingerprint
1532        };
1533        try {
1534            ContentValues values = new ContentValues();
1535            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1536            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1537                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1538                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1539                    selectionArgs) == 1;
1540        } catch (CertificateEncodingException e) {
1541            Log.d(Config.LOGTAG, "could not encode certificate");
1542            return false;
1543        }
1544    }
1545
1546    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1547        SQLiteDatabase db = this.getReadableDatabase();
1548        String[] selectionArgs = {
1549                account.getUuid(),
1550                fingerprint
1551        };
1552        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1553        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1554        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1555        if (cursor.getCount() < 1) {
1556            return null;
1557        } else {
1558            cursor.moveToFirst();
1559            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1560            cursor.close();
1561            if (certificate == null || certificate.length == 0) {
1562                return null;
1563            }
1564            try {
1565                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1566                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1567            } catch (CertificateException e) {
1568                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1569                return null;
1570            }
1571        }
1572    }
1573
1574    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1575        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1576    }
1577
1578    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1579        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1580    }
1581
1582
1583    private void recreateAxolotlDb(SQLiteDatabase db) {
1584        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1585        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1586        db.execSQL(CREATE_SESSIONS_STATEMENT);
1587        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1588        db.execSQL(CREATE_PREKEYS_STATEMENT);
1589        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1590        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1591        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1592        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1593    }
1594
1595    public void wipeAxolotlDb(Account account) {
1596        String accountName = account.getUuid();
1597        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1598        SQLiteDatabase db = this.getWritableDatabase();
1599        String[] deleteArgs = {
1600                accountName
1601        };
1602        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1603                SQLiteAxolotlStore.ACCOUNT + " = ?",
1604                deleteArgs);
1605        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1606                SQLiteAxolotlStore.ACCOUNT + " = ?",
1607                deleteArgs);
1608        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1609                SQLiteAxolotlStore.ACCOUNT + " = ?",
1610                deleteArgs);
1611        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1612                SQLiteAxolotlStore.ACCOUNT + " = ?",
1613                deleteArgs);
1614    }
1615
1616    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1617        SQLiteDatabase db = this.getReadableDatabase();
1618        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;";
1619        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1620        Cursor cursor = db.rawQuery(SQL, whereArgs);
1621        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1622        while (cursor.moveToNext()) {
1623            try {
1624                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1625            } catch (Exception e) {
1626                Log.d(Config.LOGTAG, e.getMessage());
1627            }
1628        }
1629        cursor.close();
1630        return contacts;
1631    }
1632}