DatabaseBackend.java

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