DatabaseBackend.java

  1package eu.siacs.conversations.persistance;
  2
  3import android.content.ContentValues;
  4import android.content.Context;
  5import android.database.Cursor;
  6import android.database.sqlite.SQLiteCantOpenDatabaseException;
  7import android.database.sqlite.SQLiteDatabase;
  8import android.database.sqlite.SQLiteOpenHelper;
  9import android.util.Base64;
 10import android.util.Log;
 11
 12import org.whispersystems.libaxolotl.AxolotlAddress;
 13import org.whispersystems.libaxolotl.state.PreKeyRecord;
 14import org.whispersystems.libaxolotl.state.SessionRecord;
 15import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
 16
 17import java.io.IOException;
 18import java.util.ArrayList;
 19import java.util.List;
 20import java.util.concurrent.CopyOnWriteArrayList;
 21
 22import eu.siacs.conversations.Config;
 23import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 24import eu.siacs.conversations.entities.Account;
 25import eu.siacs.conversations.entities.Contact;
 26import eu.siacs.conversations.entities.Conversation;
 27import eu.siacs.conversations.entities.Message;
 28import eu.siacs.conversations.entities.Roster;
 29import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 30import eu.siacs.conversations.xmpp.jid.Jid;
 31
 32public class DatabaseBackend extends SQLiteOpenHelper {
 33
 34	private static DatabaseBackend instance = null;
 35
 36	private static final String DATABASE_NAME = "history";
 37	private static final int DATABASE_VERSION = 15;
 38
 39	private static String CREATE_CONTATCS_STATEMENT = "create table "
 40			+ Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
 41			+ Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
 42			+ Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
 43			+ Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
 44			+ Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
 45			+ Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
 46			+ Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
 47			+ Account.TABLENAME + "(" + Account.UUID
 48			+ ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
 49			+ Contact.JID + ") ON CONFLICT REPLACE);";
 50
 51	private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
 52			+ AxolotlService.SQLiteAxolotlStore.PREKEY_TABLENAME + "("
 53				+ AxolotlService.SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 54				+ AxolotlService.SQLiteAxolotlStore.ID + " INTEGER, "
 55				+ AxolotlService.SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 56					+ AxolotlService.SQLiteAxolotlStore.ACCOUNT
 57				+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 58				+ "UNIQUE( " + AxolotlService.SQLiteAxolotlStore.ACCOUNT + ", "
 59					+ AxolotlService.SQLiteAxolotlStore.ID
 60				+ ") ON CONFLICT REPLACE"
 61			+");";
 62
 63	private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
 64			+ AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
 65				+ AxolotlService.SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 66				+ AxolotlService.SQLiteAxolotlStore.ID + " INTEGER, "
 67				+ AxolotlService.SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 68					+ AxolotlService.SQLiteAxolotlStore.ACCOUNT
 69				+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 70				+ "UNIQUE( " + AxolotlService.SQLiteAxolotlStore.ACCOUNT + ", "
 71					+ AxolotlService.SQLiteAxolotlStore.ID
 72				+ ") ON CONFLICT REPLACE"+
 73			");";
 74
 75	private static String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
 76			+ AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME + "("
 77				+ AxolotlService.SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 78				+ AxolotlService.SQLiteAxolotlStore.NAME + " TEXT, "
 79				+ AxolotlService.SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
 80				+ AxolotlService.SQLiteAxolotlStore.TRUSTED + " INTEGER, "
 81				+ AxolotlService.SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 82					+ AxolotlService.SQLiteAxolotlStore.ACCOUNT
 83				+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 84				+ "UNIQUE( " + AxolotlService.SQLiteAxolotlStore.ACCOUNT + ", "
 85					+ AxolotlService.SQLiteAxolotlStore.NAME + ", "
 86					+ AxolotlService.SQLiteAxolotlStore.DEVICE_ID
 87				+ ") ON CONFLICT REPLACE"
 88			+");";
 89
 90	private DatabaseBackend(Context context) {
 91		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 92	}
 93
 94	@Override
 95	public void onCreate(SQLiteDatabase db) {
 96		db.execSQL("PRAGMA foreign_keys=ON;");
 97		db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID
 98				+ " TEXT PRIMARY KEY," + Account.USERNAME + " TEXT,"
 99				+ Account.SERVER + " TEXT," + Account.PASSWORD + " TEXT,"
100				+ Account.ROSTERVERSION + " TEXT," + Account.OPTIONS
101				+ " NUMBER, " + Account.AVATAR + " TEXT, " + Account.KEYS
102				+ " TEXT)");
103		db.execSQL("create table " + Conversation.TABLENAME + " ("
104				+ Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
105				+ " TEXT, " + Conversation.CONTACT + " TEXT, "
106				+ Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
107				+ " TEXT, " + Conversation.CREATED + " NUMBER, "
108				+ Conversation.STATUS + " NUMBER, " + Conversation.MODE
109				+ " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
110				+ Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
111				+ "(" + Account.UUID + ") ON DELETE CASCADE);");
112		db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
113				+ " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
114				+ Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
115				+ " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
116				+ Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
117				+ Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
118				+ Message.RELATIVE_FILE_PATH + " TEXT, "
119				+ Message.SERVER_MSG_ID + " TEXT, "
120				+ Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
121				+ Message.CONVERSATION + ") REFERENCES "
122				+ Conversation.TABLENAME + "(" + Conversation.UUID
123				+ ") ON DELETE CASCADE);");
124
125		db.execSQL(CREATE_CONTATCS_STATEMENT);
126		db.execSQL(CREATE_SESSIONS_STATEMENT);
127		db.execSQL(CREATE_PREKEYS_STATEMENT);
128		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
129	}
130
131	@Override
132	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
133		if (oldVersion < 2 && newVersion >= 2) {
134			db.execSQL("update " + Account.TABLENAME + " set "
135					+ Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
136		}
137		if (oldVersion < 3 && newVersion >= 3) {
138			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
139					+ Message.TYPE + " NUMBER");
140		}
141		if (oldVersion < 5 && newVersion >= 5) {
142			db.execSQL("DROP TABLE " + Contact.TABLENAME);
143			db.execSQL(CREATE_CONTATCS_STATEMENT);
144			db.execSQL("UPDATE " + Account.TABLENAME + " SET "
145					+ Account.ROSTERVERSION + " = NULL");
146		}
147		if (oldVersion < 6 && newVersion >= 6) {
148			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
149					+ Message.TRUE_COUNTERPART + " TEXT");
150		}
151		if (oldVersion < 7 && newVersion >= 7) {
152			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
153					+ Message.REMOTE_MSG_ID + " TEXT");
154			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
155					+ Contact.AVATAR + " TEXT");
156			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
157					+ Account.AVATAR + " TEXT");
158		}
159		if (oldVersion < 8 && newVersion >= 8) {
160			db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
161					+ Conversation.ATTRIBUTES + " TEXT");
162		}
163		if (oldVersion < 9 && newVersion >= 9) {
164			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
165					+ Contact.LAST_TIME + " NUMBER");
166			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
167					+ Contact.LAST_PRESENCE + " TEXT");
168		}
169		if (oldVersion < 10 && newVersion >= 10) {
170			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
171					+ Message.RELATIVE_FILE_PATH + " TEXT");
172		}
173		if (oldVersion < 11 && newVersion >= 11) {
174			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
175					+ Contact.GROUPS + " TEXT");
176			db.execSQL("delete from "+Contact.TABLENAME);
177			db.execSQL("update "+Account.TABLENAME+" set "+Account.ROSTERVERSION+" = NULL");
178		}
179		if (oldVersion < 12 && newVersion >= 12) {
180			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
181					+ Message.SERVER_MSG_ID + " TEXT");
182		}
183		if (oldVersion < 13 && newVersion >= 13) {
184			db.execSQL("delete from "+Contact.TABLENAME);
185			db.execSQL("update "+Account.TABLENAME+" set "+Account.ROSTERVERSION+" = NULL");
186		}
187		if (oldVersion < 14 && newVersion >= 14) {
188			// migrate db to new, canonicalized JID domainpart representation
189
190			// Conversation table
191			Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
192			while(cursor.moveToNext()) {
193				String newJid;
194				try {
195					newJid = Jid.fromString(
196							cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
197					).toString();
198				} catch (InvalidJidException ignored) {
199					Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
200							+cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
201							+": " + ignored +". Skipping...");
202					continue;
203				}
204
205				String updateArgs[] = {
206						newJid,
207						cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
208				};
209				db.execSQL("update " + Conversation.TABLENAME
210						+ " set " + Conversation.CONTACTJID	+ " = ? "
211						+ " where " + Conversation.UUID + " = ?", updateArgs);
212			}
213			cursor.close();
214
215			// Contact table
216			cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
217			while(cursor.moveToNext()) {
218				String newJid;
219				try {
220					newJid = Jid.fromString(
221							cursor.getString(cursor.getColumnIndex(Contact.JID))
222					).toString();
223				} catch (InvalidJidException ignored) {
224					Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
225							+cursor.getString(cursor.getColumnIndex(Contact.JID))
226							+": " + ignored +". Skipping...");
227					continue;
228				}
229
230				String updateArgs[] = {
231						newJid,
232						cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
233						cursor.getString(cursor.getColumnIndex(Contact.JID)),
234				};
235				db.execSQL("update " + Contact.TABLENAME
236						+ " set " + Contact.JID + " = ? "
237						+ " where " + Contact.ACCOUNT + " = ? "
238						+ " AND " + Contact.JID + " = ?", updateArgs);
239			}
240			cursor.close();
241
242			// Account table
243			cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
244			while(cursor.moveToNext()) {
245				String newServer;
246				try {
247					newServer = Jid.fromParts(
248							cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
249							cursor.getString(cursor.getColumnIndex(Account.SERVER)),
250							"mobile"
251					).getDomainpart();
252				} catch (InvalidJidException ignored) {
253					Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
254							+cursor.getString(cursor.getColumnIndex(Account.SERVER))
255							+": " + ignored +". Skipping...");
256					continue;
257				}
258
259				String updateArgs[] = {
260						newServer,
261						cursor.getString(cursor.getColumnIndex(Account.UUID)),
262				};
263				db.execSQL("update " + Account.TABLENAME
264						+ " set " + Account.SERVER + " = ? "
265						+ " where " + Account.UUID + " = ?", updateArgs);
266			}
267			cursor.close();
268		}
269		if (oldVersion < 15  && newVersion >= 15) {
270			db.execSQL("DROP TABLE IF EXISTS " + AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME);
271			db.execSQL(CREATE_SESSIONS_STATEMENT);
272			db.execSQL("DROP TABLE IF EXISTS " + AxolotlService.SQLiteAxolotlStore.PREKEY_TABLENAME);
273			db.execSQL(CREATE_PREKEYS_STATEMENT);
274			db.execSQL("DROP TABLE IF EXISTS " + AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
275			db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
276		}
277	}
278
279	public static synchronized DatabaseBackend getInstance(Context context) {
280		if (instance == null) {
281			instance = new DatabaseBackend(context);
282		}
283		return instance;
284	}
285
286	public void createConversation(Conversation conversation) {
287		SQLiteDatabase db = this.getWritableDatabase();
288		db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
289	}
290
291	public void createMessage(Message message) {
292		SQLiteDatabase db = this.getWritableDatabase();
293		db.insert(Message.TABLENAME, null, message.getContentValues());
294	}
295
296	public void createAccount(Account account) {
297		SQLiteDatabase db = this.getWritableDatabase();
298		db.insert(Account.TABLENAME, null, account.getContentValues());
299	}
300
301	public void createContact(Contact contact) {
302		SQLiteDatabase db = this.getWritableDatabase();
303		db.insert(Contact.TABLENAME, null, contact.getContentValues());
304	}
305
306	public int getConversationCount() {
307		SQLiteDatabase db = this.getReadableDatabase();
308		Cursor cursor = db.rawQuery("select count(uuid) as count from "
309				+ Conversation.TABLENAME + " where " + Conversation.STATUS
310				+ "=" + Conversation.STATUS_AVAILABLE, null);
311		cursor.moveToFirst();
312		int count = cursor.getInt(0);
313		cursor.close();
314		return count;
315	}
316
317	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
318		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
319		SQLiteDatabase db = this.getReadableDatabase();
320		String[] selectionArgs = { Integer.toString(status) };
321		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
322				+ " where " + Conversation.STATUS + " = ? order by "
323				+ Conversation.CREATED + " desc", selectionArgs);
324		while (cursor.moveToNext()) {
325			list.add(Conversation.fromCursor(cursor));
326		}
327		cursor.close();
328		return list;
329	}
330
331	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
332		return getMessages(conversations, limit, -1);
333	}
334
335	public ArrayList<Message> getMessages(Conversation conversation, int limit,
336			long timestamp) {
337		ArrayList<Message> list = new ArrayList<>();
338		SQLiteDatabase db = this.getReadableDatabase();
339		Cursor cursor;
340		if (timestamp == -1) {
341			String[] selectionArgs = { conversation.getUuid() };
342			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
343					+ "=?", selectionArgs, null, null, Message.TIME_SENT
344					+ " DESC", String.valueOf(limit));
345		} else {
346			String[] selectionArgs = { conversation.getUuid(),
347					Long.toString(timestamp) };
348			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
349					+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
350					null, null, Message.TIME_SENT + " DESC",
351					String.valueOf(limit));
352		}
353		if (cursor.getCount() > 0) {
354			cursor.moveToLast();
355			do {
356				Message message = Message.fromCursor(cursor);
357				message.setConversation(conversation);
358				list.add(message);
359			} while (cursor.moveToPrevious());
360		}
361		cursor.close();
362		return list;
363	}
364
365	public Conversation findConversation(final Account account, final Jid contactJid) {
366		SQLiteDatabase db = this.getReadableDatabase();
367		String[] selectionArgs = { account.getUuid(),
368				contactJid.toBareJid().toString() + "/%",
369				contactJid.toBareJid().toString()
370				};
371		Cursor cursor = db.query(Conversation.TABLENAME, null,
372				Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
373						+ " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
374		if (cursor.getCount() == 0)
375			return null;
376		cursor.moveToFirst();
377		Conversation conversation = Conversation.fromCursor(cursor);
378		cursor.close();
379		return conversation;
380	}
381
382	public void updateConversation(final Conversation conversation) {
383		final SQLiteDatabase db = this.getWritableDatabase();
384		final String[] args = { conversation.getUuid() };
385		db.update(Conversation.TABLENAME, conversation.getContentValues(),
386				Conversation.UUID + "=?", args);
387	}
388
389	public List<Account> getAccounts() {
390		List<Account> list = new ArrayList<>();
391		SQLiteDatabase db = this.getReadableDatabase();
392		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
393				null, null);
394		while (cursor.moveToNext()) {
395			list.add(Account.fromCursor(cursor));
396		}
397		cursor.close();
398		return list;
399	}
400
401	public void updateAccount(Account account) {
402		SQLiteDatabase db = this.getWritableDatabase();
403		String[] args = { account.getUuid() };
404		db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
405				+ "=?", args);
406	}
407
408	public void deleteAccount(Account account) {
409		SQLiteDatabase db = this.getWritableDatabase();
410		String[] args = { account.getUuid() };
411		db.delete(Account.TABLENAME, Account.UUID + "=?", args);
412	}
413
414	public boolean hasEnabledAccounts() {
415		SQLiteDatabase db = this.getReadableDatabase();
416		Cursor cursor = db.rawQuery("select count(" + Account.UUID + ")  from "
417				+ Account.TABLENAME + " where not options & (1 <<1)", null);
418		try {
419			cursor.moveToFirst();
420			int count = cursor.getInt(0);
421			cursor.close();
422			return (count > 0);
423		} catch (SQLiteCantOpenDatabaseException e) {
424			return true; // better safe than sorry
425		} catch (RuntimeException e) {
426			return true; // better safe than sorry
427		}
428	}
429
430	@Override
431	public SQLiteDatabase getWritableDatabase() {
432		SQLiteDatabase db = super.getWritableDatabase();
433		db.execSQL("PRAGMA foreign_keys=ON;");
434		return db;
435	}
436
437	public void updateMessage(Message message) {
438		SQLiteDatabase db = this.getWritableDatabase();
439		String[] args = { message.getUuid() };
440		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
441				+ "=?", args);
442	}
443
444	public void readRoster(Roster roster) {
445		SQLiteDatabase db = this.getReadableDatabase();
446		Cursor cursor;
447		String args[] = { roster.getAccount().getUuid() };
448		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
449		while (cursor.moveToNext()) {
450			roster.initContact(Contact.fromCursor(cursor));
451		}
452		cursor.close();
453	}
454
455	public void writeRoster(final Roster roster) {
456		final Account account = roster.getAccount();
457		final SQLiteDatabase db = this.getWritableDatabase();
458		for (Contact contact : roster.getContacts()) {
459			if (contact.getOption(Contact.Options.IN_ROSTER)) {
460				db.insert(Contact.TABLENAME, null, contact.getContentValues());
461			} else {
462				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
463				String[] whereArgs = { account.getUuid(), contact.getJid().toString() };
464				db.delete(Contact.TABLENAME, where, whereArgs);
465			}
466		}
467		account.setRosterVersion(roster.getVersion());
468		updateAccount(account);
469	}
470
471	public void deleteMessage(Message message) {
472		SQLiteDatabase db = this.getWritableDatabase();
473		String[] args = { message.getUuid() };
474		db.delete(Message.TABLENAME, Message.UUID + "=?", args);
475	}
476
477	public void deleteMessagesInConversation(Conversation conversation) {
478		SQLiteDatabase db = this.getWritableDatabase();
479		String[] args = { conversation.getUuid() };
480		db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
481	}
482
483	public Conversation findConversationByUuid(String conversationUuid) {
484		SQLiteDatabase db = this.getReadableDatabase();
485		String[] selectionArgs = { conversationUuid };
486		Cursor cursor = db.query(Conversation.TABLENAME, null,
487				Conversation.UUID + "=?", selectionArgs, null, null, null);
488		if (cursor.getCount() == 0) {
489			return null;
490		}
491		cursor.moveToFirst();
492		Conversation conversation = Conversation.fromCursor(cursor);
493		cursor.close();
494		return conversation;
495	}
496
497	public Message findMessageByUuid(String messageUuid) {
498		SQLiteDatabase db = this.getReadableDatabase();
499		String[] selectionArgs = { messageUuid };
500		Cursor cursor = db.query(Message.TABLENAME, null, Message.UUID + "=?",
501				selectionArgs, null, null, null);
502		if (cursor.getCount() == 0) {
503			return null;
504		}
505		cursor.moveToFirst();
506		Message message = Message.fromCursor(cursor);
507		cursor.close();
508		return message;
509	}
510
511	public Account findAccountByUuid(String accountUuid) {
512		SQLiteDatabase db = this.getReadableDatabase();
513		String[] selectionArgs = { accountUuid };
514		Cursor cursor = db.query(Account.TABLENAME, null, Account.UUID + "=?",
515				selectionArgs, null, null, null);
516		if (cursor.getCount() == 0) {
517			return null;
518		}
519		cursor.moveToFirst();
520		Account account = Account.fromCursor(cursor);
521		cursor.close();
522		return account;
523	}
524
525	public List<Message> getImageMessages(Conversation conversation) {
526		ArrayList<Message> list = new ArrayList<>();
527		SQLiteDatabase db = this.getReadableDatabase();
528		Cursor cursor;
529			String[] selectionArgs = { conversation.getUuid(), String.valueOf(Message.TYPE_IMAGE) };
530			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
531					+ "=? AND "+Message.TYPE+"=?", selectionArgs, null, null,null);
532		if (cursor.getCount() > 0) {
533			cursor.moveToLast();
534			do {
535				Message message = Message.fromCursor(cursor);
536				message.setConversation(conversation);
537				list.add(message);
538			} while (cursor.moveToPrevious());
539		}
540		cursor.close();
541		return list;
542	}
543
544	private Cursor getCursorForSession(Account account, AxolotlAddress contact) {
545		final SQLiteDatabase db = this.getReadableDatabase();
546		String[] columns = null;
547		String[] selectionArgs = {account.getUuid(),
548				contact.getName(),
549				Integer.toString(contact.getDeviceId())};
550		Cursor cursor = db.query(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME,
551				columns,
552				AxolotlService.SQLiteAxolotlStore.ACCOUNT + " = ? AND "
553						+ AxolotlService.SQLiteAxolotlStore.NAME + " = ? AND "
554						+ AxolotlService.SQLiteAxolotlStore.DEVICE_ID + " = ? ",
555				selectionArgs,
556				null, null, null);
557
558		return cursor;
559	}
560
561	public SessionRecord loadSession(Account account, AxolotlAddress contact) {
562		SessionRecord session = null;
563		Cursor cursor = getCursorForSession(account, contact);
564		if(cursor.getCount() != 0) {
565			cursor.moveToFirst();
566			try {
567				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(AxolotlService.SQLiteAxolotlStore.KEY)),Base64.DEFAULT));
568			} catch (IOException e) {
569				cursor.close();
570				throw new AssertionError(e);
571			}
572		}
573		cursor.close();
574		return session;
575	}
576
577	public List<Integer> getSubDeviceSessions(Account account, AxolotlAddress contact) {
578		List<Integer> devices = new ArrayList<>();
579		final SQLiteDatabase db = this.getReadableDatabase();
580		String[] columns = {AxolotlService.SQLiteAxolotlStore.DEVICE_ID};
581		String[] selectionArgs = {account.getUuid(),
582				contact.getName()};
583		Cursor cursor = db.query(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME,
584				columns,
585				AxolotlService.SQLiteAxolotlStore.ACCOUNT + " = ? AND "
586						+ AxolotlService.SQLiteAxolotlStore.NAME + " = ? AND ",
587				selectionArgs,
588				null, null, null);
589
590		while(cursor.moveToNext()) {
591			devices.add(cursor.getInt(
592					cursor.getColumnIndex(AxolotlService.SQLiteAxolotlStore.DEVICE_ID)));
593		}
594
595		cursor.close();
596		return devices;
597	}
598
599	public boolean containsSession(Account account, AxolotlAddress contact) {
600		Cursor cursor = getCursorForSession(account, contact);
601		int count = cursor.getCount();
602		cursor.close();
603		return count != 0;
604	}
605
606	public void storeSession(Account account, AxolotlAddress contact, SessionRecord session) {
607		SQLiteDatabase db = this.getWritableDatabase();
608		ContentValues values = new ContentValues();
609		values.put(AxolotlService.SQLiteAxolotlStore.NAME, contact.getName());
610		values.put(AxolotlService.SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
611		values.put(AxolotlService.SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(),Base64.DEFAULT));
612		values.put(AxolotlService.SQLiteAxolotlStore.ACCOUNT, account.getUuid());
613		db.insert(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
614	}
615
616	public void deleteSession(Account account, AxolotlAddress contact) {
617		SQLiteDatabase db = this.getWritableDatabase();
618		String[] args = {account.getUuid(),
619				contact.getName(),
620				Integer.toString(contact.getDeviceId())};
621		db.delete(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME,
622				AxolotlService.SQLiteAxolotlStore.ACCOUNT + " = ? AND "
623						+ AxolotlService.SQLiteAxolotlStore.NAME + " = ? AND "
624						+ AxolotlService.SQLiteAxolotlStore.DEVICE_ID + " = ? ",
625				args);
626	}
627
628	public void deleteAllSessions(Account account, AxolotlAddress contact) {
629		SQLiteDatabase db = this.getWritableDatabase();
630		String[] args = {account.getUuid(), contact.getName()};
631		db.delete(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME,
632				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=? AND "
633						+ AxolotlService.SQLiteAxolotlStore.NAME + " = ?",
634				args);
635	}
636
637	public boolean isTrustedSession(Account account, AxolotlAddress contact) {
638		boolean trusted = false;
639		Cursor cursor = getCursorForSession(account, contact);
640		if(cursor.getCount() != 0) {
641			cursor.moveToFirst();
642			trusted = cursor.getInt(cursor.getColumnIndex(
643					AxolotlService.SQLiteAxolotlStore.TRUSTED)) > 0;
644		}
645		cursor.close();
646		return trusted;
647	}
648
649	public void setTrustedSession(Account account, AxolotlAddress contact, boolean trusted) {
650		SQLiteDatabase db = this.getWritableDatabase();
651		ContentValues values = new ContentValues();
652		values.put(AxolotlService.SQLiteAxolotlStore.NAME, contact.getName());
653		values.put(AxolotlService.SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
654		values.put(AxolotlService.SQLiteAxolotlStore.ACCOUNT, account.getUuid());
655		values.put(AxolotlService.SQLiteAxolotlStore.TRUSTED, trusted?1:0);
656		db.insert(AxolotlService.SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
657	}
658
659	private Cursor getCursorForPreKey(Account account, int preKeyId) {
660		SQLiteDatabase db = this.getReadableDatabase();
661		String[] columns = {AxolotlService.SQLiteAxolotlStore.KEY};
662		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
663		Cursor cursor = db.query(AxolotlService.SQLiteAxolotlStore.PREKEY_TABLENAME,
664				columns,
665				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=? AND "
666						+ AxolotlService.SQLiteAxolotlStore.ID + "=?",
667				selectionArgs,
668				null, null, null);
669
670		return cursor;
671	}
672
673	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
674		PreKeyRecord record = null;
675		Cursor cursor = getCursorForPreKey(account, preKeyId);
676		if(cursor.getCount() != 0) {
677			cursor.moveToFirst();
678			try {
679				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(AxolotlService.SQLiteAxolotlStore.KEY)),Base64.DEFAULT));
680			} catch (IOException e ) {
681				throw new AssertionError(e);
682			}
683		}
684		cursor.close();
685		return record;
686	}
687
688	public boolean containsPreKey(Account account, int preKeyId) {
689		Cursor cursor = getCursorForPreKey(account, preKeyId);
690		int count = cursor.getCount();
691		cursor.close();
692		return count != 0;
693	}
694
695	public void storePreKey(Account account, PreKeyRecord record) {
696		SQLiteDatabase db = this.getWritableDatabase();
697		ContentValues values = new ContentValues();
698		values.put(AxolotlService.SQLiteAxolotlStore.ID, record.getId());
699		values.put(AxolotlService.SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(),Base64.DEFAULT));
700		values.put(AxolotlService.SQLiteAxolotlStore.ACCOUNT, account.getUuid());
701		db.insert(AxolotlService.SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
702	}
703
704	public void deletePreKey(Account account, int preKeyId) {
705		SQLiteDatabase db = this.getWritableDatabase();
706		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
707		db.delete(AxolotlService.SQLiteAxolotlStore.PREKEY_TABLENAME,
708				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=? AND "
709						+ AxolotlService.SQLiteAxolotlStore.ID + "=?",
710				args);
711	}
712
713	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
714		SQLiteDatabase db = this.getReadableDatabase();
715		String[] columns = {AxolotlService.SQLiteAxolotlStore.KEY};
716		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
717		Cursor cursor = db.query(AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
718				columns,
719				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=? AND " + AxolotlService.SQLiteAxolotlStore.ID + "=?",
720				selectionArgs,
721				null, null, null);
722
723		return cursor;
724	}
725
726	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
727		SignedPreKeyRecord record = null;
728		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
729		if(cursor.getCount() != 0) {
730			cursor.moveToFirst();
731			try {
732				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(AxolotlService.SQLiteAxolotlStore.KEY)),Base64.DEFAULT));
733			} catch (IOException e ) {
734				throw new AssertionError(e);
735			}
736		}
737		cursor.close();
738		return record;
739	}
740
741	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
742		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
743		SQLiteDatabase db = this.getReadableDatabase();
744		String[] columns = {AxolotlService.SQLiteAxolotlStore.KEY};
745		String[] selectionArgs = {account.getUuid()};
746		Cursor cursor = db.query(AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
747				columns,
748				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=?",
749				selectionArgs,
750				null, null, null);
751
752		while(cursor.moveToNext()) {
753			try {
754				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(AxolotlService.SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
755			} catch (IOException ignored) {
756			}
757		}
758		cursor.close();
759		return prekeys;
760	}
761
762	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
763		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
764		int count = cursor.getCount();
765		cursor.close();
766		return count != 0;
767	}
768
769	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
770		SQLiteDatabase db = this.getWritableDatabase();
771		ContentValues values = new ContentValues();
772		values.put(AxolotlService.SQLiteAxolotlStore.ID, record.getId());
773		values.put(AxolotlService.SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(),Base64.DEFAULT));
774		values.put(AxolotlService.SQLiteAxolotlStore.ACCOUNT, account.getUuid());
775		db.insert(AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
776	}
777
778	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
779		SQLiteDatabase db = this.getWritableDatabase();
780		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
781		db.delete(AxolotlService.SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
782				AxolotlService.SQLiteAxolotlStore.ACCOUNT + "=? AND "
783						+ AxolotlService.SQLiteAxolotlStore.ID + "=?",
784				args);
785	}
786}