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