DatabaseBackend.java

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