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