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 (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
 539            List<Account> accounts = getAccounts(db);
 540            for (Account account : accounts) {
 541                account.setOption(Account.OPTION_MAGIC_CREATE, true);
 542                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 543                        + "=?", new String[]{account.getUuid()});
 544            }
 545        }
 546
 547        if (oldVersion < 44 && newVersion >= 44) {
 548            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.DELETED + " NUMBER DEFAULT 0");
 549            db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
 550            db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
 551            db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
 552        }
 553
 554        if (oldVersion < 45 && newVersion >= 45) {
 555            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.BODY_LANGUAGE);
 556        }
 557
 558        if (oldVersion < 46 && newVersion >= 46) {
 559            final long start = SystemClock.elapsedRealtime();
 560            db.rawQuery("PRAGMA secure_delete = FALSE", null).close();
 561            db.execSQL("update " + Message.TABLENAME + " set " + Message.EDITED + "=NULL");
 562            db.rawQuery("PRAGMA secure_delete=ON", null).close();
 563            final long diff = SystemClock.elapsedRealtime() - start;
 564            Log.d(Config.LOGTAG, "deleted old edit information in " + diff + "ms");
 565        }
 566        if (oldVersion < 47 && newVersion >= 47) {
 567            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.PRESENCE_NAME + " TEXT");
 568        }
 569        if (oldVersion < 48 && newVersion >= 48) {
 570            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.RTP_CAPABILITY + " TEXT");
 571        }
 572        if (oldVersion < 49 && newVersion >= 49) {
 573            db.beginTransaction();
 574            db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
 575            db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
 576            db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
 577            db.execSQL("DROP TABLE IF EXISTS messages_index;");
 578            // a hack that should not be necessary, but
 579            // there was at least one occurence when SQLite failed at this
 580            db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
 581            db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
 582            db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
 583            db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
 584            db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 585            db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 586            db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 587            db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
 588            db.setTransactionSuccessful();
 589            db.endTransaction();
 590            requiresMessageIndexRebuild = true;
 591        }
 592    }
 593
 594    private void canonicalizeJids(SQLiteDatabase db) {
 595        // migrate db to new, canonicalized JID domainpart representation
 596
 597        // Conversation table
 598        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 599        while (cursor.moveToNext()) {
 600            String newJid;
 601            try {
 602                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
 603            } catch (IllegalArgumentException ignored) {
 604                Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 605                        + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 606                        + ": " + ignored + ". Skipping...");
 607                continue;
 608            }
 609
 610            final String[] updateArgs = {
 611                    newJid,
 612                    cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 613            };
 614            db.execSQL("update " + Conversation.TABLENAME
 615                    + " set " + Conversation.CONTACTJID + " = ? "
 616                    + " where " + Conversation.UUID + " = ?", updateArgs);
 617        }
 618        cursor.close();
 619
 620        // Contact table
 621        cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 622        while (cursor.moveToNext()) {
 623            String newJid;
 624            try {
 625                newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
 626            } catch (final IllegalArgumentException e) {
 627                Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 628                        + cursor.getString(cursor.getColumnIndex(Contact.JID))
 629                        + ":  Skipping...", e);
 630                continue;
 631            }
 632
 633            final String[] updateArgs = {
 634                    newJid,
 635                    cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 636                    cursor.getString(cursor.getColumnIndex(Contact.JID)),
 637            };
 638            db.execSQL("update " + Contact.TABLENAME
 639                    + " set " + Contact.JID + " = ? "
 640                    + " where " + Contact.ACCOUNT + " = ? "
 641                    + " AND " + Contact.JID + " = ?", updateArgs);
 642        }
 643        cursor.close();
 644
 645        // Account table
 646        cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 647        while (cursor.moveToNext()) {
 648            String newServer;
 649            try {
 650                newServer = Jid.of(
 651                        cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 652                        cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 653                        null
 654                ).getDomain().toEscapedString();
 655            } catch (IllegalArgumentException ignored) {
 656                Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 657                        + cursor.getString(cursor.getColumnIndex(Account.SERVER))
 658                        + ": " + ignored + ". Skipping...");
 659                continue;
 660            }
 661
 662            String[] updateArgs = {
 663                    newServer,
 664                    cursor.getString(cursor.getColumnIndex(Account.UUID)),
 665            };
 666            db.execSQL("update " + Account.TABLENAME
 667                    + " set " + Account.SERVER + " = ? "
 668                    + " where " + Account.UUID + " = ?", updateArgs);
 669        }
 670        cursor.close();
 671    }
 672
 673    public void createConversation(Conversation conversation) {
 674        SQLiteDatabase db = this.getWritableDatabase();
 675        db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 676    }
 677
 678    public void createMessage(Message message) {
 679        SQLiteDatabase db = this.getWritableDatabase();
 680        db.insert(Message.TABLENAME, null, message.getContentValues());
 681    }
 682
 683    public void createAccount(Account account) {
 684        SQLiteDatabase db = this.getWritableDatabase();
 685        db.insert(Account.TABLENAME, null, account.getContentValues());
 686    }
 687
 688    public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 689        SQLiteDatabase db = this.getWritableDatabase();
 690        db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 691    }
 692
 693    public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 694        SQLiteDatabase db = this.getReadableDatabase();
 695        String[] selectionArgs = {hash, ver};
 696        Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 697                ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 698                selectionArgs, null, null, null);
 699        if (cursor.getCount() == 0) {
 700            cursor.close();
 701            return null;
 702        }
 703        cursor.moveToFirst();
 704
 705        ServiceDiscoveryResult result = null;
 706        try {
 707            result = new ServiceDiscoveryResult(cursor);
 708        } catch (JSONException e) { /* result is still null */ }
 709
 710        cursor.close();
 711        return result;
 712    }
 713
 714    public void saveResolverResult(String domain, Resolver.Result result) {
 715        SQLiteDatabase db = this.getWritableDatabase();
 716        ContentValues contentValues = result.toContentValues();
 717        contentValues.put(Resolver.Result.DOMAIN, domain);
 718        db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
 719    }
 720
 721    public synchronized Resolver.Result findResolverResult(String domain) {
 722        SQLiteDatabase db = this.getReadableDatabase();
 723        String where = Resolver.Result.DOMAIN + "=?";
 724        String[] whereArgs = {domain};
 725        final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
 726        Resolver.Result result = null;
 727        if (cursor != null) {
 728            try {
 729                if (cursor.moveToFirst()) {
 730                    result = Resolver.Result.fromCursor(cursor);
 731                }
 732            } catch (Exception e) {
 733                Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
 734                return null;
 735            } finally {
 736                cursor.close();
 737            }
 738        }
 739        return result;
 740    }
 741
 742    public void insertPresenceTemplate(PresenceTemplate template) {
 743        SQLiteDatabase db = this.getWritableDatabase();
 744        String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 745        String[] whereToDeleteArgs = {template.getStatusMessage()};
 746        db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 747        db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 748        db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 749    }
 750
 751    public List<PresenceTemplate> getPresenceTemplates() {
 752        ArrayList<PresenceTemplate> templates = new ArrayList<>();
 753        SQLiteDatabase db = this.getReadableDatabase();
 754        Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 755        while (cursor.moveToNext()) {
 756            templates.add(PresenceTemplate.fromCursor(cursor));
 757        }
 758        cursor.close();
 759        return templates;
 760    }
 761
 762    public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 763        CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 764        SQLiteDatabase db = this.getReadableDatabase();
 765        String[] selectionArgs = {Integer.toString(status)};
 766        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 767                + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
 768                + Conversation.CREATED + " desc", selectionArgs);
 769        while (cursor.moveToNext()) {
 770            final Conversation conversation = Conversation.fromCursor(cursor);
 771            if (conversation.getJid() instanceof InvalidJid) {
 772                continue;
 773            }
 774            list.add(conversation);
 775        }
 776        cursor.close();
 777        return list;
 778    }
 779
 780    public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 781        return getMessages(conversations, limit, -1);
 782    }
 783
 784    public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
 785        ArrayList<Message> list = new ArrayList<>();
 786        SQLiteDatabase db = this.getReadableDatabase();
 787        Cursor cursor;
 788        if (timestamp == -1) {
 789            String[] selectionArgs = {conversation.getUuid()};
 790            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 791                    + "=?", selectionArgs, null, null, Message.TIME_SENT
 792                    + " DESC", String.valueOf(limit));
 793        } else {
 794            String[] selectionArgs = {conversation.getUuid(),
 795                    Long.toString(timestamp)};
 796            cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 797                            + "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 798                    null, null, Message.TIME_SENT + " DESC",
 799                    String.valueOf(limit));
 800        }
 801        CursorUtils.upgradeCursorWindowSize(cursor);
 802        while (cursor.moveToNext()) {
 803            try {
 804                list.add(0, Message.fromCursor(cursor, conversation));
 805            } catch (Exception e) {
 806                Log.e(Config.LOGTAG, "unable to restore message");
 807            }
 808        }
 809        cursor.close();
 810        return list;
 811    }
 812
 813    public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
 814        final SQLiteDatabase db = this.getReadableDatabase();
 815        final StringBuilder SQL = new StringBuilder();
 816        final String[] selectionArgs;
 817        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 ?");
 818        if (uuid == null) {
 819            selectionArgs = new String[]{FtsUtils.toMatchString(term)};
 820        } else {
 821            selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
 822            SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
 823        }
 824        SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
 825        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
 826        return db.rawQuery(SQL.toString(), selectionArgs);
 827    }
 828
 829    public List<String> markFileAsDeleted(final File file, final boolean internal) {
 830        SQLiteDatabase db = this.getReadableDatabase();
 831        String selection;
 832        String[] selectionArgs;
 833        if (internal) {
 834            final String name = file.getName();
 835            if (name.endsWith(".pgp")) {
 836                selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
 837                selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
 838            } else {
 839                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
 840                selectionArgs = new String[]{file.getAbsolutePath(), name};
 841            }
 842        } else {
 843            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
 844            selectionArgs = new String[]{file.getAbsolutePath()};
 845        }
 846        final List<String> uuids = new ArrayList<>();
 847        Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
 848        while (cursor != null && cursor.moveToNext()) {
 849            uuids.add(cursor.getString(0));
 850        }
 851        if (cursor != null) {
 852            cursor.close();
 853        }
 854        markFileAsDeleted(uuids);
 855        return uuids;
 856    }
 857
 858    public void markFileAsDeleted(List<String> uuids) {
 859        SQLiteDatabase db = this.getReadableDatabase();
 860        final ContentValues contentValues = new ContentValues();
 861        final String where = Message.UUID + "=?";
 862        contentValues.put(Message.DELETED, 1);
 863        db.beginTransaction();
 864        for (String uuid : uuids) {
 865            db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
 866        }
 867        db.setTransactionSuccessful();
 868        db.endTransaction();
 869    }
 870
 871    public void markFilesAsChanged(List<FilePathInfo> files) {
 872        SQLiteDatabase db = this.getReadableDatabase();
 873        final String where = Message.UUID + "=?";
 874        db.beginTransaction();
 875        for (FilePathInfo info : files) {
 876            final ContentValues contentValues = new ContentValues();
 877            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
 878            db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
 879        }
 880        db.setTransactionSuccessful();
 881        db.endTransaction();
 882    }
 883
 884    public List<FilePathInfo> getFilePathInfo() {
 885        final SQLiteDatabase db = this.getReadableDatabase();
 886        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);
 887        final List<FilePathInfo> list = new ArrayList<>();
 888        while (cursor != null && cursor.moveToNext()) {
 889            list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
 890        }
 891        if (cursor != null) {
 892            cursor.close();
 893        }
 894        return list;
 895    }
 896
 897    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
 898        SQLiteDatabase db = this.getReadableDatabase();
 899        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";
 900        final String[] args = {account, jid.toString(), jid.toString() + "/%"};
 901        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
 902        List<FilePath> filesPaths = new ArrayList<>();
 903        while (cursor.moveToNext()) {
 904            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
 905        }
 906        cursor.close();
 907        return filesPaths;
 908    }
 909
 910    public static class FilePath {
 911        public final UUID uuid;
 912        public final String path;
 913
 914        private FilePath(String uuid, String path) {
 915            this.uuid = UUID.fromString(uuid);
 916            this.path = path;
 917        }
 918    }
 919
 920    public static class FilePathInfo extends FilePath {
 921        public boolean deleted;
 922
 923        private FilePathInfo(String uuid, String path, boolean deleted) {
 924            super(uuid, path);
 925            this.deleted = deleted;
 926        }
 927
 928        public boolean setDeleted(boolean deleted) {
 929            final boolean changed = deleted != this.deleted;
 930            this.deleted = deleted;
 931            return changed;
 932        }
 933    }
 934
 935    public Conversation findConversation(final Account account, final Jid contactJid) {
 936        SQLiteDatabase db = this.getReadableDatabase();
 937        String[] selectionArgs = {account.getUuid(),
 938                contactJid.asBareJid().toString() + "/%",
 939                contactJid.asBareJid().toString()
 940        };
 941        Cursor cursor = db.query(Conversation.TABLENAME, null,
 942                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 943                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 944        if (cursor.getCount() == 0) {
 945            cursor.close();
 946            return null;
 947        }
 948        cursor.moveToFirst();
 949        Conversation conversation = Conversation.fromCursor(cursor);
 950        cursor.close();
 951        if (conversation.getJid() instanceof InvalidJid) {
 952            return null;
 953        }
 954        return conversation;
 955    }
 956
 957    public void updateConversation(final Conversation conversation) {
 958        final SQLiteDatabase db = this.getWritableDatabase();
 959        final String[] args = {conversation.getUuid()};
 960        db.update(Conversation.TABLENAME, conversation.getContentValues(),
 961                Conversation.UUID + "=?", args);
 962    }
 963
 964    public List<Account> getAccounts() {
 965        SQLiteDatabase db = this.getReadableDatabase();
 966        return getAccounts(db);
 967    }
 968
 969    public List<Jid> getAccountJids(final boolean enabledOnly) {
 970        SQLiteDatabase db = this.getReadableDatabase();
 971        final List<Jid> jids = new ArrayList<>();
 972        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 973        String where = enabledOnly ? "not options & (1 <<1)" : null;
 974        Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
 975        try {
 976            while (cursor.moveToNext()) {
 977                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 978            }
 979            return jids;
 980        } catch (Exception e) {
 981            return jids;
 982        } finally {
 983            if (cursor != null) {
 984                cursor.close();
 985            }
 986        }
 987    }
 988
 989    private List<Account> getAccounts(SQLiteDatabase db) {
 990        List<Account> list = new ArrayList<>();
 991        Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 992                null, null);
 993        while (cursor.moveToNext()) {
 994            list.add(Account.fromCursor(cursor));
 995        }
 996        cursor.close();
 997        return list;
 998    }
 999
