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