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        if (cid == null) return null;
 806
 807        SQLiteDatabase db = this.getReadableDatabase();
 808        Cursor cursor = db.query("cheogram.cids", new String[]{"path"}, "cid=?", new String[]{cid.toString()}, null, null, null);
 809        DownloadableFile f = null;
 810        if (cursor.moveToNext()) {
 811            f = new DownloadableFile(cursor.getString(0));
 812        }
 813        cursor.close();
 814        return f;
 815    }
 816
 817    public String getUrlForCid(Cid cid) {
 818        SQLiteDatabase db = this.getReadableDatabase();
 819        Cursor cursor = db.query("cheogram.cids", new String[]{"url"}, "cid=?", new String[]{cid.toString()}, null, null, null);
 820        String url = null;
 821        if (cursor.moveToNext()) {
 822            url = cursor.getString(0);
 823        }
 824        cursor.close();
 825        return url;
 826    }
 827
 828    public void saveCid(Cid cid, File file) {
 829        saveCid(cid, file, null);
 830    }
 831
 832    public void saveCid(Cid cid, File file, String url) {
 833        SQLiteDatabase db = this.getWritableDatabase();
 834        ContentValues cv = new ContentValues();
 835        cv.put("cid", cid.toString());
 836        if (file != null) cv.put("path", file.getAbsolutePath());
 837        if (url != null) cv.put("url", url);
 838        if (db.update("cheogram.cids", cv, "cid=?", new String[]{cid.toString()}) < 1) {
 839            db.insertWithOnConflict("cheogram.cids", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
 840        }
 841    }
 842
 843    public void blockMedia(Cid cid) {
 844        SQLiteDatabase db = this.getWritableDatabase();
 845        ContentValues cv = new ContentValues();
 846        cv.put("cid", cid.toString());
 847        db.insertWithOnConflict("cheogram.blocked_media", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
 848    }
 849
 850    public boolean isBlockedMedia(Cid cid) {
 851        SQLiteDatabase db = this.getReadableDatabase();
 852        Cursor cursor = db.query("cheogram.blocked_media", new String[]{"count(*)"}, "cid=?", new String[]{cid.toString()}, null, null, null);
 853        boolean is = false;
 854        if (cursor.moveToNext()) {
 855            is = cursor.getInt(0) > 0;
 856        }
 857        cursor.close();
 858        return is;
 859    }
 860
 861    public void clearBlockedMedia() {
 862        SQLiteDatabase db = this.getWritableDatabase();
 863        db.execSQL("DELETE FROM cheogram.blocked_media");
 864    }
 865
 866    public void insertWebxdcUpdate(final WebxdcUpdate update) {
 867        SQLiteDatabase db = this.getWritableDatabase();
 868        db.insertWithOnConflict("cheogram.webxdc_updates", null, update.getContentValues(), SQLiteDatabase.CONFLICT_IGNORE);
 869    }
 870
 871    public WebxdcUpdate findLastWebxdcUpdate(Message message) {
 872        if (message.getThread() == null) {
 873            Log.w(Config.LOGTAG, "WebXDC message with no thread!");
 874            return null;
 875        }
 876
 877        SQLiteDatabase db = this.getReadableDatabase();
 878        String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent()};
 879        Cursor cursor = db.query("cheogram.webxdc_updates", null,
 880                Message.CONVERSATION + "=? AND thread=?",
 881                selectionArgs, null, null, "serial ASC");
 882        WebxdcUpdate update = null;
 883        if (cursor.moveToLast()) {
 884            update = new WebxdcUpdate(cursor, cursor.getLong(cursor.getColumnIndex("serial")));
 885        }
 886        cursor.close();
 887        return update;
 888    }
 889
 890    public List<WebxdcUpdate> findWebxdcUpdates(Message message, long serial) {
 891        SQLiteDatabase db = this.getReadableDatabase();
 892        String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent(), String.valueOf(serial)};
 893        Cursor cursor = db.query("cheogram.webxdc_updates", null,
 894                Message.CONVERSATION + "=? AND thread=? AND serial>?",
 895                selectionArgs, null, null, "serial ASC");
 896        long maxSerial = 0;
 897        if (cursor.moveToLast()) {
 898            maxSerial = cursor.getLong(cursor.getColumnIndex("serial"));
 899        }
 900        cursor.moveToFirst();
 901        cursor.moveToPrevious();
 902
 903        List<WebxdcUpdate> updates = new ArrayList<>();
 904        while (cursor.moveToNext()) {
 905            updates.add(new WebxdcUpdate(cursor, maxSerial));
 906        }
 907        cursor.close();
 908        return updates;
 909    }
 910
 911    public void createConversation(Conversation conversation) {
 912        SQLiteDatabase db = this.getWritableDatabase();
 913        db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 914    }
 915
 916    public void createMessage(Message message) {
 917        SQLiteDatabase db = this.getWritableDatabase();
 918        db.insert(Message.TABLENAME, null, message.getContentValues());
 919        db.insert("cheogram." + Message.TABLENAME, null, message.getCheogramContentValues());
 920    }
 921
 922    public void createAccount(Account account) {
 923        SQLiteDatabase db = this.getWritableDatabase();
 924        db.insert(Account.TABLENAME, null, account.getContentValues());
 925    }
 926
 927    public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 928        SQLiteDatabase db = this.getWritableDatabase();
 929        db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 930    }
 931
 932    public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 933        SQLiteDatabase db = this.getReadableDatabase();
 934        String[] selectionArgs = {hash, ver};
 935        Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 936                ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 937                selectionArgs, null, null, null);
 938        if (cursor.getCount() == 0) {
 939            cursor.close();
 940            return null;
 941        }
 942        cursor.moveToFirst();
 943
 944        ServiceDiscoveryResult result = null;
 945        try {
 946            result = new ServiceDiscoveryResult(cursor);
 947        } catch (JSONException e) { /* result is still null */ }
 948
 949        cursor.close();
 950        return result;
 951    }
 952
 953    public void saveResolverResult(String domain, Resolver.Result result) {
 954        SQLiteDatabase db = this.getWritableDatabase();
 955        ContentValues contentValues = result.toContentValues();
 956        contentValues.put(Resolver.Result.DOMAIN, domain);
 957        db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
 958    }
 959
 960    public synchronized Resolver.Result findResolverResult(String domain) {
 961        SQLiteDatabase db = this.getReadableDatabase();
 962        String where = Resolver.Result.DOMAIN + "=?";
 963        String[] whereArgs = {domain};
 964        final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
 965        Resolver.Result result = null;
 966        if (cursor != null) {
 967            try {
 968                if (cursor.moveToFirst()) {
 969                    result = Resolver.Result.fromCursor(cursor);
 970                }
 971            } catch (Exception e) {
 972                Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
 973                return null;
 974            } finally {
 975                cursor.close();
 976            }
 977        }
 978        return result;
 979    }
 980
 981    public void insertPresenceTemplate(PresenceTemplate template) {
 982        SQLiteDatabase db = this.getWritableDatabase();
 983        String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 984        String[] whereToDeleteArgs = {template.getStatusMessage()};
 985        db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 986        db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 987        db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 988    }
 989
 990    public List<PresenceTemplate> getPresenceTemplates() {
 991        ArrayList<PresenceTemplate> templates = new ArrayList<>();
 992        SQLiteDatabase db = this.getReadableDatabase();
 993        Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 994        while (cursor.moveToNext()) {
 995            templates.add(PresenceTemplate.fromCursor(cursor));
 996        }
 997        cursor.close();
 998        return templates;
 999    }
