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