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