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