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