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