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 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			if (cursor.moveToFirst()) {
 658				result = Resolver.Result.fromCursor(cursor);
 659			}
 660			cursor.close();
 661		}
 662		return result;
 663	}
 664
 665	public void insertPresenceTemplate(PresenceTemplate template) {
 666		SQLiteDatabase db = this.getWritableDatabase();
 667		String whereToDelete = PresenceTemplate.MESSAGE + "=?";
 668		String[] whereToDeleteArgs = {template.getStatusMessage()};
 669		db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
 670		db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
 671		db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 672	}
 673
 674	public List<PresenceTemplate> getPresenceTemplates() {
 675		ArrayList<PresenceTemplate> templates = new ArrayList<>();
 676		SQLiteDatabase db = this.getReadableDatabase();
 677		Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
 678		while (cursor.moveToNext()) {
 679			templates.add(PresenceTemplate.fromCursor(cursor));
 680		}
 681		cursor.close();
 682		return templates;
 683	}
 684
 685	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 686		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 687		SQLiteDatabase db = this.getReadableDatabase();
 688		String[] selectionArgs = {Integer.toString(status)};
 689		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 690				+ " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
 691				+ Conversation.CREATED + " desc", selectionArgs);
 692		while (cursor.moveToNext()) {
 693			final Conversation conversation = Conversation.fromCursor(cursor);
 694			if (conversation.getJid() instanceof InvalidJid) {
 695				continue;
 696			}
 697			list.add(conversation);
 698		}
 699		cursor.close();
 700		return list;
 701	}
 702
 703	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 704		return getMessages(conversations, limit, -1);
 705	}
 706
 707	public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
 708		ArrayList<Message> list = new ArrayList<>();
 709		SQLiteDatabase db = this.getReadableDatabase();
 710		Cursor cursor;
 711		if (timestamp == -1) {
 712			String[] selectionArgs = {conversation.getUuid()};
 713			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 714					+ "=?", selectionArgs, null, null, Message.TIME_SENT
 715					+ " DESC", String.valueOf(limit));
 716		} else {
 717			String[] selectionArgs = {conversation.getUuid(),
 718					Long.toString(timestamp)};
 719			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 720							+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 721					null, null, Message.TIME_SENT + " DESC",
 722					String.valueOf(limit));
 723		}
 724		if (cursor.getCount() > 0) {
 725			cursor.moveToLast();
 726			do {
 727				Message message = Message.fromCursor(cursor, conversation);
 728				if (message != null) {
 729					list.add(message);
 730				}
 731			} while (cursor.moveToPrevious());
 732		}
 733		cursor.close();
 734		return list;
 735	}
 736
 737	public Cursor getMessageSearchCursor(List<String> term) {
 738		SQLiteDatabase db = this.getReadableDatabase();
 739		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;
 740		Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
 741		return db.rawQuery(SQL, new String[]{FtsUtils.toMatchString(term)});
 742	}
 743
 744	public Iterable<Message> getMessagesIterable(final Conversation conversation) {
 745		return () -> {
 746			class MessageIterator implements Iterator<Message> {
 747				private SQLiteDatabase db = getReadableDatabase();
 748				private String[] selectionArgs = {conversation.getUuid()};
 749				private Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 750						+ "=?", selectionArgs, null, null, Message.TIME_SENT
 751						+ " ASC", null);
 752
 753				private MessageIterator() {
 754					cursor.moveToFirst();
 755				}
 756
 757				@Override
 758				public boolean hasNext() {
 759					return !cursor.isAfterLast();
 760				}
 761
 762				@Override
 763				public Message next() {
 764					Message message = Message.fromCursor(cursor, conversation);
 765					cursor.moveToNext();
 766					return message;
 767				}
 768
 769				@Override
 770				public void remove() {
 771					throw new UnsupportedOperationException();
 772				}
 773			}
 774			return new MessageIterator();
 775		};
 776	}
 777
 778	public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
 779		SQLiteDatabase db = this.getReadableDatabase();
 780		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";
 781		final String[] args = {account, jid.toEscapedString(), jid.toEscapedString()+"/%"};
 782		Cursor cursor = db.rawQuery(SQL+(limit > 0 ? " limit "+String.valueOf(limit) : ""), args);
 783		List<FilePath> filesPaths = new ArrayList<>();
 784		while(cursor.moveToNext()) {
 785			filesPaths.add(new FilePath(cursor.getString(0),cursor.getString(1)));
 786		}
 787		cursor.close();
 788		return filesPaths;
 789	}
 790
 791	public static class FilePath {
 792		public final UUID uuid;
 793		public final String path;
 794		private FilePath(String uuid, String path) {
 795			this.uuid = UUID.fromString(uuid);
 796			this.path = path;
 797		}
 798	}
 799
 800	public Conversation findConversation(final Account account, final Jid contactJid) {
 801		SQLiteDatabase db = this.getReadableDatabase();
 802		String[] selectionArgs = {account.getUuid(),
 803				contactJid.asBareJid().toString() + "/%",
 804				contactJid.asBareJid().toString()
 805		};
 806		Cursor cursor = db.query(Conversation.TABLENAME, null,
 807				Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 808						+ " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 809		if (cursor.getCount() == 0) {
 810			cursor.close();
 811			return null;
 812		}
 813		cursor.moveToFirst();
 814		Conversation conversation = Conversation.fromCursor(cursor);
 815		cursor.close();
 816		if (conversation.getJid() instanceof InvalidJid) {
 817			return null;
 818		}
 819		return conversation;
 820	}
 821
 822	public void updateConversation(final Conversation conversation) {
 823		final SQLiteDatabase db = this.getWritableDatabase();
 824		final String[] args = {conversation.getUuid()};
 825		db.update(Conversation.TABLENAME, conversation.getContentValues(),
 826				Conversation.UUID + "=?", args);
 827	}
 828
 829	public List<Account> getAccounts() {
 830		SQLiteDatabase db = this.getReadableDatabase();
 831		return getAccounts(db);
 832	}
 833
 834	public List<Jid> getAccountJids() {
 835		SQLiteDatabase db = this.getReadableDatabase();
 836		final List<Jid> jids = new ArrayList<>();
 837		final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
 838		String where = "not options & (1 <<1)";
 839		Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
 840		try {
 841			while (cursor.moveToNext()) {
 842				jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
 843			}
 844			return jids;
 845		} catch (Exception e) {
 846			return jids;
 847		} finally {
 848			if (cursor != null) {
 849				cursor.close();
 850			}
 851		}
 852	}
 853
 854	private List<Account> getAccounts(SQLiteDatabase db) {
 855		List<Account> list = new ArrayList<>();
 856		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 857				null, null);
 858		while (cursor.moveToNext()) {
 859			list.add(Account.fromCursor(cursor));
 860		}
 861		cursor.close();
 862		return list;
 863	}
 864
 865	public boolean updateAccount(Account account) {
 866		SQLiteDatabase db = this.getWritableDatabase();
 867		String[] args = {account.getUuid()};
 868		final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 869		return rows == 1;
 870	}
 871
 872	public boolean deleteAccount(Account account) {
 873		SQLiteDatabase db = this.getWritableDatabase();
 874		String[] args = {account.getUuid()};
 875		final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 876		return rows == 1;
 877	}
 878
 879	public boolean updateMessage(Message message, boolean includeBody) {
 880		SQLiteDatabase db = this.getWritableDatabase();
 881		String[] args = {message.getUuid()};
 882		ContentValues contentValues = message.getContentValues();
 883		contentValues.remove(Message.UUID);
 884		if (!includeBody) {
 885			contentValues.remove(Message.BODY);
 886		}
 887		return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
 888	}
 889
 890	public void updateMessage(Message message, String uuid) {
 891		SQLiteDatabase db = this.getWritableDatabase();
 892		String[] args = {uuid};
 893		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 894				+ "=?", args);
 895	}
 896
 897	public void readRoster(Roster roster) {
 898		SQLiteDatabase db = this.getReadableDatabase();
 899		Cursor cursor;
 900		String args[] = {roster.getAccount().getUuid()};
 901		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 902		while (cursor.moveToNext()) {
 903			roster.initContact(Contact.fromCursor(cursor));
 904		}
 905		cursor.close();
 906	}
 907
 908	public void writeRoster(final Roster roster) {
 909		long start = SystemClock.elapsedRealtime();
 910		final Account account = roster.getAccount();
 911		final SQLiteDatabase db = this.getWritableDatabase();
 912		db.beginTransaction();
 913		for (Contact contact : roster.getContacts()) {
 914			if (contact.getOption(Contact.Options.IN_ROSTER) || contact.getAvatarFilename() != null || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
 915				db.insert(Contact.TABLENAME, null, contact.getContentValues());
 916			} else {
 917				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
 918				String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
 919				db.delete(Contact.TABLENAME, where, whereArgs);
 920			}
 921		}
 922		db.setTransactionSuccessful();
 923		db.endTransaction();
 924		account.setRosterVersion(roster.getVersion());
 925		updateAccount(account);
 926		long duration = SystemClock.elapsedRealtime() - start;
 927		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
 928	}
 929
 930	public void deleteMessagesInConversation(Conversation conversation) {
 931		long start = SystemClock.elapsedRealtime();
 932		final SQLiteDatabase db = this.getWritableDatabase();
 933		db.beginTransaction();
 934		String[] args = {conversation.getUuid()};
 935		db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
 936		int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
 937		db.setTransactionSuccessful();
 938		db.endTransaction();
 939		Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
 940	}
 941
 942	public void expireOldMessages(long timestamp) {
 943		final String[] args = {String.valueOf(timestamp)};
 944		SQLiteDatabase db = this.getReadableDatabase();
 945		db.beginTransaction();
 946		db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
 947		db.delete(Message.TABLENAME, "timeSent<?", args);
 948		db.setTransactionSuccessful();
 949		db.endTransaction();
 950	}
 951
 952	public MamReference getLastMessageReceived(Account account) {
 953		Cursor cursor = null;
 954		try {
 955			SQLiteDatabase db = this.getReadableDatabase();
 956			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";
 957			String[] args = {account.getUuid()};
 958			cursor = db.rawQuery(sql, args);
 959			if (cursor.getCount() == 0) {
 960				return null;
 961			} else {
 962				cursor.moveToFirst();
 963				return new MamReference(cursor.getLong(0), cursor.getString(1));
 964			}
 965		} catch (Exception e) {
 966			return null;
 967		} finally {
 968			if (cursor != null) {
 969				cursor.close();
 970			}
 971		}
 972	}
 973
 974	public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
 975		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";
 976		String[] args = {account.getUuid(), fingerprint};
 977		Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
 978		long time;
 979		if (cursor.moveToFirst()) {
 980			time = cursor.getLong(0);
 981		} else {
 982			time = 0;
 983		}
 984		cursor.close();
 985		return time;
 986	}
 987
 988	public MamReference getLastClearDate(Account account) {
 989		SQLiteDatabase db = this.getReadableDatabase();
 990		String[] columns = {Conversation.ATTRIBUTES};
 991		String selection = Conversation.ACCOUNT + "=?";
 992		String[] args = {account.getUuid()};
 993		Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
 994		MamReference maxClearDate = new MamReference(0);
 995		while (cursor.moveToNext()) {
 996			try {
 997				final JSONObject o = new JSONObject(cursor.getString(0));
 998				maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
 999			} catch (Exception e) {
1000				//ignored
1001			}
1002		}
1003		cursor.close();
1004		return maxClearDate;
1005	}
1006
1007	private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1008		final SQLiteDatabase db = this.getReadableDatabase();
1009		String[] selectionArgs = {account.getUuid(),
1010				contact.getName(),
1011				Integer.toString(contact.getDeviceId())};
1012		return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1013				null,
1014				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1015						+ SQLiteAxolotlStore.NAME + " = ? AND "
1016						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1017				selectionArgs,
1018				null, null, null);
1019	}
1020
1021	public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1022		SessionRecord session = null;
1023		Cursor cursor = getCursorForSession(account, contact);
1024		if (cursor.getCount() != 0) {
1025			cursor.moveToFirst();
1026			try {
1027				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1028			} catch (IOException e) {
1029				cursor.close();
1030				throw new AssertionError(e);
1031			}
1032		}
1033		cursor.close();
1034		return session;
1035	}
1036
1037	public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1038		final SQLiteDatabase db = this.getReadableDatabase();
1039		return getSubDeviceSessions(db, account, contact);
1040	}
1041
1042	private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1043		List<Integer> devices = new ArrayList<>();
1044		String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1045		String[] selectionArgs = {account.getUuid(),
1046				contact.getName()};
1047		Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1048				columns,
1049				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1050						+ SQLiteAxolotlStore.NAME + " = ?",
1051				selectionArgs,
1052				null, null, null);
1053
1054		while (cursor.moveToNext()) {
1055			devices.add(cursor.getInt(
1056					cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1057		}
1058
1059		cursor.close();
1060		return devices;
1061	}
1062
1063	public List<String> getKnownSignalAddresses(Account account) {
1064		List<String> addresses = new ArrayList<>();
1065		String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1066		String[] selectionArgs = {account.getUuid()};
1067		Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1068				colums,
1069				SQLiteAxolotlStore.ACCOUNT + " = ?",
1070				selectionArgs,
1071				null, null, null
1072		);
1073		while (cursor.moveToNext()) {
1074			addresses.add(cursor.getString(0));
1075		}
1076		cursor.close();
1077		return addresses;
1078	}
1079
1080	public boolean containsSession(Account account, SignalProtocolAddress contact) {
1081		Cursor cursor = getCursorForSession(account, contact);
1082		int count = cursor.getCount();
1083		cursor.close();
1084		return count != 0;
1085	}
1086
1087	public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1088		SQLiteDatabase db = this.getWritableDatabase();
1089		ContentValues values = new ContentValues();
1090		values.put(SQLiteAxolotlStore.NAME, contact.getName());
1091		values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1092		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1093		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1094		db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1095	}
1096
1097	public void deleteSession(Account account, SignalProtocolAddress contact) {
1098		SQLiteDatabase db = this.getWritableDatabase();
1099		deleteSession(db, account, contact);
1100	}
1101
1102	private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1103		String[] args = {account.getUuid(),
1104				contact.getName(),
1105				Integer.toString(contact.getDeviceId())};
1106		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1107				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1108						+ SQLiteAxolotlStore.NAME + " = ? AND "
1109						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1110				args);
1111	}
1112
1113	public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1114		SQLiteDatabase db = this.getWritableDatabase();
1115		String[] args = {account.getUuid(), contact.getName()};
1116		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1117				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1118						+ SQLiteAxolotlStore.NAME + " = ?",
1119				args);
1120	}
1121
1122	private Cursor getCursorForPreKey(Account account, int preKeyId) {
1123		SQLiteDatabase db = this.getReadableDatabase();
1124		String[] columns = {SQLiteAxolotlStore.KEY};
1125		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1126		Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1127				columns,
1128				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1129						+ SQLiteAxolotlStore.ID + "=?",
1130				selectionArgs,
1131				null, null, null);
1132
1133		return cursor;
1134	}
1135
1136	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1137		PreKeyRecord record = null;
1138		Cursor cursor = getCursorForPreKey(account, preKeyId);
1139		if (cursor.getCount() != 0) {
1140			cursor.moveToFirst();
1141			try {
1142				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1143			} catch (IOException e) {
1144				throw new AssertionError(e);
1145			}
1146		}
1147		cursor.close();
1148		return record;
1149	}
1150
1151	public boolean containsPreKey(Account account, int preKeyId) {
1152		Cursor cursor = getCursorForPreKey(account, preKeyId);
1153		int count = cursor.getCount();
1154		cursor.close();
1155		return count != 0;
1156	}
1157
1158	public void storePreKey(Account account, PreKeyRecord record) {
1159		SQLiteDatabase db = this.getWritableDatabase();
1160		ContentValues values = new ContentValues();
1161		values.put(SQLiteAxolotlStore.ID, record.getId());
1162		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1163		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1164		db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1165	}
1166
1167	public void deletePreKey(Account account, int preKeyId) {
1168		SQLiteDatabase db = this.getWritableDatabase();
1169		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1170		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1171				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1172						+ SQLiteAxolotlStore.ID + "=?",
1173				args);
1174	}
1175
1176	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1177		SQLiteDatabase db = this.getReadableDatabase();
1178		String[] columns = {SQLiteAxolotlStore.KEY};
1179		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1180		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1181				columns,
1182				SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1183				selectionArgs,
1184				null, null, null);
1185
1186		return cursor;
1187	}
1188
1189	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1190		SignedPreKeyRecord record = null;
1191		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1192		if (cursor.getCount() != 0) {
1193			cursor.moveToFirst();
1194			try {
1195				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1196			} catch (IOException e) {
1197				throw new AssertionError(e);
1198			}
1199		}
1200		cursor.close();
1201		return record;
1202	}
1203
1204	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1205		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1206		SQLiteDatabase db = this.getReadableDatabase();
1207		String[] columns = {SQLiteAxolotlStore.KEY};
1208		String[] selectionArgs = {account.getUuid()};
1209		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1210				columns,
1211				SQLiteAxolotlStore.ACCOUNT + "=?",
1212				selectionArgs,
1213				null, null, null);
1214
1215		while (cursor.moveToNext()) {
1216			try {
1217				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1218			} catch (IOException ignored) {
1219			}
1220		}
1221		cursor.close();
1222		return prekeys;
1223	}
1224
1225	public int getSignedPreKeysCount(Account account) {
1226		String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1227		String[] selectionArgs = {account.getUuid()};
1228		SQLiteDatabase db = this.getReadableDatabase();
1229		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1230				columns,
1231				SQLiteAxolotlStore.ACCOUNT + "=?",
1232				selectionArgs,
1233				null, null, null);
1234		final int count;
1235		if (cursor.moveToFirst()) {
1236			count = cursor.getInt(0);
1237		} else {
1238			count = 0;
1239		}
1240		cursor.close();
1241		return count;
1242	}
1243
1244	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1245		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1246		int count = cursor.getCount();
1247		cursor.close();
1248		return count != 0;
1249	}
1250
1251	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1252		SQLiteDatabase db = this.getWritableDatabase();
1253		ContentValues values = new ContentValues();
1254		values.put(SQLiteAxolotlStore.ID, record.getId());
1255		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1256		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1257		db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1258	}
1259
1260	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1261		SQLiteDatabase db = this.getWritableDatabase();
1262		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1263		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1264				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1265						+ SQLiteAxolotlStore.ID + "=?",
1266				args);
1267	}
1268
1269	private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1270		final SQLiteDatabase db = this.getReadableDatabase();
1271		return getIdentityKeyCursor(db, account, name, own);
1272	}
1273
1274	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1275		return getIdentityKeyCursor(db, account, name, own, null);
1276	}
1277
1278	private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1279		final SQLiteDatabase db = this.getReadableDatabase();
1280		return getIdentityKeyCursor(db, account, fingerprint);
1281	}
1282
1283	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1284		return getIdentityKeyCursor(db, account, null, null, fingerprint);
1285	}
1286
1287	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1288		String[] columns = {SQLiteAxolotlStore.TRUST,
1289				SQLiteAxolotlStore.ACTIVE,
1290				SQLiteAxolotlStore.LAST_ACTIVATION,
1291				SQLiteAxolotlStore.KEY};
1292		ArrayList<String> selectionArgs = new ArrayList<>(4);
1293		selectionArgs.add(account.getUuid());
1294		String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1295		if (name != null) {
1296			selectionArgs.add(name);
1297			selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1298		}
1299		if (fingerprint != null) {
1300			selectionArgs.add(fingerprint);
1301			selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1302		}
1303		if (own != null) {
1304			selectionArgs.add(own ? "1" : "0");
1305			selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1306		}
1307		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1308				columns,
1309				selectionString,
1310				selectionArgs.toArray(new String[selectionArgs.size()]),
1311				null, null, null);
1312
1313		return cursor;
1314	}
1315
1316	public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1317		SQLiteDatabase db = getReadableDatabase();
1318		return loadOwnIdentityKeyPair(db, account);
1319	}
1320
1321	private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1322		String name = account.getJid().asBareJid().toString();
1323		IdentityKeyPair identityKeyPair = null;
1324		Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1325		if (cursor.getCount() != 0) {
1326			cursor.moveToFirst();
1327			try {
1328				identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1329			} catch (InvalidKeyException e) {
1330				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1331			}
1332		}
1333		cursor.close();
1334
1335		return identityKeyPair;
1336	}
1337
1338	public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1339		return loadIdentityKeys(account, name, null);
1340	}
1341
1342	public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1343		Set<IdentityKey> identityKeys = new HashSet<>();
1344		Cursor cursor = getIdentityKeyCursor(account, name, false);
1345
1346		while (cursor.moveToNext()) {
1347			if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1348				continue;
1349			}
1350			try {
1351				String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1352				if (key != null) {
1353					identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1354				} else {
1355					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1356				}
1357			} catch (InvalidKeyException e) {
1358				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1359			}
1360		}
1361		cursor.close();
1362
1363		return identityKeys;
1364	}
1365
1366	public long numTrustedKeys(Account account, String name) {
1367		SQLiteDatabase db = getReadableDatabase();
1368		String[] args = {
1369				account.getUuid(),
1370				name,
1371				FingerprintStatus.Trust.TRUSTED.toString(),
1372				FingerprintStatus.Trust.VERIFIED.toString(),
1373				FingerprintStatus.Trust.VERIFIED_X509.toString()
1374		};
1375		return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1376				SQLiteAxolotlStore.ACCOUNT + " = ?"
1377						+ " AND " + SQLiteAxolotlStore.NAME + " = ?"
1378						+ " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1379						+ " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1380				args
1381		);
1382	}
1383
1384	private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1385		SQLiteDatabase db = this.getWritableDatabase();
1386		ContentValues values = new ContentValues();
1387		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1388		values.put(SQLiteAxolotlStore.NAME, name);
1389		values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1390		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1391		values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1392		values.putAll(status.toContentValues());
1393		String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1394		String[] whereArgs = {account.getUuid(), name, fingerprint};
1395		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1396		if (rows == 0) {
1397			db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1398		}
1399	}
1400
1401	public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1402		SQLiteDatabase db = this.getWritableDatabase();
1403		ContentValues values = new ContentValues();
1404		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1405		values.put(SQLiteAxolotlStore.NAME, name);
1406		values.put(SQLiteAxolotlStore.OWN, 0);
1407		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1408		values.putAll(status.toContentValues());
1409		db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1410	}
1411
1412	public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1413		Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1414		final FingerprintStatus status;
1415		if (cursor.getCount() > 0) {
1416			cursor.moveToFirst();
1417			status = FingerprintStatus.fromCursor(cursor);
1418		} else {
1419			status = null;
1420		}
1421		cursor.close();
1422		return status;
1423	}
1424
1425	public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1426		SQLiteDatabase db = this.getWritableDatabase();
1427		return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1428	}
1429
1430	private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1431		String[] selectionArgs = {
1432				account.getUuid(),
1433				fingerprint
1434		};
1435		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1436				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1437						+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1438				selectionArgs);
1439		return rows == 1;
1440	}
1441
1442	public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1443		SQLiteDatabase db = this.getWritableDatabase();
1444		String[] selectionArgs = {
1445				account.getUuid(),
1446				fingerprint
1447		};
1448		try {
1449			ContentValues values = new ContentValues();
1450			values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1451			return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1452					SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1453							+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1454					selectionArgs) == 1;
1455		} catch (CertificateEncodingException e) {
1456			Log.d(Config.LOGTAG, "could not encode certificate");
1457			return false;
1458		}
1459	}
1460
1461	public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1462		SQLiteDatabase db = this.getReadableDatabase();
1463		String[] selectionArgs = {
1464				account.getUuid(),
1465				fingerprint
1466		};
1467		String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1468		String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1469		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1470		if (cursor.getCount() < 1) {
1471			return null;
1472		} else {
1473			cursor.moveToFirst();
1474			byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1475			cursor.close();
1476			if (certificate == null || certificate.length == 0) {
1477				return null;
1478			}
1479			try {
1480				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1481				return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1482			} catch (CertificateException e) {
1483				Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1484				return null;
1485			}
1486		}
1487	}
1488
1489	public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1490		storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1491	}
1492
1493	public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1494		storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1495	}
1496
1497
1498	private void recreateAxolotlDb(SQLiteDatabase db) {
1499		Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1500		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1501		db.execSQL(CREATE_SESSIONS_STATEMENT);
1502		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1503		db.execSQL(CREATE_PREKEYS_STATEMENT);
1504		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1505		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1506		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1507		db.execSQL(CREATE_IDENTITIES_STATEMENT);
1508	}
1509
1510	public void wipeAxolotlDb(Account account) {
1511		String accountName = account.getUuid();
1512		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1513		SQLiteDatabase db = this.getWritableDatabase();
1514		String[] deleteArgs = {
1515				accountName
1516		};
1517		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1518				SQLiteAxolotlStore.ACCOUNT + " = ?",
1519				deleteArgs);
1520		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1521				SQLiteAxolotlStore.ACCOUNT + " = ?",
1522				deleteArgs);
1523		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1524				SQLiteAxolotlStore.ACCOUNT + " = ?",
1525				deleteArgs);
1526		db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1527				SQLiteAxolotlStore.ACCOUNT + " = ?",
1528				deleteArgs);
1529	}
1530
1531	public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1532		SQLiteDatabase db = this.getReadableDatabase();
1533		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;";
1534		String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1535		Cursor cursor = db.rawQuery(SQL, whereArgs);
1536		ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1537		while (cursor.moveToNext()) {
1538			try {
1539				contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1540			} catch (Exception e) {
1541				Log.d(Config.LOGTAG, e.getMessage());
1542			}
1543		}
1544		cursor.close();
1545		return contacts;
1546	}
1547}