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 com.cheogram.android.WebxdcUpdate;
15
16import com.google.common.base.Stopwatch;
17
18import org.json.JSONException;
19import org.json.JSONObject;
20import org.whispersystems.libsignal.IdentityKey;
21import org.whispersystems.libsignal.IdentityKeyPair;
22import org.whispersystems.libsignal.InvalidKeyException;
23import org.whispersystems.libsignal.SignalProtocolAddress;
24import org.whispersystems.libsignal.state.PreKeyRecord;
25import org.whispersystems.libsignal.state.SessionRecord;
26import org.whispersystems.libsignal.state.SignedPreKeyRecord;
27
28import java.io.ByteArrayInputStream;
29import java.io.File;
30import java.io.IOException;
31import java.security.cert.CertificateEncodingException;
32import java.security.cert.CertificateException;
33import java.security.cert.CertificateFactory;
34import java.security.cert.X509Certificate;
35import java.util.ArrayList;
36import java.util.HashMap;
37import java.util.HashSet;
38import java.util.List;
39import java.util.Map;
40import java.util.Set;
41import java.util.UUID;
42import java.util.concurrent.CopyOnWriteArrayList;
43
44import io.ipfs.cid.Cid;
45
46import eu.siacs.conversations.Config;
47import eu.siacs.conversations.crypto.axolotl.AxolotlService;
48import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
49import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
50import eu.siacs.conversations.entities.Account;
51import eu.siacs.conversations.entities.Contact;
52import eu.siacs.conversations.entities.Conversation;
53import eu.siacs.conversations.entities.DownloadableFile;
54import eu.siacs.conversations.entities.Message;
55import eu.siacs.conversations.entities.PresenceTemplate;
56import eu.siacs.conversations.entities.Roster;
57import eu.siacs.conversations.entities.ServiceDiscoveryResult;
58import eu.siacs.conversations.services.QuickConversationsService;
59import eu.siacs.conversations.services.ShortcutService;
60import eu.siacs.conversations.utils.CryptoHelper;
61import eu.siacs.conversations.utils.CursorUtils;
62import eu.siacs.conversations.utils.FtsUtils;
63import eu.siacs.conversations.utils.MimeUtils;
64import eu.siacs.conversations.utils.Resolver;
65import eu.siacs.conversations.xmpp.InvalidJid;
66import eu.siacs.conversations.xmpp.Jid;
67import eu.siacs.conversations.xmpp.mam.MamReference;
68
69public class DatabaseBackend extends SQLiteOpenHelper {
70
71 private static final String DATABASE_NAME = "history";
72 private static final int DATABASE_VERSION = 51;
73
74 private static boolean requiresMessageIndexRebuild = false;
75 private static DatabaseBackend instance = null;
76 private static final String CREATE_CONTATCS_STATEMENT = "create table "
77 + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
78 + Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
79 + Contact.PRESENCE_NAME + " TEXT,"
80 + Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
81 + Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
82 + Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
83 + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
84 + Contact.RTP_CAPABILITY + " TEXT,"
85 + Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
86 + Account.TABLENAME + "(" + Account.UUID
87 + ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
88 + Contact.JID + ") ON CONFLICT REPLACE);";
89
90 private static final String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
91 + ServiceDiscoveryResult.TABLENAME + "("
92 + ServiceDiscoveryResult.HASH + " TEXT, "
93 + ServiceDiscoveryResult.VER + " TEXT, "
94 + ServiceDiscoveryResult.RESULT + " TEXT, "
95 + "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
96 + ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
97
98 private static final String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
99 + PresenceTemplate.TABELNAME + "("
100 + PresenceTemplate.UUID + " TEXT, "
101 + PresenceTemplate.LAST_USED + " NUMBER,"
102 + PresenceTemplate.MESSAGE + " TEXT,"
103 + PresenceTemplate.STATUS + " TEXT,"
104 + "UNIQUE(" + PresenceTemplate.MESSAGE + "," + PresenceTemplate.STATUS + ") ON CONFLICT REPLACE);";
105
106 private static final String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
107 + SQLiteAxolotlStore.PREKEY_TABLENAME + "("
108 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
109 + SQLiteAxolotlStore.ID + " INTEGER, "
110 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
111 + SQLiteAxolotlStore.ACCOUNT
112 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
113 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
114 + SQLiteAxolotlStore.ID
115 + ") ON CONFLICT REPLACE"
116 + ");";
117
118 private static final String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
119 + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
120 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
121 + SQLiteAxolotlStore.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.ID
127 + ") ON CONFLICT REPLACE" +
128 ");";
129
130 private static final String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
131 + SQLiteAxolotlStore.SESSION_TABLENAME + "("
132 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
133 + SQLiteAxolotlStore.NAME + " TEXT, "
134 + SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
135 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
136 + SQLiteAxolotlStore.ACCOUNT
137 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
138 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
139 + SQLiteAxolotlStore.NAME + ", "
140 + SQLiteAxolotlStore.DEVICE_ID
141 + ") ON CONFLICT REPLACE"
142 + ");";
143
144 private static final String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
145 + SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
146 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
147 + SQLiteAxolotlStore.NAME + " TEXT, "
148 + SQLiteAxolotlStore.OWN + " INTEGER, "
149 + SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
150 + SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
151 + SQLiteAxolotlStore.TRUST + " TEXT, "
152 + SQLiteAxolotlStore.ACTIVE + " NUMBER, "
153 + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
154 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
155 + SQLiteAxolotlStore.ACCOUNT
156 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
157 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
158 + SQLiteAxolotlStore.NAME + ", "
159 + SQLiteAxolotlStore.FINGERPRINT
160 + ") ON CONFLICT IGNORE"
161 + ");";
162
163 private static final String RESOLVER_RESULTS_TABLENAME = "resolver_results";
164
165 private static final String CREATE_RESOLVER_RESULTS_TABLE = "create table " + RESOLVER_RESULTS_TABLENAME + "("
166 + Resolver.Result.DOMAIN + " TEXT,"
167 + Resolver.Result.HOSTNAME + " TEXT,"
168 + Resolver.Result.IP + " BLOB,"
169 + Resolver.Result.PRIORITY + " NUMBER,"
170 + Resolver.Result.DIRECT_TLS + " NUMBER,"
171 + Resolver.Result.AUTHENTICATED + " NUMBER,"
172 + Resolver.Result.PORT + " NUMBER,"
173 + "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
174 + ");";
175
176 private static final String CREATE_MESSAGE_TIME_INDEX = "CREATE INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
177 private static final String CREATE_MESSAGE_CONVERSATION_INDEX = "CREATE INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
178 private static final String CREATE_MESSAGE_DELETED_INDEX = "CREATE INDEX message_deleted_index ON " + Message.TABLENAME + "(" + Message.DELETED + ")";
179 private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX = "CREATE INDEX message_file_path_index ON " + Message.TABLENAME + "(" + Message.RELATIVE_FILE_PATH + ")";
180 private static final String CREATE_MESSAGE_TYPE_INDEX = "CREATE INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
181
182 private static final String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING fts4 (uuid,body,notindexed=\"uuid\",content=\"" + Message.TABLENAME + "\",tokenize='unicode61')";
183 private static final String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index(rowid,uuid,body) VALUES(NEW.rowid,NEW.uuid,NEW.body); END;";
184 private static final String CREATE_MESSAGE_UPDATE_TRIGGER = "CREATE TRIGGER after_message_update UPDATE OF uuid,body ON " + Message.TABLENAME + " BEGIN UPDATE messages_index SET body=NEW.body,uuid=NEW.uuid WHERE rowid=OLD.rowid; END;";
185 private static final String CREATE_MESSAGE_DELETE_TRIGGER = "CREATE TRIGGER after_message_delete AFTER DELETE ON " + Message.TABLENAME + " BEGIN DELETE FROM messages_index WHERE rowid=OLD.rowid; END;";
186 private static final String COPY_PREEXISTING_ENTRIES = "INSERT INTO messages_index(messages_index) VALUES('rebuild');";
187
188 protected Context context;
189
190 private DatabaseBackend(Context context) {
191 super(context, DATABASE_NAME, null, DATABASE_VERSION);
192 this.context = context;
193 }
194
195 private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
196 ContentValues values = new ContentValues();
197 values.put(SQLiteAxolotlStore.TRUST, trust.toString());
198 values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
199 return values;
200 }
201
202 public static boolean requiresMessageIndexRebuild() {
203 return requiresMessageIndexRebuild;
204 }
205
206 public void rebuildMessagesIndex() {
207 final SQLiteDatabase db = getWritableDatabase();
208 final Stopwatch stopwatch = Stopwatch.createStarted();
209 db.execSQL(COPY_PREEXISTING_ENTRIES);
210 Log.d(Config.LOGTAG,"rebuilt message index in "+ stopwatch.stop().toString());
211 }
212
213 public static synchronized DatabaseBackend getInstance(Context context) {
214 if (instance == null) {
215 instance = new DatabaseBackend(context);
216 }
217 return instance;
218 }
219
220 protected void cheogramMigrate(SQLiteDatabase db) {
221 db.beginTransaction();
222
223 try {
224 Cursor cursor = db.rawQuery("PRAGMA cheogram.user_version", null);
225 cursor.moveToNext();
226 int cheogramVersion = cursor.getInt(0);
227 cursor.close();
228
229 if(cheogramVersion < 1) {
230 // No cross-DB foreign keys unfortunately
231 db.execSQL(
232 "CREATE TABLE cheogram." + Message.TABLENAME + "(" +
233 Message.UUID + " TEXT PRIMARY KEY, " +
234 "subject TEXT" +
235 ")"
236 );
237 db.execSQL("PRAGMA cheogram.user_version = 1");
238 }
239
240 if(cheogramVersion < 2) {
241 db.execSQL(
242 "ALTER TABLE cheogram." + Message.TABLENAME + " " +
243 "ADD COLUMN oobUri TEXT"
244 );
245 db.execSQL(
246 "ALTER TABLE cheogram." + Message.TABLENAME + " " +
247 "ADD COLUMN fileParams TEXT"
248 );
249 db.execSQL("PRAGMA cheogram.user_version = 2");
250 }
251
252 if(cheogramVersion < 3) {
253 db.execSQL(
254 "ALTER TABLE cheogram." + Message.TABLENAME + " " +
255 "ADD COLUMN payloads TEXT"
256 );
257 db.execSQL("PRAGMA cheogram.user_version = 3");
258 }
259
260 if(cheogramVersion < 4) {
261 db.execSQL(
262 "CREATE TABLE cheogram.cids (" +
263 "cid TEXT NOT NULL PRIMARY KEY," +
264 "path TEXT NOT NULL" +
265 ")"
266 );
267 db.execSQL("PRAGMA cheogram.user_version = 4");
268 }
269
270 if(cheogramVersion < 5) {
271 db.execSQL(
272 "ALTER TABLE cheogram." + Message.TABLENAME + " " +
273 "ADD COLUMN timeReceived NUMBER"
274 );
275 db.execSQL("CREATE INDEX cheogram.message_time_received_index ON " + Message.TABLENAME + " (timeReceived)");
276 db.execSQL("PRAGMA cheogram.user_version = 5");
277 }
278
279 if(cheogramVersion < 6) {
280 db.execSQL(
281 "CREATE TABLE cheogram.blocked_media (" +
282 "cid TEXT NOT NULL PRIMARY KEY" +
283 ")"
284 );
285 db.execSQL("PRAGMA cheogram.user_version = 6");
286 }
287
288 if(cheogramVersion < 7) {
289 db.execSQL(
290 "ALTER TABLE cheogram.cids " +
291 "ADD COLUMN url TEXT"
292 );
293 db.execSQL("PRAGMA cheogram.user_version = 7");
294 }
295
296 if(cheogramVersion < 8) {
297 db.execSQL(
298 "CREATE TABLE cheogram.webxdc_updates (" +
299 "serial INTEGER PRIMARY KEY AUTOINCREMENT, " +
300 Message.CONVERSATION + " TEXT NOT NULL, " +
301 "sender TEXT NOT NULL, " +
302 "thread TEXT NOT NULL, " +
303 "threadParent TEXT, " +
304 "info TEXT, " +
305 "document TEXT, " +
306 "summary TEXT, " +
307 "payload TEXT" +
308 ")"
309 );
310 db.execSQL("CREATE INDEX cheogram.webxdc_index ON webxdc_updates (" + Message.CONVERSATION + ", thread)");
311 db.execSQL("PRAGMA cheogram.user_version = 8");
312 }
313
314 if(cheogramVersion < 9) {
315 db.execSQL(
316 "ALTER TABLE cheogram.webxdc_updates " +
317 "ADD COLUMN message_id TEXT"
318 );
319 db.execSQL("CREATE UNIQUE INDEX cheogram.webxdc_message_id_index ON webxdc_updates (" + Message.CONVERSATION + ", message_id)");
320 db.execSQL("PRAGMA cheogram.user_version = 9");
321 }
322
323 db.setTransactionSuccessful();
324 } finally {
325 db.endTransaction();
326 }
327 }
328
329 @Override
330 public void onConfigure(SQLiteDatabase db) {
331 db.execSQL("PRAGMA foreign_keys=ON");
332 db.rawQuery("PRAGMA secure_delete=ON", null).close();
333 db.execSQL("ATTACH DATABASE ? AS cheogram", new Object[]{context.getDatabasePath("cheogram").getPath()});
334 cheogramMigrate(db);
335 }
336
337 @Override
338 public void onCreate(SQLiteDatabase db) {
339 db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID + " TEXT PRIMARY KEY,"
340 + Account.USERNAME + " TEXT,"
341 + Account.SERVER + " TEXT,"
342 + Account.PASSWORD + " TEXT,"
343 + Account.DISPLAY_NAME + " TEXT, "
344 + Account.STATUS + " TEXT,"
345 + Account.STATUS_MESSAGE + " TEXT,"
346 + Account.ROSTERVERSION + " TEXT,"
347 + Account.OPTIONS + " NUMBER, "
348 + Account.AVATAR + " TEXT, "
349 + Account.KEYS + " TEXT, "
350 + Account.HOSTNAME + " TEXT, "
351 + Account.RESOURCE + " TEXT,"
352 + Account.PINNED_MECHANISM + " TEXT,"
353 + Account.PINNED_CHANNEL_BINDING + " TEXT,"
354 + Account.FAST_MECHANISM + " TEXT,"
355 + Account.FAST_TOKEN + " TEXT,"
356 + Account.PORT + " NUMBER DEFAULT 5222)");
357 db.execSQL("create table " + Conversation.TABLENAME + " ("
358 + Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
359 + " TEXT, " + Conversation.CONTACT + " TEXT, "
360 + Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
361 + " TEXT, " + Conversation.CREATED + " NUMBER, "
362 + Conversation.STATUS + " NUMBER, " + Conversation.MODE
363 + " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
364 + Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
365 + "(" + Account.UUID + ") ON DELETE CASCADE);");
366 db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
367 + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
368 + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
369 + " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
370 + Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
371 + Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
372 + Message.RELATIVE_FILE_PATH + " TEXT, "
373 + Message.SERVER_MSG_ID + " TEXT, "
374 + Message.FINGERPRINT + " TEXT, "
375 + Message.CARBON + " INTEGER, "
376 + Message.EDITED + " TEXT, "
377 + Message.READ + " NUMBER DEFAULT 1, "
378 + Message.OOB + " INTEGER, "
379 + Message.ERROR_MESSAGE + " TEXT,"
380 + Message.READ_BY_MARKERS + " TEXT,"
381 + Message.MARKABLE + " NUMBER DEFAULT 0,"
382 + Message.DELETED + " NUMBER DEFAULT 0,"
383 + Message.BODY_LANGUAGE + " TEXT,"
384 + Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
385 + Message.CONVERSATION + ") REFERENCES "
386 + Conversation.TABLENAME + "(" + Conversation.UUID
387 + ") ON DELETE CASCADE);");
388 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
389 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
390 db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
391 db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
392 db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
393 db.execSQL(CREATE_CONTATCS_STATEMENT);
394 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
395 db.execSQL(CREATE_SESSIONS_STATEMENT);
396 db.execSQL(CREATE_PREKEYS_STATEMENT);
397 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
398 db.execSQL(CREATE_IDENTITIES_STATEMENT);
399 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
400 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
401 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
402 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
403 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
404 db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
405 }
406
407 @Override
408 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
409 if (oldVersion < 2 && newVersion >= 2) {
410 db.execSQL("update " + Account.TABLENAME + " set "
411 + Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
412 }
413 if (oldVersion < 3 && newVersion >= 3) {
414 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
415 + Message.TYPE + " NUMBER");
416 }
417 if (oldVersion < 5 && newVersion >= 5) {
418 db.execSQL("DROP TABLE " + Contact.TABLENAME);
419 db.execSQL(CREATE_CONTATCS_STATEMENT);
420 db.execSQL("UPDATE " + Account.TABLENAME + " SET "
421 + Account.ROSTERVERSION + " = NULL");
422 }
423 if (oldVersion < 6 && newVersion >= 6) {
424 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
425 + Message.TRUE_COUNTERPART + " TEXT");
426 }
427 if (oldVersion < 7 && newVersion >= 7) {
428 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
429 + Message.REMOTE_MSG_ID + " TEXT");
430 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
431 + Contact.AVATAR + " TEXT");
432 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
433 + Account.AVATAR + " TEXT");
434 }
435 if (oldVersion < 8 && newVersion >= 8) {
436 db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
437 + Conversation.ATTRIBUTES + " TEXT");
438 }
439 if (oldVersion < 9 && newVersion >= 9) {
440 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
441 + Contact.LAST_TIME + " NUMBER");
442 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
443 + Contact.LAST_PRESENCE + " TEXT");
444 }
445 if (oldVersion < 10 && newVersion >= 10) {
446 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
447 + Message.RELATIVE_FILE_PATH + " TEXT");
448 }
449 if (oldVersion < 11 && newVersion >= 11) {
450 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
451 + Contact.GROUPS + " TEXT");
452 db.execSQL("delete from " + Contact.TABLENAME);
453 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
454 }
455 if (oldVersion < 12 && newVersion >= 12) {
456 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
457 + Message.SERVER_MSG_ID + " TEXT");
458 }
459 if (oldVersion < 13 && newVersion >= 13) {
460 db.execSQL("delete from " + Contact.TABLENAME);
461 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
462 }
463 if (oldVersion < 14 && newVersion >= 14) {
464 canonicalizeJids(db);
465 }
466 if (oldVersion < 15 && newVersion >= 15) {
467 recreateAxolotlDb(db);
468 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
469 + Message.FINGERPRINT + " TEXT");
470 }
471 if (oldVersion < 16 && newVersion >= 16) {
472 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
473 + Message.CARBON + " INTEGER");
474 }
475 if (oldVersion < 19 && newVersion >= 19) {
476 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
477 }
478 if (oldVersion < 20 && newVersion >= 20) {
479 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
480 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
481 }
482 if (oldVersion < 26 && newVersion >= 26) {
483 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
484 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
485 }
486 if (oldVersion < 40 && newVersion >= 40) {
487 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.RESOURCE + " TEXT");
488 }
489 /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
490 * depends on account de-serialization.
491 */
492 if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
493 List<Account> accounts = getAccounts(db);
494 for (Account account : accounts) {
495 String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
496 if (ownDeviceIdString == null) {
497 continue;
498 }
499 int ownDeviceId = Integer.valueOf(ownDeviceIdString);
500 SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownDeviceId);
501 deleteSession(db, account, ownAddress);
502 IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
503 if (identityKeyPair != null) {
504 String[] selectionArgs = {
505 account.getUuid(),
506 CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
507 };
508 ContentValues values = new ContentValues();
509 values.put(SQLiteAxolotlStore.TRUSTED, 2);
510 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
511 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
512 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
513 selectionArgs);
514 } else {
515 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not load own identity key pair");
516 }
517 }
518 }
519 if (oldVersion < 18 && newVersion >= 18) {
520 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
521 }
522
523 if (oldVersion < 21 && newVersion >= 21) {
524 List<Account> accounts = getAccounts(db);
525 for (Account account : accounts) {
526 account.unsetPgpSignature();
527 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
528 + "=?", new String[]{account.getUuid()});
529 }
530 }
531
532 if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
533 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
534 }
535
536 if (oldVersion < 23 && newVersion >= 23) {
537 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
538 }
539
540 if (oldVersion < 24 && newVersion >= 24) {
541 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
542 }
543
544 if (oldVersion < 25 && newVersion >= 25) {
545 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
546 }
547
548 if (oldVersion < 26 && newVersion >= 26) {
549 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
550 }
551
552 if (oldVersion < 27 && newVersion >= 27) {
553 db.execSQL("DELETE FROM " + ServiceDiscoveryResult.TABLENAME);
554 }
555
556 if (oldVersion < 28 && newVersion >= 28) {
557 canonicalizeJids(db);
558 }
559
560 if (oldVersion < 29 && newVersion >= 29) {
561 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
562 }
563 if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
564 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.TRUST + " TEXT");
565 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.ACTIVE + " NUMBER");
566 HashMap<Integer, ContentValues> migration = new HashMap<>();
567 migration.put(0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
568 migration.put(1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
569 migration.put(2, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
570 migration.put(3, createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
571 migration.put(4, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
572 migration.put(5, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
573 migration.put(6, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
574 migration.put(7, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
575 migration.put(8, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
576 for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
577 String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
578 String[] where = {String.valueOf(entry.getKey())};
579 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, entry.getValue(), whereClause, where);
580 }
581
582 }
583 if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
584 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
585 ContentValues defaults = new ContentValues();
586 defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
587 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
588 }
589 if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
590 String whereClause = SQLiteAxolotlStore.OWN + "=1";
591 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true), whereClause, null);
592 }
593
594 if (oldVersion < 34 && newVersion >= 34) {
595 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
596
597 final File oldPicturesDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Conversations/");
598 final File oldFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/");
599 final File newFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Files/");
600 final File newVideosDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Videos/");
601 if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
602 final File newPicturesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Images/");
603 newPicturesDirectory.getParentFile().mkdirs();
604 if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
605 Log.d(Config.LOGTAG, "moved " + oldPicturesDirectory.getAbsolutePath() + " to " + newPicturesDirectory.getAbsolutePath());
606 }
607 }
608 if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
609 newFilesDirectory.mkdirs();
610 newVideosDirectory.mkdirs();
611 final File[] files = oldFilesDirectory.listFiles();
612 if (files == null) {
613 return;
614 }
615 for (File file : files) {
616 if (file.getName().equals(".nomedia")) {
617 if (file.delete()) {
618 Log.d(Config.LOGTAG, "deleted nomedia file in " + oldFilesDirectory.getAbsolutePath());
619 }
620 } else if (file.isFile()) {
621 final String name = file.getName();
622 boolean isVideo = false;
623 int start = name.lastIndexOf('.') + 1;
624 if (start < name.length()) {
625 String mime = MimeUtils.guessMimeTypeFromExtension(name.substring(start));
626 isVideo = mime != null && mime.startsWith("video/");
627 }
628 File dst = new File((isVideo ? newVideosDirectory : newFilesDirectory).getAbsolutePath() + "/" + file.getName());
629 if (file.renameTo(dst)) {
630 Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
631 }
632 }
633 }
634 }
635 }
636 if (oldVersion < 35 && newVersion >= 35) {
637 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
638 }
639 if (oldVersion < 36 && newVersion >= 36) {
640 List<Account> accounts = getAccounts(db);
641 for (Account account : accounts) {
642 account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
643 account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
644 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
645 + "=?", new String[]{account.getUuid()});
646 }
647 }
648
649 if (oldVersion < 37 && newVersion >= 37) {
650 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ_BY_MARKERS + " TEXT");
651 }
652
653 if (oldVersion < 38 && newVersion >= 38) {
654 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0");
655 }
656
657 if (oldVersion < 39 && newVersion >= 39) {
658 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
659 }
660
661 if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
662 List<Account> accounts = getAccounts(db);
663 for (Account account : accounts) {
664 account.setOption(Account.OPTION_MAGIC_CREATE, true);
665 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
666 + "=?", new String[]{account.getUuid()});
667 }
668 }
669
670 if (oldVersion < 44 && newVersion >= 44) {
671 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.DELETED + " NUMBER DEFAULT 0");
672 db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
673 db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
674 db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
675 }
676
677 if (oldVersion < 45 && newVersion >= 45) {
678 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.BODY_LANGUAGE);
679 }
680
681 if (oldVersion < 46 && newVersion >= 46) {
682 final long start = SystemClock.elapsedRealtime();
683 db.rawQuery("PRAGMA secure_delete = FALSE", null).close();
684 db.execSQL("update " + Message.TABLENAME + " set " + Message.EDITED + "=NULL");
685 db.rawQuery("PRAGMA secure_delete=ON", null).close();
686 final long diff = SystemClock.elapsedRealtime() - start;
687 Log.d(Config.LOGTAG, "deleted old edit information in " + diff + "ms");
688 }
689 if (oldVersion < 47 && newVersion >= 47) {
690 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.PRESENCE_NAME + " TEXT");
691 }
692 if (oldVersion < 48 && newVersion >= 48) {
693 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.RTP_CAPABILITY + " TEXT");
694 }
695 if (oldVersion < 49 && newVersion >= 49) {
696 db.beginTransaction();
697 db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
698 db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
699 db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
700 db.execSQL("DROP TABLE IF EXISTS messages_index;");
701 // a hack that should not be necessary, but
702 // there was at least one occurence when SQLite failed at this
703 db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
704 db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
705 db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
706 db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
707 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
708 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
709 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
710 db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
711 db.setTransactionSuccessful();
712 db.endTransaction();
713 requiresMessageIndexRebuild = true;
714 }
715 if (oldVersion < 50 && newVersion >= 50) {
716 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PINNED_MECHANISM + " TEXT");
717 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PINNED_CHANNEL_BINDING + " TEXT");
718 }
719 if (oldVersion < 51 && newVersion >= 51) {
720 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.FAST_MECHANISM + " TEXT");
721 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.FAST_TOKEN + " TEXT");
722 }
723 }
724
725 private void canonicalizeJids(SQLiteDatabase db) {
726 // migrate db to new, canonicalized JID domainpart representation
727
728 // Conversation table
729 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
730 while (cursor.moveToNext()) {
731 String newJid;
732 try {
733 newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
734 } catch (IllegalArgumentException ignored) {
735 Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
736 + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
737 + ": " + ignored + ". Skipping...");
738 continue;
739 }
740
741 final String[] updateArgs = {
742 newJid,
743 cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
744 };
745 db.execSQL("update " + Conversation.TABLENAME
746 + " set " + Conversation.CONTACTJID + " = ? "
747 + " where " + Conversation.UUID + " = ?", updateArgs);
748 }
749 cursor.close();
750
751 // Contact table
752 cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
753 while (cursor.moveToNext()) {
754 String newJid;
755 try {
756 newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
757 } catch (final IllegalArgumentException e) {
758 Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
759 + cursor.getString(cursor.getColumnIndex(Contact.JID))
760 + ": Skipping...", e);
761 continue;
762 }
763
764 final String[] updateArgs = {
765 newJid,
766 cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
767 cursor.getString(cursor.getColumnIndex(Contact.JID)),
768 };
769 db.execSQL("update " + Contact.TABLENAME
770 + " set " + Contact.JID + " = ? "
771 + " where " + Contact.ACCOUNT + " = ? "
772 + " AND " + Contact.JID + " = ?", updateArgs);
773 }
774 cursor.close();
775
776 // Account table
777 cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
778 while (cursor.moveToNext()) {
779 String newServer;
780 try {
781 newServer = Jid.of(
782 cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
783 cursor.getString(cursor.getColumnIndex(Account.SERVER)),
784 null
785 ).getDomain().toEscapedString();
786 } catch (IllegalArgumentException ignored) {
787 Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
788 + cursor.getString(cursor.getColumnIndex(Account.SERVER))
789 + ": " + ignored + ". Skipping...");
790 continue;
791 }
792
793 String[] updateArgs = {
794 newServer,
795 cursor.getString(cursor.getColumnIndex(Account.UUID)),
796 };
797 db.execSQL("update " + Account.TABLENAME
798 + " set " + Account.SERVER + " = ? "
799 + " where " + Account.UUID + " = ?", updateArgs);
800 }
801 cursor.close();
802 }
803
804 public DownloadableFile getFileForCid(Cid cid) {
805 SQLiteDatabase db = this.getReadableDatabase();
806 Cursor cursor = db.query("cheogram.cids", new String[]{"path"}, "cid=?", new String[]{cid.toString()}, null, null, null);
807 DownloadableFile f = null;
808 if (cursor.moveToNext()) {
809 f = new DownloadableFile(cursor.getString(0));
810 }
811 cursor.close();
812 return f;
813 }
814
815 public String getUrlForCid(Cid cid) {
816 SQLiteDatabase db = this.getReadableDatabase();
817 Cursor cursor = db.query("cheogram.cids", new String[]{"url"}, "cid=?", new String[]{cid.toString()}, null, null, null);
818 String url = null;
819 if (cursor.moveToNext()) {
820 url = cursor.getString(0);
821 }
822 cursor.close();
823 return url;
824 }
825
826 public void saveCid(Cid cid, File file) {
827 saveCid(cid, file, null);
828 }
829
830 public void saveCid(Cid cid, File file, String url) {
831 SQLiteDatabase db = this.getWritableDatabase();
832 ContentValues cv = new ContentValues();
833 cv.put("cid", cid.toString());
834 if (file != null) cv.put("path", file.getAbsolutePath());
835 if (url != null) cv.put("url", url);
836 if (db.update("cheogram.cids", cv, "cid=?", new String[]{cid.toString()}) < 1) {
837 db.insertWithOnConflict("cheogram.cids", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
838 }
839 }
840
841 public void blockMedia(Cid cid) {
842 SQLiteDatabase db = this.getWritableDatabase();
843 ContentValues cv = new ContentValues();
844 cv.put("cid", cid.toString());
845 db.insertWithOnConflict("cheogram.blocked_media", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
846 }
847
848 public boolean isBlockedMedia(Cid cid) {
849 SQLiteDatabase db = this.getReadableDatabase();
850 Cursor cursor = db.query("cheogram.blocked_media", new String[]{"count(*)"}, "cid=?", new String[]{cid.toString()}, null, null, null);
851 boolean is = false;
852 if (cursor.moveToNext()) {
853 is = cursor.getInt(0) > 0;
854 }
855 cursor.close();
856 return is;
857 }
858
859 public void clearBlockedMedia() {
860 SQLiteDatabase db = this.getWritableDatabase();
861 db.execSQL("DELETE FROM cheogram.blocked_media");
862 }
863
864 public void insertWebxdcUpdate(final WebxdcUpdate update) {
865 SQLiteDatabase db = this.getWritableDatabase();
866 db.insertWithOnConflict("cheogram.webxdc_updates", null, update.getContentValues(), SQLiteDatabase.CONFLICT_IGNORE);
867 }
868
869 public WebxdcUpdate findLastWebxdcUpdate(Message message) {
870 SQLiteDatabase db = this.getReadableDatabase();
871 String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent()};
872 Cursor cursor = db.query("cheogram.webxdc_updates", null,
873 Message.CONVERSATION + "=? AND thread=?",
874 selectionArgs, null, null, null);
875 WebxdcUpdate update = null;
876 if (cursor.moveToLast()) {
877 update = new WebxdcUpdate(cursor, cursor.getLong(cursor.getColumnIndex("serial")));
878 }
879 cursor.close();
880 return update;
881 }
882
883 public List<WebxdcUpdate> findWebxdcUpdates(Message message, long serial) {
884 SQLiteDatabase db = this.getReadableDatabase();
885 String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent(), String.valueOf(serial)};
886 Cursor cursor = db.query("cheogram.webxdc_updates", null,
887 Message.CONVERSATION + "=? AND thread=? AND serial>?",
888 selectionArgs, null, null, null);
889 long maxSerial = 0;
890 if (cursor.moveToLast()) {
891 maxSerial = cursor.getLong(cursor.getColumnIndex("serial"));
892 }
893 cursor.moveToFirst();
894 cursor.moveToPrevious();
895
896 List<WebxdcUpdate> updates = new ArrayList<>();
897 while (cursor.moveToNext()) {
898 updates.add(new WebxdcUpdate(cursor, maxSerial));
899 }
900 cursor.close();
901 return updates;
902 }
903
904 public void createConversation(Conversation conversation) {
905 SQLiteDatabase db = this.getWritableDatabase();
906 db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
907 }
908
909 public void createMessage(Message message) {
910 SQLiteDatabase db = this.getWritableDatabase();
911 db.insert(Message.TABLENAME, null, message.getContentValues());
912 db.insert("cheogram." + Message.TABLENAME, null, message.getCheogramContentValues());
913 }
914
915 public void createAccount(Account account) {
916 SQLiteDatabase db = this.getWritableDatabase();
917 db.insert(Account.TABLENAME, null, account.getContentValues());
918 }
919
920 public void insertDiscoveryResult(ServiceDiscoveryResult result) {
921 SQLiteDatabase db = this.getWritableDatabase();
922 db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
923 }
924
925 public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
926 SQLiteDatabase db = this.getReadableDatabase();
927 String[] selectionArgs = {hash, ver};
928 Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
929 ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
930 selectionArgs, null, null, null);
931 if (cursor.getCount() == 0) {
932 cursor.close();
933 return null;
934 }
935 cursor.moveToFirst();
936
937 ServiceDiscoveryResult result = null;
938 try {
939 result = new ServiceDiscoveryResult(cursor);
940 } catch (JSONException e) { /* result is still null */ }
941
942 cursor.close();
943 return result;
944 }
945
946 public void saveResolverResult(String domain, Resolver.Result result) {
947 SQLiteDatabase db = this.getWritableDatabase();
948 ContentValues contentValues = result.toContentValues();
949 contentValues.put(Resolver.Result.DOMAIN, domain);
950 db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
951 }
952
953 public synchronized Resolver.Result findResolverResult(String domain) {
954 SQLiteDatabase db = this.getReadableDatabase();
955 String where = Resolver.Result.DOMAIN + "=?";
956 String[] whereArgs = {domain};
957 final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
958 Resolver.Result result = null;
959 if (cursor != null) {
960 try {
961 if (cursor.moveToFirst()) {
962 result = Resolver.Result.fromCursor(cursor);
963 }
964 } catch (Exception e) {
965 Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
966 return null;
967 } finally {
968 cursor.close();
969 }
970 }
971 return result;
972 }
973
974 public void insertPresenceTemplate(PresenceTemplate template) {
975 SQLiteDatabase db = this.getWritableDatabase();
976 String whereToDelete = PresenceTemplate.MESSAGE + "=?";
977 String[] whereToDeleteArgs = {template.getStatusMessage()};
978 db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
979 db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
980 db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
981 }
982
983 public List<PresenceTemplate> getPresenceTemplates() {
984 ArrayList<PresenceTemplate> templates = new ArrayList<>();
985 SQLiteDatabase db = this.getReadableDatabase();
986 Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
987 while (cursor.moveToNext()) {
988 templates.add(PresenceTemplate.fromCursor(cursor));
989 }
990 cursor.close();
991 return templates;
992 }
993
994 public CopyOnWriteArrayList<Conversation> getConversations(int status) {
995 CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
996 SQLiteDatabase db = this.getReadableDatabase();
997 String[] selectionArgs = {Integer.toString(status)};
998 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
999 + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
1000 + Conversation.CREATED + " desc", selectionArgs);
1001 while (cursor.moveToNext()) {
1002 final Conversation conversation = Conversation.fromCursor(cursor);
1003 if (conversation.getJid() instanceof InvalidJid) {
1004 continue;
1005 }
1006 list.add(conversation);
1007 }
1008 cursor.close();
1009 return list;
1010 }
1011
1012 public ArrayList<Message> getMessages(Conversation conversations, int limit) {
1013 return getMessages(conversations, limit, -1);
1014 }
1015
1016 public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
1017 ArrayList<Message> list = new ArrayList<>();
1018 SQLiteDatabase db = this.getReadableDatabase();
1019 Cursor cursor;
1020 if (timestamp == -1) {
1021 String[] selectionArgs = {conversation.getUuid()};
1022 cursor = db.rawQuery(
1023 "SELECT * FROM " + Message.TABLENAME + " " +
1024 "LEFT JOIN cheogram." + Message.TABLENAME +
1025 " USING (" + Message.UUID + ")" +
1026 "WHERE " + Message.CONVERSATION + "=? " +
1027 "ORDER BY " + Message.TIME_SENT + " DESC " +
1028 "LIMIT " + String.valueOf(limit),
1029 selectionArgs
1030 );
1031 } else {
1032 String[] selectionArgs = {conversation.getUuid(),
1033 Long.toString(timestamp)};
1034 cursor = db.rawQuery(
1035 "SELECT * FROM " + Message.TABLENAME + " " +
1036 "LEFT JOIN cheogram." + Message.TABLENAME +
1037 " USING (" + Message.UUID + ")" +
1038 "WHERE " + Message.CONVERSATION + "=? AND " +
1039 Message.TIME_SENT + "<? " +
1040 "ORDER BY " + Message.TIME_SENT + " DESC " +
1041 "LIMIT " + String.valueOf(limit),
1042 selectionArgs
1043 );
1044 }
1045 CursorUtils.upgradeCursorWindowSize(cursor);
1046 while (cursor.moveToNext()) {
1047 try {
1048 list.add(0, Message.fromCursor(cursor, conversation));
1049 } catch (Exception e) {
1050 Log.e(Config.LOGTAG, "unable to restore message");
1051 }
1052 }
1053 cursor.close();
1054 return list;
1055 }
1056
1057 public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1058 final SQLiteDatabase db = this.getReadableDatabase();
1059 final StringBuilder SQL = new StringBuilder();
1060 final String[] selectionArgs;
1061 SQL.append("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 + " JOIN messages_index ON messages_index.rowid=messages.rowid WHERE " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + "," + Message.ENCRYPTION_PGP + "," + Message.ENCRYPTION_DECRYPTION_FAILED + "," + Message.ENCRYPTION_AXOLOTL_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + "," + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ?");
1062 if (uuid == null) {
1063 selectionArgs = new String[]{FtsUtils.toMatchString(term)};
1064 } else {
1065 selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
1066 SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1067 }
1068 SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1069 Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1070 return db.rawQuery(SQL.toString(), selectionArgs);
1071 }
1072
1073 public List<String> markFileAsDeleted(final File file, final boolean internal) {
1074 SQLiteDatabase db = this.getReadableDatabase();
1075 String selection;
1076 String[] selectionArgs;
1077 if (internal) {
1078 final String name = file.getName();
1079 if (name.endsWith(".pgp")) {
1080 selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
1081 selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
1082 } else {
1083 selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1084 selectionArgs = new String[]{file.getAbsolutePath(), name};
1085 }
1086 } else {
1087 selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1088 selectionArgs = new String[]{file.getAbsolutePath()};
1089 }
1090 final List<String> uuids = new ArrayList<>();
1091 Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
1092 while (cursor != null && cursor.moveToNext()) {
1093 uuids.add(cursor.getString(0));
1094 }
1095 if (cursor != null) {
1096 cursor.close();
1097 }
1098 markFileAsDeleted(uuids);
1099 return uuids;
1100 }
1101
1102 public void markFileAsDeleted(List<String> uuids) {
1103 SQLiteDatabase db = this.getReadableDatabase();
1104 final ContentValues contentValues = new ContentValues();
1105 final String where = Message.UUID + "=?";
1106 contentValues.put(Message.DELETED, 1);
1107 db.beginTransaction();
1108 for (String uuid : uuids) {
1109 db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
1110 }
1111 db.setTransactionSuccessful();
1112 db.endTransaction();
1113 }
1114
1115 public void markFilesAsChanged(List<FilePathInfo> files) {
1116 SQLiteDatabase db = this.getReadableDatabase();
1117 final String where = Message.UUID + "=?";
1118 db.beginTransaction();
1119 for (FilePathInfo info : files) {
1120 final ContentValues contentValues = new ContentValues();
1121 contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1122 db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
1123 }
1124 db.setTransactionSuccessful();
1125 db.endTransaction();
1126 }
1127
1128 public List<FilePathInfo> getFilePathInfo() {
1129 final SQLiteDatabase db = this.getReadableDatabase();
1130 final Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID, Message.RELATIVE_FILE_PATH, Message.DELETED}, "type in (1,2,5) and " + Message.RELATIVE_FILE_PATH + " is not null", null, null, null, null);
1131 final List<FilePathInfo> list = new ArrayList<>();
1132 while (cursor != null && cursor.moveToNext()) {
1133 list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1134 }
1135 if (cursor != null) {
1136 cursor.close();
1137 }
1138 return list;
1139 }
1140
1141 public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1142 SQLiteDatabase db = this.getReadableDatabase();
1143 final String SQL = "select uuid,relativeFilePath from messages where type in (1,2,5) and deleted=0 and " + Message.RELATIVE_FILE_PATH + " is not null and conversationUuid=(select uuid from conversations where accountUuid=? and (contactJid=? or contactJid like ?)) order by timeSent desc";
1144 final String[] args = {account, jid.toString(), jid.toString() + "/%"};
1145 Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1146 List<FilePath> filesPaths = new ArrayList<>();
1147 while (cursor.moveToNext()) {
1148 filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1149 }
1150 cursor.close();
1151 return filesPaths;
1152 }
1153
1154 public static class FilePath {
1155 public final UUID uuid;
1156 public final String path;
1157
1158 private FilePath(String uuid, String path) {
1159 this.uuid = UUID.fromString(uuid);
1160 this.path = path;
1161 }
1162 }
1163
1164 public static class FilePathInfo extends FilePath {
1165 public boolean deleted;
1166
1167 private FilePathInfo(String uuid, String path, boolean deleted) {
1168 super(uuid, path);
1169 this.deleted = deleted;
1170 }
1171
1172 public boolean setDeleted(boolean deleted) {
1173 final boolean changed = deleted != this.deleted;
1174 this.deleted = deleted;
1175 return changed;
1176 }
1177 }
1178
1179 public Conversation findConversation(final Account account, final Jid contactJid) {
1180 SQLiteDatabase db = this.getReadableDatabase();
1181 String[] selectionArgs = {account.getUuid(),
1182 contactJid.asBareJid().toString() + "/%",
1183 contactJid.asBareJid().toString()
1184 };
1185 try(final Cursor cursor = db.query(Conversation.TABLENAME, null,
1186 Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
1187 + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null)) {
1188 if (cursor.getCount() == 0) {
1189 return null;
1190 }
1191 cursor.moveToFirst();
1192 final Conversation conversation = Conversation.fromCursor(cursor);
1193 if (conversation.getJid() instanceof InvalidJid) {
1194 return null;
1195 }
1196 return conversation;
1197 }
1198 }
1199
1200 public void updateConversation(final Conversation conversation) {
1201 final SQLiteDatabase db = this.getWritableDatabase();
1202 final String[] args = {conversation.getUuid()};
1203 db.update(Conversation.TABLENAME, conversation.getContentValues(),
1204 Conversation.UUID + "=?", args);
1205 }
1206
1207 public List<Account> getAccounts() {
1208 SQLiteDatabase db = this.getReadableDatabase();
1209 return getAccounts(db);
1210 }
1211
1212 public List<Jid> getAccountJids(final boolean enabledOnly) {
1213 final SQLiteDatabase db = this.getReadableDatabase();
1214 final List<Jid> jids = new ArrayList<>();
1215 final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
1216 final String where = enabledOnly ? "not options & (1 <<1)" : null;
1217 try (final Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
1218 while (cursor != null && cursor.moveToNext()) {
1219 jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
1220 }
1221 } catch (final Exception e) {
1222 return jids;
1223 }
1224 return jids;
1225 }
1226
1227 private List<Account> getAccounts(SQLiteDatabase db) {
1228 final List<Account> list = new ArrayList<>();
1229 try (final Cursor cursor =
1230 db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1231 while (cursor != null && cursor.moveToNext()) {
1232 list.add(Account.fromCursor(cursor));
1233 }
1234 }
1235 return list;
1236 }
1237
1238 public boolean updateAccount(Account account) {
1239 SQLiteDatabase db = this.getWritableDatabase();
1240 String[] args = {account.getUuid()};
1241 final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1242 return rows == 1;
1243 }
1244
1245 public boolean deleteAccount(Account account) {
1246 SQLiteDatabase db = this.getWritableDatabase();
1247 String[] args = {account.getUuid()};
1248 final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1249 return rows == 1;
1250 }
1251
1252 public boolean updateMessage(Message message, boolean includeBody) {
1253 SQLiteDatabase db = this.getWritableDatabase();
1254 String[] args = {message.getUuid()};
1255 ContentValues contentValues = message.getContentValues();
1256 contentValues.remove(Message.UUID);
1257 if (!includeBody) {
1258 contentValues.remove(Message.BODY);
1259 }
1260 return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1261 db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1262 }
1263
1264 public boolean updateMessage(Message message, String uuid) {
1265 SQLiteDatabase db = this.getWritableDatabase();
1266 String[] args = {uuid};
1267 return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1268 db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1269 }
1270
1271 public void readRoster(Roster roster) {
1272 final SQLiteDatabase db = this.getReadableDatabase();
1273 final String[] args = {roster.getAccount().getUuid()};
1274 try (final Cursor cursor =
1275 db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1276 while (cursor.moveToNext()) {
1277 roster.initContact(Contact.fromCursor(cursor));
1278 }
1279 }
1280 }
1281
1282 public void writeRoster(final Roster roster) {
1283 long start = SystemClock.elapsedRealtime();
1284 final Account account = roster.getAccount();
1285 final SQLiteDatabase db = this.getWritableDatabase();
1286 db.beginTransaction();
1287 for (Contact contact : roster.getContacts()) {
1288 if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1289 db.insert(Contact.TABLENAME, null, contact.getContentValues());
1290 } else {
1291 String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1292 String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1293 db.delete(Contact.TABLENAME, where, whereArgs);
1294 }
1295 }
1296 db.setTransactionSuccessful();
1297 db.endTransaction();
1298 account.setRosterVersion(roster.getVersion());
1299 updateAccount(account);
1300 long duration = SystemClock.elapsedRealtime() - start;
1301 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1302 }
1303
1304 public void deleteMessagesInConversation(Conversation conversation) {
1305 long start = SystemClock.elapsedRealtime();
1306 final SQLiteDatabase db = this.getWritableDatabase();
1307 db.beginTransaction();
1308 final String[] args = {conversation.getUuid()};
1309 int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1310 db.setTransactionSuccessful();
1311 db.endTransaction();
1312 Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1313 }
1314
1315 public void expireOldMessages(long timestamp) {
1316 final String[] args = {String.valueOf(timestamp)};
1317 SQLiteDatabase db = this.getReadableDatabase();
1318 db.beginTransaction();
1319 db.delete(Message.TABLENAME, "timeSent<?", args);
1320 db.setTransactionSuccessful();
1321 db.endTransaction();
1322 }
1323
1324 public MamReference getLastMessageReceived(Account account) {
1325 Cursor cursor = null;
1326 try {
1327 SQLiteDatabase db = this.getReadableDatabase();
1328 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";
1329 String[] args = {account.getUuid()};
1330 cursor = db.rawQuery(sql, args);
1331 if (cursor.getCount() == 0) {
1332 return null;
1333 } else {
1334 cursor.moveToFirst();
1335 return new MamReference(cursor.getLong(0), cursor.getString(1));
1336 }
1337 } catch (Exception e) {
1338 return null;
1339 } finally {
1340 if (cursor != null) {
1341 cursor.close();
1342 }
1343 }
1344 }
1345
1346 public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1347 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";
1348 String[] args = {account.getUuid(), fingerprint};
1349 Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1350 long time;
1351 if (cursor.moveToFirst()) {
1352 time = cursor.getLong(0);
1353 } else {
1354 time = 0;
1355 }
1356 cursor.close();
1357 return time;
1358 }
1359
1360 public MamReference getLastClearDate(Account account) {
1361 SQLiteDatabase db = this.getReadableDatabase();
1362 String[] columns = {Conversation.ATTRIBUTES};
1363 String selection = Conversation.ACCOUNT + "=?";
1364 String[] args = {account.getUuid()};
1365 Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1366 MamReference maxClearDate = new MamReference(0);
1367 while (cursor.moveToNext()) {
1368 try {
1369 final JSONObject o = new JSONObject(cursor.getString(0));
1370 maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1371 } catch (Exception e) {
1372 //ignored
1373 }
1374 }
1375 cursor.close();
1376 return maxClearDate;
1377 }
1378
1379 private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1380 final SQLiteDatabase db = this.getReadableDatabase();
1381 String[] selectionArgs = {account.getUuid(),
1382 contact.getName(),
1383 Integer.toString(contact.getDeviceId())};
1384 return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1385 null,
1386 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1387 + SQLiteAxolotlStore.NAME + " = ? AND "
1388 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1389 selectionArgs,
1390 null, null, null);
1391 }
1392
1393 public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1394 SessionRecord session = null;
1395 Cursor cursor = getCursorForSession(account, contact);
1396 if (cursor.getCount() != 0) {
1397 cursor.moveToFirst();
1398 try {
1399 session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1400 } catch (IOException e) {
1401 cursor.close();
1402 throw new AssertionError(e);
1403 }
1404 }
1405 cursor.close();
1406 return session;
1407 }
1408
1409 public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1410 final SQLiteDatabase db = this.getReadableDatabase();
1411 return getSubDeviceSessions(db, account, contact);
1412 }
1413
1414 private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1415 List<Integer> devices = new ArrayList<>();
1416 String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1417 String[] selectionArgs = {account.getUuid(),
1418 contact.getName()};
1419 Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1420 columns,
1421 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1422 + SQLiteAxolotlStore.NAME + " = ?",
1423 selectionArgs,
1424 null, null, null);
1425
1426 while (cursor.moveToNext()) {
1427 devices.add(cursor.getInt(
1428 cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1429 }
1430
1431 cursor.close();
1432 return devices;
1433 }
1434
1435 public List<String> getKnownSignalAddresses(Account account) {
1436 List<String> addresses = new ArrayList<>();
1437 String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1438 String[] selectionArgs = {account.getUuid()};
1439 Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1440 colums,
1441 SQLiteAxolotlStore.ACCOUNT + " = ?",
1442 selectionArgs,
1443 null, null, null
1444 );
1445 while (cursor.moveToNext()) {
1446 addresses.add(cursor.getString(0));
1447 }
1448 cursor.close();
1449 return addresses;
1450 }
1451
1452 public boolean containsSession(Account account, SignalProtocolAddress contact) {
1453 Cursor cursor = getCursorForSession(account, contact);
1454 int count = cursor.getCount();
1455 cursor.close();
1456 return count != 0;
1457 }
1458
1459 public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1460 SQLiteDatabase db = this.getWritableDatabase();
1461 ContentValues values = new ContentValues();
1462 values.put(SQLiteAxolotlStore.NAME, contact.getName());
1463 values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1464 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1465 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1466 db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1467 }
1468
1469 public void deleteSession(Account account, SignalProtocolAddress contact) {
1470 SQLiteDatabase db = this.getWritableDatabase();
1471 deleteSession(db, account, contact);
1472 }
1473
1474 private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1475 String[] args = {account.getUuid(),
1476 contact.getName(),
1477 Integer.toString(contact.getDeviceId())};
1478 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1479 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1480 + SQLiteAxolotlStore.NAME + " = ? AND "
1481 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1482 args);
1483 }
1484
1485 public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1486 SQLiteDatabase db = this.getWritableDatabase();
1487 String[] args = {account.getUuid(), contact.getName()};
1488 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1489 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1490 + SQLiteAxolotlStore.NAME + " = ?",
1491 args);
1492 }
1493
1494 private Cursor getCursorForPreKey(Account account, int preKeyId) {
1495 SQLiteDatabase db = this.getReadableDatabase();
1496 String[] columns = {SQLiteAxolotlStore.KEY};
1497 String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1498 Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1499 columns,
1500 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1501 + SQLiteAxolotlStore.ID + "=?",
1502 selectionArgs,
1503 null, null, null);
1504
1505 return cursor;
1506 }
1507
1508 public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1509 PreKeyRecord record = null;
1510 Cursor cursor = getCursorForPreKey(account, preKeyId);
1511 if (cursor.getCount() != 0) {
1512 cursor.moveToFirst();
1513 try {
1514 record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1515 } catch (IOException e) {
1516 throw new AssertionError(e);
1517 }
1518 }
1519 cursor.close();
1520 return record;
1521 }
1522
1523 public boolean containsPreKey(Account account, int preKeyId) {
1524 Cursor cursor = getCursorForPreKey(account, preKeyId);
1525 int count = cursor.getCount();
1526 cursor.close();
1527 return count != 0;
1528 }
1529
1530 public void storePreKey(Account account, PreKeyRecord record) {
1531 SQLiteDatabase db = this.getWritableDatabase();
1532 ContentValues values = new ContentValues();
1533 values.put(SQLiteAxolotlStore.ID, record.getId());
1534 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1535 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1536 db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1537 }
1538
1539 public int deletePreKey(Account account, int preKeyId) {
1540 SQLiteDatabase db = this.getWritableDatabase();
1541 String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1542 return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1543 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1544 + SQLiteAxolotlStore.ID + "=?",
1545 args);
1546 }
1547
1548 private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1549 SQLiteDatabase db = this.getReadableDatabase();
1550 String[] columns = {SQLiteAxolotlStore.KEY};
1551 String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1552 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1553 columns,
1554 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1555 selectionArgs,
1556 null, null, null);
1557
1558 return cursor;
1559 }
1560
1561 public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1562 SignedPreKeyRecord record = null;
1563 Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1564 if (cursor.getCount() != 0) {
1565 cursor.moveToFirst();
1566 try {
1567 record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1568 } catch (IOException e) {
1569 throw new AssertionError(e);
1570 }
1571 }
1572 cursor.close();
1573 return record;
1574 }
1575
1576 public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1577 List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1578 SQLiteDatabase db = this.getReadableDatabase();
1579 String[] columns = {SQLiteAxolotlStore.KEY};
1580 String[] selectionArgs = {account.getUuid()};
1581 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1582 columns,
1583 SQLiteAxolotlStore.ACCOUNT + "=?",
1584 selectionArgs,
1585 null, null, null);
1586
1587 while (cursor.moveToNext()) {
1588 try {
1589 prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1590 } catch (IOException ignored) {
1591 }
1592 }
1593 cursor.close();
1594 return prekeys;
1595 }
1596
1597 public int getSignedPreKeysCount(Account account) {
1598 String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1599 String[] selectionArgs = {account.getUuid()};
1600 SQLiteDatabase db = this.getReadableDatabase();
1601 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1602 columns,
1603 SQLiteAxolotlStore.ACCOUNT + "=?",
1604 selectionArgs,
1605 null, null, null);
1606 final int count;
1607 if (cursor.moveToFirst()) {
1608 count = cursor.getInt(0);
1609 } else {
1610 count = 0;
1611 }
1612 cursor.close();
1613 return count;
1614 }
1615
1616 public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1617 Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1618 int count = cursor.getCount();
1619 cursor.close();
1620 return count != 0;
1621 }
1622
1623 public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1624 SQLiteDatabase db = this.getWritableDatabase();
1625 ContentValues values = new ContentValues();
1626 values.put(SQLiteAxolotlStore.ID, record.getId());
1627 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1628 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1629 db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1630 }
1631
1632 public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1633 SQLiteDatabase db = this.getWritableDatabase();
1634 String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1635 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1636 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1637 + SQLiteAxolotlStore.ID + "=?",
1638 args);
1639 }
1640
1641 private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1642 final SQLiteDatabase db = this.getReadableDatabase();
1643 return getIdentityKeyCursor(db, account, name, own);
1644 }
1645
1646 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1647 return getIdentityKeyCursor(db, account, name, own, null);
1648 }
1649
1650 private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1651 final SQLiteDatabase db = this.getReadableDatabase();
1652 return getIdentityKeyCursor(db, account, fingerprint);
1653 }
1654
1655 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1656 return getIdentityKeyCursor(db, account, null, null, fingerprint);
1657 }
1658
1659 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1660 String[] columns = {SQLiteAxolotlStore.TRUST,
1661 SQLiteAxolotlStore.ACTIVE,
1662 SQLiteAxolotlStore.LAST_ACTIVATION,
1663 SQLiteAxolotlStore.KEY};
1664 ArrayList<String> selectionArgs = new ArrayList<>(4);
1665 selectionArgs.add(account.getUuid());
1666 String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1667 if (name != null) {
1668 selectionArgs.add(name);
1669 selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1670 }
1671 if (fingerprint != null) {
1672 selectionArgs.add(fingerprint);
1673 selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1674 }
1675 if (own != null) {
1676 selectionArgs.add(own ? "1" : "0");
1677 selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1678 }
1679 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1680 columns,
1681 selectionString,
1682 selectionArgs.toArray(new String[selectionArgs.size()]),
1683 null, null, null);
1684
1685 return cursor;
1686 }
1687
1688 public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1689 SQLiteDatabase db = getReadableDatabase();
1690 return loadOwnIdentityKeyPair(db, account);
1691 }
1692
1693 private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1694 String name = account.getJid().asBareJid().toString();
1695 IdentityKeyPair identityKeyPair = null;
1696 Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1697 if (cursor.getCount() != 0) {
1698 cursor.moveToFirst();
1699 try {
1700 identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1701 } catch (InvalidKeyException e) {
1702 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1703 }
1704 }
1705 cursor.close();
1706
1707 return identityKeyPair;
1708 }
1709
1710 public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1711 return loadIdentityKeys(account, name, null);
1712 }
1713
1714 public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1715 Set<IdentityKey> identityKeys = new HashSet<>();
1716 Cursor cursor = getIdentityKeyCursor(account, name, false);
1717
1718 while (cursor.moveToNext()) {
1719 if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1720 continue;
1721 }
1722 try {
1723 String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1724 if (key != null) {
1725 identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1726 } else {
1727 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1728 }
1729 } catch (InvalidKeyException e) {
1730 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1731 }
1732 }
1733 cursor.close();
1734
1735 return identityKeys;
1736 }
1737
1738 public long numTrustedKeys(Account account, String name) {
1739 SQLiteDatabase db = getReadableDatabase();
1740 String[] args = {
1741 account.getUuid(),
1742 name,
1743 FingerprintStatus.Trust.TRUSTED.toString(),
1744 FingerprintStatus.Trust.VERIFIED.toString(),
1745 FingerprintStatus.Trust.VERIFIED_X509.toString()
1746 };
1747 return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1748 SQLiteAxolotlStore.ACCOUNT + " = ?"
1749 + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1750 + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1751 + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1752 args
1753 );
1754 }
1755
1756 private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1757 SQLiteDatabase db = this.getWritableDatabase();
1758 ContentValues values = new ContentValues();
1759 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1760 values.put(SQLiteAxolotlStore.NAME, name);
1761 values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1762 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1763 values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1764 values.putAll(status.toContentValues());
1765 String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1766 String[] whereArgs = {account.getUuid(), name, fingerprint};
1767 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1768 if (rows == 0) {
1769 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1770 }
1771 }
1772
1773 public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1774 SQLiteDatabase db = this.getWritableDatabase();
1775 ContentValues values = new ContentValues();
1776 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1777 values.put(SQLiteAxolotlStore.NAME, name);
1778 values.put(SQLiteAxolotlStore.OWN, 0);
1779 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1780 values.putAll(status.toContentValues());
1781 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1782 }
1783
1784 public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1785 Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1786 final FingerprintStatus status;
1787 if (cursor.getCount() > 0) {
1788 cursor.moveToFirst();
1789 status = FingerprintStatus.fromCursor(cursor);
1790 } else {
1791 status = null;
1792 }
1793 cursor.close();
1794 return status;
1795 }
1796
1797 public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1798 SQLiteDatabase db = this.getWritableDatabase();
1799 return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1800 }
1801
1802 private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1803 String[] selectionArgs = {
1804 account.getUuid(),
1805 fingerprint
1806 };
1807 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1808 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1809 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1810 selectionArgs);
1811 return rows == 1;
1812 }
1813
1814 public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1815 SQLiteDatabase db = this.getWritableDatabase();
1816 String[] selectionArgs = {
1817 account.getUuid(),
1818 fingerprint
1819 };
1820 try {
1821 ContentValues values = new ContentValues();
1822 values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1823 return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1824 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1825 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1826 selectionArgs) == 1;
1827 } catch (CertificateEncodingException e) {
1828 Log.d(Config.LOGTAG, "could not encode certificate");
1829 return false;
1830 }
1831 }
1832
1833 public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1834 SQLiteDatabase db = this.getReadableDatabase();
1835 String[] selectionArgs = {
1836 account.getUuid(),
1837 fingerprint
1838 };
1839 String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1840 String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1841 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1842 if (cursor.getCount() < 1) {
1843 return null;
1844 } else {
1845 cursor.moveToFirst();
1846 byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1847 cursor.close();
1848 if (certificate == null || certificate.length == 0) {
1849 return null;
1850 }
1851 try {
1852 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1853 return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1854 } catch (CertificateException e) {
1855 Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1856 return null;
1857 }
1858 }
1859 }
1860
1861 public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1862 storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1863 }
1864
1865 public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1866 storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1867 }
1868
1869
1870 private void recreateAxolotlDb(SQLiteDatabase db) {
1871 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1872 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1873 db.execSQL(CREATE_SESSIONS_STATEMENT);
1874 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1875 db.execSQL(CREATE_PREKEYS_STATEMENT);
1876 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1877 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1878 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1879 db.execSQL(CREATE_IDENTITIES_STATEMENT);
1880 }
1881
1882 public void wipeAxolotlDb(Account account) {
1883 String accountName = account.getUuid();
1884 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1885 SQLiteDatabase db = this.getWritableDatabase();
1886 String[] deleteArgs = {
1887 accountName
1888 };
1889 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1890 SQLiteAxolotlStore.ACCOUNT + " = ?",
1891 deleteArgs);
1892 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1893 SQLiteAxolotlStore.ACCOUNT + " = ?",
1894 deleteArgs);
1895 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1896 SQLiteAxolotlStore.ACCOUNT + " = ?",
1897 deleteArgs);
1898 db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1899 SQLiteAxolotlStore.ACCOUNT + " = ?",
1900 deleteArgs);
1901 }
1902
1903 public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1904 SQLiteDatabase db = this.getReadableDatabase();
1905 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;";
1906 String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1907 Cursor cursor = db.rawQuery(SQL, whereArgs);
1908 ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1909 while (cursor.moveToNext()) {
1910 try {
1911 contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1912 } catch (Exception e) {
1913 Log.d(Config.LOGTAG, e.getMessage());
1914 }
1915 }
1916 cursor.close();
1917 return contacts;
1918 }
1919}