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