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