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