DatabaseBackend.java

  1package eu.siacs.conversations.persistance;
  2
  3import java.util.ArrayList;
  4import java.util.List;
  5import java.util.concurrent.CopyOnWriteArrayList;
  6
  7import eu.siacs.conversations.entities.Account;
  8import eu.siacs.conversations.entities.Contact;
  9import eu.siacs.conversations.entities.Conversation;
 10import eu.siacs.conversations.entities.Message;
 11import eu.siacs.conversations.entities.Roster;
 12import eu.siacs.conversations.xmpp.jid.Jid;
 13
 14import android.content.Context;
 15import android.database.Cursor;
 16import android.database.sqlite.SQLiteCantOpenDatabaseException;
 17import android.database.sqlite.SQLiteDatabase;
 18import android.database.sqlite.SQLiteOpenHelper;
 19
 20public class DatabaseBackend extends SQLiteOpenHelper {
 21
 22	private static DatabaseBackend instance = null;
 23
 24	private static final String DATABASE_NAME = "history";
 25	private static final int DATABASE_VERSION = 11;
 26
 27	private static String CREATE_CONTATCS_STATEMENT = "create table "
 28			+ Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
 29			+ Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
 30			+ Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
 31			+ Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
 32			+ Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
 33            + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
 34			+ Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
 35			+ Account.TABLENAME + "(" + Account.UUID
 36			+ ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
 37			+ Contact.JID + ") ON CONFLICT REPLACE);";
 38
 39	private DatabaseBackend(Context context) {
 40		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 41	}
 42
 43	@Override
 44	public void onCreate(SQLiteDatabase db) {
 45		db.execSQL("PRAGMA foreign_keys=ON;");
 46		db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID
 47				+ " TEXT PRIMARY KEY," + Account.USERNAME + " TEXT,"
 48				+ Account.SERVER + " TEXT," + Account.PASSWORD + " TEXT,"
 49				+ Account.ROSTERVERSION + " TEXT," + Account.OPTIONS
 50				+ " NUMBER, " + Account.AVATAR + " TEXT, " + Account.KEYS
 51				+ " TEXT)");
 52		db.execSQL("create table " + Conversation.TABLENAME + " ("
 53				+ Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
 54				+ " TEXT, " + Conversation.CONTACT + " TEXT, "
 55				+ Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
 56				+ " TEXT, " + Conversation.CREATED + " NUMBER, "
 57				+ Conversation.STATUS + " NUMBER, " + Conversation.MODE
 58				+ " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
 59				+ Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
 60				+ "(" + Account.UUID + ") ON DELETE CASCADE);");
 61		db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
 62				+ " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
 63				+ Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
 64				+ " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
 65				+ Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
 66				+ Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
 67				+ Message.RELATIVE_FILE_PATH + " TEXT, "
 68				+ Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
 69				+ Message.CONVERSATION + ") REFERENCES "
 70				+ Conversation.TABLENAME + "(" + Conversation.UUID
 71				+ ") ON DELETE CASCADE);");
 72
 73		db.execSQL(CREATE_CONTATCS_STATEMENT);
 74	}
 75
 76	@Override
 77	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 78		if (oldVersion < 2 && newVersion >= 2) {
 79			db.execSQL("update " + Account.TABLENAME + " set "
 80					+ Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
 81		}
 82		if (oldVersion < 3 && newVersion >= 3) {
 83			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 84					+ Message.TYPE + " NUMBER");
 85		}
 86		if (oldVersion < 5 && newVersion >= 5) {
 87			db.execSQL("DROP TABLE " + Contact.TABLENAME);
 88			db.execSQL(CREATE_CONTATCS_STATEMENT);
 89			db.execSQL("UPDATE " + Account.TABLENAME + " SET "
 90					+ Account.ROSTERVERSION + " = NULL");
 91		}
 92		if (oldVersion < 6 && newVersion >= 6) {
 93			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 94					+ Message.TRUE_COUNTERPART + " TEXT");
 95		}
 96		if (oldVersion < 7 && newVersion >= 7) {
 97			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 98					+ Message.REMOTE_MSG_ID + " TEXT");
 99			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
