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