1000
1001    public CopyOnWriteArrayList<Conversation> getConversations(int status) {
1002        CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
1003        SQLiteDatabase db = this.getReadableDatabase();
1004        String[] selectionArgs = {Integer.toString(status)};
1005        Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
1006                + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
1007                + Conversation.CREATED + " desc", selectionArgs);
1008        while (cursor.moveToNext()) {
1009            final Conversation conversation = Conversation.fromCursor(cursor);
1010            if (conversation.getJid() instanceof InvalidJid) {
1011                continue;
1012            }
1013            list.add(conversation);
1014        }
1015        cursor.close();
1016        return list;
1017    }
1018
1019    public ArrayList<Message> getMessages(Conversation conversations, int limit) {
1020        return getMessages(conversations, limit, -1);
1021    }
1022
1023    public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
1024        ArrayList<Message> list = new ArrayList<>();
1025        SQLiteDatabase db = this.getReadableDatabase();
1026        Cursor cursor;
1027        if (timestamp == -1) {
1028            String[] selectionArgs = {conversation.getUuid()};
1029            cursor = db.rawQuery(
1030                "SELECT * FROM " + Message.TABLENAME + " " +
1031                "LEFT JOIN cheogram." + Message.TABLENAME +
1032                "  USING (" + Message.UUID + ")" +
1033                "WHERE " + Message.CONVERSATION + "=? " +
1034                "ORDER BY " + Message.TIME_SENT + " DESC " +
1035                "LIMIT " + String.valueOf(limit),
1036                selectionArgs
1037            );
1038        } else {
1039            String[] selectionArgs = {conversation.getUuid(),
1040                    Long.toString(timestamp)};
1041            cursor = db.rawQuery(
1042                "SELECT * FROM " + Message.TABLENAME + " " +
1043                "LEFT JOIN cheogram." + Message.TABLENAME +
1044                "  USING (" + Message.UUID + ")" +
1045                "WHERE " + Message.CONVERSATION + "=? AND " +
1046                Message.TIME_SENT + "<? " +
1047                "ORDER BY " + Message.TIME_SENT + " DESC " +
1048                "LIMIT " + String.valueOf(limit),
1049                selectionArgs
1050            );
1051        }
1052        CursorUtils.upgradeCursorWindowSize(cursor);
1053        while (cursor.moveToNext()) {
1054            try {
1055                list.add(0, Message.fromCursor(cursor, conversation));
1056            } catch (Exception e) {
1057                Log.e(Config.LOGTAG, "unable to restore message");
1058            }
1059        }
1060        cursor.close();
1061        return list;
1062    }
1063
1064    public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1065        final SQLiteDatabase db = this.getReadableDatabase();
1066        final StringBuilder SQL = new StringBuilder();
1067        final String[] selectionArgs;
1068        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 ?");
1069        if (uuid == null) {
1070            selectionArgs = new String[]{FtsUtils.toMatchString(term)};
1071        } else {
1072            selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
1073            SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1074        }
1075        SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1076        Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1077        return db.rawQuery(SQL.toString(), selectionArgs);
1078    }
1079
1080    public List<String> markFileAsDeleted(final File file, final boolean internal) {
1081        SQLiteDatabase db = this.getReadableDatabase();
1082        String selection;
1083        String[] selectionArgs;
1084        if (internal) {
1085            final String name = file.getName();
1086            if (name.endsWith(".pgp")) {
1087                selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
1088                selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
1089            } else {
1090                selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1091                selectionArgs = new String[]{file.getAbsolutePath(), name};
1092            }
1093        } else {
1094            selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1095            selectionArgs = new String[]{file.getAbsolutePath()};
1096        }
1097        final List<String> uuids = new ArrayList<>();
1098        Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
1099        while (cursor != null && cursor.moveToNext()) {
1100            uuids.add(cursor.getString(0));
1101        }
1102        if (cursor != null) {
1103            cursor.close();
1104        }
1105        markFileAsDeleted(uuids);
1106        return uuids;
1107    }
1108
1109    public void markFileAsDeleted(List<String> uuids) {
1110        SQLiteDatabase db = this.getReadableDatabase();
1111        final ContentValues contentValues = new ContentValues();
1112        final String where = Message.UUID + "=?";
1113        contentValues.put(Message.DELETED, 1);
1114        db.beginTransaction();
1115        for (String uuid : uuids) {
1116            db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
1117        }
1118        db.setTransactionSuccessful();
1119        db.endTransaction();
1120    }
1121
1122    public void markFilesAsChanged(List<FilePathInfo> files) {
1123        SQLiteDatabase db = this.getReadableDatabase();
1124        final String where = Message.UUID + "=?";
1125        db.beginTransaction();
1126        for (FilePathInfo info : files) {
1127            final ContentValues contentValues = new ContentValues();
1128            contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1129            db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
1130        }
1131        db.setTransactionSuccessful();
1132        db.endTransaction();
1133    }
1134
1135    public List<FilePathInfo> getFilePathInfo() {
1136        final SQLiteDatabase db = this.getReadableDatabase();
1137        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);
1138        final List<FilePathInfo> list = new ArrayList<>();
1139        while (cursor != null && cursor.moveToNext()) {
1140            list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1141        }
1142        if (cursor != null) {
1143            cursor.close();
1144        }
1145        return list;
1146    }
1147
1148    public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1149        SQLiteDatabase db = this.getReadableDatabase();
1150        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";
1151        final String[] args = {account, jid.toString(), jid.toString() + "/%"};
1152        Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1153        List<FilePath> filesPaths = new ArrayList<>();
1154        while (cursor.moveToNext()) {
1155            filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1156        }
1157        cursor.close();
1158        return filesPaths;
1159    }
1160
1161    public static class FilePath {
1162        public final UUID uuid;
1163        public final String path;
1164
1165        private FilePath(String uuid, String path) {
1166            this.uuid = UUID.fromString(uuid);
1167            this.path = path;
1168        }
1169    }
1170
1171    public static class FilePathInfo extends FilePath {
1172        public boolean deleted;
1173
1174        private FilePathInfo(String uuid, String path, boolean deleted) {
1175            super(uuid, path);
1176            this.deleted = deleted;
1177        }
1178
1179        public boolean setDeleted(boolean deleted) {
1180            final boolean changed = deleted != this.deleted;
1181            this.deleted = deleted;
1182            return changed;
1183        }
1184    }
1185
1186    public Conversation findConversation(final Account account, final Jid contactJid) {
1187        SQLiteDatabase db = this.getReadableDatabase();
1188        String[] selectionArgs = {account.getUuid(),
1189                contactJid.asBareJid().toString() + "/%",
1190                contactJid.asBareJid().toString()
1191        };
1192        try(final Cursor cursor = db.query(Conversation.TABLENAME, null,
1193                Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
1194                        + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null)) {
1195            if (cursor.getCount() == 0) {
1196                return null;
1197            }
1198            cursor.moveToFirst();
1199            final Conversation conversation = Conversation.fromCursor(cursor);
1200            if (conversation.getJid() instanceof InvalidJid) {
1201                return null;
1202            }
1203            return conversation;
1204        }
1205    }
1206
1207    public void updateConversation(final Conversation conversation) {
1208        final SQLiteDatabase db = this.getWritableDatabase();
1209        final String[] args = {conversation.getUuid()};
1210        db.update(Conversation.TABLENAME, conversation.getContentValues(),
1211                Conversation.UUID + "=?", args);
1212    }
1213
1214    public List<Account> getAccounts() {
1215        SQLiteDatabase db = this.getReadableDatabase();
1216        return getAccounts(db);
1217    }
1218
1219    public List<Jid> getAccountJids(final boolean enabledOnly) {
1220        final SQLiteDatabase db = this.getReadableDatabase();
1221        final List<Jid> jids = new ArrayList<>();
1222        final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
1223        final String where = enabledOnly ? "not options & (1 <<1)" : null;
1224        try (final Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
1225            while (cursor != null && cursor.moveToNext()) {
1226                jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
1227            }
1228        } catch (final Exception e) {
1229            return jids;
1230        }
1231        return jids;
1232    }
1233
1234    private List<Account> getAccounts(SQLiteDatabase db) {
1235        final List<Account> list = new ArrayList<>();
1236        try (final Cursor cursor =
1237                db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1238            while (cursor != null && cursor.moveToNext()) {
1239                list.add(Account.fromCursor(cursor));
1240            }
1241        }
1242        return list;
1243    }
1244
1245    public boolean updateAccount(Account account) {
1246        SQLiteDatabase db = this.getWritableDatabase();
1247        String[] args = {account.getUuid()};
1248        final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1249        return rows == 1;
1250    }
1251
1252    public boolean deleteAccount(Account account) {
1253        SQLiteDatabase db = this.getWritableDatabase();
1254        String[] args = {account.getUuid()};
1255        final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1256        return rows == 1;
1257    }
1258
1259    public boolean updateMessage(Message message, boolean includeBody) {
1260        SQLiteDatabase db = this.getWritableDatabase();
1261        String[] args = {message.getUuid()};
1262        ContentValues contentValues = message.getContentValues();
1263        contentValues.remove(Message.UUID);
1264        if (!includeBody) {
1265            contentValues.remove(Message.BODY);
1266        }
1267        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1268               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1269    }
1270
1271    public boolean updateMessage(Message message, String uuid) {
1272        SQLiteDatabase db = this.getWritableDatabase();
1273        String[] args = {uuid};
1274        return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1275               db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1276    }
1277
1278    public void readRoster(Roster roster) {
1279        final SQLiteDatabase db = this.getReadableDatabase();
1280        final String[] args = {roster.getAccount().getUuid()};
1281        try (final Cursor cursor =
1282                db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1283            while (cursor.moveToNext()) {
1284                roster.initContact(Contact.fromCursor(cursor));
1285            }
1286        }
1287    }
1288
1289    public void writeRoster(final Roster roster) {
1290        long start = SystemClock.elapsedRealtime();
1291        final Account account = roster.getAccount();
1292        final SQLiteDatabase db = this.getWritableDatabase();
1293        db.beginTransaction();
1294        for (Contact contact : roster.getContacts()) {
1295            if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1296                db.insert(Contact.TABLENAME, null, contact.getContentValues());
1297            } else {
1298                String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1299                String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1300                db.delete(Contact.TABLENAME, where, whereArgs);
1301            }
1302        }
1303        db.setTransactionSuccessful();
1304        db.endTransaction();
1305        account.setRosterVersion(roster.getVersion());
1306        updateAccount(account);
1307        long duration = SystemClock.elapsedRealtime() - start;
1308        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1309    }
1310
1311    public void deleteMessagesInConversation(Conversation conversation) {
1312        long start = SystemClock.elapsedRealtime();
1313        final SQLiteDatabase db = this.getWritableDatabase();
1314        db.beginTransaction();
1315        final String[] args = {conversation.getUuid()};
1316        int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1317        db.delete("cheogram.webxdc_updates", Message.CONVERSATION + "=?", args);
1318        db.setTransactionSuccessful();
1319        db.endTransaction();
1320        Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1321    }
1322
1323    public void expireOldMessages(long timestamp) {
1324        final String[] args = {String.valueOf(timestamp)};
1325        SQLiteDatabase db = this.getReadableDatabase();
1326        db.beginTransaction();
1327        db.delete(Message.TABLENAME, "timeSent<?", args);
1328        db.setTransactionSuccessful();
1329        db.endTransaction();
1330    }
1331
1332    public MamReference getLastMessageReceived(Account account) {
1333        Cursor cursor = null;
1334        try {
1335            SQLiteDatabase db = this.getReadableDatabase();
1336            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";
1337            String[] args = {account.getUuid()};
1338            cursor = db.rawQuery(sql, args);
1339            if (cursor.getCount() == 0) {
1340                return null;
1341            } else {
1342                cursor.moveToFirst();
1343                return new MamReference(cursor.getLong(0), cursor.getString(1));
1344            }
1345        } catch (Exception e) {
1346            return null;
1347        } finally {
1348            if (cursor != null) {
1349                cursor.close();
1350            }
1351        }
1352    }
1353
1354    public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1355        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";
1356        String[] args = {account.getUuid(), fingerprint};
1357        Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1358        long time;
1359        if (cursor.moveToFirst()) {
1360            time = cursor.getLong(0);
1361        } else {
1362            time = 0;
1363        }
1364        cursor.close();
1365        return time;
1366    }
1367
1368    public MamReference getLastClearDate(Account account) {
1369        SQLiteDatabase db = this.getReadableDatabase();
1370        String[] columns = {Conversation.ATTRIBUTES};
1371        String selection = Conversation.ACCOUNT + "=?";
1372        String[] args = {account.getUuid()};
1373        Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1374        MamReference maxClearDate = new MamReference(0);
1375        while (cursor.moveToNext()) {
1376            try {
1377                final JSONObject o = new JSONObject(cursor.getString(0));
1378                maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1379            } catch (Exception e) {
1380                //ignored
1381            }
1382        }
1383        cursor.close();
1384        return maxClearDate;
1385    }
1386
1387    private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1388        final SQLiteDatabase db = this.getReadableDatabase();
1389        String[] selectionArgs = {account.getUuid(),
1390                contact.getName(),
1391                Integer.toString(contact.getDeviceId())};
1392        return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1393                null,
1394                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1395                        + SQLiteAxolotlStore.NAME + " = ? AND "
1396                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1397                selectionArgs,
1398                null, null, null);
1399    }
1400
1401    public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1402        SessionRecord session = null;
1403        Cursor cursor = getCursorForSession(account, contact);
1404        if (cursor.getCount() != 0) {
1405            cursor.moveToFirst();
1406            try {
1407                session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1408            } catch (IOException e) {
1409                cursor.close();
1410                throw new AssertionError(e);
1411            }
1412        }
1413        cursor.close();
1414        return session;
1415    }
1416
1417    public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1418        final SQLiteDatabase db = this.getReadableDatabase();
1419        return getSubDeviceSessions(db, account, contact);
1420    }
1421
1422    private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1423        List<Integer> devices = new ArrayList<>();
1424        String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1425        String[] selectionArgs = {account.getUuid(),
1426                contact.getName()};
1427        Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1428                columns,
1429                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1430                        + SQLiteAxolotlStore.NAME + " = ?",
1431                selectionArgs,
1432                null, null, null);
1433
1434        while (cursor.moveToNext()) {
1435            devices.add(cursor.getInt(
1436                    cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1437        }
1438
1439        cursor.close();
1440        return devices;
1441    }
1442
1443    public List<String> getKnownSignalAddresses(Account account) {
1444        List<String> addresses = new ArrayList<>();
1445        String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1446        String[] selectionArgs = {account.getUuid()};
1447        Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1448                colums,
1449                SQLiteAxolotlStore.ACCOUNT + " = ?",
1450                selectionArgs,
1451                null, null, null
1452        );
1453        while (cursor.moveToNext()) {
1454            addresses.add(cursor.getString(0));
1455        }
1456        cursor.close();
1457        return addresses;
1458    }
1459
1460    public boolean containsSession(Account account, SignalProtocolAddress contact) {
1461        Cursor cursor = getCursorForSession(account, contact);
1462        int count = cursor.getCount();
1463        cursor.close();
1464        return count != 0;
1465    }
1466
1467    public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1468        SQLiteDatabase db = this.getWritableDatabase();
1469        ContentValues values = new ContentValues();
1470        values.put(SQLiteAxolotlStore.NAME, contact.getName());
1471        values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1472        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1473        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1474        db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1475    }
1476
1477    public void deleteSession(Account account, SignalProtocolAddress contact) {
1478        SQLiteDatabase db = this.getWritableDatabase();
1479        deleteSession(db, account, contact);
1480    }
1481
1482    private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1483        String[] args = {account.getUuid(),
1484                contact.getName(),
1485                Integer.toString(contact.getDeviceId())};
1486        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1487                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1488                        + SQLiteAxolotlStore.NAME + " = ? AND "
1489                        + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1490                args);
1491    }
1492
1493    public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1494        SQLiteDatabase db = this.getWritableDatabase();
1495        String[] args = {account.getUuid(), contact.getName()};
1496        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1497                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1498                        + SQLiteAxolotlStore.NAME + " = ?",
1499                args);
1500    }
1501
1502    private Cursor getCursorForPreKey(Account account, int preKeyId) {
1503        SQLiteDatabase db = this.getReadableDatabase();
1504        String[] columns = {SQLiteAxolotlStore.KEY};
1505        String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1506        Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1507                columns,
1508                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1509                        + SQLiteAxolotlStore.ID + "=?",
1510                selectionArgs,
1511                null, null, null);
1512
1513        return cursor;
1514    }
1515
1516    public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1517        PreKeyRecord record = null;
1518        Cursor cursor = getCursorForPreKey(account, preKeyId);
1519        if (cursor.getCount() != 0) {
1520            cursor.moveToFirst();
1521            try {
1522                record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1523            } catch (IOException e) {
1524                throw new AssertionError(e);
1525            }
1526        }
1527        cursor.close();
1528        return record;
1529    }
1530
1531    public boolean containsPreKey(Account account, int preKeyId) {
1532        Cursor cursor = getCursorForPreKey(account, preKeyId);
1533        int count = cursor.getCount();
1534        cursor.close();
1535        return count != 0;
1536    }
1537
1538    public void storePreKey(Account account, PreKeyRecord record) {
1539        SQLiteDatabase db = this.getWritableDatabase();
1540        ContentValues values = new ContentValues();
1541        values.put(SQLiteAxolotlStore.ID, record.getId());
1542        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1543        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1544        db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1545    }
1546
1547    public int deletePreKey(Account account, int preKeyId) {
1548        SQLiteDatabase db = this.getWritableDatabase();
1549        String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1550        return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1551                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1552                        + SQLiteAxolotlStore.ID + "=?",
1553                args);
1554    }
1555
1556    private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1557        SQLiteDatabase db = this.getReadableDatabase();
1558        String[] columns = {SQLiteAxolotlStore.KEY};
1559        String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1560        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1561                columns,
1562                SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1563                selectionArgs,
1564                null, null, null);
1565
1566        return cursor;
1567    }
1568
1569    public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1570        SignedPreKeyRecord record = null;
1571        Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1572        if (cursor.getCount() != 0) {
1573            cursor.moveToFirst();
1574            try {
1575                record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1576            } catch (IOException e) {
1577                throw new AssertionError(e);
1578            }
1579        }
1580        cursor.close();
1581        return record;
1582    }
1583
1584    public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1585        List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1586        SQLiteDatabase db = this.getReadableDatabase();
1587        String[] columns = {SQLiteAxolotlStore.KEY};
1588        String[] selectionArgs = {account.getUuid()};
1589        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1590                columns,
1591                SQLiteAxolotlStore.ACCOUNT + "=?",
1592                selectionArgs,
1593                null, null, null);
1594
1595        while (cursor.moveToNext()) {
1596            try {
1597                prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1598            } catch (IOException ignored) {
1599            }
1600        }
1601        cursor.close();
1602        return prekeys;
1603    }
1604
1605    public int getSignedPreKeysCount(Account account) {
1606        String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1607        String[] selectionArgs = {account.getUuid()};
1608        SQLiteDatabase db = this.getReadableDatabase();
1609        Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1610                columns,
1611                SQLiteAxolotlStore.ACCOUNT + "=?",
1612                selectionArgs,
1613                null, null, null);
1614        final int count;
1615        if (cursor.moveToFirst()) {
1616            count = cursor.getInt(0);
1617        } else {
1618            count = 0;
1619        }
1620        cursor.close();
1621        return count;
1622    }
1623
1624    public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1625        Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1626        int count = cursor.getCount();
1627        cursor.close();
1628        return count != 0;
1629    }
1630
1631    public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1632        SQLiteDatabase db = this.getWritableDatabase();
1633        ContentValues values = new ContentValues();
1634        values.put(SQLiteAxolotlStore.ID, record.getId());
1635        values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1636        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1637        db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1638    }
1639
1640    public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1641        SQLiteDatabase db = this.getWritableDatabase();
1642        String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1643        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1644                SQLiteAxolotlStore.ACCOUNT + "=? AND "
1645                        + SQLiteAxolotlStore.ID + "=?",
1646                args);
1647    }
1648
1649    private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1650        final SQLiteDatabase db = this.getReadableDatabase();
1651        return getIdentityKeyCursor(db, account, name, own);
1652    }
1653
1654    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1655        return getIdentityKeyCursor(db, account, name, own, null);
1656    }
1657
1658    private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1659        final SQLiteDatabase db = this.getReadableDatabase();
1660        return getIdentityKeyCursor(db, account, fingerprint);
1661    }
1662
1663    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1664        return getIdentityKeyCursor(db, account, null, null, fingerprint);
1665    }
1666
1667    private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1668        String[] columns = {SQLiteAxolotlStore.TRUST,
1669                SQLiteAxolotlStore.ACTIVE,
1670                SQLiteAxolotlStore.LAST_ACTIVATION,
1671                SQLiteAxolotlStore.KEY};
1672        ArrayList<String> selectionArgs = new ArrayList<>(4);
1673        selectionArgs.add(account.getUuid());
1674        String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1675        if (name != null) {
1676            selectionArgs.add(name);
1677            selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1678        }
1679        if (fingerprint != null) {
1680            selectionArgs.add(fingerprint);
1681            selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1682        }
1683        if (own != null) {
1684            selectionArgs.add(own ? "1" : "0");
1685            selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1686        }
1687        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1688                columns,
1689                selectionString,
1690                selectionArgs.toArray(new String[selectionArgs.size()]),
1691                null, null, null);
1692
1693        return cursor;
1694    }
1695
1696    public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1697        SQLiteDatabase db = getReadableDatabase();
1698        return loadOwnIdentityKeyPair(db, account);
1699    }
1700
1701    private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1702        String name = account.getJid().asBareJid().toString();
1703        IdentityKeyPair identityKeyPair = null;
1704        Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1705        if (cursor.getCount() != 0) {
1706            cursor.moveToFirst();
1707            try {
1708                identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1709            } catch (InvalidKeyException e) {
1710                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1711            }
1712        }
1713        cursor.close();
1714
1715        return identityKeyPair;
1716    }
1717
1718    public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1719        return loadIdentityKeys(account, name, null);
1720    }
1721
1722    public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1723        Set<IdentityKey> identityKeys = new HashSet<>();
1724        Cursor cursor = getIdentityKeyCursor(account, name, false);
1725
1726        while (cursor.moveToNext()) {
1727            if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1728                continue;
1729            }
1730            try {
1731                String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1732                if (key != null) {
1733                    identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1734                } else {
1735                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1736                }
1737            } catch (InvalidKeyException e) {
1738                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1739            }
1740        }
1741        cursor.close();
1742
1743        return identityKeys;
1744    }
1745
1746    public long numTrustedKeys(Account account, String name) {
1747        SQLiteDatabase db = getReadableDatabase();
1748        String[] args = {
1749                account.getUuid(),
1750                name,
1751                FingerprintStatus.Trust.TRUSTED.toString(),
1752                FingerprintStatus.Trust.VERIFIED.toString(),
1753                FingerprintStatus.Trust.VERIFIED_X509.toString()
1754        };
1755        return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1756                SQLiteAxolotlStore.ACCOUNT + " = ?"
1757                        + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1758                        + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1759                        + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1760                args
1761        );
1762    }
1763
1764    private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1765        SQLiteDatabase db = this.getWritableDatabase();
1766        ContentValues values = new ContentValues();
1767        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1768        values.put(SQLiteAxolotlStore.NAME, name);
1769        values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1770        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1771        values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1772        values.putAll(status.toContentValues());
1773        String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1774        String[] whereArgs = {account.getUuid(), name, fingerprint};
1775        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1776        if (rows == 0) {
1777            db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1778        }
1779    }
1780
1781    public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1782        SQLiteDatabase db = this.getWritableDatabase();
1783        ContentValues values = new ContentValues();
1784        values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1785        values.put(SQLiteAxolotlStore.NAME, name);
1786        values.put(SQLiteAxolotlStore.OWN, 0);
1787        values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1788        values.putAll(status.toContentValues());
1789        db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1790    }
1791
1792    public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1793        Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1794        final FingerprintStatus status;
1795        if (cursor.getCount() > 0) {
1796            cursor.moveToFirst();
1797            status = FingerprintStatus.fromCursor(cursor);
1798        } else {
1799            status = null;
1800        }
1801        cursor.close();
1802        return status;
1803    }
1804
1805    public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1806        SQLiteDatabase db = this.getWritableDatabase();
1807        return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1808    }
1809
1810    private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1811        String[] selectionArgs = {
1812                account.getUuid(),
1813                fingerprint
1814        };
1815        int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1816                SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1817                        + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1818                selectionArgs);
1819        return rows == 1;
1820    }
1821
1822    public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1823        SQLiteDatabase db = this.getWritableDatabase();
1824        String[] selectionArgs = {
1825                account.getUuid(),
1826                fingerprint
1827        };
1828        try {
1829            ContentValues values = new ContentValues();
1830            values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1831            return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1832                    SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1833                            + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1834                    selectionArgs) == 1;
1835        } catch (CertificateEncodingException e) {
1836            Log.d(Config.LOGTAG, "could not encode certificate");
1837            return false;
1838        }
1839    }
1840
1841    public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1842        SQLiteDatabase db = this.getReadableDatabase();
1843        String[] selectionArgs = {
1844                account.getUuid(),
1845                fingerprint
1846        };
1847        String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1848        String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1849        Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1850        if (cursor.getCount() < 1) {
1851            return null;
1852        } else {
1853            cursor.moveToFirst();
1854            byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1855            cursor.close();
1856            if (certificate == null || certificate.length == 0) {
1857                return null;
1858            }
1859            try {
1860                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1861                return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1862            } catch (CertificateException e) {
1863                Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1864                return null;
1865            }
1866        }
1867    }
1868
1869    public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1870        storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1871    }
1872
1873    public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1874        storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1875    }
1876
1877
1878    private void recreateAxolotlDb(SQLiteDatabase db) {
1879        Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1880        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1881        db.execSQL(CREATE_SESSIONS_STATEMENT);
1882        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1883        db.execSQL(CREATE_PREKEYS_STATEMENT);
1884        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1885        db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1886        db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1887        db.execSQL(CREATE_IDENTITIES_STATEMENT);
1888    }
1889
1890    public void wipeAxolotlDb(Account account) {
1891        String accountName = account.getUuid();
1892        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1893        SQLiteDatabase db = this.getWritableDatabase();
1894        String[] deleteArgs = {
1895                accountName
1896        };
1897        db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1898                SQLiteAxolotlStore.ACCOUNT + " = ?",
1899                deleteArgs);
1900        db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1901                SQLiteAxolotlStore.ACCOUNT + " = ?",
1902                deleteArgs);
1903        db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1904                SQLiteAxolotlStore.ACCOUNT + " = ?",
1905                deleteArgs);
1906        db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1907                SQLiteAxolotlStore.ACCOUNT + " = ?",
1908                deleteArgs);
1909    }
1910
1911    public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1912        SQLiteDatabase db = this.getReadableDatabase();
1913        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;";
1914        String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1915        Cursor cursor = db.rawQuery(SQL, whereArgs);
1916        ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1917        while (cursor.moveToNext()) {
1918            try {
1919                contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1920            } catch (Exception e) {
1921                Log.d(Config.LOGTAG, e.getMessage());
1922            }
1923        }
1924        cursor.close();
1925        return contacts;
1926    }
1927}