DatabaseBackend.java

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