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