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 org.json.JSONObject;
  15import org.whispersystems.libsignal.SignalProtocolAddress;
  16import org.whispersystems.libsignal.IdentityKey;
  17import org.whispersystems.libsignal.IdentityKeyPair;
  18import org.whispersystems.libsignal.InvalidKeyException;
  19import org.whispersystems.libsignal.state.PreKeyRecord;
  20import org.whispersystems.libsignal.state.SessionRecord;
  21import org.whispersystems.libsignal.state.SignedPreKeyRecord;
  22
  23import java.io.ByteArrayInputStream;
  24import java.io.File;
  25import java.io.IOException;
  26import java.security.cert.CertificateEncodingException;
  27import java.security.cert.CertificateException;
  28import java.security.cert.CertificateFactory;
  29import java.security.cert.X509Certificate;
  30import java.util.ArrayList;
  31import java.util.HashMap;
  32import java.util.HashSet;
  33import java.util.Iterator;
  34import java.util.List;
  35import java.util.Map;
  36import java.util.Set;
  37import java.util.concurrent.CopyOnWriteArrayList;
  38
  39import org.json.JSONException;
  40
  41import eu.siacs.conversations.Config;
  42import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  43import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  44import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
  45import eu.siacs.conversations.entities.Account;
  46import eu.siacs.conversations.entities.Contact;
  47import eu.siacs.conversations.entities.Conversation;
  48import eu.siacs.conversations.entities.Message;
  49import eu.siacs.conversations.entities.PresenceTemplate;
  50import eu.siacs.conversations.entities.Roster;
  51import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  52import eu.siacs.conversations.services.ShortcutService;
  53import eu.siacs.conversations.utils.CryptoHelper;
  54import eu.siacs.conversations.utils.FtsUtils;
  55import eu.siacs.conversations.utils.MimeUtils;
  56import eu.siacs.conversations.utils.Resolver;
  57import eu.siacs.conversations.xmpp.InvalidJid;
  58import eu.siacs.conversations.xmpp.mam.MamReference;
  59import rocks.xmpp.addr.Jid;
  60
  61public class DatabaseBackend extends SQLiteOpenHelper {
  62
  63	private static final String DATABASE_NAME = "history";
  64	private static final int DATABASE_VERSION = 42;
  65	private static DatabaseBackend instance = null;
  66	private static String CREATE_CONTATCS_STATEMENT = "create table "
  67			+ Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
  68			+ Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
  69			+ Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
  70			+ Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
  71			+ Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
  72			+ Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
  73			+ Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
  74			+ Account.TABLENAME + "(" + Account.UUID
  75			+ ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
  76			+ Contact.JID + ") ON CONFLICT REPLACE);";
  77
  78	private static String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
  79			+ ServiceDiscoveryResult.TABLENAME + "("
  80			+ ServiceDiscoveryResult.HASH + " TEXT, "
  81			+ ServiceDiscoveryResult.VER + " TEXT, "
  82			+ ServiceDiscoveryResult.RESULT + " TEXT, "
  83			+ "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
  84			+ ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
  85
  86	private static String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
  87			+ PresenceTemplate.TABELNAME + "("
  88			+ PresenceTemplate.UUID + " TEXT, "
  89			+ PresenceTemplate.LAST_USED + " NUMBER,"
  90			+ PresenceTemplate.MESSAGE + " TEXT,"
  91			+ PresenceTemplate.STATUS + " TEXT,"
  92			+ "UNIQUE(" + PresenceTemplate.MESSAGE + "," + PresenceTemplate.STATUS + ") ON CONFLICT REPLACE);";
  93
  94	private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
  95			+ SQLiteAxolotlStore.PREKEY_TABLENAME + "("
  96			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
  97			+ SQLiteAxolotlStore.ID + " INTEGER, "
  98			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
  99			+ SQLiteAxolotlStore.ACCOUNT
 100			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 101			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 102			+ SQLiteAxolotlStore.ID
 103			+ ") ON CONFLICT REPLACE"
 104			+ ");";
 105
 106	private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
 107			+ SQLiteAxolotlStore.SIGNED_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 String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
 119			+ SQLiteAxolotlStore.SESSION_TABLENAME + "("
 120			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 121			+ SQLiteAxolotlStore.NAME + " TEXT, "
 122			+ SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
 123			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 124			+ SQLiteAxolotlStore.ACCOUNT
 125			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 126			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 127			+ SQLiteAxolotlStore.NAME + ", "
 128			+ SQLiteAxolotlStore.DEVICE_ID
 129			+ ") ON CONFLICT REPLACE"
 130			+ ");";
 131
 132	private static String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
 133			+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
 134			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 135			+ SQLiteAxolotlStore.NAME + " TEXT, "
 136			+ SQLiteAxolotlStore.OWN + " INTEGER, "
 137			+ SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
 138			+ SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
 139			+ SQLiteAxolotlStore.TRUST + " TEXT, "
 140			+ SQLiteAxolotlStore.ACTIVE + " NUMBER, "
 141			+ SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
 142			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 143			+ SQLiteAxolotlStore.ACCOUNT
 144			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 145			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 146			+ SQLiteAxolotlStore.NAME + ", "
 147			+ SQLiteAxolotlStore.FINGERPRINT
 148			+ ") ON CONFLICT IGNORE"
 149			+ ");";
 150
 151	private static String RESOLVER_RESULTS_TABLENAME = "resolver_results";
 152
 153	private static String CREATE_RESOLVER_RESULTS_TABLE = "create table " + RESOLVER_RESULTS_TABLENAME + "("
 154			+ Resolver.Result.DOMAIN + " TEXT,"
 155			+ Resolver.Result.HOSTNAME + " TEXT,"
 156			+ Resolver.Result.IP + " BLOB,"
 157			+ Resolver.Result.PRIORITY + " NUMBER,"
 158			+ Resolver.Result.DIRECT_TLS + " NUMBER,"
 159			+ Resolver.Result.AUTHENTICATED + " NUMBER,"
 160			+ Resolver.Result.PORT + " NUMBER,"
 161			+ "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
 162			+ ");";
 163
 164	private static String CREATE_MESSAGE_TIME_INDEX = "create INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
 165	private static String CREATE_MESSAGE_CONVERSATION_INDEX = "create INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
 166
 167	private static String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING FTS4(uuid TEXT PRIMARY KEY, body TEXT)";
 168	private static String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index (uuid,body) VALUES (new.uuid,new.body); END;";
 169	private static 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 uuid=old.uuid; END;";
 170	private static String COPY_PREEXISTING_ENTRIES = "INSERT into messages_index(uuid,body) select uuid,body FROM " + Message.TABLENAME + ";";
 171
 172	private DatabaseBackend(Context context) {
 173		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 174	}
 175
 176	private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
 177		ContentValues values = new ContentValues();
 178		values.put(SQLiteAxolotlStore.TRUST, trust.toString());
 179		values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
 180		return values;
 181	}
 182
 183	public static synchronized DatabaseBackend getInstance(Context context) {
 184		if (instance == null) {
 185			instance = new DatabaseBackend(context);
 186		}
 187		return instance;
 188	}
 189
 190	@Override
 191	public void onConfigure(SQLiteDatabase db) {
 192		db.execSQL("PRAGMA foreign_keys=ON");
 193		db.rawQuery("PRAGMA secure_delete=ON",null);
 194	}
 195
 196	@Override
 197	public void onCreate(SQLiteDatabase db) {
 198		db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID + " TEXT PRIMARY KEY,"
 199				+ Account.USERNAME + " TEXT,"
 200				+ Account.SERVER + " TEXT,"
 201				+ Account.PASSWORD + " TEXT,"
 202				+ Account.DISPLAY_NAME + " TEXT, "
 203				+ Account.STATUS + " TEXT,"
 204				+ Account.STATUS_MESSAGE + " TEXT,"
 205				+ Account.ROSTERVERSION + " TEXT,"
 206				+ Account.OPTIONS + " NUMBER, "
 207				+ Account.AVATAR + " TEXT, "
 208				+ Account.KEYS + " TEXT, "
 209				+ Account.HOSTNAME + " TEXT, "
 210				+ Account.RESOURCE + " TEXT,"
 211				+ Account.PORT + " NUMBER DEFAULT 5222)");
 212		db.execSQL("create table " + Conversation.TABLENAME + " ("
 213				+ Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
 214				+ " TEXT, " + Conversation.CONTACT + " TEXT, "
 215				+ Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
 216				+ " TEXT, " + Conversation.CREATED + " NUMBER, "
 217				+ Conversation.STATUS + " NUMBER, " + Conversation.MODE
 218				+ " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
 219				+ Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
 220				+ "(" + Account.UUID + ") ON DELETE CASCADE);");
 221		db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
 222				+ " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
 223				+ Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
 224				+ " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
 225				+ Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
 226				+ Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
 227				+ Message.RELATIVE_FILE_PATH + " TEXT, "
 228				+ Message.SERVER_MSG_ID + " TEXT, "
 229				+ Message.FINGERPRINT + " TEXT, "
 230				+ Message.CARBON + " INTEGER, "
 231				+ Message.EDITED + " TEXT, "
 232				+ Message.READ + " NUMBER DEFAULT 1, "
 233				+ Message.OOB + " INTEGER, "
 234				+ Message.ERROR_MESSAGE + " TEXT,"
 235				+ Message.READ_BY_MARKERS + " TEXT,"
 236				+ Message.MARKABLE + " NUMBER DEFAULT 0,"
 237				+ Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
 238				+ Message.CONVERSATION + ") REFERENCES "
 239				+ Conversation.TABLENAME + "(" + Conversation.UUID
 240				+ ") ON DELETE CASCADE);");
 241		db.execSQL(CREATE_MESSAGE_TIME_INDEX);
 242		db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
 243		db.execSQL(CREATE_CONTATCS_STATEMENT);
 244		db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 245		db.execSQL(CREATE_SESSIONS_STATEMENT);
 246		db.execSQL(CREATE_PREKEYS_STATEMENT);
 247		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
 248		db.execSQL(CREATE_IDENTITIES_STATEMENT);
 249		db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 250		db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
 251		db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 252		db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 253		db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 254	}
 255
 256	@Override
 257	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 258		if (oldVersion < 2 && newVersion >= 2) {
 259			db.execSQL("update " + Account.TABLENAME + " set "
 260					+ Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
 261		}
 262		if (oldVersion < 3 && newVersion >= 3) {
 263			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 264					+ Message.TYPE + " NUMBER");
 265		}
 266		if (oldVersion < 5 && newVersion >= 5) {
 267			db.execSQL("DROP TABLE " + Contact.TABLENAME);
 268			db.execSQL(CREATE_CONTATCS_STATEMENT);
 269			db.execSQL("UPDATE " + Account.TABLENAME + " SET "
 270					+ Account.ROSTERVERSION + " = NULL");
 271		}
 272		if (oldVersion < 6 && newVersion >= 6) {
 273			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 274					+ Message.TRUE_COUNTERPART + " TEXT");
 275		}
 276		if (oldVersion < 7 && newVersion >= 7) {
 277			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 278					+ Message.REMOTE_MSG_ID + " TEXT");
 279			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 280					+ Contact.AVATAR + " TEXT");
 281			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
 282					+ Account.AVATAR + " TEXT");
 283		}
 284		if (oldVersion < 8 && newVersion >= 8) {
 285			db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
 286					+ Conversation.ATTRIBUTES + " TEXT");
 287		}
 288		if (oldVersion < 9 && newVersion >= 9) {
 289			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 290					+ Contact.LAST_TIME + " NUMBER");
 291			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 292					+ Contact.LAST_PRESENCE + " TEXT");
 293		}
 294		if (oldVersion < 10 && newVersion >= 10) {
 295			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 296					+ Message.RELATIVE_FILE_PATH + " TEXT");
 297		}
 298		if (oldVersion < 11 && newVersion >= 11) {
 299			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 300					+ Contact.GROUPS + " TEXT");
 301			db.execSQL("delete from " + Contact.TABLENAME);
 302			db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 303		}
 304		if (oldVersion < 12 && newVersion >= 12) {
 305			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 306					+ Message.SERVER_MSG_ID + " TEXT");
 307		}
 308		if (oldVersion < 13 && newVersion >= 13) {
 309			db.execSQL("delete from " + Contact.TABLENAME);
 310			db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 311		}
 312		if (oldVersion < 14 && newVersion >= 14) {
 313			canonicalizeJids(db);
 314		}
 315		if (oldVersion < 15 && newVersion >= 15) {
 316			recreateAxolotlDb(db);
 317			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 318					+ Message.FINGERPRINT + " TEXT");
 319		}
 320		if (oldVersion < 16 && newVersion >= 16) {
 321			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 322					+ Message.CARBON + " INTEGER");
 323		}
 324		if (oldVersion < 19 && newVersion >= 19) {
 325			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
 326		}
 327		if (oldVersion < 20 && newVersion >= 20) {
 328			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
 329			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
 330		}
 331		if (oldVersion < 26 && newVersion >= 26) {
 332			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
 333			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
 334		}
 335		if (oldVersion < 40 && newVersion >= 40) {
 336			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.RESOURCE + " TEXT");
 337		}
 338		/* Any migrations that alter the Account table need to happen BEFORE this migration, as it
 339		 * depends on account de-serialization.
 340		 */
 341		if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
 342			List<Account> accounts = getAccounts(db);
 343			for (Account account : accounts) {
 344				String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
 345				if (ownDeviceIdString == null) {
 346					continue;
 347				}
 348				int ownDeviceId = Integer.valueOf(ownDeviceIdString);
 349				SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownDeviceId);
 350				deleteSession(db, account, ownAddress);
 351				IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
 352				if (identityKeyPair != null) {
 353					String[] selectionArgs = {
 354							account.getUuid(),
 355							CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
 356					};
 357					ContentValues values = new ContentValues();
 358					values.put(SQLiteAxolotlStore.TRUSTED, 2);
 359					db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
 360							SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 361									+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
 362							selectionArgs);
 363				} else {
 364					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not load own identity key pair");
 365				}
 366			}
 367		}
 368		if (oldVersion < 18 && newVersion >= 18) {
 369			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
 370		}
 371
 372		if (oldVersion < 21 && newVersion >= 21) {
 373			List<Account> accounts = getAccounts(db);
 374			for (Account account : accounts) {
 375				account.unsetPgpSignature();
 376				db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 377						+ "=?", new String[]{account.getUuid()});
 378			}
 379		}
 380
 381		if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
 382			db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
 383		}
 384
 385		if (oldVersion < 23 && newVersion >= 23) {
 386			db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 387		}
 388
 389		if (oldVersion < 24 && newVersion >= 24) {
 390			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
 391		}
 392
 393		if (oldVersion < 25 && newVersion >= 25) {
 394			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
 395		}
 396
 397		if (oldVersion < 26 && newVersion >= 26) {
 398			db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 399		}
 400
 401		if (oldVersion < 27 && newVersion >= 27) {
 402			db.execSQL("DELETE FROM " + ServiceDiscoveryResult.TABLENAME);
 403		}
 404
 405		if (oldVersion < 28 && newVersion >= 28) {
 406			canonicalizeJids(db);
 407		}
 408
 409		if (oldVersion < 29 && newVersion >= 29) {
 410			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
 411		}
 412		if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
 413			db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.TRUST + " TEXT");
 414			db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.ACTIVE + " NUMBER");
 415			HashMap<Integer, ContentValues> migration = new HashMap<>();
 416			migration.put(0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 417			migration.put(1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 418			migration.put(2, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
 419			migration.put(3, createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
 420			migration.put(4, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 421			migration.put(5, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 422			migration.put(6, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
 423			migration.put(7, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
 424			migration.put(8, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
 425			for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
 426				String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
 427				String[] where = {String.valueOf(entry.getKey())};
 428				db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, entry.getValue(), whereClause, where);
 429			}
 430
 431		}
 432		if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
 433			db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
 434			ContentValues defaults = new ContentValues();
 435			defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
 436			db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
 437		}
 438		if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
 439			String whereClause = SQLiteAxolotlStore.OWN + "=1";
 440			db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true), whereClause, null);
 441		}
 442
 443		if (oldVersion < 34 && newVersion >= 34) {
 444			db.execSQL(CREATE_MESSAGE_TIME_INDEX);
 445
 446			final File oldPicturesDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Conversations/");
 447			final File oldFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/");
 448			final File newFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Files/");
 449			final File newVideosDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Videos/");
 450			if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
 451				final File newPicturesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Images/");
 452				newPicturesDirectory.getParentFile().mkdirs();
 453				if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
 454					Log.d(Config.LOGTAG, "moved " + oldPicturesDirectory.getAbsolutePath() + " to " + newPicturesDirectory.getAbsolutePath());
 455				}
 456			}
 457			if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
 458				newFilesDirectory.mkdirs();
 459				newVideosDirectory.mkdirs();
 460				final File[] files = oldFilesDirectory.listFiles();
 461				if (files == null) {
 462					return;
 463				}
 464				for (File file : files) {
 465					if (file.getName().equals(".nomedia")) {
 466						if (file.delete()) {
 467							Log.d(Config.LOGTAG, "deleted nomedia file in " + oldFilesDirectory.getAbsolutePath());
 468						}
 469					} else if (file.isFile()) {
 470						final String name = file.getName();
 471						boolean isVideo = false;
 472						int start = name.lastIndexOf('.') + 1;
 473						if (start < name.length()) {
 474							String mime = MimeUtils.guessMimeTypeFromExtension(name.substring(start));
 475							isVideo = mime != null && mime.startsWith("video/");
 476						}
 477						File dst = new File((isVideo ? newVideosDirectory : newFilesDirectory).getAbsolutePath() + "/" + file.getName());
 478						if (file.renameTo(dst)) {
 479							Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
 480						}
 481					}
 482				}
 483			}
 484		}
 485		if (oldVersion < 35 && newVersion >= 35) {
 486			db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
 487		}
 488		if (oldVersion < 36 && newVersion >= 36) {
 489			List<Account> accounts = getAccounts(db);
 490			for (Account account : accounts) {
 491				account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
 492				account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
 493				db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 494						+ "=?", new String[]{account.getUuid()});
 495			}
 496		}
 497
 498		if (oldVersion < 37 && newVersion >= 37) {
 499			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ_BY_MARKERS + " TEXT");
 500		}
 501
 502		if (oldVersion < 38 && newVersion >= 38) {
 503			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0");
 504		}
 505
 506		if (oldVersion < 39 && newVersion >= 39) {
 507			db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
 508		}
 509
 510		if (oldVersion < 41 && newVersion >= 41) {
 511			db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
 512			db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
 513			db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
 514			db.execSQL(COPY_PREEXISTING_ENTRIES);
 515		}
 516
 517		if (oldVersion < 42 && newVersion >= 42) {
 518			db.execSQL("DROP TRIGGER IF EXISTS after_message_delete");
 519		}
 520	}
 521
 522	private void canonicalizeJids(SQLiteDatabase db) {
 523		// migrate db to new, canonicalized JID domainpart representation
 524
 525		// Conversation table
 526		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 527		while (cursor.moveToNext()) {
 528			String newJid;
 529			try {
 530				newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
 531			} catch (IllegalArgumentException ignored) {
 532				Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 533						+ cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 534						+ ": " + ignored + ". Skipping...");
 535				continue;
 536			}
 537
 538			String updateArgs[] = {
 539					newJid,
 540					cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 541			};
 542			db.execSQL("update " + Conversation.TABLENAME
 543					+ " set " + Conversation.CONTACTJID + " = ? "
 544					+ " where " + Conversation.UUID + " = ?", updateArgs);
 545		}
 546		cursor.close();
 547
 548		// Contact table
 549		cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 550		while (cursor.moveToNext()) {
 551			String newJid;
 552			try {
 553				newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
 554			} catch (IllegalArgumentException ignored) {
 555				Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 556						+ cursor.getString(cursor.getColumnIndex(Contact.JID))
 557						+ ": " + ignored + ". Skipping...");
 558				continue;
 559			}
 560
 561			String updateArgs[] = {
 562					newJid,
 563					cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 564					cursor.getString(cursor.getColumnIndex(Contact.JID)),
 565			};
 566			db.execSQL("update " + Contact.TABLENAME
 567					+ " set " + Contact.JID + " = ? "
 568					+ " where " + Contact.ACCOUNT + " = ? "
 569					+ " AND " + Contact.JID + " = ?", updateArgs);
 570		}
 571		cursor.close();
 572
 573		// Account table
 574		cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 575		while (cursor.moveToNext()) {
 576			String newServer;
 577			try {
 578				newServer = Jid.of(
 579						cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 580						cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 581						null
 582				).getDomain();
 583			} catch (IllegalArgumentException ignored) {
 584				Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 585						+ cursor.getString(cursor.getColumnIndex(Account.SERVER))
 586						+ ": " + ignored + ". Skipping...");
 587				continue;
 588			}
 589
 590			String updateArgs[] = {
 591					newServer,
 592					cursor.getString(cursor.getColumnIndex(Account.UUID)),
 593			};
 594			db.execSQL("update " + Account.TABLENAME
 595					+ " set " + Account.SERVER + " = ? "
 596					+ " where " + Account.UUID + " = ?", updateArgs);
 597		}
 598		cursor.close();
 599	}
 600
 601	public void createConversation(Conversation conversation) {
 602		SQLiteDatabase db = this.getWritableDatabase();
 603		db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 604	}
 605
 606	public void createMessage(Message message) {
 607		SQLiteDatabase db = this.getWritableDatabase();
 608		db.insert(Message.TABLENAME, null, message.getContentValues());
 609	}
 610
 611	public void createAccount(Account account) {
 612		SQLiteDatabase db = this.getWritableDatabase();
 613		db.insert(Account.TABLENAME, null, account.getContentValues());
 614	}
 615
 616	public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 617		SQLiteDatabase db = this.getWritableDatabase();
 618		db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 619	}
 620
 621	public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 622		SQLiteDatabase db = this.getReadableDatabase();
 623		String[] selectionArgs = {hash, ver};
 624		Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 625				ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 626				selectionArgs, null, null, null);
 627		if (cursor.getCount() == 0) {
 628			cursor.close();
 629			return null;
 630		}
 631		cursor.moveToFirst();
 632
 633		ServiceDiscoveryResult result = null;
 634		try {
 635			result = new ServiceDiscoveryResult(cursor);
 636		} catch (JSONException e) { /* result is still null */ }
 637
 638		cursor.close();
 639		return result;
 640	}
 641
 642	public void saveResolverResult(String domain, Resolver.Result result) {
 643		SQLiteDatabase db = this.getWritableDatabase();
 644		ContentValues contentValues = result.toContentValues();
 645		contentValues.put(Resolver.Result.DOMAIN, domain);
 646		db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
 647	}
 648
 649	public Resolver.Result findResolverResult(String domain) {
 650		SQLiteDatabase db = this.getReadableDatabase();
 651		String where = Resolver.Result.DOMAIN + "=?";
 652		String[] whereArgs = {domain};
 653		Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
 654		Resolver.Result result = null;
 655		if (cursor != null) {
 656			if (cursor.moveToFirst()) {
 657				result = Resolver.Result.fromCursor(cursor);
 658			}
 659			cursor.close();
 660		}
 661		return result;
 662	}
 663
 664	public void insertPresenceTemplate(PresenceTemplate template) {
 665		SQLiteDatabase db = this.getWritableDatabase();
 666		String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 667		String[] whereToDeleteArgs = {template.getStatusMessage()};
 668		db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 669		db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 670		db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 671	}
 672
 673	public List<PresenceTemplate> getPresenceTemplates() {
 674		ArrayList<PresenceTemplate> templates = new ArrayList<>();
 675		SQLiteDatabase db = this.getReadableDatabase();
 676		Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 677		while (cursor.moveToNext()) {
 678			templates.add(PresenceTemplate.fromCursor(cursor));
 679		}
 680		cursor.close();
 681		return templates;
 682	}
 683
 684	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 685		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 686		SQLiteDatabase db = this.getReadableDatabase();
 687		String[] selectionArgs = {Integer.toString(status)};
 688		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 689				+ " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
 690				+ Conversation.CREATED + " desc", selectionArgs);
 691		while (cursor.moveToNext()) {
 692			final Conversation conversation = Conversation.fromCursor(cursor);
 693			if (conversation.getJid() instanceof InvalidJid) {
 694				continue;
 695			}
 696			list.add(conversation);
 697		}
 698		cursor.close();
 699		return list;
 700	}
 701
 702	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 703		return getMessages(conversations, limit, -1);
 704	}
 705
 706	public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
 707		ArrayList<Message> list = new ArrayList<>();
 708		SQLiteDatabase db = this.getReadableDatabase();
 709		Cursor cursor;
 710		if (timestamp == -1) {
 711			String[] selectionArgs = {conversation.getUuid()};
 712			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 713					+ "=?", selectionArgs, null, null, Message.TIME_SENT
 714					+ " DESC", String.valueOf(limit));
 715		} else {
 716			String[] selectionArgs = {conversation.getUuid(),
 717					Long.toString(timestamp)};
 718			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 719							+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 720					null, null, Message.TIME_SENT + " DESC",
 721					String.valueOf(limit));
 722		}
 723		if (cursor.getCount() > 0) {
 724			cursor.moveToLast();
 725			do {
 726				Message message = Message.fromCursor(cursor, conversation);
 727				if (message != null) {
 728					list.add(message);
 729				}
 730			} while (cursor.moveToPrevious());
 731		}
 732		cursor.close();
 733		return list;
 734	}
 735
 736	public Cursor getMessageSearchCursor(List<String> term) {
 737		SQLiteDatabase db = this.getReadableDatabase();
 738		String SQL = "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.uuid=messages.uuid where " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + ',' + Message.ENCRYPTION_PGP + ',' + Message.ENCRYPTION_DECRYPTION_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + ',' + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ? ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS;
 739		Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
 740		return db.rawQuery(SQL, new String[]{FtsUtils.toMatchString(term)});
 741	}
 742
 743	public Iterable<Message> getMessagesIterable(final Conversation conversation) {
 744		return () -> {
 745			class MessageIterator implements Iterator<Message> {
 746				private SQLiteDatabase db = getReadableDatabase();
 747				private String[] selectionArgs = {conversation.getUuid()};
 748				private Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 749						+ "=?", selectionArgs, null, null, Message.TIME_SENT
 750						+ " ASC", null);
 751
 752				private MessageIterator() {
 753					cursor.moveToFirst();
 754				}
 755
 756				@Override
 757				public boolean hasNext() {
 758					return !cursor.isAfterLast();
 759				}
 760
 761				@Override
 762				public Message next() {
 763					Message message = Message.fromCursor(cursor, conversation);
 764					cursor.moveToNext();
 765					return message;
 766				}
 767
 768				@Override
 769				public void remove() {
 770					throw new UnsupportedOperationException();
 771				}
 772			}
 773			return new MessageIterator();
 774		};
 775	}
 776
 777	public Conversation findConversation(final Account account, final Jid contactJid) {
 778		SQLiteDatabase db = this.getReadableDatabase();
 779		String[] selectionArgs = {account.getUuid(),
 780				contactJid.asBareJid().toString() + "/%",
 781				contactJid.asBareJid().toString()
 782		};
 783		Cursor cursor = db.query(Conversation.TABLENAME, null,
 784				Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 785						+ " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 786		if (cursor.getCount() == 0) {
 787			cursor.close();
 788			return null;
 789		}
 790		cursor.moveToFirst();
 791		Conversation conversation = Conversation.fromCursor(cursor);
 792		cursor.close();
 793		if (conversation.getJid() instanceof InvalidJid) {
 794			return null;
 795		}
 796		return conversation;
 797	}
 798
 799	public void updateConversation(final Conversation conversation) {
 800		final SQLiteDatabase db = this.getWritableDatabase();
 801		final String[] args = {conversation.getUuid()};
 802		db.update(Conversation.TABLENAME, conversation.getContentValues(),
 803				Conversation.UUID + "=?", args);
 804	}
 805
 806	public List<Account> getAccounts() {
 807		SQLiteDatabase db = this.getReadableDatabase();
 808		return getAccounts(db);
 809	}
 810
 811	public List<Jid> getAccountJids() {
 812		SQLiteDatabase db = this.getReadableDatabase();
 813		final List<Jid> jids = new ArrayList<>();
 814		final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 815		String where = "not options & (1 <<1)";
 816		Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
 817		try {
 818			while (cursor.moveToNext()) {
 819				jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 820			}
 821			return jids;
 822		} catch (Exception e) {
 823			return jids;
 824		} finally {
 825			if (cursor != null) {
 826				cursor.close();
 827			}
 828		}
 829	}
 830
 831	private List<Account> getAccounts(SQLiteDatabase db) {
 832		List<Account> list = new ArrayList<>();
 833		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 834				null, null);
 835		while (cursor.moveToNext()) {
 836			list.add(Account.fromCursor(cursor));
 837		}
 838		cursor.close();
 839		return list;
 840	}
 841
 842	public boolean updateAccount(Account account) {
 843		SQLiteDatabase db = this.getWritableDatabase();
 844		String[] args = {account.getUuid()};
 845		final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 846		return rows == 1;
 847	}
 848
 849	public boolean deleteAccount(Account account) {
 850		SQLiteDatabase db = this.getWritableDatabase();
 851		String[] args = {account.getUuid()};
 852		final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 853		return rows == 1;
 854	}
 855
 856	public boolean updateMessage(Message message, boolean includeBody) {
 857		SQLiteDatabase db = this.getWritableDatabase();
 858		String[] args = {message.getUuid()};
 859		ContentValues contentValues = message.getContentValues();
 860		contentValues.remove(Message.UUID);
 861		if (!includeBody) {
 862			contentValues.remove(Message.BODY);
 863		}
 864		return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
 865	}
 866
 867	public void updateMessage(Message message, String uuid) {
 868		SQLiteDatabase db = this.getWritableDatabase();
 869		String[] args = {uuid};
 870		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 871				+ "=?", args);
 872	}
 873
 874	public void readRoster(Roster roster) {
 875		SQLiteDatabase db = this.getReadableDatabase();
 876		Cursor cursor;
 877		String args[] = {roster.getAccount().getUuid()};
 878		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 879		while (cursor.moveToNext()) {
 880			roster.initContact(Contact.fromCursor(cursor));
 881		}
 882		cursor.close();
 883	}
 884
 885	public void writeRoster(final Roster roster) {
 886		long start = SystemClock.elapsedRealtime();
 887		final Account account = roster.getAccount();
 888		final SQLiteDatabase db = this.getWritableDatabase();
 889		db.beginTransaction();
 890		for (Contact contact : roster.getContacts()) {
 891			if (contact.getOption(Contact.Options.IN_ROSTER) || contact.getAvatar() != null) {
 892				db.insert(Contact.TABLENAME, null, contact.getContentValues());
 893			} else {
 894				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
 895				String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
 896				db.delete(Contact.TABLENAME, where, whereArgs);
 897			}
 898		}
 899		db.setTransactionSuccessful();
 900		db.endTransaction();
 901		account.setRosterVersion(roster.getVersion());
 902		updateAccount(account);
 903		long duration = SystemClock.elapsedRealtime() - start;
 904		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
 905	}
 906
 907	public void deleteMessagesInConversation(Conversation conversation) {
 908		long start = SystemClock.elapsedRealtime();
 909		final SQLiteDatabase db = this.getWritableDatabase();
 910		db.beginTransaction();
 911		String[] args = {conversation.getUuid()};
 912		db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
 913		int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
 914		db.setTransactionSuccessful();
 915		db.endTransaction();
 916		Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
 917	}
 918
 919	public void expireOldMessages(long timestamp) {
 920		final String[] args = {String.valueOf(timestamp)};
 921		SQLiteDatabase db = this.getReadableDatabase();
 922		db.beginTransaction();
 923		db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
 924		db.delete(Message.TABLENAME, "timeSent<?", args);
 925		db.setTransactionSuccessful();
 926		db.endTransaction();
 927	}
 928
 929	public MamReference getLastMessageReceived(Account account) {
 930		Cursor cursor = null;
 931		try {
 932			SQLiteDatabase db = this.getReadableDatabase();
 933			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";
 934			String[] args = {account.getUuid()};
 935			cursor = db.rawQuery(sql, args);
 936			if (cursor.getCount() == 0) {
 937				return null;
 938			} else {
 939				cursor.moveToFirst();
 940				return new MamReference(cursor.getLong(0), cursor.getString(1));
 941			}
 942		} catch (Exception e) {
 943			return null;
 944		} finally {
 945			if (cursor != null) {
 946				cursor.close();
 947			}
 948		}
 949	}
 950
 951	public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
 952		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";
 953		String[] args = {account.getUuid(), fingerprint};
 954		Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
 955		long time;
 956		if (cursor.moveToFirst()) {
 957			time = cursor.getLong(0);
 958		} else {
 959			time = 0;
 960		}
 961		cursor.close();
 962		return time;
 963	}
 964
 965	public MamReference getLastClearDate(Account account) {
 966		SQLiteDatabase db = this.getReadableDatabase();
 967		String[] columns = {Conversation.ATTRIBUTES};
 968		String selection = Conversation.ACCOUNT + "=?";
 969		String[] args = {account.getUuid()};
 970		Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
 971		MamReference maxClearDate = new MamReference(0);
 972		while (cursor.moveToNext()) {
 973			try {
 974				final JSONObject o = new JSONObject(cursor.getString(0));
 975				maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
 976			} catch (Exception e) {
 977				//ignored
 978			}
 979		}
 980		cursor.close();
 981		return maxClearDate;
 982	}
 983
 984	private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
 985		final SQLiteDatabase db = this.getReadableDatabase();
 986		String[] selectionArgs = {account.getUuid(),
 987				contact.getName(),
 988				Integer.toString(contact.getDeviceId())};
 989		return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 990				null,
 991				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 992						+ SQLiteAxolotlStore.NAME + " = ? AND "
 993						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 994				selectionArgs,
 995				null, null, null);
 996	}
 997
 998	public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
 999		SessionRecord session = null;
