DatabaseBackend.java

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