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.CONVERSATION + "=? " +
1111                "ORDER BY " + Message.TIME_SENT + " DESC " +
1112                "LIMIT " + String.valueOf(limit),
1113                selectionArgs
1114            );
1115        } else {
1116            String[] selectionArgs = {conversation.getUuid(),
1117                    Long.toString(timestamp)};
1118            cursor = db.rawQuery(
1119                "SELECT * FROM " + Message.TABLENAME + " " +
1120                "LEFT JOIN cheogram." + Message.TABLENAME +
1121                "  USING (" + Message.UUID + ")" +
1122                "WHERE " + Message.CONVERSATION + "=? AND " +
1123                Message.TIME_SENT + "<? " +
1124                "ORDER BY " + Message.TIME_SENT + " DESC " +
1125                "LIMIT " + String.valueOf(limit),
1126                selectionArgs
1127            );
1128        }
1129        CursorUtils.upgradeCursorWindowSize(cursor);
1130        while (cursor.moveToNext()) {
1131            try {
1132                list.add(0, Message.fromCursor(cursor, conversation));
1133            } catch (Exception e) {
1134                Log.e(Config.LOGTAG, "unable to restore message");
1135            }
1136        }
1137        cursor.close();
1138        return list;
1139    }
1140
1141    public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1142        final SQLiteDatabase db = this.getReadableDatabase();
1143        final StringBuilder SQL = new StringBuilder();
1144        final String[] selectionArgs;
1145        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 ?");
1146        if (uuid == null) {
1147            selectionArgs = new String[]{FtsUtils.toMatchString(term)};
1148        } else {
1149            selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
1150            SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1151        }
1152        SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1153        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1154        return db.rawQuery(SQL.toString(), selectionArgs);
1155    }
1156
1157    public List<String> markFileAsDeleted(final File file, final boolean internal) {
1158        SQLiteDatabase db = this.getReadableDatabase();
1159        String selection;
1160        String[] selectionArgs;
1161        if (internal) {
1162            final String name = file.getName();
1163            if (name.endsWith(".pgp")) {
1164                selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
1165                selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
1166            } else {
1167                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1168                selectionArgs = new String[]{file.getAbsolutePath(), name};
1169            }
1170        } else {
1171            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1172            selectionArgs = new String[]{file.getAbsolutePath()};
1173        }
1174        final List<String> uuids = new ArrayList<>();
1175        Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
1176        while (cursor != null && cursor.moveToNext()) {
1177            uuids.add(cursor.getString(0));
1178        }
1179        if (cursor != null) {
1180            cursor.close();
1181        }
1182        markFileAsDeleted(uuids);
1183        return uuids;
1184    }
1185
1186    public void markFileAsDeleted(List<String> uuids) {
1187        SQLiteDatabase db = this.getReadableDatabase();
1188        final ContentValues contentValues = new ContentValues();
1189        final String where = Message.UUID + "=?";
1190        contentValues.put(Message.DELETED, 1);
1191        db.beginTransaction();
1192        for (String uuid : uuids) {
1193            db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
1194        }
1195        db.setTransactionSuccessful();
1196        db.endTransaction();
1197    }
1198
1199    public void markFilesAsChanged(List<FilePathInfo> files) {
1200        SQLiteDatabase db = this.getReadableDatabase();
1201        final String where = Message.UUID + "=?";
1202        db.beginTransaction();
1203        for (FilePathInfo info : files) {
1204            final ContentValues contentValues = new ContentValues();
1205            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1206            db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
1207        }
1208        db.setTransactionSuccessful();
1209        db.endTransaction();
1210    }
1211
1212    public List<FilePathInfo> getFilePathInfo() {
1213        final SQLiteDatabase db = this.getReadableDatabase();
1214        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);
1215        final List<FilePathInfo> list = new ArrayList<>();
1216        while (cursor != null && cursor.moveToNext()) {
1217            list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1218        }
1219        if (cursor != null) {
1220            cursor.close();
1221        }
1222        return list;
1223    }
1224
1225    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1226        SQLiteDatabase db = this.getReadableDatabase();
1227        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";
1228        final String[] args = {account, jid.toString(), jid.toString() + "/%"};
1229        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1230        List<FilePath> filesPaths = new ArrayList<>();
1231        while (cursor.moveToNext()) {
1232            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1233        }
1234        cursor.close();
1235        return filesPaths;
1236    }
1237
1238    public static class FilePath {
1239        public final UUID uuid;
1240        public final String path;
1241
1242        private FilePath(String uuid, String path) {
1243            this.uuid = UUID.fromString(uuid);
1244            this.path = path;
1245        }
1246    }
1247
1248    public static class FilePathInfo extends FilePath {
1249        public boolean deleted;
1250
1251        private FilePathInfo(String uuid, String path, boolean deleted) {
1252            super(uuid, path);
1253            this.deleted = deleted;
1254        }
1255
1256        public boolean setDeleted(boolean deleted) {
1257            final boolean changed = deleted != this.deleted;
1258            this.deleted = deleted;
1259            return changed;
1260        }
1261    }
1262
1263    public Conversation findConversation(final Account account, final Jid contactJid) {
1264        SQLiteDatabase db = this.getReadableDatabase();
1265        String[] selectionArgs = {account.getUuid(),
1266                contactJid.asBareJid().toString() + "/%",
1267                contactJid.asBareJid().toString()
1268        };
1269        try(final Cursor cursor = db.query(Conversation.TABLENAME, null,
1270                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
1271                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null)) {
1272            if (cursor.getCount() == 0) {
1273                return null;
1274            }
1275            cursor.moveToFirst();
1276            final Conversation conversation = Conversation.fromCursor(cursor);
1277            if (conversation.getJid() instanceof InvalidJid) {
1278                return null;
1279            }
1280            return conversation;
1281        }
1282    }
1283
1284    public void updateConversation(final Conversation conversation) {
1285        final SQLiteDatabase db = this.getWritableDatabase();
1286        final String[] args = {conversation.getUuid()};
1287        db.update(Conversation.TABLENAME, conversation.getContentValues(),
1288                Conversation.UUID + "=?", args);
1289    }
1290
1291    public List<Account> getAccounts() {
1292        SQLiteDatabase db = this.getReadableDatabase();
1293        return getAccounts(db);
1294    }
1295
1296    public List<Jid> getAccountJids(final boolean enabledOnly) {
1297        final SQLiteDatabase db = this.getReadableDatabase();
1298        final List<Jid> jids = new ArrayList<>();
1299        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
1300        final String where = enabledOnly ? "not options & (1 <<1)" : null;
1301        try (final Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
1302            while (cursor != null && cursor.moveToNext()) {
1303                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
1304            }
1305        } catch (final Exception e) {
1306            return jids;
1307        }
1308        return jids;
1309    }
1310
1311    private List<Account> getAccounts(SQLiteDatabase db) {
1312        final List<Account> list = new ArrayList<>();
1313        try (final Cursor cursor =
1314                db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1315            while (cursor != null && cursor.moveToNext()) {
1316                list.add(Account.fromCursor(cursor));
1317            }
1318        }
1319        return list;
1320    }
1321
1322    public boolean updateAccount(Account account) {
1323        SQLiteDatabase db = this.getWritableDatabase();
1324        String[] args = {account.getUuid()};
1325        final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1326        return rows == 1;
1327    }
1328
1329    public boolean deleteAccount(Account account) {
1330        SQLiteDatabase db = this.getWritableDatabase();
1331        String[] args = {account.getUuid()};
1332        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1333        return rows == 1;
1334    }
1335
1336    public boolean updateMessage(Message message, boolean includeBody) {
1337        SQLiteDatabase db = this.getWritableDatabase();
1338        String[] args = {message.getUuid()};
1339        ContentValues contentValues = message.getContentValues();
1340        contentValues.remove(Message.UUID);
1341        if (!includeBody) {
1342            contentValues.remove(Message.BODY);
1343        }
1344        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1345               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1346    }
1347
1348    public boolean updateMessage(Message message, String uuid) {
1349        SQLiteDatabase db = this.getWritableDatabase();
1350        String[] args = {uuid};
1351        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1352               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1353    }
1354
1355
1356    public boolean deleteMessage(String uuid) {
1357        SQLiteDatabase db = this.getWritableDatabase();
1358        String[] args = {uuid};
1359        return db.delete(Message.TABLENAME, Message.UUID + "=?", args) == 1 &&
1360               db.delete("cheogram." + Message.TABLENAME, Message.UUID + "=?", args) == 1;
1361    }
1362
1363    public void readRoster(Roster roster) {
1364        final SQLiteDatabase db = this.getReadableDatabase();
1365        final String[] args = {roster.getAccount().getUuid()};
1366        try (final Cursor cursor =
1367                db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1368            while (cursor.moveToNext()) {
1369                roster.initContact(Contact.fromCursor(cursor));
1370            }
1371        }
1372    }
1373
1374    public void writeRoster(final Roster roster) {
1375        long start = SystemClock.elapsedRealtime();
1376        final Account account = roster.getAccount();
1377        final SQLiteDatabase db = this.getWritableDatabase();
1378        db.beginTransaction();
1379        for (Contact contact : roster.getContacts()) {
1380            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1381                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1382            } else {
1383                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1384                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1385                db.delete(Contact.TABLENAME, where, whereArgs);
1386            }
1387        }
1388        db.setTransactionSuccessful();
1389        db.endTransaction();
1390        account.setRosterVersion(roster.getVersion());
1391        updateAccount(account);
1392        long duration = SystemClock.elapsedRealtime() - start;
1393        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1394    }
1395
1396    public void deleteMessagesInConversation(Conversation conversation) {
1397        long start = SystemClock.elapsedRealtime();
1398        final SQLiteDatabase db = this.getWritableDatabase();
1399        db.beginTransaction();
1400        final String[] args = {conversation.getUuid()};
1401        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1402        db.delete("cheogram.webxdc_updates", Message.CONVERSATION + "=?", args);
1403        db.setTransactionSuccessful();
1404        db.endTransaction();
1405        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1406    }
1407
1408    public void expireOldMessages(long timestamp) {
1409        final String[] args = {String.valueOf(timestamp)};
1410        SQLiteDatabase db = this.getReadableDatabase();
1411        db.beginTransaction();
1412        db.delete(Message.TABLENAME, "timeSent<?", args);
1413        db.setTransactionSuccessful();
1414        db.endTransaction();
1415    }
1416
1417    public MamReference getLastMessageReceived(Account account) {
1418        Cursor cursor = null;
1419        try {
1420            SQLiteDatabase db = this.getReadableDatabase();
1421            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";
1422            String[] args = {account.getUuid()};
1423            cursor = db.rawQuery(sql, args);
1424            if (cursor.getCount() == 0) {
1425                return null;
1426            } else {
1427                cursor.moveToFirst();
1428                return new MamReference(cursor.getLong(0), cursor.getString(1));
1429            }
1430        } catch (Exception e) {
1431            return null;
1432        } finally {
1433            if (cursor != null) {
1434                cursor.close();
1435            }
1436        }
1437    }
1438
1439    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1440        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";
1441        String[] args = {account.getUuid(), fingerprint};
1442        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1443        long time;
1444        if (cursor.moveToFirst()) {
1445            time = cursor.getLong(0);
1446        } else {
1447            time = 0;
1448        }
1449        cursor.close();
1450        return time;
1451    }
1452
1453    public MamReference getLastClearDate(Account account) {
1454        SQLiteDatabase db = this.getReadableDatabase();
1455        String[] columns = {Conversation.ATTRIBUTES};
1456        String selection = Conversation.ACCOUNT + "=?";
1457        String[] args = {account.getUuid()};
1458        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1459        MamReference maxClearDate = new MamReference(0);
1460        while (cursor.moveToNext()) {
1461            try {
1462                final JSONObject o = new JSONObject(cursor.getString(0));
1463                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1464            } catch (Exception e) {
1465                //ignored
1466            }
1467        }
1468        cursor.close();
1469        return maxClearDate;
1470    }
1471
1472    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1473        final SQLiteDatabase db = this.getReadableDatabase();
1474        String[] selectionArgs = {account.getUuid(),
1475                contact.getName(),
1476                Integer.toString(contact.getDeviceId())};
1477        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1478                null,
1479                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1480                        + SQLiteAxolotlStore.NAME + " = ? AND "
1481                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1482                selectionArgs,
1483                null, null, null);
1484    }
1485
1486    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1487        SessionRecord session = null;
1488        Cursor cursor = getCursorForSession(account, contact);
1489        if (cursor.getCount() != 0) {
1490            cursor.moveToFirst();
1491            try {
1492                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1493            } catch (IOException e) {
1494                cursor.close();
1495                throw new AssertionError(e);
1496            }
1497        }
1498        cursor.close();
1499        return session;
1500    }
1501
1502    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1503        final SQLiteDatabase db = this.getReadableDatabase();
1504        return getSubDeviceSessions(db, account, contact);
1505    }
1506
1507    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1508        List<Integer> devices = new ArrayList<>();
1509        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1510        String[] selectionArgs = {account.getUuid(),
1511                contact.getName()};
1512        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1513                columns,
1514                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1515                        + SQLiteAxolotlStore.NAME + " = ?",
1516                selectionArgs,
1517                null, null, null);
1518
1519        while (cursor.moveToNext()) {
1520            devices.add(cursor.getInt(
1521                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1522        }
1523
1524        cursor.close();
1525        return devices;
1526    }
1527
1528    public List<String> getKnownSignalAddresses(Account account) {
1529        List<String> addresses = new ArrayList<>();
1530        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1531        String[] selectionArgs = {account.getUuid()};
1532        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1533                colums,
1534                SQLiteAxolotlStore.ACCOUNT + " = ?",
1535                selectionArgs,
1536                null, null, null
1537        );
1538        while (cursor.moveToNext()) {
1539            addresses.add(cursor.getString(0));
1540        }
1541        cursor.close();
1542        return addresses;
1543    }
1544
1545    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1546        Cursor cursor = getCursorForSession(account, contact);
1547        int count = cursor.getCount();
1548        cursor.close();
1549        return count != 0;
1550    }
1551
1552    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1553        SQLiteDatabase db = this.getWritableDatabase();
1554        ContentValues values = new ContentValues();
1555        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1556        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1557        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1558        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1559        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1560    }
1561
1562    public void deleteSession(Account account, SignalProtocolAddress contact) {
1563        SQLiteDatabase db = this.getWritableDatabase();
1564        deleteSession(db, account, contact);
1565    }
1566
1567    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1568        String[] args = {account.getUuid(),
1569                contact.getName(),
1570                Integer.toString(contact.getDeviceId())};
1571        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1572                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1573                        + SQLiteAxolotlStore.NAME + " = ? AND "
1574                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1575                args);
1576    }
1577
1578    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1579        SQLiteDatabase db = this.getWritableDatabase();
1580        String[] args = {account.getUuid(), contact.getName()};
1581        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1582                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1583                        + SQLiteAxolotlStore.NAME + " = ?",
1584                args);
1585    }
1586
1587    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1588        SQLiteDatabase db = this.getReadableDatabase();
1589        String[] columns = {SQLiteAxolotlStore.KEY};
1590        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1591        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1592                columns,
1593                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1594                        + SQLiteAxolotlStore.ID + "=?",
1595                selectionArgs,
1596                null, null, null);
1597
1598        return cursor;
1599    }
1600
1601    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1602        PreKeyRecord record = null;
1603        Cursor cursor = getCursorForPreKey(account, preKeyId);
1604        if (cursor.getCount() != 0) {
1605            cursor.moveToFirst();
1606            try {
1607                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1608            } catch (IOException e) {
1609                throw new AssertionError(e);
1610            }
1611        }
1612        cursor.close();
1613        return record;
1614    }
1615
1616    public boolean containsPreKey(Account account, int preKeyId) {
1617        Cursor cursor = getCursorForPreKey(account, preKeyId);
1618        int count = cursor.getCount();
1619        cursor.close();
1620        return count != 0;
1621    }
1622
1623    public void storePreKey(Account account, PreKeyRecord record) {
1624        SQLiteDatabase db = this.getWritableDatabase();
1625        ContentValues values = new ContentValues();
1626        values.put(SQLiteAxolotlStore.ID, record.getId());
1627        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1628        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1629        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1630    }
1631
1632    public int deletePreKey(Account account, int preKeyId) {
1633        SQLiteDatabase db = this.getWritableDatabase();
1634        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1635        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1636                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1637                        + SQLiteAxolotlStore.ID + "=?",
1638                args);
1639    }
1640
1641    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1642        SQLiteDatabase db = this.getReadableDatabase();
1643        String[] columns = {SQLiteAxolotlStore.KEY};
1644        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1645        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1646                columns,
1647                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1648                selectionArgs,
1649                null, null, null);
1650
1651        return cursor;
1652    }
1653
1654    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1655        SignedPreKeyRecord record = null;
1656        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1657        if (cursor.getCount() != 0) {
1658            cursor.moveToFirst();
1659            try {
1660                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1661            } catch (IOException e) {
1662                throw new AssertionError(e);
1663            }
1664        }
1665        cursor.close();
1666        return record;
1667    }
1668
1669    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1670        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1671        SQLiteDatabase db = this.getReadableDatabase();
1672        String[] columns = {SQLiteAxolotlStore.KEY};
1673        String[] selectionArgs = {account.getUuid()};
1674        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1675                columns,
1676                SQLiteAxolotlStore.ACCOUNT + "=?",
1677                selectionArgs,
1678                null, null, null);
1679
1680        while (cursor.moveToNext()) {
1681            try {
1682                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1683            } catch (IOException ignored) {
1684            }
1685        }
1686        cursor.close();
1687        return prekeys;
1688    }
1689
1690    public int getSignedPreKeysCount(Account account) {
1691        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1692        String[] selectionArgs = {account.getUuid()};
1693        SQLiteDatabase db = this.getReadableDatabase();
1694        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1695                columns,
1696                SQLiteAxolotlStore.ACCOUNT + "=?",
1697                selectionArgs,
1698                null, null, null);
1699        final int count;
1700        if (cursor.moveToFirst()) {
1701            count = cursor.getInt(0);
1702        } else {
1703            count = 0;
1704        }
1705        cursor.close();
1706        return count;
1707    }
1708
1709    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1710        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1711        int count = cursor.getCount();
1712        cursor.close();
1713        return count != 0;
1714    }
1715
1716    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1717        SQLiteDatabase db = this.getWritableDatabase();
1718        ContentValues values = new ContentValues();
1719        values.put(SQLiteAxolotlStore.ID, record.getId());
1720        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1721        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1722        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1723    }
1724
1725    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1726        SQLiteDatabase db = this.getWritableDatabase();
1727        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1728        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1729                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1730                        + SQLiteAxolotlStore.ID + "=?",
1731                args);
1732    }
1733
1734    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1735        final SQLiteDatabase db = this.getReadableDatabase();
1736        return getIdentityKeyCursor(db, account, name, own);
1737    }
1738
1739    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1740        return getIdentityKeyCursor(db, account, name, own, null);
1741    }
1742
1743    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1744        final SQLiteDatabase db = this.getReadableDatabase();
1745        return getIdentityKeyCursor(db, account, fingerprint);
1746    }
1747
1748    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1749        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1750    }
1751
1752    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1753        String[] columns = {SQLiteAxolotlStore.TRUST,
1754                SQLiteAxolotlStore.ACTIVE,
1755                SQLiteAxolotlStore.LAST_ACTIVATION,
1756                SQLiteAxolotlStore.KEY};
1757        ArrayList<String> selectionArgs = new ArrayList<>(4);
1758        selectionArgs.add(account.getUuid());
1759        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1760        if (name != null) {
1761            selectionArgs.add(name);
1762            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1763        }
1764        if (fingerprint != null) {
1765            selectionArgs.add(fingerprint);
1766            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1767        }
1768        if (own != null) {
1769            selectionArgs.add(own ? "1" : "0");
1770            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1771        }
1772        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1773                columns,
1774                selectionString,
1775                selectionArgs.toArray(new String[selectionArgs.size()]),
1776                null, null, null);
1777
1778        return cursor;
1779    }
1780
1781    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1782        SQLiteDatabase db = getReadableDatabase();
1783        return loadOwnIdentityKeyPair(db, account);
1784    }
1785
1786    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1787        String name = account.getJid().asBareJid().toString();
1788        IdentityKeyPair identityKeyPair = null;
1789        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1790        if (cursor.getCount() != 0) {
1791            cursor.moveToFirst();
1792            try {
1793                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1794            } catch (InvalidKeyException e) {
1795                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1796            }
1797        }
1798        cursor.close();
1799
1800        return identityKeyPair;
1801    }
1802
1803    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1804        return loadIdentityKeys(account, name, null);
1805    }
1806
1807    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1808        Set<IdentityKey> identityKeys = new HashSet<>();
1809        Cursor cursor = getIdentityKeyCursor(account, name, false);
1810
1811        while (cursor.moveToNext()) {
1812            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1813                continue;
1814            }
1815            try {
1816                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1817                if (key != null) {
1818                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1819                } else {
1820                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1821                }
1822            } catch (InvalidKeyException e) {
1823                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1824            }
1825        }
1826        cursor.close();
1827
1828        return identityKeys;
1829    }
1830
1831    public long numTrustedKeys(Account account, String name) {
1832        SQLiteDatabase db = getReadableDatabase();
1833        String[] args = {
1834                account.getUuid(),
1835                name,
1836                FingerprintStatus.Trust.TRUSTED.toString(),
1837                FingerprintStatus.Trust.VERIFIED.toString(),
1838                FingerprintStatus.Trust.VERIFIED_X509.toString()
1839        };
1840        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1841                SQLiteAxolotlStore.ACCOUNT + " = ?"
1842                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1843                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1844                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1845                args
1846        );
1847    }
1848
1849    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1850        SQLiteDatabase db = this.getWritableDatabase();
1851        ContentValues values = new ContentValues();
1852        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1853        values.put(SQLiteAxolotlStore.NAME, name);
1854        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1855        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1856        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1857        values.putAll(status.toContentValues());
1858        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1859        String[] whereArgs = {account.getUuid(), name, fingerprint};
1860        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1861        if (rows == 0) {
1862            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1863        }
1864    }
1865
1866    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1867        SQLiteDatabase db = this.getWritableDatabase();
1868        ContentValues values = new ContentValues();
1869        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1870        values.put(SQLiteAxolotlStore.NAME, name);
1871        values.put(SQLiteAxolotlStore.OWN, 0);
1872        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1873        values.putAll(status.toContentValues());
1874        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1875    }
1876
1877    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1878        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1879        final FingerprintStatus status;
1880        if (cursor.getCount() > 0) {
1881            cursor.moveToFirst();
1882            status = FingerprintStatus.fromCursor(cursor);
1883        } else {
1884            status = null;
1885        }
1886        cursor.close();
1887        return status;
1888    }
1889
1890    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1891        SQLiteDatabase db = this.getWritableDatabase();
1892        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1893    }
1894
1895    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1896        String[] selectionArgs = {
1897                account.getUuid(),
1898                fingerprint
1899        };
1900        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1901                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1902                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1903                selectionArgs);
1904        return rows == 1;
1905    }
1906
1907    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1908        SQLiteDatabase db = this.getWritableDatabase();
1909        String[] selectionArgs = {
1910                account.getUuid(),
1911                fingerprint
1912        };
1913        try {
1914            ContentValues values = new ContentValues();
1915            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1916            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1917                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1918                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1919                    selectionArgs) == 1;
1920        } catch (CertificateEncodingException e) {
1921            Log.d(Config.LOGTAG, "could not encode certificate");
1922            return false;
1923        }
1924    }
1925
1926    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1927        SQLiteDatabase db = this.getReadableDatabase();
1928        String[] selectionArgs = {
1929                account.getUuid(),
1930                fingerprint
1931        };
1932        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1933        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1934        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1935        if (cursor.getCount() < 1) {
1936            return null;
1937        } else {
1938            cursor.moveToFirst();
1939            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1940            cursor.close();
1941            if (certificate == null || certificate.length == 0) {
1942                return null;
1943            }
1944            try {
1945                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1946                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1947            } catch (CertificateException e) {
1948                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1949                return null;
1950            }
1951        }
1952    }
1953
1954    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1955        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1956    }
1957
1958    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1959        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1960    }
1961
1962
1963    private void recreateAxolotlDb(SQLiteDatabase db) {
1964        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1965        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1966        db.execSQL(CREATE_SESSIONS_STATEMENT);
1967        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1968        db.execSQL(CREATE_PREKEYS_STATEMENT);
1969        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1970        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1971        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1972        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1973    }
1974
1975    public void wipeAxolotlDb(Account account) {
1976        String accountName = account.getUuid();
1977        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1978        SQLiteDatabase db = this.getWritableDatabase();
1979        String[] deleteArgs = {
1980                accountName
1981        };
1982        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1983                SQLiteAxolotlStore.ACCOUNT + " = ?",
1984                deleteArgs);
1985        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1986                SQLiteAxolotlStore.ACCOUNT + " = ?",
1987                deleteArgs);
1988        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1989                SQLiteAxolotlStore.ACCOUNT + " = ?",
1990                deleteArgs);
1991        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1992                SQLiteAxolotlStore.ACCOUNT + " = ?",
1993                deleteArgs);
1994    }
1995
1996    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1997        SQLiteDatabase db = this.getReadableDatabase();
1998        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;";
1999        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
2000        Cursor cursor = db.rawQuery(SQL, whereArgs);
2001        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
2002        while (cursor.moveToNext()) {
2003            try {
2004                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
2005            } catch (Exception e) {
2006                Log.d(Config.LOGTAG, e.getMessage());
2007            }
2008        }
2009        cursor.close();
2010        return contacts;
2011    }
2012}