DatabaseBackend.java

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