1000    public boolean updateAccount(Account account) {
1001        SQLiteDatabase db = this.getWritableDatabase();
1002        String[] args = {account.getUuid()};
1003        final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1004        return rows == 1;
1005    }
1006
1007    public boolean deleteAccount(Account account) {
1008        SQLiteDatabase db = this.getWritableDatabase();
1009        String[] args = {account.getUuid()};
1010        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1011        return rows == 1;
1012    }
1013
1014    public boolean updateMessage(Message message, boolean includeBody) {
1015        SQLiteDatabase db = this.getWritableDatabase();
1016        String[] args = {message.getUuid()};
1017        ContentValues contentValues = message.getContentValues();
1018        contentValues.remove(Message.UUID);
1019        if (!includeBody) {
1020            contentValues.remove(Message.BODY);
1021        }
1022        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
1023    }
1024
1025    public boolean updateMessage(Message message, String uuid) {
1026        SQLiteDatabase db = this.getWritableDatabase();
1027        String[] args = {uuid};
1028        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
1029    }
1030
1031    public void readRoster(Roster roster) {
1032        SQLiteDatabase db = this.getReadableDatabase();
1033        Cursor cursor;
1034        String[] args = {roster.getAccount().getUuid()};
1035        cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
1036        while (cursor.moveToNext()) {
1037            roster.initContact(Contact.fromCursor(cursor));
1038        }
1039        cursor.close();
1040    }
1041
1042    public void writeRoster(final Roster roster) {
1043        long start = SystemClock.elapsedRealtime();
1044        final Account account = roster.getAccount();
1045        final SQLiteDatabase db = this.getWritableDatabase();
1046        db.beginTransaction();
1047        for (Contact contact : roster.getContacts()) {
1048            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1049                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1050            } else {
1051                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1052                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1053                db.delete(Contact.TABLENAME, where, whereArgs);
1054            }
1055        }
1056        db.setTransactionSuccessful();
1057        db.endTransaction();
1058        account.setRosterVersion(roster.getVersion());
1059        updateAccount(account);
1060        long duration = SystemClock.elapsedRealtime() - start;
1061        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1062    }
1063
1064    public void deleteMessagesInConversation(Conversation conversation) {
1065        long start = SystemClock.elapsedRealtime();
1066        final SQLiteDatabase db = this.getWritableDatabase();
1067        db.beginTransaction();
1068        final String[] args = {conversation.getUuid()};
1069        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1070        db.setTransactionSuccessful();
1071        db.endTransaction();
1072        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1073    }
1074
1075    public void expireOldMessages(long timestamp) {
1076        final String[] args = {String.valueOf(timestamp)};
1077        SQLiteDatabase db = this.getReadableDatabase();
1078        db.beginTransaction();
1079        db.delete(Message.TABLENAME, "timeSent<?", args);
1080        db.setTransactionSuccessful();
1081        db.endTransaction();
1082    }
1083
1084    public MamReference getLastMessageReceived(Account account) {
1085        Cursor cursor = null;
1086        try {
1087            SQLiteDatabase db = this.getReadableDatabase();
1088            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";
1089            String[] args = {account.getUuid()};
1090            cursor = db.rawQuery(sql, args);
1091            if (cursor.getCount() == 0) {
1092                return null;
1093            } else {
1094                cursor.moveToFirst();
1095                return new MamReference(cursor.getLong(0), cursor.getString(1));
1096            }
1097        } catch (Exception e) {
1098            return null;
1099        } finally {
1100            if (cursor != null) {
1101                cursor.close();
1102            }
1103        }
1104    }
1105
1106    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1107        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";
1108        String[] args = {account.getUuid(), fingerprint};
1109        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1110        long time;
1111        if (cursor.moveToFirst()) {
1112            time = cursor.getLong(0);
1113        } else {
1114            time = 0;
1115        }
1116        cursor.close();
1117        return time;
1118    }
1119
1120    public MamReference getLastClearDate(Account account) {
1121        SQLiteDatabase db = this.getReadableDatabase();
1122        String[] columns = {Conversation.ATTRIBUTES};
1123        String selection = Conversation.ACCOUNT + "=?";
1124        String[] args = {account.getUuid()};
1125        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1126        MamReference maxClearDate = new MamReference(0);
1127        while (cursor.moveToNext()) {
1128            try {
1129                final JSONObject o = new JSONObject(cursor.getString(0));
1130                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1131            } catch (Exception e) {
1132                //ignored
1133            }
1134        }
1135        cursor.close();
1136        return maxClearDate;
1137    }
1138
1139    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1140        final SQLiteDatabase db = this.getReadableDatabase();
1141        String[] selectionArgs = {account.getUuid(),
1142                contact.getName(),
1143                Integer.toString(contact.getDeviceId())};
1144        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1145                null,
1146                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1147                        + SQLiteAxolotlStore.NAME + " = ? AND "
1148                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1149                selectionArgs,
1150                null, null, null);
1151    }
1152
1153    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1154        SessionRecord session = null;
1155        Cursor cursor = getCursorForSession(account, contact);
1156        if (cursor.getCount() != 0) {
1157            cursor.moveToFirst();
1158            try {
1159                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1160            } catch (IOException e) {
1161                cursor.close();
1162                throw new AssertionError(e);
1163            }
1164        }
1165        cursor.close();
1166        return session;
1167    }
1168
1169    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1170        final SQLiteDatabase db = this.getReadableDatabase();
1171        return getSubDeviceSessions(db, account, contact);
1172    }
1173
1174    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1175        List<Integer> devices = new ArrayList<>();
1176        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1177        String[] selectionArgs = {account.getUuid(),
1178                contact.getName()};
1179        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1180                columns,
1181                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1182                        + SQLiteAxolotlStore.NAME + " = ?",
1183                selectionArgs,
1184                null, null, null);
1185
1186        while (cursor.moveToNext()) {
1187            devices.add(cursor.getInt(
1188                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1189        }
1190
1191        cursor.close();
1192        return devices;
1193    }
1194
1195    public List<String> getKnownSignalAddresses(Account account) {
1196        List<String> addresses = new ArrayList<>();
1197        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1198        String[] selectionArgs = {account.getUuid()};
1199        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1200                colums,
1201                SQLiteAxolotlStore.ACCOUNT + " = ?",
1202                selectionArgs,
1203                null, null, null
1204        );
1205        while (cursor.moveToNext()) {
1206            addresses.add(cursor.getString(0));
1207        }
1208        cursor.close();
1209        return addresses;
1210    }
1211
1212    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1213        Cursor cursor = getCursorForSession(account, contact);
1214        int count = cursor.getCount();
1215        cursor.close();
1216        return count != 0;
1217    }
1218
1219    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1220        SQLiteDatabase db = this.getWritableDatabase();
1221        ContentValues values = new ContentValues();
1222        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1223        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1224        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1225        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1226        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1227    }
1228
1229    public void deleteSession(Account account, SignalProtocolAddress contact) {
1230        SQLiteDatabase db = this.getWritableDatabase();
1231        deleteSession(db, account, contact);
1232    }
1233
1234    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1235        String[] args = {account.getUuid(),
1236                contact.getName(),
1237                Integer.toString(contact.getDeviceId())};
1238        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1239                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1240                        + SQLiteAxolotlStore.NAME + " = ? AND "
1241                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1242                args);
1243    }
1244
1245    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1246        SQLiteDatabase db = this.getWritableDatabase();
1247        String[] args = {account.getUuid(), contact.getName()};
1248        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1249                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1250                        + SQLiteAxolotlStore.NAME + " = ?",
1251                args);
1252    }
1253
1254    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1255        SQLiteDatabase db = this.getReadableDatabase();
1256        String[] columns = {SQLiteAxolotlStore.KEY};
1257        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1258        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1259                columns,
1260                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1261                        + SQLiteAxolotlStore.ID + "=?",
1262                selectionArgs,
1263                null, null, null);
1264
1265        return cursor;
1266    }
1267
1268    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1269        PreKeyRecord record = null;
1270        Cursor cursor = getCursorForPreKey(account, preKeyId);
1271        if (cursor.getCount() != 0) {
1272            cursor.moveToFirst();
1273            try {
1274                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1275            } catch (IOException e) {
1276                throw new AssertionError(e);
1277            }
1278        }
1279        cursor.close();
1280        return record;
1281    }
1282
1283    public boolean containsPreKey(Account account, int preKeyId) {
1284        Cursor cursor = getCursorForPreKey(account, preKeyId);
1285        int count = cursor.getCount();
1286        cursor.close();
1287        return count != 0;
1288    }
1289
1290    public void storePreKey(Account account, PreKeyRecord record) {
1291        SQLiteDatabase db = this.getWritableDatabase();
1292        ContentValues values = new ContentValues();
1293        values.put(SQLiteAxolotlStore.ID, record.getId());
1294        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1295        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1296        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1297    }
1298
1299    public int deletePreKey(Account account, int preKeyId) {
1300        SQLiteDatabase db = this.getWritableDatabase();
1301        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1302        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1303                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1304                        + SQLiteAxolotlStore.ID + "=?",
1305                args);
1306    }
1307
1308    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1309        SQLiteDatabase db = this.getReadableDatabase();
1310        String[] columns = {SQLiteAxolotlStore.KEY};
1311        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1312        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1313                columns,
1314                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1315                selectionArgs,
1316                null, null, null);
1317
1318        return cursor;
1319    }
1320
1321    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1322        SignedPreKeyRecord record = null;
1323        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1324        if (cursor.getCount() != 0) {
1325            cursor.moveToFirst();
1326            try {
1327                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1328            } catch (IOException e) {
1329                throw new AssertionError(e);
1330            }
1331        }
1332        cursor.close();
1333        return record;
1334    }
1335
1336    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1337        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1338        SQLiteDatabase db = this.getReadableDatabase();
1339        String[] columns = {SQLiteAxolotlStore.KEY};
1340        String[] selectionArgs = {account.getUuid()};
1341        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1342                columns,
1343                SQLiteAxolotlStore.ACCOUNT + "=?",
1344                selectionArgs,
1345                null, null, null);
1346
1347        while (cursor.moveToNext()) {
1348            try {
1349                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1350            } catch (IOException ignored) {
1351            }
1352        }
1353        cursor.close();
1354        return prekeys;
1355    }
1356
1357    public int getSignedPreKeysCount(Account account) {
1358        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1359        String[] selectionArgs = {account.getUuid()};
1360        SQLiteDatabase db = this.getReadableDatabase();
1361        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1362                columns,
1363                SQLiteAxolotlStore.ACCOUNT + "=?",
1364                selectionArgs,
1365                null, null, null);
1366        final int count;
1367        if (cursor.moveToFirst()) {
1368            count = cursor.getInt(0);
1369        } else {
1370            count = 0;
1371        }
1372        cursor.close();
1373        return count;
1374    }
1375
1376    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1377        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1378        int count = cursor.getCount();
1379        cursor.close();
1380        return count != 0;
1381    }
1382
1383    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1384        SQLiteDatabase db = this.getWritableDatabase();
1385        ContentValues values = new ContentValues();
1386        values.put(SQLiteAxolotlStore.ID, record.getId());
1387        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1388        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1389        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1390    }
1391
1392    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1393        SQLiteDatabase db = this.getWritableDatabase();
1394        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1395        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1396                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1397                        + SQLiteAxolotlStore.ID + "=?",
1398                args);
1399    }
1400
1401    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1402        final SQLiteDatabase db = this.getReadableDatabase();
1403        return getIdentityKeyCursor(db, account, name, own);
1404    }
1405
1406    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1407        return getIdentityKeyCursor(db, account, name, own, null);
1408    }
1409
1410    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1411        final SQLiteDatabase db = this.getReadableDatabase();
1412        return getIdentityKeyCursor(db, account, fingerprint);
1413    }
1414
1415    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1416        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1417    }
1418
1419    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1420        String[] columns = {SQLiteAxolotlStore.TRUST,
1421                SQLiteAxolotlStore.ACTIVE,
1422                SQLiteAxolotlStore.LAST_ACTIVATION,
1423                SQLiteAxolotlStore.KEY};
1424        ArrayList<String> selectionArgs = new ArrayList<>(4);
1425        selectionArgs.add(account.getUuid());
1426        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1427        if (name != null) {
1428            selectionArgs.add(name);
1429            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1430        }
1431        if (fingerprint != null) {
1432            selectionArgs.add(fingerprint);
1433            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1434        }
1435        if (own != null) {
1436            selectionArgs.add(own ? "1" : "0");
1437            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1438        }
1439        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1440                columns,
1441                selectionString,
1442                selectionArgs.toArray(new String[selectionArgs.size()]),
1443                null, null, null);
1444
1445        return cursor;
1446    }
1447
1448    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1449        SQLiteDatabase db = getReadableDatabase();
1450        return loadOwnIdentityKeyPair(db, account);
1451    }
1452
1453    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1454        String name = account.getJid().asBareJid().toString();
1455        IdentityKeyPair identityKeyPair = null;
1456        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1457        if (cursor.getCount() != 0) {
1458            cursor.moveToFirst();
1459            try {
1460                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1461            } catch (InvalidKeyException e) {
1462                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1463            }
1464        }
1465        cursor.close();
1466
1467        return identityKeyPair;
1468    }
1469
1470    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1471        return loadIdentityKeys(account, name, null);
1472    }
1473
1474    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1475        Set<IdentityKey> identityKeys = new HashSet<>();
1476        Cursor cursor = getIdentityKeyCursor(account, name, false);
1477
1478        while (cursor.moveToNext()) {
1479            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1480                continue;
1481            }
1482            try {
1483                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1484                if (key != null) {
1485                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1486                } else {
1487                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1488                }
1489            } catch (InvalidKeyException e) {
1490                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1491            }
1492        }
1493        cursor.close();
1494
1495        return identityKeys;
1496    }
1497
1498    public long numTrustedKeys(Account account, String name) {
1499        SQLiteDatabase db = getReadableDatabase();
1500        String[] args = {
1501                account.getUuid(),
1502                name,
1503                FingerprintStatus.Trust.TRUSTED.toString(),
1504                FingerprintStatus.Trust.VERIFIED.toString(),
1505                FingerprintStatus.Trust.VERIFIED_X509.toString()
1506        };
1507        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1508                SQLiteAxolotlStore.ACCOUNT + " = ?"
1509                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1510                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1511                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1512                args
1513        );
1514    }
1515
1516    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1517        SQLiteDatabase db = this.getWritableDatabase();
1518        ContentValues values = new ContentValues();
1519        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1520        values.put(SQLiteAxolotlStore.NAME, name);
1521        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1522        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1523        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1524        values.putAll(status.toContentValues());
1525        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1526        String[] whereArgs = {account.getUuid(), name, fingerprint};
1527        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1528        if (rows == 0) {
1529            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1530        }
1531    }
1532
1533    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1534        SQLiteDatabase db = this.getWritableDatabase();
1535        ContentValues values = new ContentValues();
1536        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1537        values.put(SQLiteAxolotlStore.NAME, name);
1538        values.put(SQLiteAxolotlStore.OWN, 0);
1539        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1540        values.putAll(status.toContentValues());
1541        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1542    }
1543
1544    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1545        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1546        final FingerprintStatus status;
1547        if (cursor.getCount() > 0) {
1548            cursor.moveToFirst();
1549            status = FingerprintStatus.fromCursor(cursor);
1550        } else {
1551            status = null;
1552        }
1553        cursor.close();
1554        return status;
1555    }
1556
1557    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1558        SQLiteDatabase db = this.getWritableDatabase();
1559        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1560    }
1561
1562    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1563        String[] selectionArgs = {
1564                account.getUuid(),
1565                fingerprint
1566        };
1567        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1568                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1569                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1570                selectionArgs);
1571        return rows == 1;
1572    }
1573
1574    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1575        SQLiteDatabase db = this.getWritableDatabase();
1576        String[] selectionArgs = {
1577                account.getUuid(),
1578                fingerprint
1579        };
1580        try {
1581            ContentValues values = new ContentValues();
1582            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1583            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1584                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1585                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1586                    selectionArgs) == 1;
1587        } catch (CertificateEncodingException e) {
1588            Log.d(Config.LOGTAG, "could not encode certificate");
1589            return false;
1590        }
1591    }
1592
1593    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1594        SQLiteDatabase db = this.getReadableDatabase();
1595        String[] selectionArgs = {
1596                account.getUuid(),
1597                fingerprint
1598        };
1599        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1600        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1601        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1602        if (cursor.getCount() < 1) {
1603            return null;
1604        } else {
1605            cursor.moveToFirst();
1606            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1607            cursor.close();
1608            if (certificate == null || certificate.length == 0) {
1609                return null;
1610            }
1611            try {
1612                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1613                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1614            } catch (CertificateException e) {
1615                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1616                return null;
1617            }
1618        }
1619    }
1620
1621    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1622        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1623    }
1624
1625    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1626        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1627    }
1628
1629
1630    private void recreateAxolotlDb(SQLiteDatabase db) {
1631        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1632        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1633        db.execSQL(CREATE_SESSIONS_STATEMENT);
1634        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1635        db.execSQL(CREATE_PREKEYS_STATEMENT);
1636        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1637        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1638        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1639        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1640    }
1641
1642    public void wipeAxolotlDb(Account account) {
1643        String accountName = account.getUuid();
1644        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1645        SQLiteDatabase db = this.getWritableDatabase();
1646        String[] deleteArgs = {
1647                accountName
1648        };
1649        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1650                SQLiteAxolotlStore.ACCOUNT + " = ?",
1651                deleteArgs);
1652        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1653                SQLiteAxolotlStore.ACCOUNT + " = ?",
1654                deleteArgs);
1655        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1656                SQLiteAxolotlStore.ACCOUNT + " = ?",
1657                deleteArgs);
1658        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1659                SQLiteAxolotlStore.ACCOUNT + " = ?",
1660                deleteArgs);
1661    }
1662
1663    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1664        SQLiteDatabase db = this.getReadableDatabase();
1665        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;";
1666        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1667        Cursor cursor = db.rawQuery(SQL, whereArgs);
1668        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1669        while (cursor.moveToNext()) {
1670            try {
1671                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1672            } catch (Exception e) {
1673                Log.d(Config.LOGTAG, e.getMessage());
1674            }
1675        }
1676        cursor.close();
1677        return contacts;
1678    }
1679}