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