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