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