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 if (cid == null) return null;
806
807 SQLiteDatabase db = this.getReadableDatabase();
808 Cursor cursor = db.query("cheogram.cids", new String[]{"path"}, "cid=?", new String[]{cid.toString()}, null, null, null);
809 DownloadableFile f = null;
810 if (cursor.moveToNext()) {
811 f = new DownloadableFile(cursor.getString(0));
812 }
813 cursor.close();
814 return f;
815 }
816
817 public String getUrlForCid(Cid cid) {
818 SQLiteDatabase db = this.getReadableDatabase();
819 Cursor cursor = db.query("cheogram.cids", new String[]{"url"}, "cid=?", new String[]{cid.toString()}, null, null, null);
820 String url = null;
821 if (cursor.moveToNext()) {
822 url = cursor.getString(0);
823 }
824 cursor.close();
825 return url;
826 }
827
828 public void saveCid(Cid cid, File file) {
829 saveCid(cid, file, null);
830 }
831
832 public void saveCid(Cid cid, File file, String url) {
833 SQLiteDatabase db = this.getWritableDatabase();
834 ContentValues cv = new ContentValues();
835 cv.put("cid", cid.toString());
836 if (file != null) cv.put("path", file.getAbsolutePath());
837 if (url != null) cv.put("url", url);
838 if (db.update("cheogram.cids", cv, "cid=?", new String[]{cid.toString()}) < 1) {
839 db.insertWithOnConflict("cheogram.cids", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
840 }
841 }
842
843 public void blockMedia(Cid cid) {
844 SQLiteDatabase db = this.getWritableDatabase();
845 ContentValues cv = new ContentValues();
846 cv.put("cid", cid.toString());
847 db.insertWithOnConflict("cheogram.blocked_media", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
848 }
849
850 public boolean isBlockedMedia(Cid cid) {
851 SQLiteDatabase db = this.getReadableDatabase();
852 Cursor cursor = db.query("cheogram.blocked_media", new String[]{"count(*)"}, "cid=?", new String[]{cid.toString()}, null, null, null);
853 boolean is = false;
854 if (cursor.moveToNext()) {
855 is = cursor.getInt(0) > 0;
856 }
857 cursor.close();
858 return is;
859 }
860
861 public void clearBlockedMedia() {
862 SQLiteDatabase db = this.getWritableDatabase();
863 db.execSQL("DELETE FROM cheogram.blocked_media");
864 }
865
866 public void insertWebxdcUpdate(final WebxdcUpdate update) {
867 SQLiteDatabase db = this.getWritableDatabase();
868 db.insertWithOnConflict("cheogram.webxdc_updates", null, update.getContentValues(), SQLiteDatabase.CONFLICT_IGNORE);
869 }
870
871 public WebxdcUpdate findLastWebxdcUpdate(Message message) {
872 if (message.getThread() == null) {
873 Log.w(Config.LOGTAG, "WebXDC message with no thread!");
874 return null;
875 }
876
877 SQLiteDatabase db = this.getReadableDatabase();
878 String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent()};
879 Cursor cursor = db.query("cheogram.webxdc_updates", null,
880 Message.CONVERSATION + "=? AND thread=?",
881 selectionArgs, null, null, "serial ASC");
882 WebxdcUpdate update = null;
883 if (cursor.moveToLast()) {
884 update = new WebxdcUpdate(cursor, cursor.getLong(cursor.getColumnIndex("serial")));
885 }
886 cursor.close();
887 return update;
888 }
889
890 public List<WebxdcUpdate> findWebxdcUpdates(Message message, long serial) {
891 SQLiteDatabase db = this.getReadableDatabase();
892 String[] selectionArgs = {message.getConversation().getUuid(), message.getThread().getContent(), String.valueOf(serial)};
893 Cursor cursor = db.query("cheogram.webxdc_updates", null,
894 Message.CONVERSATION + "=? AND thread=? AND serial>?",
895 selectionArgs, null, null, "serial ASC");
896 long maxSerial = 0;
897 if (cursor.moveToLast()) {
898 maxSerial = cursor.getLong(cursor.getColumnIndex("serial"));
899 }
900 cursor.moveToFirst();
901 cursor.moveToPrevious();
902
903 List<WebxdcUpdate> updates = new ArrayList<>();
904 while (cursor.moveToNext()) {
905 updates.add(new WebxdcUpdate(cursor, maxSerial));
906 }
907 cursor.close();
908 return updates;
909 }
910
911 public void createConversation(Conversation conversation) {
912 SQLiteDatabase db = this.getWritableDatabase();
913 db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
914 }
915
916 public void createMessage(Message message) {
917 SQLiteDatabase db = this.getWritableDatabase();
918 db.insert(Message.TABLENAME, null, message.getContentValues());
919 db.insert("cheogram." + Message.TABLENAME, null, message.getCheogramContentValues());
920 }
921
922 public void createAccount(Account account) {
923 SQLiteDatabase db = this.getWritableDatabase();
924 db.insert(Account.TABLENAME, null, account.getContentValues());
925 }
926
927 public void insertDiscoveryResult(ServiceDiscoveryResult result) {
928 SQLiteDatabase db = this.getWritableDatabase();
929 db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
930 }
931
932 public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
933 SQLiteDatabase db = this.getReadableDatabase();
934 String[] selectionArgs = {hash, ver};
935 Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
936 ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
937 selectionArgs, null, null, null);
938 if (cursor.getCount() == 0) {
939 cursor.close();
940 return null;
941 }
942 cursor.moveToFirst();
943
944 ServiceDiscoveryResult result = null;
945 try {
946 result = new ServiceDiscoveryResult(cursor);
947 } catch (JSONException e) { /* result is still null */ }
948
949 cursor.close();
950 return result;
951 }
952
953 public void saveResolverResult(String domain, Resolver.Result result) {
954 SQLiteDatabase db = this.getWritableDatabase();
955 ContentValues contentValues = result.toContentValues();
956 contentValues.put(Resolver.Result.DOMAIN, domain);
957 db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
958 }
959
960 public synchronized Resolver.Result findResolverResult(String domain) {
961 SQLiteDatabase db = this.getReadableDatabase();
962 String where = Resolver.Result.DOMAIN + "=?";
963 String[] whereArgs = {domain};
964 final Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
965 Resolver.Result result = null;
966 if (cursor != null) {
967 try {
968 if (cursor.moveToFirst()) {
969 result = Resolver.Result.fromCursor(cursor);
970 }
971 } catch (Exception e) {
972 Log.d(Config.LOGTAG, "unable to find cached resolver result in database " + e.getMessage());
973 return null;
974 } finally {
975 cursor.close();
976 }
977 }
978 return result;
979 }
980
981 public void insertPresenceTemplate(PresenceTemplate template) {
982 SQLiteDatabase db = this.getWritableDatabase();
983 String whereToDelete = PresenceTemplate.MESSAGE + "=?";
984 String[] whereToDeleteArgs = {template.getStatusMessage()};
985 db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
986 db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
987 db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
988 }
989
990 public List<PresenceTemplate> getPresenceTemplates() {
991 ArrayList<PresenceTemplate> templates = new ArrayList<>();
992 SQLiteDatabase db = this.getReadableDatabase();
993 Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
994 while (cursor.moveToNext()) {
995 templates.add(PresenceTemplate.fromCursor(cursor));
996 }
997 cursor.close();
998 return templates;
999 }
1000
1001 public CopyOnWriteArrayList<Conversation> getConversations(int status) {
1002 CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
1003 SQLiteDatabase db = this.getReadableDatabase();
1004 String[] selectionArgs = {Integer.toString(status)};
1005 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
1006 + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
1007 + Conversation.CREATED + " desc", selectionArgs);
1008 while (cursor.moveToNext()) {
1009 final Conversation conversation = Conversation.fromCursor(cursor);
1010 if (conversation.getJid() instanceof InvalidJid) {
1011 continue;
1012 }
1013 list.add(conversation);
1014 }
1015 cursor.close();
1016 return list;
1017 }
1018
1019 public Message getMessage(Conversation conversation, String uuid) {
1020 ArrayList<Message> list = new ArrayList<>();
1021 SQLiteDatabase db = this.getReadableDatabase();
1022 Cursor cursor;
1023 cursor = db.rawQuery(
1024 "SELECT * FROM " + Message.TABLENAME + " " +
1025 "LEFT JOIN cheogram." + Message.TABLENAME +
1026 " USING (" + Message.UUID + ")" +
1027 "WHERE " + Message.UUID + "=?",
1028 new String[]{uuid}
1029 );
1030 while (cursor.moveToNext()) {
1031 try {
1032 return Message.fromCursor(cursor, conversation);
1033 } catch (Exception e) {
1034 Log.e(Config.LOGTAG, "unable to restore message");
1035 }
1036 }
1037 cursor.close();
1038 return null;
1039 }
1040
1041 public ArrayList<Message> getMessages(Conversation conversations, int limit) {
1042 return getMessages(conversations, limit, -1);
1043 }
1044
1045 public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
1046 ArrayList<Message> list = new ArrayList<>();
1047 SQLiteDatabase db = this.getReadableDatabase();
1048 Cursor cursor;
1049 if (timestamp == -1) {
1050 String[] selectionArgs = {conversation.getUuid()};
1051 cursor = db.rawQuery(
1052 "SELECT * FROM " + Message.TABLENAME + " " +
1053 "LEFT JOIN cheogram." + Message.TABLENAME +
1054 " USING (" + Message.UUID + ")" +
1055 "WHERE " + Message.CONVERSATION + "=? " +
1056 "ORDER BY " + Message.TIME_SENT + " DESC " +
1057 "LIMIT " + String.valueOf(limit),
1058 selectionArgs
1059 );
1060 } else {
1061 String[] selectionArgs = {conversation.getUuid(),
1062 Long.toString(timestamp)};
1063 cursor = db.rawQuery(
1064 "SELECT * FROM " + Message.TABLENAME + " " +
1065 "LEFT JOIN cheogram." + Message.TABLENAME +
1066 " USING (" + Message.UUID + ")" +
1067 "WHERE " + Message.CONVERSATION + "=? AND " +
1068 Message.TIME_SENT + "<? " +
1069 "ORDER BY " + Message.TIME_SENT + " DESC " +
1070 "LIMIT " + String.valueOf(limit),
1071 selectionArgs
1072 );
1073 }
1074 CursorUtils.upgradeCursorWindowSize(cursor);
1075 while (cursor.moveToNext()) {
1076 try {
1077 list.add(0, Message.fromCursor(cursor, conversation));
1078 } catch (Exception e) {
1079 Log.e(Config.LOGTAG, "unable to restore message");
1080 }
1081 }
1082 cursor.close();
1083 return list;
1084 }
1085
1086 public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1087 final SQLiteDatabase db = this.getReadableDatabase();
1088 final StringBuilder SQL = new StringBuilder();
1089 final String[] selectionArgs;
1090 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 ?");
1091 if (uuid == null) {
1092 selectionArgs = new String[]{FtsUtils.toMatchString(term)};
1093 } else {
1094 selectionArgs = new String[]{FtsUtils.toMatchString(term), uuid};
1095 SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1096 }
1097 SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1098 Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1099 return db.rawQuery(SQL.toString(), selectionArgs);
1100 }
1101
1102 public List<String> markFileAsDeleted(final File file, final boolean internal) {
1103 SQLiteDatabase db = this.getReadableDatabase();
1104 String selection;
1105 String[] selectionArgs;
1106 if (internal) {
1107 final String name = file.getName();
1108 if (name.endsWith(".pgp")) {
1109 selection = "(" + Message.RELATIVE_FILE_PATH + " IN(?,?) OR (" + Message.RELATIVE_FILE_PATH + "=? and encryption in(1,4))) and type in (1,2,5)";
1110 selectionArgs = new String[]{file.getAbsolutePath(), name, name.substring(0, name.length() - 4)};
1111 } else {
1112 selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1113 selectionArgs = new String[]{file.getAbsolutePath(), name};
1114 }
1115 } else {
1116 selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1117 selectionArgs = new String[]{file.getAbsolutePath()};
1118 }
1119 final List<String> uuids = new ArrayList<>();
1120 Cursor cursor = db.query(Message.TABLENAME, new String[]{Message.UUID}, selection, selectionArgs, null, null, null);
1121 while (cursor != null && cursor.moveToNext()) {
1122 uuids.add(cursor.getString(0));
1123 }
1124 if (cursor != null) {
1125 cursor.close();
1126 }
1127 markFileAsDeleted(uuids);
1128 return uuids;
1129 }
1130
1131 public void markFileAsDeleted(List<String> uuids) {
1132 SQLiteDatabase db = this.getReadableDatabase();
1133 final ContentValues contentValues = new ContentValues();
1134 final String where = Message.UUID + "=?";
1135 contentValues.put(Message.DELETED, 1);
1136 db.beginTransaction();
1137 for (String uuid : uuids) {
1138 db.update(Message.TABLENAME, contentValues, where, new String[]{uuid});
1139 }
1140 db.setTransactionSuccessful();
1141 db.endTransaction();
1142 }
1143
1144 public void markFilesAsChanged(List<FilePathInfo> files) {
1145 SQLiteDatabase db = this.getReadableDatabase();
1146 final String where = Message.UUID + "=?";
1147 db.beginTransaction();
1148 for (FilePathInfo info : files) {
1149 final ContentValues contentValues = new ContentValues();
1150 contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1151 db.update(Message.TABLENAME, contentValues, where, new String[]{info.uuid.toString()});
1152 }
1153 db.setTransactionSuccessful();
1154 db.endTransaction();
1155 }
1156
1157 public List<FilePathInfo> getFilePathInfo() {
1158 final SQLiteDatabase db = this.getReadableDatabase();
1159 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);
1160 final List<FilePathInfo> list = new ArrayList<>();
1161 while (cursor != null && cursor.moveToNext()) {
1162 list.add(new FilePathInfo(cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1163 }
1164 if (cursor != null) {
1165 cursor.close();
1166 }
1167 return list;
1168 }
1169
1170 public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1171 SQLiteDatabase db = this.getReadableDatabase();
1172 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";
1173 final String[] args = {account, jid.toString(), jid.toString() + "/%"};
1174 Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1175 List<FilePath> filesPaths = new ArrayList<>();
1176 while (cursor.moveToNext()) {
1177 filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1178 }
1179 cursor.close();
1180 return filesPaths;
1181 }
1182
1183 public static class FilePath {
1184 public final UUID uuid;
1185 public final String path;
1186
1187 private FilePath(String uuid, String path) {
1188 this.uuid = UUID.fromString(uuid);
1189 this.path = path;
1190 }
1191 }
1192
1193 public static class FilePathInfo extends FilePath {
1194 public boolean deleted;
1195
1196 private FilePathInfo(String uuid, String path, boolean deleted) {
1197 super(uuid, path);
1198 this.deleted = deleted;
1199 }
1200
1201 public boolean setDeleted(boolean deleted) {
1202 final boolean changed = deleted != this.deleted;
1203 this.deleted = deleted;
1204 return changed;
1205 }
1206 }
1207
1208 public Conversation findConversation(final Account account, final Jid contactJid) {
1209 SQLiteDatabase db = this.getReadableDatabase();
1210 String[] selectionArgs = {account.getUuid(),
1211 contactJid.asBareJid().toString() + "/%",
1212 contactJid.asBareJid().toString()
1213 };
1214 try(final Cursor cursor = db.query(Conversation.TABLENAME, null,
1215 Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
1216 + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null)) {
1217 if (cursor.getCount() == 0) {
1218 return null;
1219 }
1220 cursor.moveToFirst();
1221 final Conversation conversation = Conversation.fromCursor(cursor);
1222 if (conversation.getJid() instanceof InvalidJid) {
1223 return null;
1224 }
1225 return conversation;
1226 }
1227 }
1228
1229 public void updateConversation(final Conversation conversation) {
1230 final SQLiteDatabase db = this.getWritableDatabase();
1231 final String[] args = {conversation.getUuid()};
1232 db.update(Conversation.TABLENAME, conversation.getContentValues(),
1233 Conversation.UUID + "=?", args);
1234 }
1235
1236 public List<Account> getAccounts() {
1237 SQLiteDatabase db = this.getReadableDatabase();
1238 return getAccounts(db);
1239 }
1240
1241 public List<Jid> getAccountJids(final boolean enabledOnly) {
1242 final SQLiteDatabase db = this.getReadableDatabase();
1243 final List<Jid> jids = new ArrayList<>();
1244 final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
1245 final String where = enabledOnly ? "not options & (1 <<1)" : null;
1246 try (final Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
1247 while (cursor != null && cursor.moveToNext()) {
1248 jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
1249 }
1250 } catch (final Exception e) {
1251 return jids;
1252 }
1253 return jids;
1254 }
1255
1256 private List<Account> getAccounts(SQLiteDatabase db) {
1257 final List<Account> list = new ArrayList<>();
1258 try (final Cursor cursor =
1259 db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1260 while (cursor != null && cursor.moveToNext()) {
1261 list.add(Account.fromCursor(cursor));
1262 }
1263 }
1264 return list;
1265 }
1266
1267 public boolean updateAccount(Account account) {
1268 SQLiteDatabase db = this.getWritableDatabase();
1269 String[] args = {account.getUuid()};
1270 final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1271 return rows == 1;
1272 }
1273
1274 public boolean deleteAccount(Account account) {
1275 SQLiteDatabase db = this.getWritableDatabase();
1276 String[] args = {account.getUuid()};
1277 final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1278 return rows == 1;
1279 }
1280
1281 public boolean updateMessage(Message message, boolean includeBody) {
1282 SQLiteDatabase db = this.getWritableDatabase();
1283 String[] args = {message.getUuid()};
1284 ContentValues contentValues = message.getContentValues();
1285 contentValues.remove(Message.UUID);
1286 if (!includeBody) {
1287 contentValues.remove(Message.BODY);
1288 }
1289 return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1290 db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1291 }
1292
1293 public boolean updateMessage(Message message, String uuid) {
1294 SQLiteDatabase db = this.getWritableDatabase();
1295 String[] args = {uuid};
1296 return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1 &&
1297 db.update("cheogram." + Message.TABLENAME, message.getCheogramContentValues(), Message.UUID + "=?", args) == 1;
1298 }
1299
1300 public void readRoster(Roster roster) {
1301 final SQLiteDatabase db = this.getReadableDatabase();
1302 final String[] args = {roster.getAccount().getUuid()};
1303 try (final Cursor cursor =
1304 db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1305 while (cursor.moveToNext()) {
1306 roster.initContact(Contact.fromCursor(cursor));
1307 }
1308 }
1309 }
1310
1311 public void writeRoster(final Roster roster) {
1312 long start = SystemClock.elapsedRealtime();
1313 final Account account = roster.getAccount();
1314 final SQLiteDatabase db = this.getWritableDatabase();
1315 db.beginTransaction();
1316 for (Contact contact : roster.getContacts()) {
1317 if (contact.getOption(Contact.Options.IN_ROSTER) || contact.hasAvatarOrPresenceName() || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1318 db.insert(Contact.TABLENAME, null, contact.getContentValues());
1319 } else {
1320 String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1321 String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1322 db.delete(Contact.TABLENAME, where, whereArgs);
1323 }
1324 }
1325 db.setTransactionSuccessful();
1326 db.endTransaction();
1327 account.setRosterVersion(roster.getVersion());
1328 updateAccount(account);
1329 long duration = SystemClock.elapsedRealtime() - start;
1330 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1331 }
1332
1333 public void deleteMessagesInConversation(Conversation conversation) {
1334 long start = SystemClock.elapsedRealtime();
1335 final SQLiteDatabase db = this.getWritableDatabase();
1336 db.beginTransaction();
1337 final String[] args = {conversation.getUuid()};
1338 int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1339 db.delete("cheogram.webxdc_updates", Message.CONVERSATION + "=?", args);
1340 db.setTransactionSuccessful();
1341 db.endTransaction();
1342 Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
1343 }
1344
1345 public void expireOldMessages(long timestamp) {
1346 final String[] args = {String.valueOf(timestamp)};
1347 SQLiteDatabase db = this.getReadableDatabase();
1348 db.beginTransaction();
1349 db.delete(Message.TABLENAME, "timeSent<?", args);
1350 db.setTransactionSuccessful();
1351 db.endTransaction();
1352 }
1353
1354 public MamReference getLastMessageReceived(Account account) {
1355 Cursor cursor = null;
1356 try {
1357 SQLiteDatabase db = this.getReadableDatabase();
1358 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";
1359 String[] args = {account.getUuid()};
1360 cursor = db.rawQuery(sql, args);
1361 if (cursor.getCount() == 0) {
1362 return null;
1363 } else {
1364 cursor.moveToFirst();
1365 return new MamReference(cursor.getLong(0), cursor.getString(1));
1366 }
1367 } catch (Exception e) {
1368 return null;
1369 } finally {
1370 if (cursor != null) {
1371 cursor.close();
1372 }
1373 }
1374 }
1375
1376 public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1377 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";
1378 String[] args = {account.getUuid(), fingerprint};
1379 Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1380 long time;
1381 if (cursor.moveToFirst()) {
1382 time = cursor.getLong(0);
1383 } else {
1384 time = 0;
1385 }
1386 cursor.close();
1387 return time;
1388 }
1389
1390 public MamReference getLastClearDate(Account account) {
1391 SQLiteDatabase db = this.getReadableDatabase();
1392 String[] columns = {Conversation.ATTRIBUTES};
1393 String selection = Conversation.ACCOUNT + "=?";
1394 String[] args = {account.getUuid()};
1395 Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1396 MamReference maxClearDate = new MamReference(0);
1397 while (cursor.moveToNext()) {
1398 try {
1399 final JSONObject o = new JSONObject(cursor.getString(0));
1400 maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1401 } catch (Exception e) {
1402 //ignored
1403 }
1404 }
1405 cursor.close();
1406 return maxClearDate;
1407 }
1408
1409 private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1410 final SQLiteDatabase db = this.getReadableDatabase();
1411 String[] selectionArgs = {account.getUuid(),
1412 contact.getName(),
1413 Integer.toString(contact.getDeviceId())};
1414 return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1415 null,
1416 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1417 + SQLiteAxolotlStore.NAME + " = ? AND "
1418 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1419 selectionArgs,
1420 null, null, null);
1421 }
1422
1423 public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1424 SessionRecord session = null;
1425 Cursor cursor = getCursorForSession(account, contact);
1426 if (cursor.getCount() != 0) {
1427 cursor.moveToFirst();
1428 try {
1429 session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1430 } catch (IOException e) {
1431 cursor.close();
1432 throw new AssertionError(e);
1433 }
1434 }
1435 cursor.close();
1436 return session;
1437 }
1438
1439 public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1440 final SQLiteDatabase db = this.getReadableDatabase();
1441 return getSubDeviceSessions(db, account, contact);
1442 }
1443
1444 private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1445 List<Integer> devices = new ArrayList<>();
1446 String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1447 String[] selectionArgs = {account.getUuid(),
1448 contact.getName()};
1449 Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1450 columns,
1451 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1452 + SQLiteAxolotlStore.NAME + " = ?",
1453 selectionArgs,
1454 null, null, null);
1455
1456 while (cursor.moveToNext()) {
1457 devices.add(cursor.getInt(
1458 cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1459 }
1460
1461 cursor.close();
1462 return devices;
1463 }
1464
1465 public List<String> getKnownSignalAddresses(Account account) {
1466 List<String> addresses = new ArrayList<>();
1467 String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1468 String[] selectionArgs = {account.getUuid()};
1469 Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1470 colums,
1471 SQLiteAxolotlStore.ACCOUNT + " = ?",
1472 selectionArgs,
1473 null, null, null
1474 );
1475 while (cursor.moveToNext()) {
1476 addresses.add(cursor.getString(0));
1477 }
1478 cursor.close();
1479 return addresses;
1480 }
1481
1482 public boolean containsSession(Account account, SignalProtocolAddress contact) {
1483 Cursor cursor = getCursorForSession(account, contact);
1484 int count = cursor.getCount();
1485 cursor.close();
1486 return count != 0;
1487 }
1488
1489 public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1490 SQLiteDatabase db = this.getWritableDatabase();
1491 ContentValues values = new ContentValues();
1492 values.put(SQLiteAxolotlStore.NAME, contact.getName());
1493 values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1494 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1495 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1496 db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1497 }
1498
1499 public void deleteSession(Account account, SignalProtocolAddress contact) {
1500 SQLiteDatabase db = this.getWritableDatabase();
1501 deleteSession(db, account, contact);
1502 }
1503
1504 private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1505 String[] args = {account.getUuid(),
1506 contact.getName(),
1507 Integer.toString(contact.getDeviceId())};
1508 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1509 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1510 + SQLiteAxolotlStore.NAME + " = ? AND "
1511 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1512 args);
1513 }
1514
1515 public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1516 SQLiteDatabase db = this.getWritableDatabase();
1517 String[] args = {account.getUuid(), contact.getName()};
1518 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1519 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1520 + SQLiteAxolotlStore.NAME + " = ?",
1521 args);
1522 }
1523
1524 private Cursor getCursorForPreKey(Account account, int preKeyId) {
1525 SQLiteDatabase db = this.getReadableDatabase();
1526 String[] columns = {SQLiteAxolotlStore.KEY};
1527 String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1528 Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1529 columns,
1530 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1531 + SQLiteAxolotlStore.ID + "=?",
1532 selectionArgs,
1533 null, null, null);
1534
1535 return cursor;
1536 }
1537
1538 public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1539 PreKeyRecord record = null;
1540 Cursor cursor = getCursorForPreKey(account, preKeyId);
1541 if (cursor.getCount() != 0) {
1542 cursor.moveToFirst();
1543 try {
1544 record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1545 } catch (IOException e) {
1546 throw new AssertionError(e);
1547 }
1548 }
1549 cursor.close();
1550 return record;
1551 }
1552
1553 public boolean containsPreKey(Account account, int preKeyId) {
1554 Cursor cursor = getCursorForPreKey(account, preKeyId);
1555 int count = cursor.getCount();
1556 cursor.close();
1557 return count != 0;
1558 }
1559
1560 public void storePreKey(Account account, PreKeyRecord record) {
1561 SQLiteDatabase db = this.getWritableDatabase();
1562 ContentValues values = new ContentValues();
1563 values.put(SQLiteAxolotlStore.ID, record.getId());
1564 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1565 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1566 db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1567 }
1568
1569 public int deletePreKey(Account account, int preKeyId) {
1570 SQLiteDatabase db = this.getWritableDatabase();
1571 String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1572 return db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1573 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1574 + SQLiteAxolotlStore.ID + "=?",
1575 args);
1576 }
1577
1578 private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1579 SQLiteDatabase db = this.getReadableDatabase();
1580 String[] columns = {SQLiteAxolotlStore.KEY};
1581 String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1582 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1583 columns,
1584 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1585 selectionArgs,
1586 null, null, null);
1587
1588 return cursor;
1589 }
1590
1591 public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1592 SignedPreKeyRecord record = null;
1593 Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1594 if (cursor.getCount() != 0) {
1595 cursor.moveToFirst();
1596 try {
1597 record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1598 } catch (IOException e) {
1599 throw new AssertionError(e);
1600 }
1601 }
1602 cursor.close();
1603 return record;
1604 }
1605
1606 public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1607 List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1608 SQLiteDatabase db = this.getReadableDatabase();
1609 String[] columns = {SQLiteAxolotlStore.KEY};
1610 String[] selectionArgs = {account.getUuid()};
1611 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1612 columns,
1613 SQLiteAxolotlStore.ACCOUNT + "=?",
1614 selectionArgs,
1615 null, null, null);
1616
1617 while (cursor.moveToNext()) {
1618 try {
1619 prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1620 } catch (IOException ignored) {
1621 }
1622 }
1623 cursor.close();
1624 return prekeys;
1625 }
1626
1627 public int getSignedPreKeysCount(Account account) {
1628 String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1629 String[] selectionArgs = {account.getUuid()};
1630 SQLiteDatabase db = this.getReadableDatabase();
1631 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1632 columns,
1633 SQLiteAxolotlStore.ACCOUNT + "=?",
1634 selectionArgs,
1635 null, null, null);
1636 final int count;
1637 if (cursor.moveToFirst()) {
1638 count = cursor.getInt(0);
1639 } else {
1640 count = 0;
1641 }
1642 cursor.close();
1643 return count;
1644 }
1645
1646 public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1647 Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1648 int count = cursor.getCount();
1649 cursor.close();
1650 return count != 0;
1651 }
1652
1653 public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1654 SQLiteDatabase db = this.getWritableDatabase();
1655 ContentValues values = new ContentValues();
1656 values.put(SQLiteAxolotlStore.ID, record.getId());
1657 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1658 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1659 db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1660 }
1661
1662 public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1663 SQLiteDatabase db = this.getWritableDatabase();
1664 String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1665 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1666 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1667 + SQLiteAxolotlStore.ID + "=?",
1668 args);
1669 }
1670
1671 private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1672 final SQLiteDatabase db = this.getReadableDatabase();
1673 return getIdentityKeyCursor(db, account, name, own);
1674 }
1675
1676 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1677 return getIdentityKeyCursor(db, account, name, own, null);
1678 }
1679
1680 private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1681 final SQLiteDatabase db = this.getReadableDatabase();
1682 return getIdentityKeyCursor(db, account, fingerprint);
1683 }
1684
1685 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1686 return getIdentityKeyCursor(db, account, null, null, fingerprint);
1687 }
1688
1689 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1690 String[] columns = {SQLiteAxolotlStore.TRUST,
1691 SQLiteAxolotlStore.ACTIVE,
1692 SQLiteAxolotlStore.LAST_ACTIVATION,
1693 SQLiteAxolotlStore.KEY};
1694 ArrayList<String> selectionArgs = new ArrayList<>(4);
1695 selectionArgs.add(account.getUuid());
1696 String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1697 if (name != null) {
1698 selectionArgs.add(name);
1699 selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1700 }
1701 if (fingerprint != null) {
1702 selectionArgs.add(fingerprint);
1703 selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1704 }
1705 if (own != null) {
1706 selectionArgs.add(own ? "1" : "0");
1707 selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1708 }
1709 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1710 columns,
1711 selectionString,
1712 selectionArgs.toArray(new String[selectionArgs.size()]),
1713 null, null, null);
1714
1715 return cursor;
1716 }
1717
1718 public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1719 SQLiteDatabase db = getReadableDatabase();
1720 return loadOwnIdentityKeyPair(db, account);
1721 }
1722
1723 private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1724 String name = account.getJid().asBareJid().toString();
1725 IdentityKeyPair identityKeyPair = null;
1726 Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1727 if (cursor.getCount() != 0) {
1728 cursor.moveToFirst();
1729 try {
1730 identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1731 } catch (InvalidKeyException e) {
1732 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1733 }
1734 }
1735 cursor.close();
1736
1737 return identityKeyPair;
1738 }
1739
1740 public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1741 return loadIdentityKeys(account, name, null);
1742 }
1743
1744 public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1745 Set<IdentityKey> identityKeys = new HashSet<>();
1746 Cursor cursor = getIdentityKeyCursor(account, name, false);
1747
1748 while (cursor.moveToNext()) {
1749 if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1750 continue;
1751 }
1752 try {
1753 String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1754 if (key != null) {
1755 identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1756 } else {
1757 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1758 }
1759 } catch (InvalidKeyException e) {
1760 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1761 }
1762 }
1763 cursor.close();
1764
1765 return identityKeys;
1766 }
1767
1768 public long numTrustedKeys(Account account, String name) {
1769 SQLiteDatabase db = getReadableDatabase();
1770 String[] args = {
1771 account.getUuid(),
1772 name,
1773 FingerprintStatus.Trust.TRUSTED.toString(),
1774 FingerprintStatus.Trust.VERIFIED.toString(),
1775 FingerprintStatus.Trust.VERIFIED_X509.toString()
1776 };
1777 return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1778 SQLiteAxolotlStore.ACCOUNT + " = ?"
1779 + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1780 + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1781 + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1782 args
1783 );
1784 }
1785
1786 private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1787 SQLiteDatabase db = this.getWritableDatabase();
1788 ContentValues values = new ContentValues();
1789 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1790 values.put(SQLiteAxolotlStore.NAME, name);
1791 values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1792 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1793 values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1794 values.putAll(status.toContentValues());
1795 String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1796 String[] whereArgs = {account.getUuid(), name, fingerprint};
1797 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1798 if (rows == 0) {
1799 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1800 }
1801 }
1802
1803 public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1804 SQLiteDatabase db = this.getWritableDatabase();
1805 ContentValues values = new ContentValues();
1806 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1807 values.put(SQLiteAxolotlStore.NAME, name);
1808 values.put(SQLiteAxolotlStore.OWN, 0);
1809 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1810 values.putAll(status.toContentValues());
1811 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1812 }
1813
1814 public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1815 Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1816 final FingerprintStatus status;
1817 if (cursor.getCount() > 0) {
1818 cursor.moveToFirst();
1819 status = FingerprintStatus.fromCursor(cursor);
1820 } else {
1821 status = null;
1822 }
1823 cursor.close();
1824 return status;
1825 }
1826
1827 public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1828 SQLiteDatabase db = this.getWritableDatabase();
1829 return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1830 }
1831
1832 private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1833 String[] selectionArgs = {
1834 account.getUuid(),
1835 fingerprint
1836 };
1837 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1838 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1839 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1840 selectionArgs);
1841 return rows == 1;
1842 }
1843
1844 public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1845 SQLiteDatabase db = this.getWritableDatabase();
1846 String[] selectionArgs = {
1847 account.getUuid(),
1848 fingerprint
1849 };
1850 try {
1851 ContentValues values = new ContentValues();
1852 values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1853 return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1854 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1855 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1856 selectionArgs) == 1;
1857 } catch (CertificateEncodingException e) {
1858 Log.d(Config.LOGTAG, "could not encode certificate");
1859 return false;
1860 }
1861 }
1862
1863 public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1864 SQLiteDatabase db = this.getReadableDatabase();
1865 String[] selectionArgs = {
1866 account.getUuid(),
1867 fingerprint
1868 };
1869 String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1870 String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1871 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1872 if (cursor.getCount() < 1) {
1873 return null;
1874 } else {
1875 cursor.moveToFirst();
1876 byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1877 cursor.close();
1878 if (certificate == null || certificate.length == 0) {
1879 return null;
1880 }
1881 try {
1882 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1883 return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1884 } catch (CertificateException e) {
1885 Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1886 return null;
1887 }
1888 }
1889 }
1890
1891 public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1892 storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1893 }
1894
1895 public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1896 storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1897 }
1898
1899
1900 private void recreateAxolotlDb(SQLiteDatabase db) {
1901 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1902 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1903 db.execSQL(CREATE_SESSIONS_STATEMENT);
1904 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1905 db.execSQL(CREATE_PREKEYS_STATEMENT);
1906 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1907 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1908 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1909 db.execSQL(CREATE_IDENTITIES_STATEMENT);
1910 }
1911
1912 public void wipeAxolotlDb(Account account) {
1913 String accountName = account.getUuid();
1914 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1915 SQLiteDatabase db = this.getWritableDatabase();
1916 String[] deleteArgs = {
1917 accountName
1918 };
1919 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1920 SQLiteAxolotlStore.ACCOUNT + " = ?",
1921 deleteArgs);
1922 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1923 SQLiteAxolotlStore.ACCOUNT + " = ?",
1924 deleteArgs);
1925 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1926 SQLiteAxolotlStore.ACCOUNT + " = ?",
1927 deleteArgs);
1928 db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1929 SQLiteAxolotlStore.ACCOUNT + " = ?",
1930 deleteArgs);
1931 }
1932
1933 public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1934 SQLiteDatabase db = this.getReadableDatabase();
1935 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;";
1936 String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1937 Cursor cursor = db.rawQuery(SQL, whereArgs);
1938 ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1939 while (cursor.moveToNext()) {
1940 try {
1941 contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1942 } catch (Exception e) {
1943 Log.d(Config.LOGTAG, e.getMessage());
1944 }
1945 }
1946 cursor.close();
1947 return contacts;
1948 }
1949}