DatabaseBackend.java

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