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