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