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