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