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