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