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