1000		Cursor cursor = getCursorForSession(account, contact);
1001		if (cursor.getCount() != 0) {
1002			cursor.moveToFirst();
1003			try {
1004				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1005			} catch (IOException e) {
1006				cursor.close();
1007				throw new AssertionError(e);
1008			}
1009		}
1010		cursor.close();
1011		return session;
1012	}
1013
1014	public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1015		final SQLiteDatabase db = this.getReadableDatabase();
1016		return getSubDeviceSessions(db, account, contact);
1017	}
1018
1019	private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1020		List<Integer> devices = new ArrayList<>();
1021		String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1022		String[] selectionArgs = {account.getUuid(),
1023				contact.getName()};
1024		Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1025				columns,
1026				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1027						+ SQLiteAxolotlStore.NAME + " = ?",
1028				selectionArgs,
1029				null, null, null);
1030
1031		while (cursor.moveToNext()) {
1032			devices.add(cursor.getInt(
1033					cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1034		}
1035
1036		cursor.close();
1037		return devices;
1038	}
1039
1040	public List<String> getKnownSignalAddresses(Account account) {
1041		List<String> addresses = new ArrayList<>();
1042		String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1043		String[] selectionArgs = {account.getUuid()};
1044		Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1045				colums,
1046				SQLiteAxolotlStore.ACCOUNT + " = ?",
1047				selectionArgs,
1048				null, null, null
1049		);
1050		while (cursor.moveToNext()) {
1051			addresses.add(cursor.getString(0));
1052		}
1053		cursor.close();
1054		return addresses;
1055	}
1056
1057	public boolean containsSession(Account account, SignalProtocolAddress contact) {
1058		Cursor cursor = getCursorForSession(account, contact);
1059		int count = cursor.getCount();
1060		cursor.close();
1061		return count != 0;
1062	}
1063
1064	public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1065		SQLiteDatabase db = this.getWritableDatabase();
1066		ContentValues values = new ContentValues();
1067		values.put(SQLiteAxolotlStore.NAME, contact.getName());
1068		values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1069		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1070		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1071		db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1072	}
1073
1074	public void deleteSession(Account account, SignalProtocolAddress contact) {
1075		SQLiteDatabase db = this.getWritableDatabase();
1076		deleteSession(db, account, contact);
1077	}
1078
1079	private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1080		String[] args = {account.getUuid(),
1081				contact.getName(),
1082				Integer.toString(contact.getDeviceId())};
1083		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1084				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1085						+ SQLiteAxolotlStore.NAME + " = ? AND "
1086						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1087				args);
1088	}
1089
1090	public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1091		SQLiteDatabase db = this.getWritableDatabase();
1092		String[] args = {account.getUuid(), contact.getName()};
1093		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1094				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1095						+ SQLiteAxolotlStore.NAME + " = ?",
1096				args);
1097	}
1098
1099	private Cursor getCursorForPreKey(Account account, int preKeyId) {
1100		SQLiteDatabase db = this.getReadableDatabase();
1101		String[] columns = {SQLiteAxolotlStore.KEY};
1102		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1103		Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1104				columns,
1105				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1106						+ SQLiteAxolotlStore.ID + "=?",
1107				selectionArgs,
1108				null, null, null);
1109
1110		return cursor;
1111	}
1112
1113	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1114		PreKeyRecord record = null;
1115		Cursor cursor = getCursorForPreKey(account, preKeyId);
1116		if (cursor.getCount() != 0) {
1117			cursor.moveToFirst();
1118			try {
1119				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1120			} catch (IOException e) {
1121				throw new AssertionError(e);
1122			}
1123		}
1124		cursor.close();
1125		return record;
1126	}
1127
1128	public boolean containsPreKey(Account account, int preKeyId) {
1129		Cursor cursor = getCursorForPreKey(account, preKeyId);
1130		int count = cursor.getCount();
1131		cursor.close();
1132		return count != 0;
1133	}
1134
1135	public void storePreKey(Account account, PreKeyRecord record) {
1136		SQLiteDatabase db = this.getWritableDatabase();
1137		ContentValues values = new ContentValues();
1138		values.put(SQLiteAxolotlStore.ID, record.getId());
1139		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1140		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1141		db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1142	}
1143
1144	public void deletePreKey(Account account, int preKeyId) {
1145		SQLiteDatabase db = this.getWritableDatabase();
1146		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1147		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1148				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1149						+ SQLiteAxolotlStore.ID + "=?",
1150				args);
1151	}
1152
1153	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1154		SQLiteDatabase db = this.getReadableDatabase();
1155		String[] columns = {SQLiteAxolotlStore.KEY};
1156		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1157		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1158				columns,
1159				SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1160				selectionArgs,
1161				null, null, null);
1162
1163		return cursor;
1164	}
1165
1166	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1167		SignedPreKeyRecord record = null;
1168		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1169		if (cursor.getCount() != 0) {
1170			cursor.moveToFirst();
1171			try {
1172				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1173			} catch (IOException e) {
1174				throw new AssertionError(e);
1175			}
1176		}
1177		cursor.close();
1178		return record;
1179	}
1180
1181	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1182		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1183		SQLiteDatabase db = this.getReadableDatabase();
1184		String[] columns = {SQLiteAxolotlStore.KEY};
1185		String[] selectionArgs = {account.getUuid()};
1186		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1187				columns,
1188				SQLiteAxolotlStore.ACCOUNT + "=?",
1189				selectionArgs,
1190				null, null, null);
1191
1192		while (cursor.moveToNext()) {
1193			try {
1194				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1195			} catch (IOException ignored) {
1196			}
1197		}
1198		cursor.close();
1199		return prekeys;
1200	}
1201
1202	public int getSignedPreKeysCount(Account account) {
1203		String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1204		String[] selectionArgs = {account.getUuid()};
1205		SQLiteDatabase db = this.getReadableDatabase();
1206		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1207				columns,
1208				SQLiteAxolotlStore.ACCOUNT + "=?",
1209				selectionArgs,
1210				null, null, null);
1211		final int count;
1212		if (cursor.moveToFirst()) {
1213			count = cursor.getInt(0);
1214		} else {
1215			count = 0;
1216		}
1217		cursor.close();
1218		return count;
1219	}
1220
1221	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1222		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1223		int count = cursor.getCount();
1224		cursor.close();
1225		return count != 0;
1226	}
1227
1228	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1229		SQLiteDatabase db = this.getWritableDatabase();
1230		ContentValues values = new ContentValues();
1231		values.put(SQLiteAxolotlStore.ID, record.getId());
1232		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1233		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1234		db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1235	}
1236
1237	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1238		SQLiteDatabase db = this.getWritableDatabase();
1239		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1240		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1241				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1242						+ SQLiteAxolotlStore.ID + "=?",
1243				args);
1244	}
1245
1246	private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1247		final SQLiteDatabase db = this.getReadableDatabase();
1248		return getIdentityKeyCursor(db, account, name, own);
1249	}
1250
1251	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1252		return getIdentityKeyCursor(db, account, name, own, null);
1253	}
1254
1255	private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1256		final SQLiteDatabase db = this.getReadableDatabase();
1257		return getIdentityKeyCursor(db, account, fingerprint);
1258	}
1259
1260	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1261		return getIdentityKeyCursor(db, account, null, null, fingerprint);
1262	}
1263
1264	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1265		String[] columns = {SQLiteAxolotlStore.TRUST,
1266				SQLiteAxolotlStore.ACTIVE,
1267				SQLiteAxolotlStore.LAST_ACTIVATION,
1268				SQLiteAxolotlStore.KEY};
1269		ArrayList<String> selectionArgs = new ArrayList<>(4);
1270		selectionArgs.add(account.getUuid());
1271		String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1272		if (name != null) {
1273			selectionArgs.add(name);
1274			selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1275		}
1276		if (fingerprint != null) {
1277			selectionArgs.add(fingerprint);
1278			selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1279		}
1280		if (own != null) {
1281			selectionArgs.add(own ? "1" : "0");
1282			selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1283		}
1284		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1285				columns,
1286				selectionString,
1287				selectionArgs.toArray(new String[selectionArgs.size()]),
1288				null, null, null);
1289
1290		return cursor;
1291	}
1292
1293	public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1294		SQLiteDatabase db = getReadableDatabase();
1295		return loadOwnIdentityKeyPair(db, account);
1296	}
1297
1298	private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1299		String name = account.getJid().asBareJid().toString();
1300		IdentityKeyPair identityKeyPair = null;
1301		Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1302		if (cursor.getCount() != 0) {
1303			cursor.moveToFirst();
1304			try {
1305				identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1306			} catch (InvalidKeyException e) {
1307				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1308			}
1309		}
1310		cursor.close();
1311
1312		return identityKeyPair;
1313	}
1314
1315	public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1316		return loadIdentityKeys(account, name, null);
1317	}
1318
1319	public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1320		Set<IdentityKey> identityKeys = new HashSet<>();
1321		Cursor cursor = getIdentityKeyCursor(account, name, false);
1322
1323		while (cursor.moveToNext()) {
1324			if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1325				continue;
1326			}
1327			try {
1328				String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1329				if (key != null) {
1330					identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1331				} else {
1332					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1333				}
1334			} catch (InvalidKeyException e) {
1335				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1336			}
1337		}
1338		cursor.close();
1339
1340		return identityKeys;
1341	}
1342
1343	public long numTrustedKeys(Account account, String name) {
1344		SQLiteDatabase db = getReadableDatabase();
1345		String[] args = {
1346				account.getUuid(),
1347				name,
1348				FingerprintStatus.Trust.TRUSTED.toString(),
1349				FingerprintStatus.Trust.VERIFIED.toString(),
1350				FingerprintStatus.Trust.VERIFIED_X509.toString()
1351		};
1352		return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1353				SQLiteAxolotlStore.ACCOUNT + " = ?"
1354						+ " AND " + SQLiteAxolotlStore.NAME + " = ?"
1355						+ " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1356						+ " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1357				args
1358		);
1359	}
1360
1361	private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1362		SQLiteDatabase db = this.getWritableDatabase();
1363		ContentValues values = new ContentValues();
1364		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1365		values.put(SQLiteAxolotlStore.NAME, name);
1366		values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1367		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1368		values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1369		values.putAll(status.toContentValues());
1370		String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1371		String[] whereArgs = {account.getUuid(), name, fingerprint};
1372		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1373		if (rows == 0) {
1374			db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1375		}
1376	}
1377
1378	public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1379		SQLiteDatabase db = this.getWritableDatabase();
1380		ContentValues values = new ContentValues();
1381		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1382		values.put(SQLiteAxolotlStore.NAME, name);
1383		values.put(SQLiteAxolotlStore.OWN, 0);
1384		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1385		values.putAll(status.toContentValues());
1386		db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1387	}
1388
1389	public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1390		Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1391		final FingerprintStatus status;
1392		if (cursor.getCount() > 0) {
1393			cursor.moveToFirst();
1394			status = FingerprintStatus.fromCursor(cursor);
1395		} else {
1396			status = null;
1397		}
1398		cursor.close();
1399		return status;
1400	}
1401
1402	public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1403		SQLiteDatabase db = this.getWritableDatabase();
1404		return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1405	}
1406
1407	private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1408		String[] selectionArgs = {
1409				account.getUuid(),
1410				fingerprint
1411		};
1412		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1413				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1414						+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1415				selectionArgs);
1416		return rows == 1;
1417	}
1418
1419	public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1420		SQLiteDatabase db = this.getWritableDatabase();
1421		String[] selectionArgs = {
1422				account.getUuid(),
1423				fingerprint
1424		};
1425		try {
1426			ContentValues values = new ContentValues();
1427			values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1428			return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1429					SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1430							+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1431					selectionArgs) == 1;
1432		} catch (CertificateEncodingException e) {
1433			Log.d(Config.LOGTAG, "could not encode certificate");
1434			return false;
1435		}
1436	}
1437
1438	public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1439		SQLiteDatabase db = this.getReadableDatabase();
1440		String[] selectionArgs = {
1441				account.getUuid(),
1442				fingerprint
1443		};
1444		String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1445		String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1446		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1447		if (cursor.getCount() < 1) {
1448			return null;
1449		} else {
1450			cursor.moveToFirst();
1451			byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1452			cursor.close();
1453			if (certificate == null || certificate.length == 0) {
1454				return null;
1455			}
1456			try {
1457				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1458				return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1459			} catch (CertificateException e) {
1460				Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1461				return null;
1462			}
1463		}
1464	}
1465
1466	public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1467		storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1468	}
1469
1470	public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1471		storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1472	}
1473
1474
1475	private void recreateAxolotlDb(SQLiteDatabase db) {
1476		Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1477		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1478		db.execSQL(CREATE_SESSIONS_STATEMENT);
1479		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1480		db.execSQL(CREATE_PREKEYS_STATEMENT);
1481		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1482		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1483		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1484		db.execSQL(CREATE_IDENTITIES_STATEMENT);
1485	}
1486
1487	public void wipeAxolotlDb(Account account) {
1488		String accountName = account.getUuid();
1489		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1490		SQLiteDatabase db = this.getWritableDatabase();
1491		String[] deleteArgs = {
1492				accountName
1493		};
1494		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1495				SQLiteAxolotlStore.ACCOUNT + " = ?",
1496				deleteArgs);
1497		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1498				SQLiteAxolotlStore.ACCOUNT + " = ?",
1499				deleteArgs);
1500		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1501				SQLiteAxolotlStore.ACCOUNT + " = ?",
1502				deleteArgs);
1503		db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1504				SQLiteAxolotlStore.ACCOUNT + " = ?",
1505				deleteArgs);
1506	}
1507
1508	public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1509		SQLiteDatabase db = this.getReadableDatabase();
1510		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;";
1511		String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1512		Cursor cursor = db.rawQuery(SQL, whereArgs);
1513		ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1514		while (cursor.moveToNext()) {
1515			try {
1516				contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1517			} catch (Exception e) {
1518				Log.d(Config.LOGTAG, e.getMessage());
1519			}
1520		}
1521		cursor.close();
1522		return contacts;
1523	}
1524}