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		Cursor cursor = db.query(Account.TABLENAME,columns,null,null,null,null,null);
 780		try {
 781			while(cursor.moveToNext()) {
 782				jids.add(Jid.of(cursor.getString(0),cursor.getString(1),null));
 783			}
 784			return jids;
 785		} catch (Exception e) {
 786			return jids;
 787		} finally {
 788			if (cursor != null) {
 789				cursor.close();
 790			}
 791		}
 792	}
 793
 794	private List<Account> getAccounts(SQLiteDatabase db) {
 795		List<Account> list = new ArrayList<>();
 796		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 797				null, null);
 798		while (cursor.moveToNext()) {
 799			list.add(Account.fromCursor(cursor));
 800		}
 801		cursor.close();
 802		return list;
 803	}
 804
 805	public boolean updateAccount(Account account) {
 806		SQLiteDatabase db = this.getWritableDatabase();
 807		String[] args = {account.getUuid()};
 808		final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 809		return rows == 1;
 810	}
 811
 812	public boolean deleteAccount(Account account) {
 813		SQLiteDatabase db = this.getWritableDatabase();
 814		String[] args = {account.getUuid()};
 815		final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 816		return rows == 1;
 817	}
 818
 819	@Override
 820	public SQLiteDatabase getWritableDatabase() {
 821		SQLiteDatabase db = super.getWritableDatabase();
 822		db.execSQL("PRAGMA foreign_keys=ON;");
 823		return db;
 824	}
 825
 826	public void updateMessage(Message message) {
 827		SQLiteDatabase db = this.getWritableDatabase();
 828		String[] args = {message.getUuid()};
 829		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 830				+ "=?", args);
 831	}
 832
 833	public void updateMessage(Message message, String uuid) {
 834		SQLiteDatabase db = this.getWritableDatabase();
 835		String[] args = {uuid};
 836		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 837				+ "=?", args);
 838	}
 839
 840	public void readRoster(Roster roster) {
 841		SQLiteDatabase db = this.getReadableDatabase();
 842		Cursor cursor;
 843		String args[] = {roster.getAccount().getUuid()};
 844		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 845		while (cursor.moveToNext()) {
 846			roster.initContact(Contact.fromCursor(cursor));
 847		}
 848		cursor.close();
 849	}
 850
 851	public void writeRoster(final Roster roster) {
 852		final Account account = roster.getAccount();
 853		final SQLiteDatabase db = this.getWritableDatabase();
 854		db.beginTransaction();
 855		for (Contact contact : roster.getContacts()) {
 856			if (contact.getOption(Contact.Options.IN_ROSTER)) {
 857				db.insert(Contact.TABLENAME, null, contact.getContentValues());
 858			} else {
 859				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
 860				String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
 861				db.delete(Contact.TABLENAME, where, whereArgs);
 862			}
 863		}
 864		db.setTransactionSuccessful();
 865		db.endTransaction();
 866		account.setRosterVersion(roster.getVersion());
 867		updateAccount(account);
 868	}
 869
 870	public void deleteMessagesInConversation(Conversation conversation) {
 871		SQLiteDatabase db = this.getWritableDatabase();
 872		String[] args = {conversation.getUuid()};
 873		db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
 874	}
 875
 876	public boolean expireOldMessages(long timestamp) {
 877		String where = Message.TIME_SENT+"<?";
 878		String[] whereArgs = {String.valueOf(timestamp)};
 879		SQLiteDatabase db = this.getReadableDatabase();
 880		return db.delete(Message.TABLENAME,where,whereArgs) > 0;
 881	}
 882
 883	public MamReference getLastMessageReceived(Account account) {
 884		Cursor cursor = null;
 885		try {
 886			SQLiteDatabase db = this.getReadableDatabase();
 887			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";
 888			String[] args = {account.getUuid()};
 889			cursor = db.rawQuery(sql, args);
 890			if (cursor.getCount() == 0) {
 891				return null;
 892			} else {
 893				cursor.moveToFirst();
 894				return new MamReference(cursor.getLong(0), cursor.getString(1));
 895			}
 896		} catch (Exception e) {
 897			return null;
 898		} finally {
 899			if (cursor != null) {
 900				cursor.close();
 901			}
 902		}
 903	}
 904
 905	public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
 906		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";
 907		String[] args = {account.getUuid(), fingerprint};
 908		Cursor cursor = getReadableDatabase().rawQuery(SQL,args);
 909		long time;
 910		if (cursor.moveToFirst()) {
 911			time = cursor.getLong(0);
 912		} else {
 913			time = 0;
 914		}
 915		cursor.close();
 916		return time;
 917	}
 918
 919	public MamReference getLastClearDate(Account account) {
 920		SQLiteDatabase db = this.getReadableDatabase();
 921		String[] columns = {Conversation.ATTRIBUTES};
 922		String selection = Conversation.ACCOUNT + "=?";
 923		String[] args = {account.getUuid()};
 924		Cursor cursor = db.query(Conversation.TABLENAME,columns,selection,args,null,null,null);
 925		MamReference maxClearDate = new MamReference(0);
 926		while (cursor.moveToNext()) {
 927			try {
 928				final JSONObject o = new JSONObject(cursor.getString(0));
 929				maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
 930			} catch (Exception e) {
 931				//ignored
 932			}
 933		}
 934		cursor.close();
 935		return maxClearDate;
 936	}
 937
 938	private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
 939		final SQLiteDatabase db = this.getReadableDatabase();
 940		String[] selectionArgs = {account.getUuid(),
 941				contact.getName(),
 942				Integer.toString(contact.getDeviceId())};
 943		return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 944				null,
 945				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 946						+ SQLiteAxolotlStore.NAME + " = ? AND "
 947						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 948				selectionArgs,
 949				null, null, null);
 950	}
 951
 952	public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
 953		SessionRecord session = null;
 954		Cursor cursor = getCursorForSession(account, contact);
 955		if (cursor.getCount() != 0) {
 956			cursor.moveToFirst();
 957			try {
 958				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 959			} catch (IOException e) {
 960				cursor.close();
 961				throw new AssertionError(e);
 962			}
 963		}
 964		cursor.close();
 965		return session;
 966	}
 967
 968	public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
 969		final SQLiteDatabase db = this.getReadableDatabase();
 970		return getSubDeviceSessions(db, account, contact);
 971	}
 972
 973	private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
 974		List<Integer> devices = new ArrayList<>();
 975		String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
 976		String[] selectionArgs = {account.getUuid(),
 977				contact.getName()};
 978		Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 979				columns,
 980				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 981						+ SQLiteAxolotlStore.NAME + " = ?",
 982				selectionArgs,
 983				null, null, null);
 984
 985		while (cursor.moveToNext()) {
 986			devices.add(cursor.getInt(
 987					cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
 988		}
 989
 990		cursor.close();
 991		return devices;
 992	}
 993
 994	public List<String> getKnownSignalAddresses(Account account) {
 995		List<String> addresses = new ArrayList<>();
 996		String[] colums = {"DISTINCT "+SQLiteAxolotlStore.NAME};
 997		String[] selectionArgs = {account.getUuid()};
 998		Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
 999				colums,
1000				SQLiteAxolotlStore.ACCOUNT + " = ?",
1001				selectionArgs,
1002				null,null,null
1003				);
1004		while (cursor.moveToNext()) {
1005			addresses.add(cursor.getString(0));
1006		}
1007		cursor.close();
1008		return addresses;
1009	}
1010
1011	public boolean containsSession(Account account, SignalProtocolAddress contact) {
1012		Cursor cursor = getCursorForSession(account, contact);
1013		int count = cursor.getCount();
1014		cursor.close();
1015		return count != 0;
1016	}
1017
1018	public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1019		SQLiteDatabase db = this.getWritableDatabase();
1020		ContentValues values = new ContentValues();
1021		values.put(SQLiteAxolotlStore.NAME, contact.getName());
1022		values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1023		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1024		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1025		db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1026	}
1027
1028	public void deleteSession(Account account, SignalProtocolAddress contact) {
1029		SQLiteDatabase db = this.getWritableDatabase();
1030		deleteSession(db, account, contact);
1031	}
1032
1033	private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1034		String[] args = {account.getUuid(),
1035				contact.getName(),
1036				Integer.toString(contact.getDeviceId())};
1037		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1038				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1039						+ SQLiteAxolotlStore.NAME + " = ? AND "
1040						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1041				args);
1042	}
1043
1044	public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1045		SQLiteDatabase db = this.getWritableDatabase();
1046		String[] args = {account.getUuid(), contact.getName()};
1047		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1048				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1049						+ SQLiteAxolotlStore.NAME + " = ?",
1050				args);
1051	}
1052
1053	private Cursor getCursorForPreKey(Account account, int preKeyId) {
1054		SQLiteDatabase db = this.getReadableDatabase();
1055		String[] columns = {SQLiteAxolotlStore.KEY};
1056		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1057		Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1058				columns,
1059				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1060						+ SQLiteAxolotlStore.ID + "=?",
1061				selectionArgs,
1062				null, null, null);
1063
1064		return cursor;
1065	}
1066
1067	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1068		PreKeyRecord record = null;
1069		Cursor cursor = getCursorForPreKey(account, preKeyId);
1070		if (cursor.getCount() != 0) {
1071			cursor.moveToFirst();
1072			try {
1073				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1074			} catch (IOException e) {
1075				throw new AssertionError(e);
1076			}
1077		}
1078		cursor.close();
1079		return record;
1080	}
1081
1082	public boolean containsPreKey(Account account, int preKeyId) {
1083		Cursor cursor = getCursorForPreKey(account, preKeyId);
1084		int count = cursor.getCount();
1085		cursor.close();
1086		return count != 0;
1087	}
1088
1089	public void storePreKey(Account account, PreKeyRecord record) {
1090		SQLiteDatabase db = this.getWritableDatabase();
1091		ContentValues values = new ContentValues();
1092		values.put(SQLiteAxolotlStore.ID, record.getId());
1093		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1094		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1095		db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1096	}
1097
1098	public void deletePreKey(Account account, int preKeyId) {
1099		SQLiteDatabase db = this.getWritableDatabase();
1100		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1101		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1102				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1103						+ SQLiteAxolotlStore.ID + "=?",
1104				args);
1105	}
1106
1107	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1108		SQLiteDatabase db = this.getReadableDatabase();
1109		String[] columns = {SQLiteAxolotlStore.KEY};
1110		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1111		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1112				columns,
1113				SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1114				selectionArgs,
1115				null, null, null);
1116
1117		return cursor;
1118	}
1119
1120	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1121		SignedPreKeyRecord record = null;
1122		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1123		if (cursor.getCount() != 0) {
1124			cursor.moveToFirst();
1125			try {
1126				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1127			} catch (IOException e) {
1128				throw new AssertionError(e);
1129			}
1130		}
1131		cursor.close();
1132		return record;
1133	}
1134
1135	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1136		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1137		SQLiteDatabase db = this.getReadableDatabase();
1138		String[] columns = {SQLiteAxolotlStore.KEY};
1139		String[] selectionArgs = {account.getUuid()};
1140		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1141				columns,
1142				SQLiteAxolotlStore.ACCOUNT + "=?",
1143				selectionArgs,
1144				null, null, null);
1145
1146		while (cursor.moveToNext()) {
1147			try {
1148				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1149			} catch (IOException ignored) {
1150			}
1151		}
1152		cursor.close();
1153		return prekeys;
1154	}
1155
1156	public int getSignedPreKeysCount(Account account) {
1157		String[] columns = {"count("+SQLiteAxolotlStore.KEY+")"};
1158		String[] selectionArgs = {account.getUuid()};
1159		SQLiteDatabase db = this.getReadableDatabase();
1160		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1161				columns,
1162				SQLiteAxolotlStore.ACCOUNT + "=?",
1163				selectionArgs,
1164				null, null, null);
1165		final int count;
1166		if (cursor.moveToFirst()) {
1167			count = cursor.getInt(0);
1168		} else {
1169			count = 0;
1170		}
1171		cursor.close();
1172		return count;
1173	}
1174
1175	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1176		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1177		int count = cursor.getCount();
1178		cursor.close();
1179		return count != 0;
1180	}
1181
1182	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1183		SQLiteDatabase db = this.getWritableDatabase();
1184		ContentValues values = new ContentValues();
1185		values.put(SQLiteAxolotlStore.ID, record.getId());
1186		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1187		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1188		db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1189	}
1190
1191	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1192		SQLiteDatabase db = this.getWritableDatabase();
1193		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1194		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1195				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1196						+ SQLiteAxolotlStore.ID + "=?",
1197				args);
1198	}
1199
1200	private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1201		final SQLiteDatabase db = this.getReadableDatabase();
1202		return getIdentityKeyCursor(db, account, name, own);
1203	}
1204
1205	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1206		return getIdentityKeyCursor(db, account, name, own, null);
1207	}
1208
1209	private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1210		final SQLiteDatabase db = this.getReadableDatabase();
1211		return getIdentityKeyCursor(db, account, fingerprint);
1212	}
1213
1214	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1215		return getIdentityKeyCursor(db, account, null, null, fingerprint);
1216	}
1217
1218	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1219		String[] columns = {SQLiteAxolotlStore.TRUST,
1220				SQLiteAxolotlStore.ACTIVE,
1221				SQLiteAxolotlStore.LAST_ACTIVATION,
1222				SQLiteAxolotlStore.KEY};
1223		ArrayList<String> selectionArgs = new ArrayList<>(4);
1224		selectionArgs.add(account.getUuid());
1225		String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1226		if (name != null) {
1227			selectionArgs.add(name);
1228			selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1229		}
1230		if (fingerprint != null) {
1231			selectionArgs.add(fingerprint);
1232			selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1233		}
1234		if (own != null) {
1235			selectionArgs.add(own ? "1" : "0");
1236			selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1237		}
1238		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1239				columns,
1240				selectionString,
1241				selectionArgs.toArray(new String[selectionArgs.size()]),
1242				null, null, null);
1243
1244		return cursor;
1245	}
1246
1247	public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1248		SQLiteDatabase db = getReadableDatabase();
1249		return loadOwnIdentityKeyPair(db, account);
1250	}
1251
1252	private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1253		String name = account.getJid().asBareJid().toString();
1254		IdentityKeyPair identityKeyPair = null;
1255		Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1256		if (cursor.getCount() != 0) {
1257			cursor.moveToFirst();
1258			try {
1259				identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1260			} catch (InvalidKeyException e) {
1261				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1262			}
1263		}
1264		cursor.close();
1265
1266		return identityKeyPair;
1267	}
1268
1269	public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1270		return loadIdentityKeys(account, name, null);
1271	}
1272
1273	public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1274		Set<IdentityKey> identityKeys = new HashSet<>();
1275		Cursor cursor = getIdentityKeyCursor(account, name, false);
1276
1277		while (cursor.moveToNext()) {
1278			if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1279				continue;
1280			}
1281			try {
1282				String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1283				if (key != null) {
1284					identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1285				} else {
1286					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1287				}
1288			} catch (InvalidKeyException e) {
1289				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1290			}
1291		}
1292		cursor.close();
1293
1294		return identityKeys;
1295	}
1296
1297	public long numTrustedKeys(Account account, String name) {
1298		SQLiteDatabase db = getReadableDatabase();
1299		String[] args = {
1300				account.getUuid(),
1301				name,
1302				FingerprintStatus.Trust.TRUSTED.toString(),
1303				FingerprintStatus.Trust.VERIFIED.toString(),
1304				FingerprintStatus.Trust.VERIFIED_X509.toString()
1305		};
1306		return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1307				SQLiteAxolotlStore.ACCOUNT + " = ?"
1308						+ " AND " + SQLiteAxolotlStore.NAME + " = ?"
1309						+ " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " +SQLiteAxolotlStore.TRUST +" = ?)"
1310						+ " AND " +SQLiteAxolotlStore.ACTIVE + " > 0",
1311				args
1312		);
1313	}
1314
1315	private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1316		SQLiteDatabase db = this.getWritableDatabase();
1317		ContentValues values = new ContentValues();
1318		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1319		values.put(SQLiteAxolotlStore.NAME, name);
1320		values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1321		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1322		values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1323		values.putAll(status.toContentValues());
1324		String where = SQLiteAxolotlStore.ACCOUNT+"=? AND "+SQLiteAxolotlStore.NAME+"=? AND "+SQLiteAxolotlStore.FINGERPRINT+" =?";
1325		String[] whereArgs = {account.getUuid(),name,fingerprint};
1326		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,values,where,whereArgs);
1327		if (rows == 0) {
1328			db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1329		}
1330	}
1331
1332	public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1333		SQLiteDatabase db = this.getWritableDatabase();
1334		ContentValues values = new ContentValues();
1335		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1336		values.put(SQLiteAxolotlStore.NAME, name);
1337		values.put(SQLiteAxolotlStore.OWN, 0);
1338		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1339		values.putAll(status.toContentValues());
1340		db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1341	}
1342
1343	public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1344		Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1345		final FingerprintStatus status;
1346		if (cursor.getCount() > 0) {
1347			cursor.moveToFirst();
1348			status = FingerprintStatus.fromCursor(cursor);
1349		} else {
1350			status = null;
1351		}
1352		cursor.close();
1353		return status;
1354	}
1355
1356	public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1357		SQLiteDatabase db = this.getWritableDatabase();
1358		return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1359	}
1360
1361	private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1362		String[] selectionArgs = {
1363				account.getUuid(),
1364				fingerprint
1365		};
1366		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1367				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1368						+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1369				selectionArgs);
1370		return rows == 1;
1371	}
1372
1373	public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1374		SQLiteDatabase db = this.getWritableDatabase();
1375		String[] selectionArgs = {
1376				account.getUuid(),
1377				fingerprint
1378		};
1379		try {
1380			ContentValues values = new ContentValues();
1381			values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1382			return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1383					SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1384							+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1385					selectionArgs) == 1;
1386		} catch (CertificateEncodingException e) {
1387			Log.d(Config.LOGTAG, "could not encode certificate");
1388			return false;
1389		}
1390	}
1391
1392	public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1393		SQLiteDatabase db = this.getReadableDatabase();
1394		String[] selectionArgs = {
1395				account.getUuid(),
1396				fingerprint
1397		};
1398		String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1399		String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1400		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1401		if (cursor.getCount() < 1) {
1402			return null;
1403		} else {
1404			cursor.moveToFirst();
1405			byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1406			cursor.close();
1407			if (certificate == null || certificate.length == 0) {
1408				return null;
1409			}
1410			try {
1411				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1412				return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1413			} catch (CertificateException e) {
1414				Log.d(Config.LOGTAG,"certificate exception "+e.getMessage());
1415				return null;
1416			}
1417		}
1418	}
1419
1420	public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1421		storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1422	}
1423
1424	public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1425		storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1426	}
1427
1428
1429	private void recreateAxolotlDb(SQLiteDatabase db) {
1430		Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1431		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1432		db.execSQL(CREATE_SESSIONS_STATEMENT);
1433		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1434		db.execSQL(CREATE_PREKEYS_STATEMENT);
1435		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1436		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1437		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1438		db.execSQL(CREATE_IDENTITIES_STATEMENT);
1439	}
1440
1441	public void wipeAxolotlDb(Account account) {
1442		String accountName = account.getUuid();
1443		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1444		SQLiteDatabase db = this.getWritableDatabase();
1445		String[] deleteArgs = {
1446				accountName
1447		};
1448		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1449				SQLiteAxolotlStore.ACCOUNT + " = ?",
1450				deleteArgs);
1451		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1452				SQLiteAxolotlStore.ACCOUNT + " = ?",
1453				deleteArgs);
1454		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1455				SQLiteAxolotlStore.ACCOUNT + " = ?",
1456				deleteArgs);
1457		db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1458				SQLiteAxolotlStore.ACCOUNT + " = ?",
1459				deleteArgs);
1460	}
1461
1462	public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1463		SQLiteDatabase db = this.getReadableDatabase();
1464		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;";
1465		String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1466		Cursor cursor = db.rawQuery(SQL,whereArgs);
1467		ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1468		while(cursor.moveToNext()) {
1469			try {
1470				contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1471			} catch (Exception e) {
1472				Log.d(Config.LOGTAG,e.getMessage());
1473			}
1474		}
1475		cursor.close();
1476		return contacts;
1477	}
1478}