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