DatabaseBackend.java

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