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