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.Build;
  11import android.os.Environment;
  12import android.os.SystemClock;
  13import android.util.Base64;
  14import android.util.Log;
  15
  16import com.cheogram.android.WebxdcUpdate;
  17
  18import com.google.common.base.Stopwatch;
  19import com.google.common.collect.Multimap;
  20import com.google.common.collect.HashMultimap;
  21
  22import org.json.JSONException;
  23import org.json.JSONObject;
  24import org.whispersystems.libsignal.IdentityKey;
  25import org.whispersystems.libsignal.IdentityKeyPair;
  26import org.whispersystems.libsignal.InvalidKeyException;
  27import org.whispersystems.libsignal.SignalProtocolAddress;
  28import org.whispersystems.libsignal.state.PreKeyRecord;
  29import org.whispersystems.libsignal.state.SessionRecord;
  30import org.whispersystems.libsignal.state.SignedPreKeyRecord;
  31
  32import java.io.ByteArrayInputStream;
  33import java.io.File;
  34import java.io.IOException;
  35import java.security.cert.CertificateEncodingException;
  36import java.security.cert.CertificateException;
  37import java.security.cert.CertificateFactory;
  38import java.security.cert.X509Certificate;
  39import java.util.ArrayList;
  40import java.util.Collection;
  41import java.util.HashMap;
  42import java.util.Hashtable;
  43import java.util.HashSet;
  44import java.util.List;
  45import java.util.Map;
  46import java.util.Set;
  47import java.util.UUID;
  48import java.util.concurrent.CopyOnWriteArrayList;
  49
  50import io.ipfs.cid.Cid;
  51
  52import com.google.common.collect.ImmutableMap;
  53import eu.siacs.conversations.Config;
  54import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  55import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  56import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
  57import eu.siacs.conversations.entities.Account;
  58import eu.siacs.conversations.entities.Contact;
  59import eu.siacs.conversations.entities.Conversation;
  60import eu.siacs.conversations.entities.DownloadableFile;
  61import eu.siacs.conversations.entities.Message;
  62import eu.siacs.conversations.entities.MucOptions;
  63import eu.siacs.conversations.entities.PresenceTemplate;
  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.Jid;
  72import eu.siacs.conversations.xmpp.mam.MamReference;
  73import im.conversations.android.xml.XmlElementReader;
  74import im.conversations.android.xmpp.EntityCapabilities;
  75import im.conversations.android.xmpp.EntityCapabilities2;
  76import im.conversations.android.xmpp.model.disco.info.InfoQuery;
  77import java.io.ByteArrayInputStream;
  78import java.io.File;
  79import java.io.IOException;
  80import java.nio.charset.StandardCharsets;
  81import java.security.cert.CertificateEncodingException;
  82import java.security.cert.CertificateException;
  83import java.security.cert.CertificateFactory;
  84import java.security.cert.X509Certificate;
  85import java.util.ArrayList;
  86import java.util.HashMap;
  87import java.util.HashSet;
  88import java.util.List;
  89import java.util.Map;
  90import java.util.Set;
  91import java.util.UUID;
  92import java.util.concurrent.CopyOnWriteArrayList;
  93import org.json.JSONObject;
  94import org.jxmpp.jid.parts.Localpart;
  95import org.jxmpp.stringprep.XmppStringprepException;
  96import org.whispersystems.libsignal.IdentityKey;
  97import org.whispersystems.libsignal.IdentityKeyPair;
  98import org.whispersystems.libsignal.InvalidKeyException;
  99import org.whispersystems.libsignal.SignalProtocolAddress;
 100import org.whispersystems.libsignal.state.PreKeyRecord;
 101import org.whispersystems.libsignal.state.SessionRecord;
 102import org.whispersystems.libsignal.state.SignedPreKeyRecord;
 103
 104public class DatabaseBackend extends SQLiteOpenHelper {
 105
 106    private static final String DATABASE_NAME = "history";
 107    private static final int DATABASE_VERSION = 54;
 108
 109    private static boolean requiresMessageIndexRebuild = false;
 110    private static DatabaseBackend instance = null;
 111    private static final String CREATE_CONTACTS_STATEMENT =
 112            "create table "
 113                    + Contact.TABLENAME
 114                    + "("
 115                    + Contact.ACCOUNT
 116                    + " TEXT, "
 117                    + Contact.SERVERNAME
 118                    + " TEXT, "
 119                    + Contact.SYSTEMNAME
 120                    + " TEXT,"
 121                    + Contact.PRESENCE_NAME
 122                    + " TEXT,"
 123                    + Contact.JID
 124                    + " TEXT,"
 125                    + Contact.KEYS
 126                    + " TEXT,"
 127                    + Contact.PHOTOURI
 128                    + " TEXT,"
 129                    + Contact.OPTIONS
 130                    + " NUMBER,"
 131                    + Contact.SYSTEMACCOUNT
 132                    + " NUMBER, "
 133                    + Contact.AVATAR
 134                    + " TEXT, "
 135                    + Contact.LAST_PRESENCE
 136                    + " TEXT, "
 137                    + Contact.LAST_TIME
 138                    + " NUMBER, "
 139                    + Contact.RTP_CAPABILITY
 140                    + " TEXT,"
 141                    + Contact.GROUPS
 142                    + " TEXT, FOREIGN KEY("
 143                    + Contact.ACCOUNT
 144                    + ") REFERENCES "
 145                    + Account.TABLENAME
 146                    + "("
 147                    + Account.UUID
 148                    + ") ON DELETE CASCADE, UNIQUE("
 149                    + Contact.ACCOUNT
 150                    + ", "
 151                    + Contact.JID
 152                    + ") ON CONFLICT REPLACE);";
 153
 154    private static final String CREATE_PRESENCE_TEMPLATES_STATEMENT =
 155            "CREATE TABLE "
 156                    + PresenceTemplate.TABELNAME
 157                    + "("
 158                    + PresenceTemplate.UUID
 159                    + " TEXT, "
 160                    + PresenceTemplate.LAST_USED
 161                    + " NUMBER,"
 162                    + PresenceTemplate.MESSAGE
 163                    + " TEXT,"
 164                    + PresenceTemplate.STATUS
 165                    + " TEXT,"
 166                    + "UNIQUE("
 167                    + PresenceTemplate.MESSAGE
 168                    + ","
 169                    + PresenceTemplate.STATUS
 170                    + ") ON CONFLICT REPLACE);";
 171
 172    private static final String CREATE_PREKEYS_STATEMENT =
 173            "CREATE TABLE "
 174                    + SQLiteAxolotlStore.PREKEY_TABLENAME
 175                    + "("
 176                    + SQLiteAxolotlStore.ACCOUNT
 177                    + " TEXT,  "
 178                    + SQLiteAxolotlStore.ID
 179                    + " INTEGER, "
 180                    + SQLiteAxolotlStore.KEY
 181                    + " TEXT, FOREIGN KEY("
 182                    + SQLiteAxolotlStore.ACCOUNT
 183                    + ") REFERENCES "
 184                    + Account.TABLENAME
 185                    + "("
 186                    + Account.UUID
 187                    + ") ON DELETE CASCADE, "
 188                    + "UNIQUE( "
 189                    + SQLiteAxolotlStore.ACCOUNT
 190                    + ", "
 191                    + SQLiteAxolotlStore.ID
 192                    + ") ON CONFLICT REPLACE"
 193                    + ");";
 194
 195    private static final String CREATE_SIGNED_PREKEYS_STATEMENT =
 196            "CREATE TABLE "
 197                    + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME
 198                    + "("
 199                    + SQLiteAxolotlStore.ACCOUNT
 200                    + " TEXT,  "
 201                    + SQLiteAxolotlStore.ID
 202                    + " INTEGER, "
 203                    + SQLiteAxolotlStore.KEY
 204                    + " TEXT, FOREIGN KEY("
 205                    + SQLiteAxolotlStore.ACCOUNT
 206                    + ") REFERENCES "
 207                    + Account.TABLENAME
 208                    + "("
 209                    + Account.UUID
 210                    + ") ON DELETE CASCADE, "
 211                    + "UNIQUE( "
 212                    + SQLiteAxolotlStore.ACCOUNT
 213                    + ", "
 214                    + SQLiteAxolotlStore.ID
 215                    + ") ON CONFLICT REPLACE"
 216                    + ");";
 217
 218    private static final String CREATE_SESSIONS_STATEMENT =
 219            "CREATE TABLE "
 220                    + SQLiteAxolotlStore.SESSION_TABLENAME
 221                    + "("
 222                    + SQLiteAxolotlStore.ACCOUNT
 223                    + " TEXT,  "
 224                    + SQLiteAxolotlStore.NAME
 225                    + " TEXT, "
 226                    + SQLiteAxolotlStore.DEVICE_ID
 227                    + " INTEGER, "
 228                    + SQLiteAxolotlStore.KEY
 229                    + " TEXT, FOREIGN KEY("
 230                    + SQLiteAxolotlStore.ACCOUNT
 231                    + ") REFERENCES "
 232                    + Account.TABLENAME
 233                    + "("
 234                    + Account.UUID
 235                    + ") ON DELETE CASCADE, "
 236                    + "UNIQUE( "
 237                    + SQLiteAxolotlStore.ACCOUNT
 238                    + ", "
 239                    + SQLiteAxolotlStore.NAME
 240                    + ", "
 241                    + SQLiteAxolotlStore.DEVICE_ID
 242                    + ") ON CONFLICT REPLACE"
 243                    + ");";
 244
 245    private static final String CREATE_IDENTITIES_STATEMENT =
 246            "CREATE TABLE "
 247                    + SQLiteAxolotlStore.IDENTITIES_TABLENAME
 248                    + "("
 249                    + SQLiteAxolotlStore.ACCOUNT
 250                    + " TEXT,  "
 251                    + SQLiteAxolotlStore.NAME
 252                    + " TEXT, "
 253                    + SQLiteAxolotlStore.OWN
 254                    + " INTEGER, "
 255                    + SQLiteAxolotlStore.FINGERPRINT
 256                    + " TEXT, "
 257                    + SQLiteAxolotlStore.CERTIFICATE
 258                    + " BLOB, "
 259                    + SQLiteAxolotlStore.TRUST
 260                    + " TEXT, "
 261                    + SQLiteAxolotlStore.ACTIVE
 262                    + " NUMBER, "
 263                    + SQLiteAxolotlStore.LAST_ACTIVATION
 264                    + " NUMBER,"
 265                    + SQLiteAxolotlStore.KEY
 266                    + " TEXT, FOREIGN KEY("
 267                    + SQLiteAxolotlStore.ACCOUNT
 268                    + ") REFERENCES "
 269                    + Account.TABLENAME
 270                    + "("
 271                    + Account.UUID
 272                    + ") ON DELETE CASCADE, "
 273                    + "UNIQUE( "
 274                    + SQLiteAxolotlStore.ACCOUNT
 275                    + ", "
 276                    + SQLiteAxolotlStore.NAME
 277                    + ", "
 278                    + SQLiteAxolotlStore.FINGERPRINT
 279                    + ") ON CONFLICT IGNORE"
 280                    + ");";
 281
 282    private static final String CREATE_CAPS_CACHE_TABLE =
 283            "CREATE TABLE caps_cache (caps TEXT, caps2 TEXT, disco_info TEXT, UNIQUE (caps), UNIQUE"
 284                    + " (caps2));";
 285    private static final String CREATE_CAPS_CACHE_INDEX_CAPS =
 286            "CREATE INDEX idx_caps ON caps_cache(caps);";
 287    private static final String CREATE_CAPS_CACHE_INDEX_CAPS2 =
 288            "CREATE INDEX idx_caps2 ON caps_cache(caps2);";
 289
 290    private static final String RESOLVER_RESULTS_TABLENAME = "resolver_results";
 291
 292    private static final String CREATE_RESOLVER_RESULTS_TABLE =
 293            "create table "
 294                    + RESOLVER_RESULTS_TABLENAME
 295                    + "("
 296                    + Resolver.Result.DOMAIN
 297                    + " TEXT,"
 298                    + Resolver.Result.HOSTNAME
 299                    + " TEXT,"
 300                    + Resolver.Result.IP
 301                    + " BLOB,"
 302                    + Resolver.Result.PRIORITY
 303                    + " NUMBER,"
 304                    + Resolver.Result.DIRECT_TLS
 305                    + " NUMBER,"
 306                    + Resolver.Result.AUTHENTICATED
 307                    + " NUMBER,"
 308                    + Resolver.Result.PORT
 309                    + " NUMBER,"
 310                    + "UNIQUE("
 311                    + Resolver.Result.DOMAIN
 312                    + ") ON CONFLICT REPLACE"
 313                    + ");";
 314
 315    private static final String CREATE_MESSAGE_TIME_INDEX =
 316            "CREATE INDEX message_time_index ON "
 317                    + Message.TABLENAME
 318                    + "("
 319                    + Message.TIME_SENT
 320                    + ")";
 321    private static final String CREATE_MESSAGE_CONVERSATION_INDEX =
 322            "CREATE INDEX message_conversation_index ON "
 323                    + Message.TABLENAME
 324                    + "("
 325                    + Message.CONVERSATION
 326                    + ")";
 327    private static final String CREATE_MESSAGE_DELETED_INDEX =
 328            "CREATE INDEX message_deleted_index ON "
 329                    + Message.TABLENAME
 330                    + "("
 331                    + Message.DELETED
 332                    + ")";
 333    private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX =
 334            "CREATE INDEX message_file_path_index ON "
 335                    + Message.TABLENAME
 336                    + "("
 337                    + Message.RELATIVE_FILE_PATH
 338                    + ")";
 339    private static final String CREATE_MESSAGE_TYPE_INDEX =
 340            "CREATE INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
 341
 342    private static final String CREATE_MESSAGE_INDEX_TABLE =
 343            "CREATE VIRTUAL TABLE messages_index USING fts4"
 344                    + " (uuid,body,notindexed=\"uuid\",content=\""
 345                    + Message.TABLENAME
 346                    + "\",tokenize='unicode61')";
 347    private static final String CREATE_MESSAGE_INSERT_TRIGGER =
 348            "CREATE TRIGGER after_message_insert AFTER INSERT ON "
 349                    + Message.TABLENAME
 350                    + " BEGIN INSERT INTO messages_index(rowid,uuid,body)"
 351                    + " VALUES(NEW.rowid,NEW.uuid,NEW.body); END;";
 352    private static final String CREATE_MESSAGE_UPDATE_TRIGGER =
 353            "CREATE TRIGGER after_message_update UPDATE OF uuid,body ON "
 354                    + Message.TABLENAME
 355                    + " BEGIN UPDATE messages_index SET body=NEW.body,uuid=NEW.uuid WHERE"
 356                    + " rowid=OLD.rowid; END;";
 357    private static final String CREATE_MESSAGE_DELETE_TRIGGER =
 358            "CREATE TRIGGER after_message_delete AFTER DELETE ON "
 359                    + Message.TABLENAME
 360                    + " BEGIN DELETE FROM messages_index WHERE rowid=OLD.rowid; END;";
 361    private static final String COPY_PREEXISTING_ENTRIES =
 362            "INSERT INTO messages_index(messages_index) VALUES('rebuild');";
 363
 364    protected Context context;
 365
 366    private DatabaseBackend(Context context) {
 367        super(context, DATABASE_NAME, null, DATABASE_VERSION);
 368        this.context = context;
 369        setWriteAheadLoggingEnabled(true);
 370    }
 371
 372    private static ContentValues createFingerprintStatusContentValues(
 373            FingerprintStatus.Trust trust, boolean active) {
 374        ContentValues values = new ContentValues();
 375        values.put(SQLiteAxolotlStore.TRUST, trust.toString());
 376        values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
 377        return values;
 378    }
 379
 380    public static boolean requiresMessageIndexRebuild() {
 381        return requiresMessageIndexRebuild;
 382    }
 383
 384    public void rebuildMessagesIndex() {
 385        final SQLiteDatabase db = getWritableDatabase();
 386        final Stopwatch stopwatch = Stopwatch.createStarted();
 387        db.execSQL(COPY_PREEXISTING_ENTRIES);
 388        Log.d(Config.LOGTAG, "rebuilt message index in " + stopwatch.stop());
 389    }
 390
 391    public static synchronized DatabaseBackend getInstance(Context context) {
 392        if (instance == null) {
 393            instance = new DatabaseBackend(context);
 394        }
 395        return instance;
 396    }
 397
 398    protected void cheogramMigrate(SQLiteDatabase db) {
 399        db.beginTransaction();
 400
 401        try {
 402            Cursor cursor = db.rawQuery("PRAGMA cheogram.user_version", null);
 403            cursor.moveToNext();
 404            int cheogramVersion = cursor.getInt(0);
 405            cursor.close();
 406
 407            if(cheogramVersion < 1) {
 408                // No cross-DB foreign keys unfortunately
 409                db.execSQL(
 410                    "CREATE TABLE cheogram." + Message.TABLENAME + "(" +
 411                    Message.UUID + " TEXT PRIMARY KEY, " +
 412                    "subject TEXT" +
 413                    ")"
 414                );
 415                db.execSQL("PRAGMA cheogram.user_version = 1");
 416            }
 417
 418            if(cheogramVersion < 2) {
 419                db.execSQL(
 420                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 421                    "ADD COLUMN oobUri TEXT"
 422                );
 423                db.execSQL(
 424                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 425                    "ADD COLUMN fileParams TEXT"
 426                );
 427                db.execSQL("PRAGMA cheogram.user_version = 2");
 428            }
 429
 430            if(cheogramVersion < 3) {
 431                db.execSQL(
 432                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 433                    "ADD COLUMN payloads TEXT"
 434                );
 435                db.execSQL("PRAGMA cheogram.user_version = 3");
 436            }
 437
 438            if(cheogramVersion < 4) {
 439                db.execSQL(
 440                    "CREATE TABLE cheogram.cids (" +
 441                    "cid TEXT NOT NULL PRIMARY KEY," +
 442                    "path TEXT NOT NULL" +
 443                    ")"
 444                );
 445                db.execSQL("PRAGMA cheogram.user_version = 4");
 446            }
 447
 448            if(cheogramVersion < 5) {
 449                db.execSQL(
 450                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 451                    "ADD COLUMN timeReceived NUMBER"
 452                );
 453                db.execSQL("CREATE INDEX cheogram.message_time_received_index ON " + Message.TABLENAME + " (timeReceived)");
 454                db.execSQL("PRAGMA cheogram.user_version = 5");
 455            }
 456
 457            if(cheogramVersion < 6) {
 458                db.execSQL(
 459                    "CREATE TABLE cheogram.blocked_media (" +
 460                    "cid TEXT NOT NULL PRIMARY KEY" +
 461                    ")"
 462                );
 463                db.execSQL("PRAGMA cheogram.user_version = 6");
 464            }
 465
 466            if(cheogramVersion < 7) {
 467                db.execSQL(
 468                    "ALTER TABLE cheogram.cids " +
 469                    "ADD COLUMN url TEXT"
 470                );
 471                db.execSQL("PRAGMA cheogram.user_version = 7");
 472            }
 473
 474            if(cheogramVersion < 8) {
 475                db.execSQL(
 476                    "CREATE TABLE cheogram.webxdc_updates (" +
 477                    "serial INTEGER PRIMARY KEY AUTOINCREMENT, " +
 478                    Message.CONVERSATION + " TEXT NOT NULL, " +
 479                    "sender TEXT NOT NULL, " +
 480                    "thread TEXT NOT NULL, " +
 481                    "threadParent TEXT, " +
 482                    "info TEXT, " +
 483                    "document TEXT, " +
 484                    "summary TEXT, " +
 485                    "payload TEXT" +
 486                    ")"
 487                );
 488                db.execSQL("CREATE INDEX cheogram.webxdc_index ON webxdc_updates (" + Message.CONVERSATION + ", thread)");
 489                db.execSQL("PRAGMA cheogram.user_version = 8");
 490				}
 491
 492            if(cheogramVersion < 9) {
 493                db.execSQL(
 494                    "ALTER TABLE cheogram.webxdc_updates " +
 495                    "ADD COLUMN message_id TEXT"
 496                );
 497                db.execSQL("CREATE UNIQUE INDEX cheogram.webxdc_message_id_index ON webxdc_updates (" + Message.CONVERSATION + ", message_id)");
 498                db.execSQL("PRAGMA cheogram.user_version = 9");
 499            }
 500
 501            if(cheogramVersion < 10) {
 502                db.execSQL(
 503                    "CREATE TABLE cheogram.muted_participants (" +
 504                    "muc_jid TEXT NOT NULL, " +
 505                    "occupant_id TEXT NOT NULL, " +
 506                    "nick TEXT NOT NULL," +
 507                    "PRIMARY KEY (muc_jid, occupant_id)" +
 508                    ")"
 509                );
 510                db.execSQL(
 511                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 512                    "ADD COLUMN occupant_id TEXT"
 513                );
 514                db.execSQL("PRAGMA cheogram.user_version = 10");
 515            }
 516
 517            if(cheogramVersion < 11) {
 518                if (Build.VERSION.SDK_INT >= 34) {
 519                    db.execSQL(
 520                        "ALTER TABLE cheogram.muted_participants " +
 521                        "DROP COLUMN nick"
 522                    );
 523                } else {
 524                    db.execSQL("DROP TABLE cheogram.muted_participants");
 525                    db.execSQL(
 526                        "CREATE TABLE cheogram.muted_participants (" +
 527                        "muc_jid TEXT NOT NULL, " +
 528                        "occupant_id TEXT NOT NULL, " +
 529                        "PRIMARY KEY (muc_jid, occupant_id)" +
 530                        ")"
 531                    );
 532                }
 533                db.execSQL("PRAGMA cheogram.user_version = 11");
 534            }
 535
 536            if(cheogramVersion < 12) {
 537                db.execSQL(
 538                    "ALTER TABLE cheogram." + Message.TABLENAME + " " +
 539                    "ADD COLUMN notificationDismissed NUMBER DEFAULT 0"
 540                );
 541                db.execSQL("PRAGMA cheogram.user_version = 12");
 542            }
 543
 544            db.setTransactionSuccessful();
 545        } finally {
 546            db.endTransaction();
 547        }
 548    }
 549
 550    @Override
 551    public void onConfigure(SQLiteDatabase db) {
 552        db.execSQL("PRAGMA foreign_keys=ON");
 553        db.rawQuery("PRAGMA secure_delete=ON", null).close();
 554        db.execSQL("ATTACH DATABASE ? AS cheogram", new Object[]{context.getDatabasePath("cheogram").getPath()});
 555        cheogramMigrate(db);
 556    }
 557
 558    @Override
 559    public void onCreate(SQLiteDatabase db) {
 560        db.execSQL(
 561                "create table "
 562                        + Account.TABLENAME
 563                        + "("
 564                        + Account.UUID
 565                        + " TEXT PRIMARY KEY,"
 566                        + Account.USERNAME
 567                        + " TEXT,"
 568                        + Account.SERVER
 569                        + " TEXT,"
 570                        + Account.PASSWORD
 571                        + " TEXT,"
 572                        + Account.DISPLAY_NAME
 573                        + " TEXT, "
 574                        + Account.STATUS
 575                        + " TEXT,"
 576                        + Account.STATUS_MESSAGE
 577                        + " TEXT,"
 578                        + Account.ROSTERVERSION
 579                        + " TEXT,"
 580                        + Account.OPTIONS
 581                        + " NUMBER, "
 582                        + Account.AVATAR
 583                        + " TEXT, "
 584                        + Account.KEYS
 585                        + " TEXT, "
 586                        + Account.HOSTNAME
 587                        + " TEXT, "
 588                        + Account.RESOURCE
 589                        + " TEXT,"
 590                        + Account.PINNED_MECHANISM
 591                        + " TEXT,"
 592                        + Account.PINNED_CHANNEL_BINDING
 593                        + " TEXT,"
 594                        + Account.FAST_MECHANISM
 595                        + " TEXT,"
 596                        + Account.FAST_TOKEN
 597                        + " TEXT,"
 598                        + Account.PORT
 599                        + " NUMBER DEFAULT 5222)");
 600        db.execSQL(
 601                "create table "
 602                        + Conversation.TABLENAME
 603                        + " ("
 604                        + Conversation.UUID
 605                        + " TEXT PRIMARY KEY, "
 606                        + Conversation.NAME
 607                        + " TEXT, "
 608                        + Conversation.CONTACT
 609                        + " TEXT, "
 610                        + Conversation.ACCOUNT
 611                        + " TEXT, "
 612                        + Conversation.CONTACTJID
 613                        + " TEXT, "
 614                        + Conversation.CREATED
 615                        + " NUMBER, "
 616                        + Conversation.STATUS
 617                        + " NUMBER, "
 618                        + Conversation.MODE
 619                        + " NUMBER, "
 620                        + Conversation.ATTRIBUTES
 621                        + " TEXT, FOREIGN KEY("
 622                        + Conversation.ACCOUNT
 623                        + ") REFERENCES "
 624                        + Account.TABLENAME
 625                        + "("
 626                        + Account.UUID
 627                        + ") ON DELETE CASCADE);");
 628        db.execSQL(
 629                "create table "
 630                        + Message.TABLENAME
 631                        + "( "
 632                        + Message.UUID
 633                        + " TEXT PRIMARY KEY, "
 634                        + Message.CONVERSATION
 635                        + " TEXT, "
 636                        + Message.TIME_SENT
 637                        + " NUMBER, "
 638                        + Message.COUNTERPART
 639                        + " TEXT, "
 640                        + Message.TRUE_COUNTERPART
 641                        + " TEXT,"
 642                        + Message.BODY
 643                        + " TEXT, "
 644                        + Message.ENCRYPTION
 645                        + " NUMBER, "
 646                        + Message.STATUS
 647                        + " NUMBER,"
 648                        + Message.TYPE
 649                        + " NUMBER, "
 650                        + Message.RELATIVE_FILE_PATH
 651                        + " TEXT, "
 652                        + Message.SERVER_MSG_ID
 653                        + " TEXT, "
 654                        + Message.FINGERPRINT
 655                        + " TEXT, "
 656                        + Message.CARBON
 657                        + " INTEGER, "
 658                        + Message.EDITED
 659                        + " TEXT, "
 660                        + Message.READ
 661                        + " NUMBER DEFAULT 1, "
 662                        + Message.OOB
 663                        + " INTEGER, "
 664                        + Message.ERROR_MESSAGE
 665                        + " TEXT,"
 666                        + Message.READ_BY_MARKERS
 667                        + " TEXT,"
 668                        + Message.MARKABLE
 669                        + " NUMBER DEFAULT 0,"
 670                        + Message.DELETED
 671                        + " NUMBER DEFAULT 0,"
 672                        + Message.BODY_LANGUAGE
 673                        + " TEXT,"
 674                        + Message.OCCUPANT_ID
 675                        + " TEXT,"
 676                        + Message.REACTIONS
 677                        + " TEXT,"
 678                        + Message.REMOTE_MSG_ID
 679                        + " TEXT, FOREIGN KEY("
 680                        + Message.CONVERSATION
 681                        + ") REFERENCES "
 682                        + Conversation.TABLENAME
 683                        + "("
 684                        + Conversation.UUID
 685                        + ") ON DELETE CASCADE);");
 686        db.execSQL(CREATE_MESSAGE_TIME_INDEX);
 687        db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
 688        db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
 689        db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
 690        db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
 691        db.execSQL(CREATE_CONTACTS_STATEMENT);
 692        db.execSQL(CREATE_SESSIONS_STATEMENT);
 693        db.execSQL(CREATE_PREKEYS_STATEMENT);
 694        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
 695        db.execSQL(CREATE_IDENTITIES_STATEMENT);
 696        db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 697        db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
 698        db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 699        db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 700        db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 701        db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
 702        db.execSQL(CREATE_CAPS_CACHE_TABLE);
 703        db.execSQL(CREATE_CAPS_CACHE_INDEX_CAPS);
 704        db.execSQL(CREATE_CAPS_CACHE_INDEX_CAPS2);
 705    }
 706
 707    @Override
 708    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 709        if (oldVersion < 2 && newVersion >= 2) {
 710            db.execSQL(
 711                    "update "
 712                            + Account.TABLENAME
 713                            + " set "
 714                            + Account.OPTIONS
 715                            + " = "
 716                            + Account.OPTIONS
 717                            + " | 8");
 718        }
 719        if (oldVersion < 3 && newVersion >= 3) {
 720            db.execSQL(
 721                    "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.TYPE + " NUMBER");
 722        }
 723        if (oldVersion < 5 && newVersion >= 5) {
 724            db.execSQL("DROP TABLE " + Contact.TABLENAME);
 725            db.execSQL(CREATE_CONTACTS_STATEMENT);
 726            db.execSQL("UPDATE " + Account.TABLENAME + " SET " + Account.ROSTERVERSION + " = NULL");
 727        }
 728        if (oldVersion < 6 && newVersion >= 6) {
 729            db.execSQL(
 730                    "ALTER TABLE "
 731                            + Message.TABLENAME
 732                            + " ADD COLUMN "
 733                            + Message.TRUE_COUNTERPART
 734                            + " TEXT");
 735        }
 736        if (oldVersion < 7 && newVersion >= 7) {
 737            db.execSQL(
 738                    "ALTER TABLE "
 739                            + Message.TABLENAME
 740                            + " ADD COLUMN "
 741                            + Message.REMOTE_MSG_ID
 742                            + " TEXT");
 743            db.execSQL(
 744                    "ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.AVATAR + " TEXT");
 745            db.execSQL(
 746                    "ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.AVATAR + " TEXT");
 747        }
 748        if (oldVersion < 8 && newVersion >= 8) {
 749            db.execSQL(
 750                    "ALTER TABLE "
 751                            + Conversation.TABLENAME
 752                            + " ADD COLUMN "
 753                            + Conversation.ATTRIBUTES
 754                            + " TEXT");
 755        }
 756        if (oldVersion < 9 && newVersion >= 9) {
 757            db.execSQL(
 758                    "ALTER TABLE "
 759                            + Contact.TABLENAME
 760                            + " ADD COLUMN "
 761                            + Contact.LAST_TIME
 762                            + " NUMBER");
 763            db.execSQL(
 764                    "ALTER TABLE "
 765                            + Contact.TABLENAME
 766                            + " ADD COLUMN "
 767                            + Contact.LAST_PRESENCE
 768                            + " TEXT");
 769        }
 770        if (oldVersion < 10 && newVersion >= 10) {
 771            db.execSQL(
 772                    "ALTER TABLE "
 773                            + Message.TABLENAME
 774                            + " ADD COLUMN "
 775                            + Message.RELATIVE_FILE_PATH
 776                            + " TEXT");
 777        }
 778        if (oldVersion < 11 && newVersion >= 11) {
 779            db.execSQL(
 780                    "ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.GROUPS + " TEXT");
 781            db.execSQL("delete from " + Contact.TABLENAME);
 782            db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 783        }
 784        if (oldVersion < 12 && newVersion >= 12) {
 785            db.execSQL(
 786                    "ALTER TABLE "
 787                            + Message.TABLENAME
 788                            + " ADD COLUMN "
 789                            + Message.SERVER_MSG_ID
 790                            + " TEXT");
 791        }
 792        if (oldVersion < 13 && newVersion >= 13) {
 793            db.execSQL("delete from " + Contact.TABLENAME);
 794            db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 795        }
 796        if (oldVersion < 14 && newVersion >= 14) {
 797            canonicalizeJids(db);
 798        }
 799        if (oldVersion < 15 && newVersion >= 15) {
 800            recreateAxolotlDb(db);
 801            db.execSQL(
 802                    "ALTER TABLE "
 803                            + Message.TABLENAME
 804                            + " ADD COLUMN "
 805                            + Message.FINGERPRINT
 806                            + " TEXT");
 807        }
 808        if (oldVersion < 16 && newVersion >= 16) {
 809            db.execSQL(
 810                    "ALTER TABLE "
 811                            + Message.TABLENAME
 812                            + " ADD COLUMN "
 813                            + Message.CARBON
 814                            + " INTEGER");
 815        }
 816        if (oldVersion < 19 && newVersion >= 19) {
 817            db.execSQL(
 818                    "ALTER TABLE "
 819                            + Account.TABLENAME
 820                            + " ADD COLUMN "
 821                            + Account.DISPLAY_NAME
 822                            + " TEXT");
 823        }
 824        if (oldVersion < 20 && newVersion >= 20) {
 825            db.execSQL(
 826                    "ALTER TABLE "
 827                            + Account.TABLENAME
 828                            + " ADD COLUMN "
 829                            + Account.HOSTNAME
 830                            + " TEXT");
 831            db.execSQL(
 832                    "ALTER TABLE "
 833                            + Account.TABLENAME
 834                            + " ADD COLUMN "
 835                            + Account.PORT
 836                            + " NUMBER DEFAULT 5222");
 837        }
 838        if (oldVersion < 26 && newVersion >= 26) {
 839            db.execSQL(
 840                    "ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
 841            db.execSQL(
 842                    "ALTER TABLE "
 843                            + Account.TABLENAME
 844                            + " ADD COLUMN "
 845                            + Account.STATUS_MESSAGE
 846                            + " TEXT");
 847        }
 848        if (oldVersion < 40 && newVersion >= 40) {
 849            db.execSQL(
 850                    "ALTER TABLE "
 851                            + Account.TABLENAME
 852                            + " ADD COLUMN "
 853                            + Account.RESOURCE
 854                            + " TEXT");
 855        }
 856        /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
 857         * depends on account de-serialization.
 858         */
 859        if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
 860            List<Account> accounts = getAccounts(db);
 861            for (Account account : accounts) {
 862                String ownDeviceIdString =
 863                        account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
 864                if (ownDeviceIdString == null) {
 865                    continue;
 866                }
 867                int ownDeviceId = Integer.valueOf(ownDeviceIdString);
 868                SignalProtocolAddress ownAddress =
 869                        new SignalProtocolAddress(
 870                                account.getJid().asBareJid().toString(), ownDeviceId);
 871                deleteSession(db, account, ownAddress);
 872                IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
 873                if (identityKeyPair != null) {
 874                    String[] selectionArgs = {
 875                        account.getUuid(),
 876                        CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
 877                    };
 878                    ContentValues values = new ContentValues();
 879                    values.put(SQLiteAxolotlStore.TRUSTED, 2);
 880                    db.update(
 881                            SQLiteAxolotlStore.IDENTITIES_TABLENAME,
 882                            values,
 883                            SQLiteAxolotlStore.ACCOUNT
 884                                    + " = ? AND "
 885                                    + SQLiteAxolotlStore.FINGERPRINT
 886                                    + " = ? ",
 887                            selectionArgs);
 888                } else {
 889                    Log.d(
 890                            Config.LOGTAG,
 891                            account.getJid().asBareJid()
 892                                    + ": could not load own identity key pair");
 893                }
 894            }
 895        }
 896        if (oldVersion < 18 && newVersion >= 18) {
 897            db.execSQL(
 898                    "ALTER TABLE "
 899                            + Message.TABLENAME
 900                            + " ADD COLUMN "
 901                            + Message.READ
 902                            + " NUMBER DEFAULT 1");
 903        }
 904
 905        if (oldVersion < 21 && newVersion >= 21) {
 906            List<Account> accounts = getAccounts(db);
 907            for (Account account : accounts) {
 908                account.unsetPgpSignature();
 909                db.update(
 910                        Account.TABLENAME,
 911                        account.getContentValues(),
 912                        Account.UUID + "=?",
 913                        new String[] {account.getUuid()});
 914            }
 915        }
 916
 917        if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
 918            db.execSQL(
 919                    "ALTER TABLE "
 920                            + SQLiteAxolotlStore.IDENTITIES_TABLENAME
 921                            + " ADD COLUMN "
 922                            + SQLiteAxolotlStore.CERTIFICATE);
 923        }
 924
 925        if (oldVersion < 24 && newVersion >= 24) {
 926            db.execSQL(
 927                    "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
 928        }
 929
 930        if (oldVersion < 25 && newVersion >= 25) {
 931            db.execSQL(
 932                    "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
 933        }
 934
 935        if (oldVersion < 26 && newVersion >= 26) {
 936            db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 937        }
 938
 939        if (oldVersion < 28 && newVersion >= 28) {
 940            canonicalizeJids(db);
 941        }
 942
 943        if (oldVersion < 29 && newVersion >= 29) {
 944            db.execSQL(
 945                    "ALTER TABLE "
 946                            + Message.TABLENAME
 947                            + " ADD COLUMN "
 948                            + Message.ERROR_MESSAGE
 949                            + " TEXT");
 950        }
 951        if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
 952            db.execSQL(
 953                    "ALTER TABLE "
 954                            + SQLiteAxolotlStore.IDENTITIES_TABLENAME
 955                            + " ADD COLUMN "
 956                            + SQLiteAxolotlStore.TRUST
 957                            + " TEXT");
 958            db.execSQL(
 959                    "ALTER TABLE "
 960                            + SQLiteAxolotlStore.IDENTITIES_TABLENAME
 961                            + " ADD COLUMN "
 962                            + SQLiteAxolotlStore.ACTIVE
 963                            + " NUMBER");
 964            HashMap<Integer, ContentValues> migration = new HashMap<>();
 965            migration.put(
 966                    0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 967            migration.put(
 968                    1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 969            migration.put(
 970                    2,
 971                    createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
 972            migration.put(
 973                    3,
 974                    createFingerprintStatusContentValues(
 975                            FingerprintStatus.Trust.COMPROMISED, false));
 976            migration.put(
 977                    4,
 978                    createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 979            migration.put(
 980                    5,
 981                    createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 982            migration.put(
 983                    6,
 984                    createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
 985            migration.put(
 986                    7,
 987                    createFingerprintStatusContentValues(
 988                            FingerprintStatus.Trust.VERIFIED_X509, true));
 989            migration.put(
 990                    8,
 991                    createFingerprintStatusContentValues(
 992                            FingerprintStatus.Trust.VERIFIED_X509, false));
 993            for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
 994                String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
 995                String[] where = {String.valueOf(entry.getKey())};
 996                db.update(
 997                        SQLiteAxolotlStore.IDENTITIES_TABLENAME,
 998                        entry.getValue(),
 999                        whereClause,
1000                        where);
1001            }
1002        }
1003        if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
1004            db.execSQL(
1005                    "ALTER TABLE "
1006                            + SQLiteAxolotlStore.IDENTITIES_TABLENAME
1007                            + " ADD COLUMN "
1008                            + SQLiteAxolotlStore.LAST_ACTIVATION
1009                            + " NUMBER");
1010            ContentValues defaults = new ContentValues();
1011            defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
1012            db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
1013        }
1014        if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
1015            String whereClause = SQLiteAxolotlStore.OWN + "=1";
1016            db.update(
1017                    SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1018                    createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true),
1019                    whereClause,
1020                    null);
1021        }
1022
1023        if (oldVersion < 34 && newVersion >= 34) {
1024            db.execSQL(CREATE_MESSAGE_TIME_INDEX);
1025
1026            final File oldPicturesDirectory =
1027                    new File(
1028                            Environment.getExternalStoragePublicDirectory(
1029                                            Environment.DIRECTORY_PICTURES)
1030                                    + "/Conversations/");
1031            final File oldFilesDirectory =
1032                    new File(Environment.getExternalStorageDirectory() + "/Conversations/");
1033            final File newFilesDirectory =
1034                    new File(
1035                            Environment.getExternalStorageDirectory()
1036                                    + "/Conversations/Media/Conversations Files/");
1037            final File newVideosDirectory =
1038                    new File(
1039                            Environment.getExternalStorageDirectory()
1040                                    + "/Conversations/Media/Conversations Videos/");
1041            if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
1042                final File newPicturesDirectory =
1043                        new File(
1044                                Environment.getExternalStorageDirectory()
1045                                        + "/Conversations/Media/Conversations Images/");
1046                newPicturesDirectory.getParentFile().mkdirs();
1047                if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
1048                    Log.d(
1049                            Config.LOGTAG,
1050                            "moved "
1051                                    + oldPicturesDirectory.getAbsolutePath()
1052                                    + " to "
1053                                    + newPicturesDirectory.getAbsolutePath());
1054                }
1055            }
1056            if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
1057                newFilesDirectory.mkdirs();
1058                newVideosDirectory.mkdirs();
1059                final File[] files = oldFilesDirectory.listFiles();
1060                if (files == null) {
1061                    return;
1062                }
1063                for (File file : files) {
1064                    if (file.getName().equals(".nomedia")) {
1065                        if (file.delete()) {
1066                            Log.d(
1067                                    Config.LOGTAG,
1068                                    "deleted nomedia file in "
1069                                            + oldFilesDirectory.getAbsolutePath());
1070                        }
1071                    } else if (file.isFile()) {
1072                        final String name = file.getName();
1073                        boolean isVideo = false;
1074                        int start = name.lastIndexOf('.') + 1;
1075                        if (start < name.length()) {
1076                            String mime =
1077                                    MimeUtils.guessMimeTypeFromExtension(name.substring(start));
1078                            isVideo = mime != null && mime.startsWith("video/");
1079                        }
1080                        File dst =
1081                                new File(
1082                                        (isVideo ? newVideosDirectory : newFilesDirectory)
1083                                                        .getAbsolutePath()
1084                                                + "/"
1085                                                + file.getName());
1086                        if (file.renameTo(dst)) {
1087                            Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
1088                        }
1089                    }
1090                }
1091            }
1092        }
1093        if (oldVersion < 35 && newVersion >= 35) {
1094            db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
1095        }
1096        if (oldVersion < 36 && newVersion >= 36) {
1097            List<Account> accounts = getAccounts(db);
1098            for (Account account : accounts) {
1099                account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
1100                account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
1101                db.update(
1102                        Account.TABLENAME,
1103                        account.getContentValues(),
1104                        Account.UUID + "=?",
1105                        new String[] {account.getUuid()});
1106            }
1107        }
1108
1109        if (oldVersion < 37 && newVersion >= 37) {
1110            db.execSQL(
1111                    "ALTER TABLE "
1112                            + Message.TABLENAME
1113                            + " ADD COLUMN "
1114                            + Message.READ_BY_MARKERS
1115                            + " TEXT");
1116        }
1117
1118        if (oldVersion < 38 && newVersion >= 38) {
1119            db.execSQL(
1120                    "ALTER TABLE "
1121                            + Message.TABLENAME
1122                            + " ADD COLUMN "
1123                            + Message.MARKABLE
1124                            + " NUMBER DEFAULT 0");
1125        }
1126
1127        if (oldVersion < 39 && newVersion >= 39) {
1128            db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
1129        }
1130
1131        if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
1132            List<Account> accounts = getAccounts(db);
1133            for (Account account : accounts) {
1134                account.setOption(Account.OPTION_MAGIC_CREATE, true);
1135                db.update(
1136                        Account.TABLENAME,
1137                        account.getContentValues(),
1138                        Account.UUID + "=?",
1139                        new String[] {account.getUuid()});
1140            }
1141        }
1142
1143        if (oldVersion < 44 && newVersion >= 44) {
1144            db.execSQL(
1145                    "ALTER TABLE "
1146                            + Message.TABLENAME
1147                            + " ADD COLUMN "
1148                            + Message.DELETED
1149                            + " NUMBER DEFAULT 0");
1150            db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
1151            db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
1152            db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
1153        }
1154
1155        if (oldVersion < 45 && newVersion >= 45) {
1156            db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.BODY_LANGUAGE);
1157        }
1158
1159        if (oldVersion < 46 && newVersion >= 46) {
1160            final long start = SystemClock.elapsedRealtime();
1161            db.rawQuery("PRAGMA secure_delete = FALSE", null).close();
1162            db.execSQL("update " + Message.TABLENAME + " set " + Message.EDITED + "=NULL");
1163            db.rawQuery("PRAGMA secure_delete=ON", null).close();
1164            final long diff = SystemClock.elapsedRealtime() - start;
1165            Log.d(Config.LOGTAG, "deleted old edit information in " + diff + "ms");
1166        }
1167        if (oldVersion < 47 && newVersion >= 47) {
1168            db.execSQL(
1169                    "ALTER TABLE "
1170                            + Contact.TABLENAME
1171                            + " ADD COLUMN "
1172                            + Contact.PRESENCE_NAME
1173                            + " TEXT");
1174        }
1175        if (oldVersion < 48 && newVersion >= 48) {
1176            db.execSQL(
1177                    "ALTER TABLE "
1178                            + Contact.TABLENAME
1179                            + " ADD COLUMN "
1180                            + Contact.RTP_CAPABILITY
1181                            + " TEXT");
1182        }
1183        if (oldVersion < 49 && newVersion >= 49) {
1184            db.beginTransaction();
1185            db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
1186            db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
1187            db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
1188            db.execSQL("DROP TABLE IF EXISTS messages_index;");
1189            // a hack that should not be necessary, but
1190            // there was at least one occurence when SQLite failed at this
1191            db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
1192            db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
1193            db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
1194            db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
1195            db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
1196            db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
1197            db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
1198            db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
1199            db.setTransactionSuccessful();
1200            db.endTransaction();
1201            requiresMessageIndexRebuild = true;
1202        }
1203        if (oldVersion < 50 && newVersion >= 50) {
1204            db.execSQL(
1205                    "ALTER TABLE "
1206                            + Account.TABLENAME
1207                            + " ADD COLUMN "
1208                            + Account.PINNED_MECHANISM
1209                            + " TEXT");
1210            db.execSQL(
1211                    "ALTER TABLE "
1212                            + Account.TABLENAME
1213                            + " ADD COLUMN "
1214                            + Account.PINNED_CHANNEL_BINDING
1215                            + " TEXT");
1216        }
1217        if (oldVersion < 51 && newVersion >= 51) {
1218            db.execSQL(
1219                    "ALTER TABLE "
1220                            + Account.TABLENAME
1221                            + " ADD COLUMN "
1222                            + Account.FAST_MECHANISM
1223                            + " TEXT");
1224            db.execSQL(
1225                    "ALTER TABLE "
1226                            + Account.TABLENAME
1227                            + " ADD COLUMN "
1228                            + Account.FAST_TOKEN
1229                            + " TEXT");
1230        }
1231        if (oldVersion < 52 && newVersion >= 52) {
1232            db.execSQL(
1233                    "ALTER TABLE "
1234                            + Message.TABLENAME
1235                            + " ADD COLUMN "
1236                            + Message.OCCUPANT_ID
1237                            + " TEXT");
1238            db.execSQL(
1239                    "ALTER TABLE "
1240                            + Message.TABLENAME
1241                            + " ADD COLUMN "
1242                            + Message.REACTIONS
1243                            + " TEXT");
1244        }
1245        if (oldVersion < 53 && newVersion >= 53) {
1246            try (final Cursor cursor =
1247                    db.query(
1248                            Account.TABLENAME,
1249                            new String[] {Account.UUID, Account.USERNAME},
1250                            null,
1251                            null,
1252                            null,
1253                            null,
1254                            null)) {
1255                while (cursor != null && cursor.moveToNext()) {
1256                    final var uuid = cursor.getString(0);
1257                    final var username = cursor.getString(1);
1258                    final Localpart localpart;
1259                    try {
1260                        localpart = Localpart.fromUnescaped(username);
1261                    } catch (final XmppStringprepException e) {
1262                        Log.d(Config.LOGTAG, "unable to parse jid");
1263                        continue;
1264                    }
1265                    final var contentValues = new ContentValues();
1266                    contentValues.putNull(Account.ROSTERVERSION);
1267                    contentValues.put(Account.USERNAME, localpart.toString());
1268                    db.update(
1269                            Account.TABLENAME,
1270                            contentValues,
1271                            Account.UUID + "=?",
1272                            new String[] {uuid});
1273                }
1274            }
1275        }
1276        if (oldVersion < 54 && newVersion >= 54) {
1277            db.execSQL("DROP TABLE discovery_results");
1278            db.execSQL(CREATE_CAPS_CACHE_TABLE);
1279            db.execSQL(CREATE_CAPS_CACHE_INDEX_CAPS);
1280            db.execSQL(CREATE_CAPS_CACHE_INDEX_CAPS2);
1281        }
1282    }
1283
1284    private void canonicalizeJids(SQLiteDatabase db) {
1285        // migrate db to new, canonicalized JID domainpart representation
1286
1287        // Conversation table
1288        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
1289        while (cursor.moveToNext()) {
1290            String newJid;
1291            try {
1292                newJid =
1293                        Jid.of(
1294                                        cursor.getString(
1295                                                cursor.getColumnIndexOrThrow(
1296                                                        Conversation.CONTACTJID)))
1297                                .toString();
1298            } catch (final IllegalArgumentException e) {
1299                Log.e(
1300                        Config.LOGTAG,
1301                        "Failed to migrate Conversation CONTACTJID "
1302                                + cursor.getString(
1303                                        cursor.getColumnIndexOrThrow(Conversation.CONTACTJID))
1304                                + ". Skipping...",
1305                        e);
1306                continue;
1307            }
1308
1309            final String[] updateArgs = {
1310                newJid, cursor.getString(cursor.getColumnIndexOrThrow(Conversation.UUID)),
1311            };
1312            db.execSQL(
1313                    "update "
1314                            + Conversation.TABLENAME
1315                            + " set "
1316                            + Conversation.CONTACTJID
1317                            + " = ? "
1318                            + " where "
1319                            + Conversation.UUID
1320                            + " = ?",
1321                    updateArgs);
1322        }
1323        cursor.close();
1324
1325        // Contact table
1326        cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
1327        while (cursor.moveToNext()) {
1328            String newJid;
1329            try {
1330                newJid =
1331                        Jid.of(cursor.getString(cursor.getColumnIndexOrThrow(Contact.JID)))
1332                                .toString();
1333            } catch (final IllegalArgumentException e) {
1334                Log.e(
1335                        Config.LOGTAG,
1336                        "Failed to migrate Contact JID "
1337                                + cursor.getString(cursor.getColumnIndexOrThrow(Contact.JID))
1338                                + ":  Skipping...",
1339                        e);
1340                continue;
1341            }
1342
1343            final String[] updateArgs = {
1344                newJid,
1345                cursor.getString(cursor.getColumnIndexOrThrow(Contact.ACCOUNT)),
1346                cursor.getString(cursor.getColumnIndexOrThrow(Contact.JID)),
1347            };
1348            db.execSQL(
1349                    "update "
1350                            + Contact.TABLENAME
1351                            + " set "
1352                            + Contact.JID
1353                            + " = ? "
1354                            + " where "
1355                            + Contact.ACCOUNT
1356                            + " = ? "
1357                            + " AND "
1358                            + Contact.JID
1359                            + " = ?",
1360                    updateArgs);
1361        }
1362        cursor.close();
1363
1364        // Account table
1365        cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
1366        while (cursor.moveToNext()) {
1367            String newServer;
1368            try {
1369                newServer =
1370                        Jid.of(
1371                                        cursor.getString(
1372                                                cursor.getColumnIndexOrThrow(Account.USERNAME)),
1373                                        cursor.getString(
1374                                                cursor.getColumnIndexOrThrow(Account.SERVER)),
1375                                        null)
1376                                .getDomain()
1377                                .toString();
1378            } catch (final IllegalArgumentException e) {
1379                Log.e(
1380                        Config.LOGTAG,
1381                        "Failed to migrate Account SERVER "
1382                                + cursor.getString(cursor.getColumnIndexOrThrow(Account.SERVER))
1383                                + ". Skipping...",
1384                        e);
1385                continue;
1386            }
1387
1388            String[] updateArgs = {
1389                newServer, cursor.getString(cursor.getColumnIndexOrThrow(Account.UUID)),
1390            };
1391            db.execSQL(
1392                    "update "
1393                            + Account.TABLENAME
1394                            + " set "
1395                            + Account.SERVER
1396                            + " = ? "
1397                            + " where "
1398                            + Account.UUID
1399                            + " = ?",
1400                    updateArgs);
1401        }
1402        cursor.close();
1403    }
1404
1405    public DownloadableFile getFileForCid(Cid cid) {
1406        if (cid == null) return null;
1407
1408        SQLiteDatabase db = this.getReadableDatabase();
1409        Cursor cursor = db.query("cheogram.cids", new String[]{"path"}, "cid=?", new String[]{cid.toString()}, null, null, null);
1410        DownloadableFile f = null;
1411        if (cursor.moveToNext()) {
1412            f = new DownloadableFile(cursor.getString(0));
1413        }
1414        cursor.close();
1415        return f;
1416    }
1417
1418    public String getUrlForCid(Cid cid) {
1419        SQLiteDatabase db = this.getReadableDatabase();
1420        Cursor cursor = db.query("cheogram.cids", new String[]{"url"}, "cid=?", new String[]{cid.toString()}, null, null, null);
1421        String url = null;
1422        if (cursor.moveToNext()) {
1423            url = cursor.getString(0);
1424        }
1425        cursor.close();
1426        return url;
1427    }
1428
1429    public void saveCid(Cid cid, File file) {
1430        saveCid(cid, file, null);
1431    }
1432
1433    public void saveCid(Cid cid, File file, String url) {
1434        SQLiteDatabase db = this.getWritableDatabase();
1435        ContentValues cv = new ContentValues();
1436        cv.put("cid", cid.toString());
1437        if (file != null) cv.put("path", file.getAbsolutePath());
1438        if (url != null) cv.put("url", url);
1439        if (db.update("cheogram.cids", cv, "cid=?", new String[]{cid.toString()}) < 1) {
1440            db.insertWithOnConflict("cheogram.cids", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
1441        }
1442    }
1443
1444    public void blockMedia(Cid cid) {
1445        SQLiteDatabase db = this.getWritableDatabase();
1446        ContentValues cv = new ContentValues();
1447        cv.put("cid", cid.toString());
1448        db.insertWithOnConflict("cheogram.blocked_media", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
1449    }
1450
1451    public boolean isBlockedMedia(Cid cid) {
1452        SQLiteDatabase db = this.getReadableDatabase();
1453        Cursor cursor = db.query("cheogram.blocked_media", new String[]{"count(*)"}, "cid=?", new String[]{cid.toString()}, null, null, null);
1454        boolean is = false;
1455        if (cursor.moveToNext()) {
1456            is = cursor.getInt(0) > 0;
1457        }
1458        cursor.close();
1459        return is;
1460    }
1461
1462    public void clearBlockedMedia() {
1463        SQLiteDatabase db = this.getWritableDatabase();
1464        db.execSQL("DELETE FROM cheogram.blocked_media");
1465    }
1466
1467    public Multimap<String, String> loadMutedMucUsers() {
1468        Multimap<String, String> result = HashMultimap.create();
1469        SQLiteDatabase db = this.getReadableDatabase();
1470        Cursor cursor = db.query("cheogram.muted_participants", new String[]{"muc_jid", "occupant_id"}, null, null, null, null, null);
1471        while (cursor.moveToNext()) {
1472            result.put(cursor.getString(0), cursor.getString(1));
1473        }
1474        cursor.close();
1475        return result;
1476    }
1477
1478    public boolean muteMucUser(MucOptions.User user) {
1479        if (user.getMuc() == null || user.getOccupantId() == null) return false;
1480
1481        SQLiteDatabase db = this.getWritableDatabase();
1482        ContentValues cv = new ContentValues();
1483        cv.put("muc_jid", user.getMuc().toString());
1484        cv.put("occupant_id", user.getOccupantId());
1485        db.insertWithOnConflict("cheogram.muted_participants", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
1486
1487        return true;
1488    }
1489
1490    public boolean unmuteMucUser(MucOptions.User user) {
1491        if (user.getMuc() == null || user.getOccupantId() == null) return false;
1492
1493        SQLiteDatabase db = this.getWritableDatabase();
1494        String where = "muc_jid=? AND occupant_id=?";
1495        String[] whereArgs = {user.getMuc().toString(), user.getOccupantId()};
1496        db.delete("cheogram.muted_participants", where, whereArgs);
1497
1498        return true;
1499    }
1500
1501    public void insertWebxdcUpdate(final WebxdcUpdate update) {
1502        SQLiteDatabase db = this.getWritableDatabase();
1503        db.insertWithOnConflict("cheogram.webxdc_updates", null, update.getContentValues(), SQLiteDatabase.CONFLICT_IGNORE);
1504    }
1505
1506    public WebxdcUpdate findLastWebxdcUpdate(Message message) {
1507        if (message.getThread() == null) {
1508            Log.w(Config.LOGTAG, "WebXDC message with no thread!");
1509            return null;
1510        }
1511
1512        SQLiteDatabase db = this.getReadableDatabase();
1513        String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent()};
1514        Cursor cursor = db.query("cheogram.webxdc_updates", null,
1515                Message.CONVERSATION + "=? AND thread=?",
1516                selectionArgs, null, null, "serial ASC");
1517        WebxdcUpdate update = null;
1518        if (cursor.moveToLast()) {
1519            update = new WebxdcUpdate(cursor, cursor.getLong(cursor.getColumnIndex("serial")));
1520        }
1521        cursor.close();
1522        return update;
1523    }
1524
1525    public List<WebxdcUpdate> findWebxdcUpdates(Message message, long serial) {
1526        SQLiteDatabase db = this.getReadableDatabase();
1527        String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent(), String.valueOf(serial)};
1528        Cursor cursor = db.query("cheogram.webxdc_updates", null,
1529                Message.CONVERSATION + "=? AND thread=? AND serial>?",
1530                selectionArgs, null, null, "serial ASC");
1531        long maxSerial = 0;
1532        if (cursor.moveToLast()) {
1533            maxSerial = cursor.getLong(cursor.getColumnIndex("serial"));
1534        }
1535        cursor.moveToFirst();
1536        cursor.moveToPrevious();
1537
1538        List<WebxdcUpdate> updates = new ArrayList<>();
1539        while (cursor.moveToNext()) {
1540            updates.add(new WebxdcUpdate(cursor, maxSerial));
1541        }
1542        cursor.close();
1543        return updates;
1544    }
1545
1546    public void createConversation(Conversation conversation) {
1547        SQLiteDatabase db = this.getWritableDatabase();
1548        db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
1549    }
1550
1551    public void createMessage(Message message) {
1552        SQLiteDatabase db = this.getWritableDatabase();
1553        db.insert(Message.TABLENAME, null, message.getContentValues());
1554        db.insert("cheogram." + Message.TABLENAME, null, message.getCheogramContentValues());
1555    }
1556
1557    public void createAccount(Account account) {
1558        SQLiteDatabase db = this.getWritableDatabase();
1559        db.insert(Account.TABLENAME, null, account.getContentValues());
1560    }
1561
1562    public void saveResolverResult(String domain, Resolver.Result result) {
1563        SQLiteDatabase db = this.getWritableDatabase();
1564        ContentValues contentValues = result.toContentValues();
1565        contentValues.put(Resolver.Result.DOMAIN, domain);
1566        db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
1567    }
1568
1569    public synchronized Resolver.Result findResolverResult(String domain) {
1570        SQLiteDatabase db = this.getReadableDatabase();
1571        String where = Resolver.Result.DOMAIN + "=?";
1572        String[] whereArgs = {domain};
1573        final Cursor cursor =
1574                db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
1575        Resolver.Result result = null;
1576        if (cursor != null) {
1577            try {
1578                if (cursor.moveToFirst()) {
1579                    result = Resolver.Result.fromCursor(cursor);
1580                }
1581            } catch (Exception e) {
1582                Log.d(
1583                        Config.LOGTAG,
1584                        "unable to find cached resolver result in database " + e.getMessage());
1585                return null;
1586            } finally {
1587                cursor.close();
1588            }
1589        }
1590        return result;
1591    }
1592
1593    public void insertPresenceTemplate(PresenceTemplate template) {
1594        SQLiteDatabase db = this.getWritableDatabase();
1595        String whereToDelete = PresenceTemplate.MESSAGE + "=?";
1596        String[] whereToDeleteArgs = {template.getStatusMessage()};
1597        db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
1598        db.delete(
1599                PresenceTemplate.TABELNAME,
1600                PresenceTemplate.UUID
1601                        + " not in (select "
1602                        + PresenceTemplate.UUID
1603                        + " from "
1604                        + PresenceTemplate.TABELNAME
1605                        + " order by "
1606                        + PresenceTemplate.LAST_USED
1607                        + " desc limit 9)",
1608                null);
1609        db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
1610    }
1611
1612    public List<PresenceTemplate> getPresenceTemplates() {
1613        ArrayList<PresenceTemplate> templates = new ArrayList<>();
1614        SQLiteDatabase db = this.getReadableDatabase();
1615        Cursor cursor =
1616                db.query(
1617                        PresenceTemplate.TABELNAME,
1618                        null,
1619                        null,
1620                        null,
1621                        null,
1622                        null,
1623                        PresenceTemplate.LAST_USED + " desc");
1624        while (cursor.moveToNext()) {
1625            templates.add(PresenceTemplate.fromCursor(cursor));
1626        }
1627        cursor.close();
1628        return templates;
1629    }
1630
1631    public CopyOnWriteArrayList<Conversation> getConversations(int status) {
1632        CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
1633        SQLiteDatabase db = this.getReadableDatabase();
1634        String[] selectionArgs = {Integer.toString(status)};
1635        Cursor cursor =
1636                db.rawQuery(
1637                        "select * from "
1638                                + Conversation.TABLENAME
1639                                + " where "
1640                                + Conversation.STATUS
1641                                + " = ? and "
1642                                + Conversation.CONTACTJID
1643                                + " is not null order by "
1644                                + Conversation.CREATED
1645                                + " desc",
1646                        selectionArgs);
1647        while (cursor.moveToNext()) {
1648            final Conversation conversation = Conversation.fromCursor(cursor);
1649            if (conversation.getJid() instanceof Jid.Invalid) {
1650                continue;
1651            }
1652            list.add(conversation);
1653        }
1654        cursor.close();
1655        return list;
1656    }
1657
1658    public Message getMessage(Conversation conversation, String uuid) {
1659        ArrayList<Message> list = new ArrayList<>();
1660        SQLiteDatabase db = this.getReadableDatabase();
1661        Cursor cursor;
1662        cursor = db.rawQuery(
1663            "SELECT * FROM " + Message.TABLENAME + " " +
1664            "LEFT JOIN cheogram." + Message.TABLENAME +
1665            "  USING (" + Message.UUID + ")" +
1666            "WHERE " + Message.UUID + "=?",
1667            new String[]{uuid}
1668        );
1669        while (cursor.moveToNext()) {
1670            try {
1671                return Message.fromCursor(cursor, conversation);
1672            } catch (Exception e) {
1673                Log.e(Config.LOGTAG, "unable to restore message");
1674            }
1675        }
1676        cursor.close();
1677        return null;
1678    }
1679
1680    public ArrayList<Message> getMessages(Conversation conversations, int limit) {
1681        return getMessages(conversations, limit, -1);
1682    }
1683
1684    public Map<String, Message> getMessageFuzzyIds(Conversation conversation, Collection<String> ids) {
1685        final var result = new Hashtable<String, Message>();
1686        if (ids.size() < 1) return result;
1687        final ArrayList<String> params = new ArrayList<>();
1688        final ArrayList<String> template = new ArrayList<>();
1689        for (final var id : ids) {
1690            template.add("?");
1691        }
1692        params.addAll(ids);
1693        params.addAll(ids);
1694        params.addAll(ids);
1695        ArrayList<Message> list = new ArrayList<>();
1696        SQLiteDatabase db = this.getReadableDatabase();
1697        Cursor cursor;
1698        cursor = db.rawQuery(
1699            "SELECT * FROM " + Message.TABLENAME + " " +
1700            "LEFT JOIN cheogram." + Message.TABLENAME +
1701            "  USING (" + Message.UUID + ")" +
1702            "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) + ")",
1703            params.toArray(new String[0])
1704        );
1705
1706        while (cursor.moveToNext()) {
1707            try {
1708                final var m = Message.fromCursor(cursor, conversation);
1709                if (ids.contains(m.getUuid())) result.put(m.getUuid(), m);
1710                if (ids.contains(m.getServerMsgId())) result.put(m.getServerMsgId(), m);
1711                if (ids.contains(m.getRemoteMsgId())) result.put(m.getRemoteMsgId(), m);
1712            } catch (Exception e) {
1713                Log.e(Config.LOGTAG, "unable to restore message");
1714            }
1715        }
1716        cursor.close();
1717        return result;
1718    }
1719
1720    public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
1721        ArrayList<Message> list = new ArrayList<>();
1722        SQLiteDatabase db = this.getReadableDatabase();
1723        Cursor cursor;
1724        if (timestamp == -1) {
1725            String[] selectionArgs = {conversation.getUuid()};
1726            cursor = db.rawQuery(
1727                "SELECT * FROM " + Message.TABLENAME + " " +
1728                "LEFT JOIN cheogram." + Message.TABLENAME +
1729                "  USING (" + Message.UUID + ")" +
1730                " WHERE " + Message.UUID + " IN (" +
1731                "SELECT " + Message.UUID + " FROM " + Message.TABLENAME +
1732                " WHERE " + Message.CONVERSATION + "=? " +
1733                "ORDER BY " + Message.TIME_SENT + " DESC " +
1734                "LIMIT " + String.valueOf(limit) + ") " +
1735                "ORDER BY " + Message.TIME_SENT + " DESC ",
1736                selectionArgs
1737            );
1738        } else {
1739            String[] selectionArgs = {conversation.getUuid(),
1740                    Long.toString(timestamp)};
1741            cursor = db.rawQuery(
1742                "SELECT * FROM " + Message.TABLENAME + " " +
1743                "LEFT JOIN cheogram." + Message.TABLENAME +
1744                "  USING (" + Message.UUID + ")" +
1745                " WHERE " + Message.UUID + " IN (" +
1746                "SELECT " + Message.UUID + " FROM " + Message.TABLENAME +
1747                " WHERE " + Message.CONVERSATION + "=? AND " +
1748                Message.TIME_SENT + "<? " +
1749                "ORDER BY " + Message.TIME_SENT + " DESC " +
1750                "LIMIT " + String.valueOf(limit) + ") " +
1751                "ORDER BY " + Message.TIME_SENT + " DESC ",
1752                selectionArgs
1753            );
1754        }
1755        CursorUtils.upgradeCursorWindowSize(cursor);
1756        final Multimap<String, Message> waitingForReplies = HashMultimap.create();
1757        final var replyIds = new HashSet<String>();
1758        while (cursor.moveToNext()) {
1759            try {
1760                final var m = Message.fromCursor(cursor, conversation);
1761                final var reply = m.getReply();
1762                if (reply != null && reply.getAttribute("id") != null) { // Guard against busted replies
1763                    replyIds.add(reply.getAttribute("id"));
1764                    waitingForReplies.put(reply.getAttribute("id"), m);
1765                }
1766                list.add(0, m);
1767            } catch (Exception e) {
1768                Log.e(Config.LOGTAG, "unable to restore message", e);
1769            }
1770        }
1771        for (final var parent : getMessageFuzzyIds(conversation, replyIds).entrySet()) {
1772            for (final var m : waitingForReplies.get(parent.getKey())) {
1773                m.setInReplyTo(parent.getValue());
1774            }
1775        }
1776        cursor.close();
1777        return list;
1778    }
1779
1780    public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1781        final SQLiteDatabase db = this.getReadableDatabase();
1782        final StringBuilder SQL = new StringBuilder();
1783        final String[] selectionArgs;
1784        SQL.append(
1785                "SELECT "
1786                        + Message.TABLENAME
1787                        + ".*,"
1788                        + Conversation.TABLENAME
1789                        + "."
1790                        + Conversation.CONTACTJID
1791                        + ","
1792                        + Conversation.TABLENAME
1793                        + "."
1794                        + Conversation.ACCOUNT
1795                        + ","
1796                        + Conversation.TABLENAME
1797                        + "."
1798                        + Conversation.MODE
1799                        + " FROM "
1800                        + Message.TABLENAME
1801                        + " JOIN "
1802                        + Conversation.TABLENAME
1803                        + " ON "
1804                        + Message.TABLENAME
1805                        + "."
1806                        + Message.CONVERSATION
1807                        + "="
1808                        + Conversation.TABLENAME
1809                        + "."
1810                        + Conversation.UUID
1811                        + " JOIN messages_index ON messages_index.rowid=messages.rowid WHERE "
1812                        + Message.ENCRYPTION
1813                        + " NOT IN("
1814                        + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1815                        + ","
1816                        + Message.ENCRYPTION_PGP
1817                        + ","
1818                        + Message.ENCRYPTION_DECRYPTION_FAILED
1819                        + ","
1820                        + Message.ENCRYPTION_AXOLOTL_FAILED
1821                        + ") AND "
1822                        + Message.TYPE
1823                        + " IN("
1824                        + Message.TYPE_TEXT
1825                        + ","
1826                        + Message.TYPE_PRIVATE
1827                        + ") AND messages_index.body MATCH ?");
1828        if (uuid == null) {
1829            selectionArgs = new String[] {FtsUtils.toMatchString(term)};
1830        } else {
1831            selectionArgs = new String[] {FtsUtils.toMatchString(term), uuid};
1832            SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1833        }
1834        SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1835        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1836        return db.rawQuery(SQL.toString(), selectionArgs);
1837    }
1838
1839    public List<String> markFileAsDeleted(final File file, final boolean internal) {
1840        SQLiteDatabase db = this.getReadableDatabase();
1841        String selection;
1842        String[] selectionArgs;
1843        if (internal) {
1844            final String name = file.getName();
1845            if (name.endsWith(".pgp")) {
1846                selection =
1847                        "("
1848                                + Message.RELATIVE_FILE_PATH
1849                                + " IN(?,?) OR ("
1850                                + Message.RELATIVE_FILE_PATH
1851                                + "=? and encryption in(1,4))) and type in (1,2,5)";
1852                selectionArgs =
1853                        new String[] {
1854                            file.getAbsolutePath(), name, name.substring(0, name.length() - 4)
1855                        };
1856            } else {
1857                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1858                selectionArgs = new String[] {file.getAbsolutePath(), name};
1859            }
1860        } else {
1861            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1862            selectionArgs = new String[] {file.getAbsolutePath()};
1863        }
1864        final List<String> uuids = new ArrayList<>();
1865        Cursor cursor =
1866                db.query(
1867                        Message.TABLENAME,
1868                        new String[] {Message.UUID},
1869                        selection,
1870                        selectionArgs,
1871                        null,
1872                        null,
1873                        null);
1874        while (cursor != null && cursor.moveToNext()) {
1875            uuids.add(cursor.getString(0));
1876        }
1877        if (cursor != null) {
1878            cursor.close();
1879        }
1880        markFileAsDeleted(uuids);
1881        return uuids;
1882    }
1883
1884    public void markFileAsDeleted(List<String> uuids) {
1885        SQLiteDatabase db = this.getReadableDatabase();
1886        final ContentValues contentValues = new ContentValues();
1887        final String where = Message.UUID + "=?";
1888        contentValues.put(Message.DELETED, 1);
1889        db.beginTransaction();
1890        for (String uuid : uuids) {
1891            db.update(Message.TABLENAME, contentValues, where, new String[] {uuid});
1892        }
1893        db.setTransactionSuccessful();
1894        db.endTransaction();
1895    }
1896
1897    public void markFilesAsChanged(List<FilePathInfo> files) {
1898        SQLiteDatabase db = this.getReadableDatabase();
1899        final String where = Message.UUID + "=?";
1900        db.beginTransaction();
1901        for (FilePathInfo info : files) {
1902            final ContentValues contentValues = new ContentValues();
1903            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1904            db.update(Message.TABLENAME, contentValues, where, new String[] {info.uuid.toString()});
1905        }
1906        db.setTransactionSuccessful();
1907        db.endTransaction();
1908    }
1909
1910    public List<FilePathInfo> getFilePathInfo() {
1911        final SQLiteDatabase db = this.getReadableDatabase();
1912        final Cursor cursor =
1913                db.query(
1914                        Message.TABLENAME,
1915                        new String[] {Message.UUID, Message.RELATIVE_FILE_PATH, Message.DELETED},
1916                        "type in (1,2,5) and " + Message.RELATIVE_FILE_PATH + " is not null",
1917                        null,
1918                        null,
1919                        null,
1920                        null);
1921        final List<FilePathInfo> list = new ArrayList<>();
1922        while (cursor != null && cursor.moveToNext()) {
1923            list.add(
1924                    new FilePathInfo(
1925                            cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1926        }
1927        if (cursor != null) {
1928            cursor.close();
1929        }
1930        return list;
1931    }
1932
1933    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1934        SQLiteDatabase db = this.getReadableDatabase();
1935        final String SQL =
1936                "select uuid,relativeFilePath from messages where type in (1,2,5) and deleted=0 and"
1937                        + " "
1938                        + Message.RELATIVE_FILE_PATH
1939                        + " is not null and conversationUuid=(select uuid from conversations where"
1940                        + " accountUuid=? and (contactJid=? or contactJid like ?)) order by"
1941                        + " timeSent desc";
1942        final String[] args = {account, jid.toString(), jid + "/%"};
1943        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1944        List<FilePath> filesPaths = new ArrayList<>();
1945        while (cursor.moveToNext()) {
1946            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1947        }
1948        cursor.close();
1949        return filesPaths;
1950    }
1951
1952    public Message getMessageWithServerMsgId(
1953            final Conversation conversation, final String messageId) {
1954        final var db = this.getReadableDatabase();
1955        final String sql =
1956                "select * from messages LEFT JOIN cheogram.messages USING (uuid) where conversationUuid=? and serverMsgId=? LIMIT 1";
1957        final String[] args = {conversation.getUuid(), messageId};
1958        final Cursor cursor = db.rawQuery(sql, args);
1959        if (cursor == null) {
1960            return null;
1961        }
1962        Message message = null;
1963        try {
1964            if (cursor.moveToFirst()) {
1965                message = Message.fromCursor(cursor, conversation);
1966            }
1967        } catch (final IOException e) { }
1968        cursor.close();
1969        return message;
1970    }
1971
1972    public Message getMessageWithUuidOrRemoteId(
1973            final Conversation conversation, final String messageId) {
1974        final var db = this.getReadableDatabase();
1975        final String sql =
1976                "select * from messages LEFT JOIN cheogram.messages USING (uuid) where conversationUuid=? and (uuid=? OR remoteMsgId=?) LIMIT 1";
1977        final String[] args = {conversation.getUuid(), messageId, messageId};
1978        final Cursor cursor = db.rawQuery(sql, args);
1979        if (cursor == null) {
1980            return null;
1981        }
1982        Message message = null;
1983        try {
1984            if (cursor.moveToFirst()) {
1985                message = Message.fromCursor(cursor, conversation);
1986            }
1987        } catch (final IOException e) { }
1988        cursor.close();
1989        return message;
1990    }
1991
1992    public void insertCapsCache(
1993            EntityCapabilities.EntityCapsHash caps,
1994            EntityCapabilities2.EntityCaps2Hash caps2,
1995            InfoQuery infoQuery) {
1996        final var contentValues = new ContentValues();
1997        contentValues.put("caps", caps.encoded());
1998        contentValues.put("caps2", caps2.encoded());
1999        contentValues.put("disco_info", infoQuery.toString());
2000        getWritableDatabase()
2001                .insertWithOnConflict(
2002                        "caps_cache", null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
2003    }
2004
2005    public InfoQuery getInfoQuery(final EntityCapabilities.Hash hash) {
2006        final String selection;
2007        final String[] args;
2008        if (hash instanceof EntityCapabilities.EntityCapsHash) {
2009            selection = "caps=?";
2010            args = new String[] {hash.encoded()};
2011        } else if (hash instanceof EntityCapabilities2.EntityCaps2Hash) {
2012            selection = "caps2=?";
2013            args = new String[] {hash.encoded()};
2014        } else {
2015            return null;
2016        }
2017        try (final Cursor cursor =
2018                getReadableDatabase()
2019                        .query(
2020                                "caps_cache",
2021                                new String[] {"disco_info"},
2022                                selection,
2023                                args,
2024                                null,
2025                                null,
2026                                null)) {
2027            if (cursor.moveToFirst()) {
2028                final var cached = cursor.getString(0);
2029                try {
2030                    final var element =
2031                            XmlElementReader.read(cached.getBytes(StandardCharsets.UTF_8));
2032                    if (element instanceof InfoQuery infoQuery) {
2033                        return infoQuery;
2034                    }
2035                } catch (final IOException e) {
2036                    Log.e(Config.LOGTAG, "could not restore info query from cache", e);
2037                    return null;
2038                }
2039            } else {
2040                return null;
2041            }
2042        }
2043        return null;
2044    }
2045
2046    public static class FilePath {
2047        public final UUID uuid;
2048        public final String path;
2049
2050        private FilePath(String uuid, String path) {
2051            this.uuid = UUID.fromString(uuid);
2052            this.path = path;
2053        }
2054    }
2055
2056    public static class FilePathInfo extends FilePath {
2057        public boolean deleted;
2058
2059        private FilePathInfo(String uuid, String path, boolean deleted) {
2060            super(uuid, path);
2061            this.deleted = deleted;
2062        }
2063
2064        public boolean setDeleted(boolean deleted) {
2065            final boolean changed = deleted != this.deleted;
2066            this.deleted = deleted;
2067            return changed;
2068        }
2069    }
2070
2071    public Conversation findConversation(final String uuid) {
2072        final var db = this.getReadableDatabase();
2073        final String[] selectionArgs = {uuid};
2074        try (final Cursor cursor =
2075                db.query(
2076                        Conversation.TABLENAME,
2077                        null,
2078                        Conversation.UUID + "=?",
2079                        selectionArgs,
2080                        null,
2081                        null,
2082                        null)) {
2083            if (cursor.getCount() == 0) {
2084                return null;
2085            }
2086            cursor.moveToFirst();
2087            final Conversation conversation = Conversation.fromCursor(cursor);
2088            if (conversation.getJid() instanceof Jid.Invalid) {
2089                return null;
2090            }
2091            return conversation;
2092        }
2093    }
2094
2095    public Conversation findConversation(final Account account, final Jid contactJid) {
2096        final SQLiteDatabase db = this.getReadableDatabase();
2097        final String[] selectionArgs = {
2098            account.getUuid(),
2099            contactJid.asBareJid().toString() + "/%",
2100            contactJid.asBareJid().toString()
2101        };
2102        try (final Cursor cursor =
2103                db.query(
2104                        Conversation.TABLENAME,
2105                        null,
2106                        Conversation.ACCOUNT
2107                                + "=? AND ("
2108                                + Conversation.CONTACTJID
2109                                + " like ? OR "
2110                                + Conversation.CONTACTJID
2111                                + "=?)",
2112                        selectionArgs,
2113                        null,
2114                        null,
2115                        null)) {
2116            if (cursor.getCount() == 0) {
2117                return null;
2118            }
2119            cursor.moveToFirst();
2120            final Conversation conversation = Conversation.fromCursor(cursor);
2121            if (conversation.getJid() instanceof Jid.Invalid) {
2122                return null;
2123            }
2124            conversation.setAccount(account);
2125            return conversation;
2126        }
2127    }
2128
2129    public String findConversationUuid(final Jid account, final Jid jid) {
2130        final SQLiteDatabase db = this.getReadableDatabase();
2131        final String[] selectionArgs = {
2132            account.getLocal(),
2133            account.getDomain().toString(),
2134            jid.asBareJid().toString() + "/%",
2135            jid.asBareJid().toString()
2136        };
2137        try (final Cursor cursor =
2138                db.rawQuery(
2139                        "SELECT conversations.uuid FROM conversations JOIN accounts ON"
2140                            + " conversations.accountUuid=accounts.uuid WHERE accounts.username=?"
2141                            + " AND accounts.server=? AND (contactJid=? OR contactJid LIKE ?)",
2142                        selectionArgs)) {
2143            if (cursor.getCount() == 0) {
2144                return null;
2145            }
2146            cursor.moveToFirst();
2147            return cursor.getString(0);
2148        }
2149    }
2150
2151    public void updateConversation(final Conversation conversation) {
2152        final SQLiteDatabase db = this.getWritableDatabase();
2153        final String[] args = {conversation.getUuid()};
2154        db.update(
2155                Conversation.TABLENAME,
2156                conversation.getContentValues(),
2157                Conversation.UUID + "=?",
2158                args);
2159    }
2160
2161    public List<Account> getAccounts() {
2162        SQLiteDatabase db = this.getReadableDatabase();
2163        return getAccounts(db);
2164    }
2165
2166    public List<Jid> getAccountJids(final boolean enabledOnly) {
2167        final SQLiteDatabase db = this.getReadableDatabase();
2168        final List<Jid> jids = new ArrayList<>();
2169        final String[] columns = new String[] {Account.USERNAME, Account.SERVER};
2170        final String where = enabledOnly ? "not options & (1 <<1)" : null;
2171        try (final Cursor cursor =
2172                db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
2173            while (cursor != null && cursor.moveToNext()) {
2174                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
2175            }
2176        } catch (final Exception e) {
2177            return jids;
2178        }
2179        return jids;
2180    }
2181
2182    private List<Account> getAccounts(SQLiteDatabase db) {
2183        final List<Account> list = new ArrayList<>();
2184        try (final Cursor cursor =
2185                db.query(Account.TABLENAME, null, null, null, null, null, null)) {
2186            while (cursor != null && cursor.moveToNext()) {
2187                list.add(Account.fromCursor(cursor));
2188            }
2189        }
2190        return list;
2191    }
2192
2193    public boolean updateAccount(Account account) {
2194        final var db = this.getWritableDatabase();
2195        final String[] args = {account.getUuid()};
2196        final int rows =
2197                db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
2198        return rows == 1;
2199    }
2200
2201    public boolean deleteAccount(final Account account) {
2202        final var db = this.getWritableDatabase();
2203        final String[] args = {account.getUuid()};
2204        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
2205        return rows == 1;
2206    }
2207
2208    public boolean updateMessage(final Message message, final boolean includeBody) {
2209        final var db = this.getWritableDatabase();
2210        final String[] args = {message.getUuid()};
2211        final var contentValues = message.getContentValues();
2212        contentValues.remove(Message.UUID);
2213        if (!includeBody) {
2214            contentValues.remove(Message.BODY);
2215        }
2216        return db.update(Message.TABLENAME, contentValues, Message.UUID + "=?", args) == 1 &&
2217               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
2218    }
2219
2220    public boolean updateMessage(Message message, String uuid) {
2221        SQLiteDatabase db = this.getWritableDatabase();
2222        String[] args = {uuid};
2223        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
2224               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
2225    }
2226
2227
2228    public boolean deleteMessage(String uuid) {
2229        SQLiteDatabase db = this.getWritableDatabase();
2230        String[] args = {uuid};
2231        return db.delete(Message.TABLENAME, Message.UUID + "=?", args) == 1 &&
2232               db.delete("cheogram." + Message.TABLENAME, Message.UUID + "=?", args) == 1;
2233    }
2234
2235    public Map<Jid, Contact> readRoster(final Account account) {
2236        final var builder = new ImmutableMap.Builder<Jid, Contact>();
2237        final SQLiteDatabase db = this.getReadableDatabase();
2238        final String[] args = {account.getUuid()};
2239        try (final Cursor cursor =
2240                db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
2241            while (cursor.moveToNext()) {
2242                final var contact = Contact.fromCursor(cursor);
2243                if (contact != null) {
2244                    contact.setAccount(account);
2245                    builder.put(contact.getJid(), contact);
2246                }
2247            }
2248        }
2249        return builder.buildKeepingLast();
2250    }
2251
2252    public void writeRoster(
2253            final Account account, final String version, final List<Contact> contacts) {
2254        final long start = SystemClock.elapsedRealtime();
2255        final SQLiteDatabase db = this.getWritableDatabase();
2256        db.beginTransaction();
2257        for (final Contact contact : contacts) {
2258            if (contact.getOption(Contact.Options.IN_ROSTER)
2259                    || contact.hasAvatarOrPresenceName()
2260                    || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
2261                db.insert(Contact.TABLENAME, null, contact.getContentValues());
2262            } else {
2263                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
2264                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
2265                db.delete(Contact.TABLENAME, where, whereArgs);
2266            }
2267        }
2268        db.setTransactionSuccessful();
2269        db.endTransaction();
2270        account.setRosterVersion(version);
2271        updateAccount(account);
2272        long duration = SystemClock.elapsedRealtime() - start;
2273        Log.d(
2274                Config.LOGTAG,
2275                account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
2276    }
2277
2278    public void deleteMessagesInConversation(Conversation conversation) {
2279        long start = SystemClock.elapsedRealtime();
2280        final SQLiteDatabase db = this.getWritableDatabase();
2281        db.beginTransaction();
2282        final String[] args = {conversation.getUuid()};
2283        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
2284        db.delete("cheogram.webxdc_updates", Message.CONVERSATION + "=?", args);
2285        db.setTransactionSuccessful();
2286        db.endTransaction();
2287        Log.d(
2288                Config.LOGTAG,
2289                "deleted "
2290                        + num
2291                        + " messages for "
2292                        + conversation.getJid().asBareJid()
2293                        + " in "
2294                        + (SystemClock.elapsedRealtime() - start)
2295                        + "ms");
2296    }
2297
2298    public void expireOldMessages(long timestamp) {
2299        final String[] args = {String.valueOf(timestamp)};
2300        SQLiteDatabase db = this.getReadableDatabase();
2301        db.beginTransaction();
2302        db.delete(Message.TABLENAME, "timeSent<?", args);
2303        db.delete("cheogram.messages", "timeReceived<?", args);
2304        db.setTransactionSuccessful();
2305        db.endTransaction();
2306    }
2307
2308    public MamReference getLastMessageReceived(Account account) {
2309        Cursor cursor = null;
2310        try {
2311            SQLiteDatabase db = this.getReadableDatabase();
2312            String sql =
2313                    "select messages.timeSent,messages.serverMsgId from accounts join conversations"
2314                        + " on accounts.uuid=conversations.accountUuid join messages on"
2315                        + " conversations.uuid=messages.conversationUuid where accounts.uuid=? and"
2316                        + " (messages.status=0 or messages.carbon=1 or messages.serverMsgId not"
2317                        + " null) and (conversations.mode=0 or (messages.serverMsgId not null and"
2318                        + " messages.type=4)) order by messages.timesent desc limit 1";
2319            String[] args = {account.getUuid()};
2320            cursor = db.rawQuery(sql, args);
2321            if (cursor.getCount() == 0) {
2322                return null;
2323            } else {
2324                cursor.moveToFirst();
2325                return new MamReference(cursor.getLong(0), cursor.getString(1));
2326            }
2327        } catch (Exception e) {
2328            return null;
2329        } finally {
2330            if (cursor != null) {
2331                cursor.close();
2332            }
2333        }
2334    }
2335
2336    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
2337        String SQL =
2338                "select messages.timeSent from accounts join conversations on"
2339                        + " accounts.uuid=conversations.accountUuid join messages on"
2340                        + " conversations.uuid=messages.conversationUuid where accounts.uuid=? and"
2341                        + " messages.axolotl_fingerprint=? order by messages.timesent desc limit 1";
2342        String[] args = {account.getUuid(), fingerprint};
2343        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
2344        long time;
2345        if (cursor.moveToFirst()) {
2346            time = cursor.getLong(0);
2347        } else {
2348            time = 0;
2349        }
2350        cursor.close();
2351        return time;
2352    }
2353
2354    public MamReference getLastClearDate(Account account) {
2355        SQLiteDatabase db = this.getReadableDatabase();
2356        String[] columns = {Conversation.ATTRIBUTES};
2357        String selection = Conversation.ACCOUNT + "=?";
2358        String[] args = {account.getUuid()};
2359        Cursor cursor =
2360                db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
2361        MamReference maxClearDate = new MamReference(0);
2362        while (cursor.moveToNext()) {
2363            try {
2364                final JSONObject o = new JSONObject(cursor.getString(0));
2365                maxClearDate =
2366                        MamReference.max(
2367                                maxClearDate,
2368                                MamReference.fromAttribute(
2369                                        o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
2370            } catch (Exception e) {
2371                // ignored
2372            }
2373        }
2374        cursor.close();
2375        return maxClearDate;
2376    }
2377
2378    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
2379        final SQLiteDatabase db = this.getReadableDatabase();
2380        String[] selectionArgs = {
2381            account.getUuid(), contact.getName(), Integer.toString(contact.getDeviceId())
2382        };
2383        return db.query(
2384                SQLiteAxolotlStore.SESSION_TABLENAME,
2385                null,
2386                SQLiteAxolotlStore.ACCOUNT
2387                        + " = ? AND "
2388                        + SQLiteAxolotlStore.NAME
2389                        + " = ? AND "
2390                        + SQLiteAxolotlStore.DEVICE_ID
2391                        + " = ? ",
2392                selectionArgs,
2393                null,
2394                null,
2395                null);
2396    }
2397
2398    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
2399        SessionRecord session = null;
2400        Cursor cursor = getCursorForSession(account, contact);
2401        if (cursor.getCount() != 0) {
2402            cursor.moveToFirst();
2403            try {
2404                session =
2405                        new SessionRecord(
2406                                Base64.decode(
2407                                        cursor.getString(
2408                                                cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2409                                        Base64.DEFAULT));
2410            } catch (IOException e) {
2411                cursor.close();
2412                throw new AssertionError(e);
2413            }
2414        }
2415        cursor.close();
2416        return session;
2417    }
2418
2419    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
2420        final SQLiteDatabase db = this.getReadableDatabase();
2421        return getSubDeviceSessions(db, account, contact);
2422    }
2423
2424    private List<Integer> getSubDeviceSessions(
2425            SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
2426        List<Integer> devices = new ArrayList<>();
2427        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
2428        String[] selectionArgs = {account.getUuid(), contact.getName()};
2429        Cursor cursor =
2430                db.query(
2431                        SQLiteAxolotlStore.SESSION_TABLENAME,
2432                        columns,
2433                        SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.NAME + " = ?",
2434                        selectionArgs,
2435                        null,
2436                        null,
2437                        null);
2438
2439        while (cursor.moveToNext()) {
2440            devices.add(cursor.getInt(cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
2441        }
2442
2443        cursor.close();
2444        return devices;
2445    }
2446
2447    public List<String> getKnownSignalAddresses(Account account) {
2448        List<String> addresses = new ArrayList<>();
2449        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
2450        String[] selectionArgs = {account.getUuid()};
2451        Cursor cursor =
2452                getReadableDatabase()
2453                        .query(
2454                                SQLiteAxolotlStore.SESSION_TABLENAME,
2455                                colums,
2456                                SQLiteAxolotlStore.ACCOUNT + " = ?",
2457                                selectionArgs,
2458                                null,
2459                                null,
2460                                null);
2461        while (cursor.moveToNext()) {
2462            addresses.add(cursor.getString(0));
2463        }
2464        cursor.close();
2465        return addresses;
2466    }
2467
2468    public boolean containsSession(Account account, SignalProtocolAddress contact) {
2469        Cursor cursor = getCursorForSession(account, contact);
2470        int count = cursor.getCount();
2471        cursor.close();
2472        return count != 0;
2473    }
2474
2475    public void storeSession(
2476            Account account, SignalProtocolAddress contact, SessionRecord session) {
2477        SQLiteDatabase db = this.getWritableDatabase();
2478        ContentValues values = new ContentValues();
2479        values.put(SQLiteAxolotlStore.NAME, contact.getName());
2480        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
2481        values.put(
2482                SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
2483        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2484        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
2485    }
2486
2487    public void deleteSession(Account account, SignalProtocolAddress contact) {
2488        SQLiteDatabase db = this.getWritableDatabase();
2489        deleteSession(db, account, contact);
2490    }
2491
2492    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
2493        String[] args = {
2494            account.getUuid(), contact.getName(), Integer.toString(contact.getDeviceId())
2495        };
2496        db.delete(
2497                SQLiteAxolotlStore.SESSION_TABLENAME,
2498                SQLiteAxolotlStore.ACCOUNT
2499                        + " = ? AND "
2500                        + SQLiteAxolotlStore.NAME
2501                        + " = ? AND "
2502                        + SQLiteAxolotlStore.DEVICE_ID
2503                        + " = ? ",
2504                args);
2505    }
2506
2507    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
2508        SQLiteDatabase db = this.getWritableDatabase();
2509        String[] args = {account.getUuid(), contact.getName()};
2510        db.delete(
2511                SQLiteAxolotlStore.SESSION_TABLENAME,
2512                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + " = ?",
2513                args);
2514    }
2515
2516    private Cursor getCursorForPreKey(Account account, int preKeyId) {
2517        SQLiteDatabase db = this.getReadableDatabase();
2518        String[] columns = {SQLiteAxolotlStore.KEY};
2519        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
2520        Cursor cursor =
2521                db.query(
2522                        SQLiteAxolotlStore.PREKEY_TABLENAME,
2523                        columns,
2524                        SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2525                        selectionArgs,
2526                        null,
2527                        null,
2528                        null);
2529
2530        return cursor;
2531    }
2532
2533    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
2534        PreKeyRecord record = null;
2535        Cursor cursor = getCursorForPreKey(account, preKeyId);
2536        if (cursor.getCount() != 0) {
2537            cursor.moveToFirst();
2538            try {
2539                record =
2540                        new PreKeyRecord(
2541                                Base64.decode(
2542                                        cursor.getString(
2543                                                cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2544                                        Base64.DEFAULT));
2545            } catch (IOException e) {
2546                throw new AssertionError(e);
2547            }
2548        }
2549        cursor.close();
2550        return record;
2551    }
2552
2553    public boolean containsPreKey(Account account, int preKeyId) {
2554        Cursor cursor = getCursorForPreKey(account, preKeyId);
2555        int count = cursor.getCount();
2556        cursor.close();
2557        return count != 0;
2558    }
2559
2560    public void storePreKey(Account account, PreKeyRecord record) {
2561        SQLiteDatabase db = this.getWritableDatabase();
2562        ContentValues values = new ContentValues();
2563        values.put(SQLiteAxolotlStore.ID, record.getId());
2564        values.put(
2565                SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
2566        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2567        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
2568    }
2569
2570    public int deletePreKey(Account account, int preKeyId) {
2571        SQLiteDatabase db = this.getWritableDatabase();
2572        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
2573        return db.delete(
2574                SQLiteAxolotlStore.PREKEY_TABLENAME,
2575                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2576                args);
2577    }
2578
2579    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
2580        SQLiteDatabase db = this.getReadableDatabase();
2581        String[] columns = {SQLiteAxolotlStore.KEY};
2582        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
2583        Cursor cursor =
2584                db.query(
2585                        SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2586                        columns,
2587                        SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2588                        selectionArgs,
2589                        null,
2590                        null,
2591                        null);
2592
2593        return cursor;
2594    }
2595
2596    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
2597        SignedPreKeyRecord record = null;
2598        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
2599        if (cursor.getCount() != 0) {
2600            cursor.moveToFirst();
2601            try {
2602                record =
2603                        new SignedPreKeyRecord(
2604                                Base64.decode(
2605                                        cursor.getString(
2606                                                cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2607                                        Base64.DEFAULT));
2608            } catch (IOException e) {
2609                throw new AssertionError(e);
2610            }
2611        }
2612        cursor.close();
2613        return record;
2614    }
2615
2616    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
2617        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
2618        SQLiteDatabase db = this.getReadableDatabase();
2619        String[] columns = {SQLiteAxolotlStore.KEY};
2620        String[] selectionArgs = {account.getUuid()};
2621        Cursor cursor =
2622                db.query(
2623                        SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2624                        columns,
2625                        SQLiteAxolotlStore.ACCOUNT + "=?",
2626                        selectionArgs,
2627                        null,
2628                        null,
2629                        null);
2630
2631        while (cursor.moveToNext()) {
2632            try {
2633                prekeys.add(
2634                        new SignedPreKeyRecord(
2635                                Base64.decode(
2636                                        cursor.getString(
2637                                                cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2638                                        Base64.DEFAULT)));
2639            } catch (IOException ignored) {
2640            }
2641        }
2642        cursor.close();
2643        return prekeys;
2644    }
2645
2646    public int getSignedPreKeysCount(Account account) {
2647        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
2648        String[] selectionArgs = {account.getUuid()};
2649        SQLiteDatabase db = this.getReadableDatabase();
2650        Cursor cursor =
2651                db.query(
2652                        SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2653                        columns,
2654                        SQLiteAxolotlStore.ACCOUNT + "=?",
2655                        selectionArgs,
2656                        null,
2657                        null,
2658                        null);
2659        final int count;
2660        if (cursor.moveToFirst()) {
2661            count = cursor.getInt(0);
2662        } else {
2663            count = 0;
2664        }
2665        cursor.close();
2666        return count;
2667    }
2668
2669    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
2670        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
2671        int count = cursor.getCount();
2672        cursor.close();
2673        return count != 0;
2674    }
2675
2676    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
2677        SQLiteDatabase db = this.getWritableDatabase();
2678        ContentValues values = new ContentValues();
2679        values.put(SQLiteAxolotlStore.ID, record.getId());
2680        values.put(
2681                SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
2682        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2683        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
2684    }
2685
2686    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
2687        SQLiteDatabase db = this.getWritableDatabase();
2688        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
2689        db.delete(
2690                SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2691                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2692                args);
2693    }
2694
2695    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
2696        final SQLiteDatabase db = this.getReadableDatabase();
2697        return getIdentityKeyCursor(db, account, name, own);
2698    }
2699
2700    private Cursor getIdentityKeyCursor(
2701            SQLiteDatabase db, Account account, String name, boolean own) {
2702        return getIdentityKeyCursor(db, account, name, own, null);
2703    }
2704
2705    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
2706        final SQLiteDatabase db = this.getReadableDatabase();
2707        return getIdentityKeyCursor(db, account, fingerprint);
2708    }
2709
2710    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
2711        return getIdentityKeyCursor(db, account, null, null, fingerprint);
2712    }
2713
2714    private Cursor getIdentityKeyCursor(
2715            SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
2716        String[] columns = {
2717            SQLiteAxolotlStore.TRUST,
2718            SQLiteAxolotlStore.ACTIVE,
2719            SQLiteAxolotlStore.LAST_ACTIVATION,
2720            SQLiteAxolotlStore.KEY
2721        };
2722        ArrayList<String> selectionArgs = new ArrayList<>(4);
2723        selectionArgs.add(account.getUuid());
2724        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
2725        if (name != null) {
2726            selectionArgs.add(name);
2727            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
2728        }
2729        if (fingerprint != null) {
2730            selectionArgs.add(fingerprint);
2731            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
2732        }
2733        if (own != null) {
2734            selectionArgs.add(own ? "1" : "0");
2735            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
2736        }
2737        Cursor cursor =
2738                db.query(
2739                        SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2740                        columns,
2741                        selectionString,
2742                        selectionArgs.toArray(new String[selectionArgs.size()]),
2743                        null,
2744                        null,
2745                        null);
2746
2747        return cursor;
2748    }
2749
2750    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
2751        SQLiteDatabase db = getReadableDatabase();
2752        return loadOwnIdentityKeyPair(db, account);
2753    }
2754
2755    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
2756        String name = account.getJid().asBareJid().toString();
2757        IdentityKeyPair identityKeyPair = null;
2758        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
2759        if (cursor.getCount() != 0) {
2760            cursor.moveToFirst();
2761            try {
2762                identityKeyPair =
2763                        new IdentityKeyPair(
2764                                Base64.decode(
2765                                        cursor.getString(
2766                                                cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2767                                        Base64.DEFAULT));
2768            } catch (InvalidKeyException e) {
2769                Log.d(
2770                        Config.LOGTAG,
2771                        AxolotlService.getLogprefix(account)
2772                                + "Encountered invalid IdentityKey in database for account"
2773                                + account.getJid().asBareJid()
2774                                + ", address: "
2775                                + name);
2776            }
2777        }
2778        cursor.close();
2779
2780        return identityKeyPair;
2781    }
2782
2783    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
2784        return loadIdentityKeys(account, name, null);
2785    }
2786
2787    public Set<IdentityKey> loadIdentityKeys(
2788            Account account, String name, FingerprintStatus status) {
2789        Set<IdentityKey> identityKeys = new HashSet<>();
2790        Cursor cursor = getIdentityKeyCursor(account, name, false);
2791
2792        while (cursor.moveToNext()) {
2793            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
2794                continue;
2795            }
2796            try {
2797                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
2798                if (key != null) {
2799                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
2800                } else {
2801                    Log.d(
2802                            Config.LOGTAG,
2803                            AxolotlService.getLogprefix(account)
2804                                    + "Missing key (possibly preverified) in database for account"
2805                                    + account.getJid().asBareJid()
2806                                    + ", address: "
2807                                    + name);
2808                }
2809            } catch (InvalidKeyException e) {
2810                Log.d(
2811                        Config.LOGTAG,
2812                        AxolotlService.getLogprefix(account)
2813                                + "Encountered invalid IdentityKey in database for account"
2814                                + account.getJid().asBareJid()
2815                                + ", address: "
2816                                + name);
2817            }
2818        }
2819        cursor.close();
2820
2821        return identityKeys;
2822    }
2823
2824    public long numTrustedKeys(Account account, String name) {
2825        SQLiteDatabase db = getReadableDatabase();
2826        String[] args = {
2827            account.getUuid(),
2828            name,
2829            FingerprintStatus.Trust.TRUSTED.toString(),
2830            FingerprintStatus.Trust.VERIFIED.toString(),
2831            FingerprintStatus.Trust.VERIFIED_X509.toString()
2832        };
2833        return DatabaseUtils.queryNumEntries(
2834                db,
2835                SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2836                SQLiteAxolotlStore.ACCOUNT
2837                        + " = ?"
2838                        + " AND "
2839                        + SQLiteAxolotlStore.NAME
2840                        + " = ?"
2841                        + " AND ("
2842                        + SQLiteAxolotlStore.TRUST
2843                        + " = ? OR "
2844                        + SQLiteAxolotlStore.TRUST
2845                        + " = ? OR "
2846                        + SQLiteAxolotlStore.TRUST
2847                        + " = ?)"
2848                        + " AND "
2849                        + SQLiteAxolotlStore.ACTIVE
2850                        + " > 0",
2851                args);
2852    }
2853
2854    private void storeIdentityKey(
2855            Account account,
2856            String name,
2857            boolean own,
2858            String fingerprint,
2859            String base64Serialized,
2860            FingerprintStatus status) {
2861        SQLiteDatabase db = this.getWritableDatabase();
2862        ContentValues values = new ContentValues();
2863        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2864        values.put(SQLiteAxolotlStore.NAME, name);
2865        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
2866        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
2867        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
2868        values.putAll(status.toContentValues());
2869        String where =
2870                SQLiteAxolotlStore.ACCOUNT
2871                        + "=? AND "
2872                        + SQLiteAxolotlStore.NAME
2873                        + "=? AND "
2874                        + SQLiteAxolotlStore.FINGERPRINT
2875                        + " =?";
2876        String[] whereArgs = {account.getUuid(), name, fingerprint};
2877        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
2878        if (rows == 0) {
2879            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
2880        }
2881    }
2882
2883    public void storePreVerification(
2884            Account account, String name, String fingerprint, FingerprintStatus status) {
2885        SQLiteDatabase db = this.getWritableDatabase();
2886        ContentValues values = new ContentValues();
2887        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2888        values.put(SQLiteAxolotlStore.NAME, name);
2889        values.put(SQLiteAxolotlStore.OWN, 0);
2890        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
2891        values.putAll(status.toContentValues());
2892        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
2893    }
2894
2895    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
2896        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
2897        final FingerprintStatus status;
2898        if (cursor.getCount() > 0) {
2899            cursor.moveToFirst();
2900            status = FingerprintStatus.fromCursor(cursor);
2901        } else {
2902            status = null;
2903        }
2904        cursor.close();
2905        return status;
2906    }
2907
2908    public boolean setIdentityKeyTrust(
2909            Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
2910        SQLiteDatabase db = this.getWritableDatabase();
2911        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
2912    }
2913
2914    private boolean setIdentityKeyTrust(
2915            SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
2916        String[] selectionArgs = {account.getUuid(), fingerprint};
2917        int rows =
2918                db.update(
2919                        SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2920                        status.toContentValues(),
2921                        SQLiteAxolotlStore.ACCOUNT
2922                                + " = ? AND "
2923                                + SQLiteAxolotlStore.FINGERPRINT
2924                                + " = ? ",
2925                        selectionArgs);
2926        return rows == 1;
2927    }
2928
2929    public boolean setIdentityKeyCertificate(
2930            Account account, String fingerprint, X509Certificate x509Certificate) {
2931        SQLiteDatabase db = this.getWritableDatabase();
2932        String[] selectionArgs = {account.getUuid(), fingerprint};
2933        try {
2934            ContentValues values = new ContentValues();
2935            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
2936            return db.update(
2937                            SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2938                            values,
2939                            SQLiteAxolotlStore.ACCOUNT
2940                                    + " = ? AND "
2941                                    + SQLiteAxolotlStore.FINGERPRINT
2942                                    + " = ? ",
2943                            selectionArgs)
2944                    == 1;
2945        } catch (CertificateEncodingException e) {
2946            Log.d(Config.LOGTAG, "could not encode certificate");
2947            return false;
2948        }
2949    }
2950
2951    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
2952        SQLiteDatabase db = this.getReadableDatabase();
2953        String[] selectionArgs = {account.getUuid(), fingerprint};
2954        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
2955        String selection =
2956                SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
2957        Cursor cursor =
2958                db.query(
2959                        SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2960                        colums,
2961                        selection,
2962                        selectionArgs,
2963                        null,
2964                        null,
2965                        null);
2966        if (cursor.getCount() < 1) {
2967            return null;
2968        } else {
2969            cursor.moveToFirst();
2970            byte[] certificate =
2971                    cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
2972            cursor.close();
2973            if (certificate == null || certificate.length == 0) {
2974                return null;
2975            }
2976            try {
2977                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
2978                return (X509Certificate)
2979                        certificateFactory.generateCertificate(
2980                                new ByteArrayInputStream(certificate));
2981            } catch (CertificateException e) {
2982                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
2983                return null;
2984            }
2985        }
2986    }
2987
2988    public void storeIdentityKey(
2989            Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
2990        storeIdentityKey(
2991                account,
2992                name,
2993                false,
2994                CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()),
2995                Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT),
2996                status);
2997    }
2998
2999    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
3000        storeIdentityKey(
3001                account,
3002                account.getJid().asBareJid().toString(),
3003                true,
3004                CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()),
3005                Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT),
3006                FingerprintStatus.createActiveVerified(false));
3007    }
3008
3009    private void recreateAxolotlDb(SQLiteDatabase db) {
3010        Log.d(
3011                Config.LOGTAG,
3012                AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
3013        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
3014        db.execSQL(CREATE_SESSIONS_STATEMENT);
3015        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
3016        db.execSQL(CREATE_PREKEYS_STATEMENT);
3017        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
3018        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
3019        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
3020        db.execSQL(CREATE_IDENTITIES_STATEMENT);
3021    }
3022
3023    public void wipeAxolotlDb(Account account) {
3024        String accountName = account.getUuid();
3025        Log.d(
3026                Config.LOGTAG,
3027                AxolotlService.getLogprefix(account)
3028                        + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT "
3029                        + accountName
3030                        + " <<<");
3031        SQLiteDatabase db = this.getWritableDatabase();
3032        String[] deleteArgs = {accountName};
3033        db.delete(
3034                SQLiteAxolotlStore.SESSION_TABLENAME,
3035                SQLiteAxolotlStore.ACCOUNT + " = ?",
3036                deleteArgs);
3037        db.delete(
3038                SQLiteAxolotlStore.PREKEY_TABLENAME,
3039                SQLiteAxolotlStore.ACCOUNT + " = ?",
3040                deleteArgs);
3041        db.delete(
3042                SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
3043                SQLiteAxolotlStore.ACCOUNT + " = ?",
3044                deleteArgs);
3045        db.delete(
3046                SQLiteAxolotlStore.IDENTITIES_TABLENAME,
3047                SQLiteAxolotlStore.ACCOUNT + " = ?",
3048                deleteArgs);
3049    }
3050
3051    public List<ShortcutService.FrequentContact> getFrequentContacts(final int days) {
3052        final var db = this.getReadableDatabase();
3053        final String SQL =
3054                "select "
3055                        + Conversation.TABLENAME
3056                        + "."
3057                        + Conversation.UUID
3058                        + ","
3059                        + Conversation.TABLENAME
3060                        + "."
3061                        + Conversation.ACCOUNT
3062                        + ","
3063                        + Conversation.TABLENAME
3064                        + "."
3065                        + Conversation.CONTACTJID
3066                        + " from "
3067                        + Conversation.TABLENAME
3068                        + " join "
3069                        + Message.TABLENAME
3070                        + " on conversations.uuid=messages.conversationUuid where"
3071                        + " messages.status!=0 and carbon==0  and conversations.mode=0 and"
3072                        + " messages.timeSent>=? group by conversations.uuid order by count(body)"
3073                        + " desc limit 4;";
3074        String[] whereArgs =
3075                new String[] {
3076                    String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))
3077                };
3078        Cursor cursor = db.rawQuery(SQL, whereArgs);
3079        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
3080        while (cursor.moveToNext()) {
3081            try {
3082                contacts.add(
3083                        new ShortcutService.FrequentContact(
3084                                cursor.getString(0),
3085                                cursor.getString(1),
3086                                Jid.of(cursor.getString(2))));
3087            } catch (final Exception e) {
3088                Log.e(Config.LOGTAG, "could not create frequent contact", e);
3089            }
3090        }
3091        cursor.close();
3092        return contacts;
3093    }
3094}