100					+ Contact.AVATAR + " TEXT");
101			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
102					+ Account.AVATAR + " TEXT");
103		}
104		if (oldVersion < 8 && newVersion >= 8) {
105			db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
106					+ Conversation.ATTRIBUTES + " TEXT");
107		}
108        if (oldVersion < 9 && newVersion >= 9) {
109            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
110                    + Contact.LAST_TIME + " NUMBER");
111            db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
112                    + Contact.LAST_PRESENCE + " TEXT");
113        }
114		if (oldVersion < 10 && newVersion >= 10) {
115			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
116					+ Message.RELATIVE_FILE_PATH + " TEXT");
117		}
118		if (oldVersion < 11 && newVersion >= 11) {
119			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
120					+ Contact.GROUPS + " TEXT");
121			db.execSQL("delete from "+Contact.TABLENAME);
122			db.execSQL("update "+Account.TABLENAME+" set "+Account.ROSTERVERSION+" = NULL");
123		}
124	}
125
126	public static synchronized DatabaseBackend getInstance(Context context) {
127		if (instance == null) {
128			instance = new DatabaseBackend(context);
129		}
130		return instance;
131	}
132
133	public void createConversation(Conversation conversation) {
134		SQLiteDatabase db = this.getWritableDatabase();
135		db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
136	}
137
138	public void createMessage(Message message) {
139		SQLiteDatabase db = this.getWritableDatabase();
140		db.insert(Message.TABLENAME, null, message.getContentValues());
141	}
142
143	public void createAccount(Account account) {
144		SQLiteDatabase db = this.getWritableDatabase();
145		db.insert(Account.TABLENAME, null, account.getContentValues());
146	}
147
148	public void createContact(Contact contact) {
149		SQLiteDatabase db = this.getWritableDatabase();
150		db.insert(Contact.TABLENAME, null, contact.getContentValues());
151	}
152
153	public int getConversationCount() {
154		SQLiteDatabase db = this.getReadableDatabase();
155		Cursor cursor = db.rawQuery("select count(uuid) as count from "
156				+ Conversation.TABLENAME + " where " + Conversation.STATUS
157				+ "=" + Conversation.STATUS_AVAILABLE, null);
158		cursor.moveToFirst();
159		int count = cursor.getInt(0);
160		cursor.close();
161		return count;
162	}
163
164	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
165		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
166		SQLiteDatabase db = this.getReadableDatabase();
167		String[] selectionArgs = { Integer.toString(status) };
168		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
169				+ " where " + Conversation.STATUS + " = ? order by "
170				+ Conversation.CREATED + " desc", selectionArgs);
171		while (cursor.moveToNext()) {
172			list.add(Conversation.fromCursor(cursor));
173		}
174		cursor.close();
175		return list;
176	}
177
178	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
179		return getMessages(conversations, limit, -1);
180	}
181
182	public ArrayList<Message> getMessages(Conversation conversation, int limit,
183			long timestamp) {
184		ArrayList<Message> list = new ArrayList<>();
185		SQLiteDatabase db = this.getReadableDatabase();
186		Cursor cursor;
187		if (timestamp == -1) {
188			String[] selectionArgs = { conversation.getUuid() };
189			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
190					+ "=?", selectionArgs, null, null, Message.TIME_SENT
191					+ " DESC", String.valueOf(limit));
192		} else {
193			String[] selectionArgs = { conversation.getUuid(),
194					Long.toString(timestamp) };
195			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
196					+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
197					null, null, Message.TIME_SENT + " DESC",
198					String.valueOf(limit));
199		}
200		if (cursor.getCount() > 0) {
201			cursor.moveToLast();
202			do {
203				Message message = Message.fromCursor(cursor);
204				message.setConversation(conversation);
205				list.add(message);
206			} while (cursor.moveToPrevious());
207		}
208		cursor.close();
209		return list;
210	}
211
212	public Conversation findConversation(final Account account, final Jid contactJid) {
213		SQLiteDatabase db = this.getReadableDatabase();
214		String[] selectionArgs = { account.getUuid(), contactJid.toBareJid().toString() + "%" };
215		Cursor cursor = db.query(Conversation.TABLENAME, null,
216				Conversation.ACCOUNT + "=? AND " + Conversation.CONTACTJID
217						+ " like ?", selectionArgs, null, null, null);
218		if (cursor.getCount() == 0)
219			return null;
220		cursor.moveToFirst();
221		Conversation conversation = Conversation.fromCursor(cursor);
222		cursor.close();
223		return conversation;
224	}
225
226	public void updateConversation(Conversation conversation) {
227		SQLiteDatabase db = this.getWritableDatabase();
228		String[] args = { conversation.getUuid() };
229		db.update(Conversation.TABLENAME, conversation.getContentValues(),
230				Conversation.UUID + "=?", args);
231	}
232
233	public List<Account> getAccounts() {
234		List<Account> list = new ArrayList<>();
235		SQLiteDatabase db = this.getReadableDatabase();
236		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
237				null, null);
238		while (cursor.moveToNext()) {
239			list.add(Account.fromCursor(cursor));
240		}
241		cursor.close();
242		return list;
243	}
244
245	public void updateAccount(Account account) {
246		SQLiteDatabase db = this.getWritableDatabase();
247		String[] args = { account.getUuid() };
248		db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
249				+ "=?", args);
250	}
251
252	public void deleteAccount(Account account) {
253		SQLiteDatabase db = this.getWritableDatabase();
254		String[] args = { account.getUuid() };
255		db.delete(Account.TABLENAME, Account.UUID + "=?", args);
256	}
257
258	public boolean hasEnabledAccounts() {
259		SQLiteDatabase db = this.getReadableDatabase();
260		Cursor cursor = db.rawQuery("select count(" + Account.UUID + ")  from "
261				+ Account.TABLENAME + " where not options & (1 <<1)", null);
262		try {
263			cursor.moveToFirst();
264			int count = cursor.getInt(0);
265			cursor.close();
266			return (count > 0);
267		} catch (SQLiteCantOpenDatabaseException e) {
268			return true; // better safe than sorry
269		}
270	}
271
272	@Override
273	public SQLiteDatabase getWritableDatabase() {
274		SQLiteDatabase db = super.getWritableDatabase();
275		db.execSQL("PRAGMA foreign_keys=ON;");
276		return db;
277	}
278
279	public void updateMessage(Message message) {
280		SQLiteDatabase db = this.getWritableDatabase();
281		String[] args = { message.getUuid() };
282		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
283				+ "=?", args);
284	}
285
286	public void readRoster(Roster roster) {
287		SQLiteDatabase db = this.getReadableDatabase();
288		Cursor cursor;
289		String args[] = { roster.getAccount().getUuid() };
290		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?",
291				args, null, null, null);
292		while (cursor.moveToNext()) {
293			roster.initContact(Contact.fromCursor(cursor));
294		}
295		cursor.close();
296	}
297
298	public void writeRoster(final Roster roster) {
299		final Account account = roster.getAccount();
300		final SQLiteDatabase db = this.getWritableDatabase();
301		for (Contact contact : roster.getContacts()) {
302			if (contact.getOption(Contact.Options.IN_ROSTER)) {
303				db.insert(Contact.TABLENAME, null, contact.getContentValues());
304			} else {
305				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
306				String[] whereArgs = { account.getUuid(), contact.getJid().toString() };
307				db.delete(Contact.TABLENAME, where, whereArgs);
308			}
309		}
310		account.setRosterVersion(roster.getVersion());
311		updateAccount(account);
312	}
313
314	public void deleteMessage(Message message) {
315		SQLiteDatabase db = this.getWritableDatabase();
316		String[] args = { message.getUuid() };
317		db.delete(Message.TABLENAME, Message.UUID + "=?", args);
318	}
319
320	public void deleteMessagesInConversation(Conversation conversation) {
321		SQLiteDatabase db = this.getWritableDatabase();
322		String[] args = { conversation.getUuid() };
323		db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
324	}
325
326	public Conversation findConversationByUuid(String conversationUuid) {
327		SQLiteDatabase db = this.getReadableDatabase();
328		String[] selectionArgs = { conversationUuid };
329		Cursor cursor = db.query(Conversation.TABLENAME, null,
330				Conversation.UUID + "=?", selectionArgs, null, null, null);
331		if (cursor.getCount() == 0) {
332			return null;
333		}
334		cursor.moveToFirst();
335		Conversation conversation = Conversation.fromCursor(cursor);
336		cursor.close();
337		return conversation;
338	}
339
340	public Message findMessageByUuid(String messageUuid) {
341		SQLiteDatabase db = this.getReadableDatabase();
342		String[] selectionArgs = { messageUuid };
343		Cursor cursor = db.query(Message.TABLENAME, null, Message.UUID + "=?",
344				selectionArgs, null, null, null);
345		if (cursor.getCount() == 0) {
346			return null;
347		}
348		cursor.moveToFirst();
349		Message message = Message.fromCursor(cursor);
350		cursor.close();
351		return message;
352	}
353
354	public Account findAccountByUuid(String accountUuid) {
355		SQLiteDatabase db = this.getReadableDatabase();
356		String[] selectionArgs = { accountUuid };
357		Cursor cursor = db.query(Account.TABLENAME, null, Account.UUID + "=?",
358				selectionArgs, null, null, null);
359		if (cursor.getCount() == 0) {
360			return null;
361		}
362		cursor.moveToFirst();
363		Account account = Account.fromCursor(cursor);
364		cursor.close();
365		return account;
366	}
367
368	public List<Message> getImageMessages(Conversation conversation) {
369		ArrayList<Message> list = new ArrayList<>();
370		SQLiteDatabase db = this.getReadableDatabase();
371		Cursor cursor;
372			String[] selectionArgs = { conversation.getUuid(), String.valueOf(Message.TYPE_IMAGE) };
373			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
374					+ "=? AND "+Message.TYPE+"=?", selectionArgs, null, null,null);
375		if (cursor.getCount() > 0) {
376			cursor.moveToLast();
377			do {
378				Message message = Message.fromCursor(cursor);
379				message.setConversation(conversation);
380				list.add(message);
381			} while (cursor.moveToPrevious());
382		}
383		cursor.close();
384		return list;
385	}
386}