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