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