DatabaseBackend.java

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