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;
13import com.google.common.base.Stopwatch;
14import eu.siacs.conversations.Config;
15import eu.siacs.conversations.crypto.axolotl.AxolotlService;
16import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
17import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
18import eu.siacs.conversations.entities.Account;
19import eu.siacs.conversations.entities.Contact;
20import eu.siacs.conversations.entities.Conversation;
21import eu.siacs.conversations.entities.Message;
22import eu.siacs.conversations.entities.PresenceTemplate;
23import eu.siacs.conversations.entities.Roster;
24import eu.siacs.conversations.entities.ServiceDiscoveryResult;
25import eu.siacs.conversations.services.QuickConversationsService;
26import eu.siacs.conversations.services.ShortcutService;
27import eu.siacs.conversations.utils.CryptoHelper;
28import eu.siacs.conversations.utils.CursorUtils;
29import eu.siacs.conversations.utils.FtsUtils;
30import eu.siacs.conversations.utils.MimeUtils;
31import eu.siacs.conversations.utils.Resolver;
32import eu.siacs.conversations.xmpp.Jid;
33import eu.siacs.conversations.xmpp.mam.MamReference;
34import java.io.ByteArrayInputStream;
35import java.io.File;
36import java.io.IOException;
37import java.security.cert.CertificateEncodingException;
38import java.security.cert.CertificateException;
39import java.security.cert.CertificateFactory;
40import java.security.cert.X509Certificate;
41import java.util.ArrayList;
42import java.util.HashMap;
43import java.util.HashSet;
44import java.util.List;
45import java.util.Map;
46import java.util.Set;
47import java.util.UUID;
48import java.util.concurrent.CopyOnWriteArrayList;
49import org.json.JSONException;
50import org.json.JSONObject;
51import org.whispersystems.libsignal.IdentityKey;
52import org.whispersystems.libsignal.IdentityKeyPair;
53import org.whispersystems.libsignal.InvalidKeyException;
54import org.whispersystems.libsignal.SignalProtocolAddress;
55import org.whispersystems.libsignal.state.PreKeyRecord;
56import org.whispersystems.libsignal.state.SessionRecord;
57import org.whispersystems.libsignal.state.SignedPreKeyRecord;
58
59public class DatabaseBackend extends SQLiteOpenHelper {
60
61 private static final String DATABASE_NAME = "history";
62 private static final int DATABASE_VERSION = 52;
63
64 private static boolean requiresMessageIndexRebuild = false;
65 private static DatabaseBackend instance = null;
66 private static final String CREATE_CONTATCS_STATEMENT =
67 "create table "
68 + Contact.TABLENAME
69 + "("
70 + Contact.ACCOUNT
71 + " TEXT, "
72 + Contact.SERVERNAME
73 + " TEXT, "
74 + Contact.SYSTEMNAME
75 + " TEXT,"
76 + Contact.PRESENCE_NAME
77 + " TEXT,"
78 + Contact.JID
79 + " TEXT,"
80 + Contact.KEYS
81 + " TEXT,"
82 + Contact.PHOTOURI
83 + " TEXT,"
84 + Contact.OPTIONS
85 + " NUMBER,"
86 + Contact.SYSTEMACCOUNT
87 + " NUMBER, "
88 + Contact.AVATAR
89 + " TEXT, "
90 + Contact.LAST_PRESENCE
91 + " TEXT, "
92 + Contact.LAST_TIME
93 + " NUMBER, "
94 + Contact.RTP_CAPABILITY
95 + " TEXT,"
96 + Contact.GROUPS
97 + " TEXT, FOREIGN KEY("
98 + Contact.ACCOUNT
99 + ") REFERENCES "
100 + Account.TABLENAME
101 + "("
102 + Account.UUID
103 + ") ON DELETE CASCADE, UNIQUE("
104 + Contact.ACCOUNT
105 + ", "
106 + Contact.JID
107 + ") ON CONFLICT REPLACE);";
108
109 private static final String CREATE_DISCOVERY_RESULTS_STATEMENT =
110 "create table "
111 + ServiceDiscoveryResult.TABLENAME
112 + "("
113 + ServiceDiscoveryResult.HASH
114 + " TEXT, "
115 + ServiceDiscoveryResult.VER
116 + " TEXT, "
117 + ServiceDiscoveryResult.RESULT
118 + " TEXT, "
119 + "UNIQUE("
120 + ServiceDiscoveryResult.HASH
121 + ", "
122 + ServiceDiscoveryResult.VER
123 + ") ON CONFLICT REPLACE);";
124
125 private static final String CREATE_PRESENCE_TEMPLATES_STATEMENT =
126 "CREATE TABLE "
127 + PresenceTemplate.TABELNAME
128 + "("
129 + PresenceTemplate.UUID
130 + " TEXT, "
131 + PresenceTemplate.LAST_USED
132 + " NUMBER,"
133 + PresenceTemplate.MESSAGE
134 + " TEXT,"
135 + PresenceTemplate.STATUS
136 + " TEXT,"
137 + "UNIQUE("
138 + PresenceTemplate.MESSAGE
139 + ","
140 + PresenceTemplate.STATUS
141 + ") ON CONFLICT REPLACE);";
142
143 private static final String CREATE_PREKEYS_STATEMENT =
144 "CREATE TABLE "
145 + SQLiteAxolotlStore.PREKEY_TABLENAME
146 + "("
147 + SQLiteAxolotlStore.ACCOUNT
148 + " TEXT, "
149 + SQLiteAxolotlStore.ID
150 + " INTEGER, "
151 + SQLiteAxolotlStore.KEY
152 + " TEXT, FOREIGN KEY("
153 + SQLiteAxolotlStore.ACCOUNT
154 + ") REFERENCES "
155 + Account.TABLENAME
156 + "("
157 + Account.UUID
158 + ") ON DELETE CASCADE, "
159 + "UNIQUE( "
160 + SQLiteAxolotlStore.ACCOUNT
161 + ", "
162 + SQLiteAxolotlStore.ID
163 + ") ON CONFLICT REPLACE"
164 + ");";
165
166 private static final String CREATE_SIGNED_PREKEYS_STATEMENT =
167 "CREATE TABLE "
168 + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME
169 + "("
170 + SQLiteAxolotlStore.ACCOUNT
171 + " TEXT, "
172 + SQLiteAxolotlStore.ID
173 + " INTEGER, "
174 + SQLiteAxolotlStore.KEY
175 + " TEXT, FOREIGN KEY("
176 + SQLiteAxolotlStore.ACCOUNT
177 + ") REFERENCES "
178 + Account.TABLENAME
179 + "("
180 + Account.UUID
181 + ") ON DELETE CASCADE, "
182 + "UNIQUE( "
183 + SQLiteAxolotlStore.ACCOUNT
184 + ", "
185 + SQLiteAxolotlStore.ID
186 + ") ON CONFLICT REPLACE"
187 + ");";
188
189 private static final String CREATE_SESSIONS_STATEMENT =
190 "CREATE TABLE "
191 + SQLiteAxolotlStore.SESSION_TABLENAME
192 + "("
193 + SQLiteAxolotlStore.ACCOUNT
194 + " TEXT, "
195 + SQLiteAxolotlStore.NAME
196 + " TEXT, "
197 + SQLiteAxolotlStore.DEVICE_ID
198 + " INTEGER, "
199 + SQLiteAxolotlStore.KEY
200 + " TEXT, FOREIGN KEY("
201 + SQLiteAxolotlStore.ACCOUNT
202 + ") REFERENCES "
203 + Account.TABLENAME
204 + "("
205 + Account.UUID
206 + ") ON DELETE CASCADE, "
207 + "UNIQUE( "
208 + SQLiteAxolotlStore.ACCOUNT
209 + ", "
210 + SQLiteAxolotlStore.NAME
211 + ", "
212 + SQLiteAxolotlStore.DEVICE_ID
213 + ") ON CONFLICT REPLACE"
214 + ");";
215
216 private static final String CREATE_IDENTITIES_STATEMENT =
217 "CREATE TABLE "
218 + SQLiteAxolotlStore.IDENTITIES_TABLENAME
219 + "("
220 + SQLiteAxolotlStore.ACCOUNT
221 + " TEXT, "
222 + SQLiteAxolotlStore.NAME
223 + " TEXT, "
224 + SQLiteAxolotlStore.OWN
225 + " INTEGER, "
226 + SQLiteAxolotlStore.FINGERPRINT
227 + " TEXT, "
228 + SQLiteAxolotlStore.CERTIFICATE
229 + " BLOB, "
230 + SQLiteAxolotlStore.TRUST
231 + " TEXT, "
232 + SQLiteAxolotlStore.ACTIVE
233 + " NUMBER, "
234 + SQLiteAxolotlStore.LAST_ACTIVATION
235 + " NUMBER,"
236 + SQLiteAxolotlStore.KEY
237 + " TEXT, FOREIGN KEY("
238 + SQLiteAxolotlStore.ACCOUNT
239 + ") REFERENCES "
240 + Account.TABLENAME
241 + "("
242 + Account.UUID
243 + ") ON DELETE CASCADE, "
244 + "UNIQUE( "
245 + SQLiteAxolotlStore.ACCOUNT
246 + ", "
247 + SQLiteAxolotlStore.NAME
248 + ", "
249 + SQLiteAxolotlStore.FINGERPRINT
250 + ") ON CONFLICT IGNORE"
251 + ");";
252
253 private static final String RESOLVER_RESULTS_TABLENAME = "resolver_results";
254
255 private static final String CREATE_RESOLVER_RESULTS_TABLE =
256 "create table "
257 + RESOLVER_RESULTS_TABLENAME
258 + "("
259 + Resolver.Result.DOMAIN
260 + " TEXT,"
261 + Resolver.Result.HOSTNAME
262 + " TEXT,"
263 + Resolver.Result.IP
264 + " BLOB,"
265 + Resolver.Result.PRIORITY
266 + " NUMBER,"
267 + Resolver.Result.DIRECT_TLS
268 + " NUMBER,"
269 + Resolver.Result.AUTHENTICATED
270 + " NUMBER,"
271 + Resolver.Result.PORT
272 + " NUMBER,"
273 + "UNIQUE("
274 + Resolver.Result.DOMAIN
275 + ") ON CONFLICT REPLACE"
276 + ");";
277
278 private static final String CREATE_MESSAGE_TIME_INDEX =
279 "CREATE INDEX message_time_index ON "
280 + Message.TABLENAME
281 + "("
282 + Message.TIME_SENT
283 + ")";
284 private static final String CREATE_MESSAGE_CONVERSATION_INDEX =
285 "CREATE INDEX message_conversation_index ON "
286 + Message.TABLENAME
287 + "("
288 + Message.CONVERSATION
289 + ")";
290 private static final String CREATE_MESSAGE_DELETED_INDEX =
291 "CREATE INDEX message_deleted_index ON "
292 + Message.TABLENAME
293 + "("
294 + Message.DELETED
295 + ")";
296 private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX =
297 "CREATE INDEX message_file_path_index ON "
298 + Message.TABLENAME
299 + "("
300 + Message.RELATIVE_FILE_PATH
301 + ")";
302 private static final String CREATE_MESSAGE_TYPE_INDEX =
303 "CREATE INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
304
305 private static final String CREATE_MESSAGE_INDEX_TABLE =
306 "CREATE VIRTUAL TABLE messages_index USING fts4"
307 + " (uuid,body,notindexed=\"uuid\",content=\""
308 + Message.TABLENAME
309 + "\",tokenize='unicode61')";
310 private static final String CREATE_MESSAGE_INSERT_TRIGGER =
311 "CREATE TRIGGER after_message_insert AFTER INSERT ON "
312 + Message.TABLENAME
313 + " BEGIN INSERT INTO messages_index(rowid,uuid,body)"
314 + " VALUES(NEW.rowid,NEW.uuid,NEW.body); END;";
315 private static final String CREATE_MESSAGE_UPDATE_TRIGGER =
316 "CREATE TRIGGER after_message_update UPDATE OF uuid,body ON "
317 + Message.TABLENAME
318 + " BEGIN UPDATE messages_index SET body=NEW.body,uuid=NEW.uuid WHERE"
319 + " rowid=OLD.rowid; END;";
320 private static final String CREATE_MESSAGE_DELETE_TRIGGER =
321 "CREATE TRIGGER after_message_delete AFTER DELETE ON "
322 + Message.TABLENAME
323 + " BEGIN DELETE FROM messages_index WHERE rowid=OLD.rowid; END;";
324 private static final String COPY_PREEXISTING_ENTRIES =
325 "INSERT INTO messages_index(messages_index) VALUES('rebuild');";
326
327 private DatabaseBackend(Context context) {
328 super(context, DATABASE_NAME, null, DATABASE_VERSION);
329 }
330
331 private static ContentValues createFingerprintStatusContentValues(
332 FingerprintStatus.Trust trust, boolean active) {
333 ContentValues values = new ContentValues();
334 values.put(SQLiteAxolotlStore.TRUST, trust.toString());
335 values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
336 return values;
337 }
338
339 public static boolean requiresMessageIndexRebuild() {
340 return requiresMessageIndexRebuild;
341 }
342
343 public void rebuildMessagesIndex() {
344 final SQLiteDatabase db = getWritableDatabase();
345 final Stopwatch stopwatch = Stopwatch.createStarted();
346 db.execSQL(COPY_PREEXISTING_ENTRIES);
347 Log.d(Config.LOGTAG, "rebuilt message index in " + stopwatch.stop().toString());
348 }
349
350 public static synchronized DatabaseBackend getInstance(Context context) {
351 if (instance == null) {
352 instance = new DatabaseBackend(context);
353 }
354 return instance;
355 }
356
357 @Override
358 public void onConfigure(SQLiteDatabase db) {
359 db.execSQL("PRAGMA foreign_keys=ON");
360 db.rawQuery("PRAGMA secure_delete=ON", null).close();
361 }
362
363 @Override
364 public void onCreate(SQLiteDatabase db) {
365 db.execSQL(
366 "create table "
367 + Account.TABLENAME
368 + "("
369 + Account.UUID
370 + " TEXT PRIMARY KEY,"
371 + Account.USERNAME
372 + " TEXT,"
373 + Account.SERVER
374 + " TEXT,"
375 + Account.PASSWORD
376 + " TEXT,"
377 + Account.DISPLAY_NAME
378 + " TEXT, "
379 + Account.STATUS
380 + " TEXT,"
381 + Account.STATUS_MESSAGE
382 + " TEXT,"
383 + Account.ROSTERVERSION
384 + " TEXT,"
385 + Account.OPTIONS
386 + " NUMBER, "
387 + Account.AVATAR
388 + " TEXT, "
389 + Account.KEYS
390 + " TEXT, "
391 + Account.HOSTNAME
392 + " TEXT, "
393 + Account.RESOURCE
394 + " TEXT,"
395 + Account.PINNED_MECHANISM
396 + " TEXT,"
397 + Account.PINNED_CHANNEL_BINDING
398 + " TEXT,"
399 + Account.FAST_MECHANISM
400 + " TEXT,"
401 + Account.FAST_TOKEN
402 + " TEXT,"
403 + Account.PORT
404 + " NUMBER DEFAULT 5222)");
405 db.execSQL(
406 "create table "
407 + Conversation.TABLENAME
408 + " ("
409 + Conversation.UUID
410 + " TEXT PRIMARY KEY, "
411 + Conversation.NAME
412 + " TEXT, "
413 + Conversation.CONTACT
414 + " TEXT, "
415 + Conversation.ACCOUNT
416 + " TEXT, "
417 + Conversation.CONTACTJID
418 + " TEXT, "
419 + Conversation.CREATED
420 + " NUMBER, "
421 + Conversation.STATUS
422 + " NUMBER, "
423 + Conversation.MODE
424 + " NUMBER, "
425 + Conversation.ATTRIBUTES
426 + " TEXT, FOREIGN KEY("
427 + Conversation.ACCOUNT
428 + ") REFERENCES "
429 + Account.TABLENAME
430 + "("
431 + Account.UUID
432 + ") ON DELETE CASCADE);");
433 db.execSQL(
434 "create table "
435 + Message.TABLENAME
436 + "( "
437 + Message.UUID
438 + " TEXT PRIMARY KEY, "
439 + Message.CONVERSATION
440 + " TEXT, "
441 + Message.TIME_SENT
442 + " NUMBER, "
443 + Message.COUNTERPART
444 + " TEXT, "
445 + Message.TRUE_COUNTERPART
446 + " TEXT,"
447 + Message.BODY
448 + " TEXT, "
449 + Message.ENCRYPTION
450 + " NUMBER, "
451 + Message.STATUS
452 + " NUMBER,"
453 + Message.TYPE
454 + " NUMBER, "
455 + Message.RELATIVE_FILE_PATH
456 + " TEXT, "
457 + Message.SERVER_MSG_ID
458 + " TEXT, "
459 + Message.FINGERPRINT
460 + " TEXT, "
461 + Message.CARBON
462 + " INTEGER, "
463 + Message.EDITED
464 + " TEXT, "
465 + Message.READ
466 + " NUMBER DEFAULT 1, "
467 + Message.OOB
468 + " INTEGER, "
469 + Message.ERROR_MESSAGE
470 + " TEXT,"
471 + Message.READ_BY_MARKERS
472 + " TEXT,"
473 + Message.MARKABLE
474 + " NUMBER DEFAULT 0,"
475 + Message.DELETED
476 + " NUMBER DEFAULT 0,"
477 + Message.BODY_LANGUAGE
478 + " TEXT,"
479 + Message.OCCUPANT_ID
480 + " TEXT,"
481 + Message.REACTIONS
482 + " TEXT,"
483 + Message.REMOTE_MSG_ID
484 + " TEXT, FOREIGN KEY("
485 + Message.CONVERSATION
486 + ") REFERENCES "
487 + Conversation.TABLENAME
488 + "("
489 + Conversation.UUID
490 + ") ON DELETE CASCADE);");
491 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
492 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
493 db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
494 db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
495 db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
496 db.execSQL(CREATE_CONTATCS_STATEMENT);
497 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
498 db.execSQL(CREATE_SESSIONS_STATEMENT);
499 db.execSQL(CREATE_PREKEYS_STATEMENT);
500 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
501 db.execSQL(CREATE_IDENTITIES_STATEMENT);
502 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
503 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
504 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
505 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
506 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
507 db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
508 }
509
510 @Override
511 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
512 if (oldVersion < 2 && newVersion >= 2) {
513 db.execSQL(
514 "update "
515 + Account.TABLENAME
516 + " set "
517 + Account.OPTIONS
518 + " = "
519 + Account.OPTIONS
520 + " | 8");
521 }
522 if (oldVersion < 3 && newVersion >= 3) {
523 db.execSQL(
524 "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.TYPE + " NUMBER");
525 }
526 if (oldVersion < 5 && newVersion >= 5) {
527 db.execSQL("DROP TABLE " + Contact.TABLENAME);
528 db.execSQL(CREATE_CONTATCS_STATEMENT);
529 db.execSQL("UPDATE " + Account.TABLENAME + " SET " + Account.ROSTERVERSION + " = NULL");
530 }
531 if (oldVersion < 6 && newVersion >= 6) {
532 db.execSQL(
533 "ALTER TABLE "
534 + Message.TABLENAME
535 + " ADD COLUMN "
536 + Message.TRUE_COUNTERPART
537 + " TEXT");
538 }
539 if (oldVersion < 7 && newVersion >= 7) {
540 db.execSQL(
541 "ALTER TABLE "
542 + Message.TABLENAME
543 + " ADD COLUMN "
544 + Message.REMOTE_MSG_ID
545 + " TEXT");
546 db.execSQL(
547 "ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.AVATAR + " TEXT");
548 db.execSQL(
549 "ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.AVATAR + " TEXT");
550 }
551 if (oldVersion < 8 && newVersion >= 8) {
552 db.execSQL(
553 "ALTER TABLE "
554 + Conversation.TABLENAME
555 + " ADD COLUMN "
556 + Conversation.ATTRIBUTES
557 + " TEXT");
558 }
559 if (oldVersion < 9 && newVersion >= 9) {
560 db.execSQL(
561 "ALTER TABLE "
562 + Contact.TABLENAME
563 + " ADD COLUMN "
564 + Contact.LAST_TIME
565 + " NUMBER");
566 db.execSQL(
567 "ALTER TABLE "
568 + Contact.TABLENAME
569 + " ADD COLUMN "
570 + Contact.LAST_PRESENCE
571 + " TEXT");
572 }
573 if (oldVersion < 10 && newVersion >= 10) {
574 db.execSQL(
575 "ALTER TABLE "
576 + Message.TABLENAME
577 + " ADD COLUMN "
578 + Message.RELATIVE_FILE_PATH
579 + " TEXT");
580 }
581 if (oldVersion < 11 && newVersion >= 11) {
582 db.execSQL(
583 "ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.GROUPS + " TEXT");
584 db.execSQL("delete from " + Contact.TABLENAME);
585 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
586 }
587 if (oldVersion < 12 && newVersion >= 12) {
588 db.execSQL(
589 "ALTER TABLE "
590 + Message.TABLENAME
591 + " ADD COLUMN "
592 + Message.SERVER_MSG_ID
593 + " TEXT");
594 }
595 if (oldVersion < 13 && newVersion >= 13) {
596 db.execSQL("delete from " + Contact.TABLENAME);
597 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
598 }
599 if (oldVersion < 14 && newVersion >= 14) {
600 canonicalizeJids(db);
601 }
602 if (oldVersion < 15 && newVersion >= 15) {
603 recreateAxolotlDb(db);
604 db.execSQL(
605 "ALTER TABLE "
606 + Message.TABLENAME
607 + " ADD COLUMN "
608 + Message.FINGERPRINT
609 + " TEXT");
610 }
611 if (oldVersion < 16 && newVersion >= 16) {
612 db.execSQL(
613 "ALTER TABLE "
614 + Message.TABLENAME
615 + " ADD COLUMN "
616 + Message.CARBON
617 + " INTEGER");
618 }
619 if (oldVersion < 19 && newVersion >= 19) {
620 db.execSQL(
621 "ALTER TABLE "
622 + Account.TABLENAME
623 + " ADD COLUMN "
624 + Account.DISPLAY_NAME
625 + " TEXT");
626 }
627 if (oldVersion < 20 && newVersion >= 20) {
628 db.execSQL(
629 "ALTER TABLE "
630 + Account.TABLENAME
631 + " ADD COLUMN "
632 + Account.HOSTNAME
633 + " TEXT");
634 db.execSQL(
635 "ALTER TABLE "
636 + Account.TABLENAME
637 + " ADD COLUMN "
638 + Account.PORT
639 + " NUMBER DEFAULT 5222");
640 }
641 if (oldVersion < 26 && newVersion >= 26) {
642 db.execSQL(
643 "ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
644 db.execSQL(
645 "ALTER TABLE "
646 + Account.TABLENAME
647 + " ADD COLUMN "
648 + Account.STATUS_MESSAGE
649 + " TEXT");
650 }
651 if (oldVersion < 40 && newVersion >= 40) {
652 db.execSQL(
653 "ALTER TABLE "
654 + Account.TABLENAME
655 + " ADD COLUMN "
656 + Account.RESOURCE
657 + " TEXT");
658 }
659 /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
660 * depends on account de-serialization.
661 */
662 if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
663 List<Account> accounts = getAccounts(db);
664 for (Account account : accounts) {
665 String ownDeviceIdString =
666 account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
667 if (ownDeviceIdString == null) {
668 continue;
669 }
670 int ownDeviceId = Integer.valueOf(ownDeviceIdString);
671 SignalProtocolAddress ownAddress =
672 new SignalProtocolAddress(
673 account.getJid().asBareJid().toString(), ownDeviceId);
674 deleteSession(db, account, ownAddress);
675 IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
676 if (identityKeyPair != null) {
677 String[] selectionArgs = {
678 account.getUuid(),
679 CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
680 };
681 ContentValues values = new ContentValues();
682 values.put(SQLiteAxolotlStore.TRUSTED, 2);
683 db.update(
684 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
685 values,
686 SQLiteAxolotlStore.ACCOUNT
687 + " = ? AND "
688 + SQLiteAxolotlStore.FINGERPRINT
689 + " = ? ",
690 selectionArgs);
691 } else {
692 Log.d(
693 Config.LOGTAG,
694 account.getJid().asBareJid()
695 + ": could not load own identity key pair");
696 }
697 }
698 }
699 if (oldVersion < 18 && newVersion >= 18) {
700 db.execSQL(
701 "ALTER TABLE "
702 + Message.TABLENAME
703 + " ADD COLUMN "
704 + Message.READ
705 + " NUMBER DEFAULT 1");
706 }
707
708 if (oldVersion < 21 && newVersion >= 21) {
709 List<Account> accounts = getAccounts(db);
710 for (Account account : accounts) {
711 account.unsetPgpSignature();
712 db.update(
713 Account.TABLENAME,
714 account.getContentValues(),
715 Account.UUID + "=?",
716 new String[] {account.getUuid()});
717 }
718 }
719
720 if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
721 db.execSQL(
722 "ALTER TABLE "
723 + SQLiteAxolotlStore.IDENTITIES_TABLENAME
724 + " ADD COLUMN "
725 + SQLiteAxolotlStore.CERTIFICATE);
726 }
727
728 if (oldVersion < 23 && newVersion >= 23) {
729 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
730 }
731
732 if (oldVersion < 24 && newVersion >= 24) {
733 db.execSQL(
734 "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
735 }
736
737 if (oldVersion < 25 && newVersion >= 25) {
738 db.execSQL(
739 "ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
740 }
741
742 if (oldVersion < 26 && newVersion >= 26) {
743 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
744 }
745
746 if (oldVersion < 27 && newVersion >= 27) {
747 db.execSQL("DELETE FROM " + ServiceDiscoveryResult.TABLENAME);
748 }
749
750 if (oldVersion < 28 && newVersion >= 28) {
751 canonicalizeJids(db);
752 }
753
754 if (oldVersion < 29 && newVersion >= 29) {
755 db.execSQL(
756 "ALTER TABLE "
757 + Message.TABLENAME
758 + " ADD COLUMN "
759 + Message.ERROR_MESSAGE
760 + " TEXT");
761 }
762 if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
763 db.execSQL(
764 "ALTER TABLE "
765 + SQLiteAxolotlStore.IDENTITIES_TABLENAME
766 + " ADD COLUMN "
767 + SQLiteAxolotlStore.TRUST
768 + " TEXT");
769 db.execSQL(
770 "ALTER TABLE "
771 + SQLiteAxolotlStore.IDENTITIES_TABLENAME
772 + " ADD COLUMN "
773 + SQLiteAxolotlStore.ACTIVE
774 + " NUMBER");
775 HashMap<Integer, ContentValues> migration = new HashMap<>();
776 migration.put(
777 0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
778 migration.put(
779 1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
780 migration.put(
781 2,
782 createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
783 migration.put(
784 3,
785 createFingerprintStatusContentValues(
786 FingerprintStatus.Trust.COMPROMISED, false));
787 migration.put(
788 4,
789 createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
790 migration.put(
791 5,
792 createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
793 migration.put(
794 6,
795 createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
796 migration.put(
797 7,
798 createFingerprintStatusContentValues(
799 FingerprintStatus.Trust.VERIFIED_X509, true));
800 migration.put(
801 8,
802 createFingerprintStatusContentValues(
803 FingerprintStatus.Trust.VERIFIED_X509, false));
804 for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
805 String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
806 String[] where = {String.valueOf(entry.getKey())};
807 db.update(
808 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
809 entry.getValue(),
810 whereClause,
811 where);
812 }
813 }
814 if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
815 db.execSQL(
816 "ALTER TABLE "
817 + SQLiteAxolotlStore.IDENTITIES_TABLENAME
818 + " ADD COLUMN "
819 + SQLiteAxolotlStore.LAST_ACTIVATION
820 + " NUMBER");
821 ContentValues defaults = new ContentValues();
822 defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
823 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
824 }
825 if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
826 String whereClause = SQLiteAxolotlStore.OWN + "=1";
827 db.update(
828 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
829 createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true),
830 whereClause,
831 null);
832 }
833
834 if (oldVersion < 34 && newVersion >= 34) {
835 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
836
837 final File oldPicturesDirectory =
838 new File(
839 Environment.getExternalStoragePublicDirectory(
840 Environment.DIRECTORY_PICTURES)
841 + "/Conversations/");
842 final File oldFilesDirectory =
843 new File(Environment.getExternalStorageDirectory() + "/Conversations/");
844 final File newFilesDirectory =
845 new File(
846 Environment.getExternalStorageDirectory()
847 + "/Conversations/Media/Conversations Files/");
848 final File newVideosDirectory =
849 new File(
850 Environment.getExternalStorageDirectory()
851 + "/Conversations/Media/Conversations Videos/");
852 if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
853 final File newPicturesDirectory =
854 new File(
855 Environment.getExternalStorageDirectory()
856 + "/Conversations/Media/Conversations Images/");
857 newPicturesDirectory.getParentFile().mkdirs();
858 if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
859 Log.d(
860 Config.LOGTAG,
861 "moved "
862 + oldPicturesDirectory.getAbsolutePath()
863 + " to "
864 + newPicturesDirectory.getAbsolutePath());
865 }
866 }
867 if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
868 newFilesDirectory.mkdirs();
869 newVideosDirectory.mkdirs();
870 final File[] files = oldFilesDirectory.listFiles();
871 if (files == null) {
872 return;
873 }
874 for (File file : files) {
875 if (file.getName().equals(".nomedia")) {
876 if (file.delete()) {
877 Log.d(
878 Config.LOGTAG,
879 "deleted nomedia file in "
880 + oldFilesDirectory.getAbsolutePath());
881 }
882 } else if (file.isFile()) {
883 final String name = file.getName();
884 boolean isVideo = false;
885 int start = name.lastIndexOf('.') + 1;
886 if (start < name.length()) {
887 String mime =
888 MimeUtils.guessMimeTypeFromExtension(name.substring(start));
889 isVideo = mime != null && mime.startsWith("video/");
890 }
891 File dst =
892 new File(
893 (isVideo ? newVideosDirectory : newFilesDirectory)
894 .getAbsolutePath()
895 + "/"
896 + file.getName());
897 if (file.renameTo(dst)) {
898 Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
899 }
900 }
901 }
902 }
903 }
904 if (oldVersion < 35 && newVersion >= 35) {
905 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
906 }
907 if (oldVersion < 36 && newVersion >= 36) {
908 List<Account> accounts = getAccounts(db);
909 for (Account account : accounts) {
910 account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
911 account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
912 db.update(
913 Account.TABLENAME,
914 account.getContentValues(),
915 Account.UUID + "=?",
916 new String[] {account.getUuid()});
917 }
918 }
919
920 if (oldVersion < 37 && newVersion >= 37) {
921 db.execSQL(
922 "ALTER TABLE "
923 + Message.TABLENAME
924 + " ADD COLUMN "
925 + Message.READ_BY_MARKERS
926 + " TEXT");
927 }
928
929 if (oldVersion < 38 && newVersion >= 38) {
930 db.execSQL(
931 "ALTER TABLE "
932 + Message.TABLENAME
933 + " ADD COLUMN "
934 + Message.MARKABLE
935 + " NUMBER DEFAULT 0");
936 }
937
938 if (oldVersion < 39 && newVersion >= 39) {
939 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
940 }
941
942 if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
943 List<Account> accounts = getAccounts(db);
944 for (Account account : accounts) {
945 account.setOption(Account.OPTION_MAGIC_CREATE, true);
946 db.update(
947 Account.TABLENAME,
948 account.getContentValues(),
949 Account.UUID + "=?",
950 new String[] {account.getUuid()});
951 }
952 }
953
954 if (oldVersion < 44 && newVersion >= 44) {
955 db.execSQL(
956 "ALTER TABLE "
957 + Message.TABLENAME
958 + " ADD COLUMN "
959 + Message.DELETED
960 + " NUMBER DEFAULT 0");
961 db.execSQL(CREATE_MESSAGE_DELETED_INDEX);
962 db.execSQL(CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX);
963 db.execSQL(CREATE_MESSAGE_TYPE_INDEX);
964 }
965
966 if (oldVersion < 45 && newVersion >= 45) {
967 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.BODY_LANGUAGE);
968 }
969
970 if (oldVersion < 46 && newVersion >= 46) {
971 final long start = SystemClock.elapsedRealtime();
972 db.rawQuery("PRAGMA secure_delete = FALSE", null).close();
973 db.execSQL("update " + Message.TABLENAME + " set " + Message.EDITED + "=NULL");
974 db.rawQuery("PRAGMA secure_delete=ON", null).close();
975 final long diff = SystemClock.elapsedRealtime() - start;
976 Log.d(Config.LOGTAG, "deleted old edit information in " + diff + "ms");
977 }
978 if (oldVersion < 47 && newVersion >= 47) {
979 db.execSQL(
980 "ALTER TABLE "
981 + Contact.TABLENAME
982 + " ADD COLUMN "
983 + Contact.PRESENCE_NAME
984 + " TEXT");
985 }
986 if (oldVersion < 48 && newVersion >= 48) {
987 db.execSQL(
988 "ALTER TABLE "
989 + Contact.TABLENAME
990 + " ADD COLUMN "
991 + Contact.RTP_CAPABILITY
992 + " TEXT");
993 }
994 if (oldVersion < 49 && newVersion >= 49) {
995 db.beginTransaction();
996 db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
997 db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
998 db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
999 db.execSQL("DROP TABLE IF EXISTS messages_index;");
1000 // a hack that should not be necessary, but
1001 // there was at least one occurence when SQLite failed at this
1002 db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
1003 db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
1004 db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
1005 db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
1006 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
1007 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
1008 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
1009 db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
1010 db.setTransactionSuccessful();
1011 db.endTransaction();
1012 requiresMessageIndexRebuild = true;
1013 }
1014 if (oldVersion < 50 && newVersion >= 50) {
1015 db.execSQL(
1016 "ALTER TABLE "
1017 + Account.TABLENAME
1018 + " ADD COLUMN "
1019 + Account.PINNED_MECHANISM
1020 + " TEXT");
1021 db.execSQL(
1022 "ALTER TABLE "
1023 + Account.TABLENAME
1024 + " ADD COLUMN "
1025 + Account.PINNED_CHANNEL_BINDING
1026 + " TEXT");
1027 }
1028 if (oldVersion < 51 && newVersion >= 51) {
1029 db.execSQL(
1030 "ALTER TABLE "
1031 + Account.TABLENAME
1032 + " ADD COLUMN "
1033 + Account.FAST_MECHANISM
1034 + " TEXT");
1035 db.execSQL(
1036 "ALTER TABLE "
1037 + Account.TABLENAME
1038 + " ADD COLUMN "
1039 + Account.FAST_TOKEN
1040 + " TEXT");
1041 }
1042 if (oldVersion < 52 && newVersion >= 52) {
1043 db.execSQL(
1044 "ALTER TABLE "
1045 + Message.TABLENAME
1046 + " ADD COLUMN "
1047 + Message.OCCUPANT_ID
1048 + " TEXT");
1049 db.execSQL(
1050 "ALTER TABLE "
1051 + Message.TABLENAME
1052 + " ADD COLUMN "
1053 + Message.REACTIONS
1054 + " TEXT");
1055 }
1056 }
1057
1058 private void canonicalizeJids(SQLiteDatabase db) {
1059 // migrate db to new, canonicalized JID domainpart representation
1060
1061 // Conversation table
1062 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
1063 while (cursor.moveToNext()) {
1064 String newJid;
1065 try {
1066 newJid =
1067 Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID)))
1068 .toString();
1069 } catch (IllegalArgumentException ignored) {
1070 Log.e(
1071 Config.LOGTAG,
1072 "Failed to migrate Conversation CONTACTJID "
1073 + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
1074 + ": "
1075 + ignored
1076 + ". Skipping...");
1077 continue;
1078 }
1079
1080 final String[] updateArgs = {
1081 newJid, cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
1082 };
1083 db.execSQL(
1084 "update "
1085 + Conversation.TABLENAME
1086 + " set "
1087 + Conversation.CONTACTJID
1088 + " = ? "
1089 + " where "
1090 + Conversation.UUID
1091 + " = ?",
1092 updateArgs);
1093 }
1094 cursor.close();
1095
1096 // Contact table
1097 cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
1098 while (cursor.moveToNext()) {
1099 String newJid;
1100 try {
1101 newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
1102 } catch (final IllegalArgumentException e) {
1103 Log.e(
1104 Config.LOGTAG,
1105 "Failed to migrate Contact JID "
1106 + cursor.getString(cursor.getColumnIndex(Contact.JID))
1107 + ": Skipping...",
1108 e);
1109 continue;
1110 }
1111
1112 final String[] updateArgs = {
1113 newJid,
1114 cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
1115 cursor.getString(cursor.getColumnIndex(Contact.JID)),
1116 };
1117 db.execSQL(
1118 "update "
1119 + Contact.TABLENAME
1120 + " set "
1121 + Contact.JID
1122 + " = ? "
1123 + " where "
1124 + Contact.ACCOUNT
1125 + " = ? "
1126 + " AND "
1127 + Contact.JID
1128 + " = ?",
1129 updateArgs);
1130 }
1131 cursor.close();
1132
1133 // Account table
1134 cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
1135 while (cursor.moveToNext()) {
1136 String newServer;
1137 try {
1138 newServer =
1139 Jid.of(
1140 cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
1141 cursor.getString(cursor.getColumnIndex(Account.SERVER)),
1142 null)
1143 .getDomain()
1144 .toString();
1145 } catch (IllegalArgumentException ignored) {
1146 Log.e(
1147 Config.LOGTAG,
1148 "Failed to migrate Account SERVER "
1149 + cursor.getString(cursor.getColumnIndex(Account.SERVER))
1150 + ": "
1151 + ignored
1152 + ". Skipping...");
1153 continue;
1154 }
1155
1156 String[] updateArgs = {
1157 newServer, cursor.getString(cursor.getColumnIndex(Account.UUID)),
1158 };
1159 db.execSQL(
1160 "update "
1161 + Account.TABLENAME
1162 + " set "
1163 + Account.SERVER
1164 + " = ? "
1165 + " where "
1166 + Account.UUID
1167 + " = ?",
1168 updateArgs);
1169 }
1170 cursor.close();
1171 }
1172
1173 public void createConversation(Conversation conversation) {
1174 SQLiteDatabase db = this.getWritableDatabase();
1175 db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
1176 }
1177
1178 public void createMessage(Message message) {
1179 SQLiteDatabase db = this.getWritableDatabase();
1180 db.insert(Message.TABLENAME, null, message.getContentValues());
1181 }
1182
1183 public void createAccount(Account account) {
1184 SQLiteDatabase db = this.getWritableDatabase();
1185 db.insert(Account.TABLENAME, null, account.getContentValues());
1186 }
1187
1188 public void insertDiscoveryResult(ServiceDiscoveryResult result) {
1189 SQLiteDatabase db = this.getWritableDatabase();
1190 db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
1191 }
1192
1193 public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
1194 SQLiteDatabase db = this.getReadableDatabase();
1195 String[] selectionArgs = {hash, ver};
1196 Cursor cursor =
1197 db.query(
1198 ServiceDiscoveryResult.TABLENAME,
1199 null,
1200 ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
1201 selectionArgs,
1202 null,
1203 null,
1204 null);
1205 if (cursor.getCount() == 0) {
1206 cursor.close();
1207 return null;
1208 }
1209 cursor.moveToFirst();
1210
1211 ServiceDiscoveryResult result = null;
1212 try {
1213 result = new ServiceDiscoveryResult(cursor);
1214 } catch (JSONException e) {
1215 /* result is still null */
1216 }
1217
1218 cursor.close();
1219 return result;
1220 }
1221
1222 public void saveResolverResult(String domain, Resolver.Result result) {
1223 SQLiteDatabase db = this.getWritableDatabase();
1224 ContentValues contentValues = result.toContentValues();
1225 contentValues.put(Resolver.Result.DOMAIN, domain);
1226 db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
1227 }
1228
1229 public synchronized Resolver.Result findResolverResult(String domain) {
1230 SQLiteDatabase db = this.getReadableDatabase();
1231 String where = Resolver.Result.DOMAIN + "=?";
1232 String[] whereArgs = {domain};
1233 final Cursor cursor =
1234 db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
1235 Resolver.Result result = null;
1236 if (cursor != null) {
1237 try {
1238 if (cursor.moveToFirst()) {
1239 result = Resolver.Result.fromCursor(cursor);
1240 }
1241 } catch (Exception e) {
1242 Log.d(
1243 Config.LOGTAG,
1244 "unable to find cached resolver result in database " + e.getMessage());
1245 return null;
1246 } finally {
1247 cursor.close();
1248 }
1249 }
1250 return result;
1251 }
1252
1253 public void insertPresenceTemplate(PresenceTemplate template) {
1254 SQLiteDatabase db = this.getWritableDatabase();
1255 String whereToDelete = PresenceTemplate.MESSAGE + "=?";
1256 String[] whereToDeleteArgs = {template.getStatusMessage()};
1257 db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
1258 db.delete(
1259 PresenceTemplate.TABELNAME,
1260 PresenceTemplate.UUID
1261 + " not in (select "
1262 + PresenceTemplate.UUID
1263 + " from "
1264 + PresenceTemplate.TABELNAME
1265 + " order by "
1266 + PresenceTemplate.LAST_USED
1267 + " desc limit 9)",
1268 null);
1269 db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
1270 }
1271
1272 public List<PresenceTemplate> getPresenceTemplates() {
1273 ArrayList<PresenceTemplate> templates = new ArrayList<>();
1274 SQLiteDatabase db = this.getReadableDatabase();
1275 Cursor cursor =
1276 db.query(
1277 PresenceTemplate.TABELNAME,
1278 null,
1279 null,
1280 null,
1281 null,
1282 null,
1283 PresenceTemplate.LAST_USED + " desc");
1284 while (cursor.moveToNext()) {
1285 templates.add(PresenceTemplate.fromCursor(cursor));
1286 }
1287 cursor.close();
1288 return templates;
1289 }
1290
1291 public CopyOnWriteArrayList<Conversation> getConversations(int status) {
1292 CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
1293 SQLiteDatabase db = this.getReadableDatabase();
1294 String[] selectionArgs = {Integer.toString(status)};
1295 Cursor cursor =
1296 db.rawQuery(
1297 "select * from "
1298 + Conversation.TABLENAME
1299 + " where "
1300 + Conversation.STATUS
1301 + " = ? and "
1302 + Conversation.CONTACTJID
1303 + " is not null order by "
1304 + Conversation.CREATED
1305 + " desc",
1306 selectionArgs);
1307 while (cursor.moveToNext()) {
1308 final Conversation conversation = Conversation.fromCursor(cursor);
1309 if (conversation.getJid() instanceof Jid.Invalid) {
1310 continue;
1311 }
1312 list.add(conversation);
1313 }
1314 cursor.close();
1315 return list;
1316 }
1317
1318 public ArrayList<Message> getMessages(Conversation conversations, int limit) {
1319 return getMessages(conversations, limit, -1);
1320 }
1321
1322 public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
1323 ArrayList<Message> list = new ArrayList<>();
1324 SQLiteDatabase db = this.getReadableDatabase();
1325 Cursor cursor;
1326 if (timestamp == -1) {
1327 String[] selectionArgs = {conversation.getUuid()};
1328 cursor =
1329 db.query(
1330 Message.TABLENAME,
1331 null,
1332 Message.CONVERSATION + "=?",
1333 selectionArgs,
1334 null,
1335 null,
1336 Message.TIME_SENT + " DESC",
1337 String.valueOf(limit));
1338 } else {
1339 String[] selectionArgs = {conversation.getUuid(), Long.toString(timestamp)};
1340 cursor =
1341 db.query(
1342 Message.TABLENAME,
1343 null,
1344 Message.CONVERSATION + "=? and " + Message.TIME_SENT + "<?",
1345 selectionArgs,
1346 null,
1347 null,
1348 Message.TIME_SENT + " DESC",
1349 String.valueOf(limit));
1350 }
1351 CursorUtils.upgradeCursorWindowSize(cursor);
1352 while (cursor.moveToNext()) {
1353 try {
1354 list.add(0, Message.fromCursor(cursor, conversation));
1355 } catch (final Exception e) {
1356 Log.e(Config.LOGTAG, "unable to restore message", e);
1357 }
1358 }
1359 cursor.close();
1360 return list;
1361 }
1362
1363 public Cursor getMessageSearchCursor(final List<String> term, final String uuid) {
1364 final SQLiteDatabase db = this.getReadableDatabase();
1365 final StringBuilder SQL = new StringBuilder();
1366 final String[] selectionArgs;
1367 SQL.append(
1368 "SELECT "
1369 + Message.TABLENAME
1370 + ".*,"
1371 + Conversation.TABLENAME
1372 + "."
1373 + Conversation.CONTACTJID
1374 + ","
1375 + Conversation.TABLENAME
1376 + "."
1377 + Conversation.ACCOUNT
1378 + ","
1379 + Conversation.TABLENAME
1380 + "."
1381 + Conversation.MODE
1382 + " FROM "
1383 + Message.TABLENAME
1384 + " JOIN "
1385 + Conversation.TABLENAME
1386 + " ON "
1387 + Message.TABLENAME
1388 + "."
1389 + Message.CONVERSATION
1390 + "="
1391 + Conversation.TABLENAME
1392 + "."
1393 + Conversation.UUID
1394 + " JOIN messages_index ON messages_index.rowid=messages.rowid WHERE "
1395 + Message.ENCRYPTION
1396 + " NOT IN("
1397 + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE
1398 + ","
1399 + Message.ENCRYPTION_PGP
1400 + ","
1401 + Message.ENCRYPTION_DECRYPTION_FAILED
1402 + ","
1403 + Message.ENCRYPTION_AXOLOTL_FAILED
1404 + ") AND "
1405 + Message.TYPE
1406 + " IN("
1407 + Message.TYPE_TEXT
1408 + ","
1409 + Message.TYPE_PRIVATE
1410 + ") AND messages_index.body MATCH ?");
1411 if (uuid == null) {
1412 selectionArgs = new String[] {FtsUtils.toMatchString(term)};
1413 } else {
1414 selectionArgs = new String[] {FtsUtils.toMatchString(term), uuid};
1415 SQL.append(" AND " + Conversation.TABLENAME + '.' + Conversation.UUID + "=?");
1416 }
1417 SQL.append(" ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS);
1418 Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
1419 return db.rawQuery(SQL.toString(), selectionArgs);
1420 }
1421
1422 public List<String> markFileAsDeleted(final File file, final boolean internal) {
1423 SQLiteDatabase db = this.getReadableDatabase();
1424 String selection;
1425 String[] selectionArgs;
1426 if (internal) {
1427 final String name = file.getName();
1428 if (name.endsWith(".pgp")) {
1429 selection =
1430 "("
1431 + Message.RELATIVE_FILE_PATH
1432 + " IN(?,?) OR ("
1433 + Message.RELATIVE_FILE_PATH
1434 + "=? and encryption in(1,4))) and type in (1,2,5)";
1435 selectionArgs =
1436 new String[] {
1437 file.getAbsolutePath(), name, name.substring(0, name.length() - 4)
1438 };
1439 } else {
1440 selection = Message.RELATIVE_FILE_PATH + " IN(?,?) and type in (1,2,5)";
1441 selectionArgs = new String[] {file.getAbsolutePath(), name};
1442 }
1443 } else {
1444 selection = Message.RELATIVE_FILE_PATH + "=? and type in (1,2,5)";
1445 selectionArgs = new String[] {file.getAbsolutePath()};
1446 }
1447 final List<String> uuids = new ArrayList<>();
1448 Cursor cursor =
1449 db.query(
1450 Message.TABLENAME,
1451 new String[] {Message.UUID},
1452 selection,
1453 selectionArgs,
1454 null,
1455 null,
1456 null);
1457 while (cursor != null && cursor.moveToNext()) {
1458 uuids.add(cursor.getString(0));
1459 }
1460 if (cursor != null) {
1461 cursor.close();
1462 }
1463 markFileAsDeleted(uuids);
1464 return uuids;
1465 }
1466
1467 public void markFileAsDeleted(List<String> uuids) {
1468 SQLiteDatabase db = this.getReadableDatabase();
1469 final ContentValues contentValues = new ContentValues();
1470 final String where = Message.UUID + "=?";
1471 contentValues.put(Message.DELETED, 1);
1472 db.beginTransaction();
1473 for (String uuid : uuids) {
1474 db.update(Message.TABLENAME, contentValues, where, new String[] {uuid});
1475 }
1476 db.setTransactionSuccessful();
1477 db.endTransaction();
1478 }
1479
1480 public void markFilesAsChanged(List<FilePathInfo> files) {
1481 SQLiteDatabase db = this.getReadableDatabase();
1482 final String where = Message.UUID + "=?";
1483 db.beginTransaction();
1484 for (FilePathInfo info : files) {
1485 final ContentValues contentValues = new ContentValues();
1486 contentValues.put(Message.DELETED, info.deleted ? 1 : 0);
1487 db.update(Message.TABLENAME, contentValues, where, new String[] {info.uuid.toString()});
1488 }
1489 db.setTransactionSuccessful();
1490 db.endTransaction();
1491 }
1492
1493 public List<FilePathInfo> getFilePathInfo() {
1494 final SQLiteDatabase db = this.getReadableDatabase();
1495 final Cursor cursor =
1496 db.query(
1497 Message.TABLENAME,
1498 new String[] {Message.UUID, Message.RELATIVE_FILE_PATH, Message.DELETED},
1499 "type in (1,2,5) and " + Message.RELATIVE_FILE_PATH + " is not null",
1500 null,
1501 null,
1502 null,
1503 null);
1504 final List<FilePathInfo> list = new ArrayList<>();
1505 while (cursor != null && cursor.moveToNext()) {
1506 list.add(
1507 new FilePathInfo(
1508 cursor.getString(0), cursor.getString(1), cursor.getInt(2) > 0));
1509 }
1510 if (cursor != null) {
1511 cursor.close();
1512 }
1513 return list;
1514 }
1515
1516 public List<FilePath> getRelativeFilePaths(String account, Jid jid, int limit) {
1517 SQLiteDatabase db = this.getReadableDatabase();
1518 final String SQL =
1519 "select uuid,relativeFilePath from messages where type in (1,2,5) and deleted=0 and"
1520 + " "
1521 + Message.RELATIVE_FILE_PATH
1522 + " is not null and conversationUuid=(select uuid from conversations where"
1523 + " accountUuid=? and (contactJid=? or contactJid like ?)) order by"
1524 + " timeSent desc";
1525 final String[] args = {account, jid.toString(), jid.toString() + "/%"};
1526 Cursor cursor = db.rawQuery(SQL + (limit > 0 ? " limit " + limit : ""), args);
1527 List<FilePath> filesPaths = new ArrayList<>();
1528 while (cursor.moveToNext()) {
1529 filesPaths.add(new FilePath(cursor.getString(0), cursor.getString(1)));
1530 }
1531 cursor.close();
1532 return filesPaths;
1533 }
1534
1535 public Message getMessageWithServerMsgId(
1536 final Conversation conversation, final String messageId) {
1537 final var db = this.getReadableDatabase();
1538 final String sql =
1539 "select * from messages where conversationUuid=? and serverMsgId=? LIMIT 1";
1540 final String[] args = {conversation.getUuid(), messageId};
1541 final Cursor cursor = db.rawQuery(sql, args);
1542 if (cursor == null) {
1543 return null;
1544 }
1545 final Message message;
1546 if (cursor.moveToFirst()) {
1547 message = Message.fromCursor(cursor, conversation);
1548 } else {
1549 message = null;
1550 }
1551 cursor.close();
1552 return message;
1553 }
1554
1555 public Message getMessageWithUuidOrRemoteId(
1556 final Conversation conversation, final String messageId) {
1557 final var db = this.getReadableDatabase();
1558 final String sql =
1559 "select * from messages where conversationUuid=? and (uuid=? OR remoteMsgId=?)"
1560 + " LIMIT 1";
1561 final String[] args = {conversation.getUuid(), messageId, messageId};
1562 final Cursor cursor = db.rawQuery(sql, args);
1563 if (cursor == null) {
1564 return null;
1565 }
1566 final Message message;
1567 if (cursor.moveToFirst()) {
1568 message = Message.fromCursor(cursor, conversation);
1569 } else {
1570 message = null;
1571 }
1572 cursor.close();
1573 return message;
1574 }
1575
1576 public static class FilePath {
1577 public final UUID uuid;
1578 public final String path;
1579
1580 private FilePath(String uuid, String path) {
1581 this.uuid = UUID.fromString(uuid);
1582 this.path = path;
1583 }
1584 }
1585
1586 public static class FilePathInfo extends FilePath {
1587 public boolean deleted;
1588
1589 private FilePathInfo(String uuid, String path, boolean deleted) {
1590 super(uuid, path);
1591 this.deleted = deleted;
1592 }
1593
1594 public boolean setDeleted(boolean deleted) {
1595 final boolean changed = deleted != this.deleted;
1596 this.deleted = deleted;
1597 return changed;
1598 }
1599 }
1600
1601 public Conversation findConversation(final String uuid) {
1602 final var db = this.getReadableDatabase();
1603 final String[] selectionArgs = {uuid};
1604 try (final Cursor cursor =
1605 db.query(
1606 Conversation.TABLENAME,
1607 null,
1608 Conversation.UUID + "=?",
1609 selectionArgs,
1610 null,
1611 null,
1612 null)) {
1613 if (cursor.getCount() == 0) {
1614 return null;
1615 }
1616 cursor.moveToFirst();
1617 final Conversation conversation = Conversation.fromCursor(cursor);
1618 if (conversation.getJid() instanceof Jid.Invalid) {
1619 return null;
1620 }
1621 return conversation;
1622 }
1623 }
1624
1625 public Conversation findConversation(final Account account, final Jid contactJid) {
1626 final SQLiteDatabase db = this.getReadableDatabase();
1627 final String[] selectionArgs = {
1628 account.getUuid(),
1629 contactJid.asBareJid().toString() + "/%",
1630 contactJid.asBareJid().toString()
1631 };
1632 try (final Cursor cursor =
1633 db.query(
1634 Conversation.TABLENAME,
1635 null,
1636 Conversation.ACCOUNT
1637 + "=? AND ("
1638 + Conversation.CONTACTJID
1639 + " like ? OR "
1640 + Conversation.CONTACTJID
1641 + "=?)",
1642 selectionArgs,
1643 null,
1644 null,
1645 null)) {
1646 if (cursor.getCount() == 0) {
1647 return null;
1648 }
1649 cursor.moveToFirst();
1650 final Conversation conversation = Conversation.fromCursor(cursor);
1651 if (conversation.getJid() instanceof Jid.Invalid) {
1652 return null;
1653 }
1654 conversation.setAccount(account);
1655 return conversation;
1656 }
1657 }
1658
1659 public String findConversationUuid(final Jid account, final Jid jid) {
1660 final SQLiteDatabase db = this.getReadableDatabase();
1661 final String[] selectionArgs = {
1662 account.getLocal(),
1663 account.getDomain().toString(),
1664 jid.asBareJid().toString() + "/%",
1665 jid.asBareJid().toString()
1666 };
1667 try (final Cursor cursor =
1668 db.rawQuery(
1669 "SELECT conversations.uuid FROM conversations JOIN accounts ON"
1670 + " conversations.accountUuid=accounts.uuid WHERE accounts.username=?"
1671 + " AND accounts.server=? AND (contactJid=? OR contactJid LIKE ?)",
1672 selectionArgs)) {
1673 if (cursor.getCount() == 0) {
1674 return null;
1675 }
1676 cursor.moveToFirst();
1677 return cursor.getString(0);
1678 }
1679 }
1680
1681 public void updateConversation(final Conversation conversation) {
1682 final SQLiteDatabase db = this.getWritableDatabase();
1683 final String[] args = {conversation.getUuid()};
1684 db.update(
1685 Conversation.TABLENAME,
1686 conversation.getContentValues(),
1687 Conversation.UUID + "=?",
1688 args);
1689 }
1690
1691 public List<Account> getAccounts() {
1692 SQLiteDatabase db = this.getReadableDatabase();
1693 return getAccounts(db);
1694 }
1695
1696 public List<Jid> getAccountJids(final boolean enabledOnly) {
1697 final SQLiteDatabase db = this.getReadableDatabase();
1698 final List<Jid> jids = new ArrayList<>();
1699 final String[] columns = new String[] {Account.USERNAME, Account.SERVER};
1700 final String where = enabledOnly ? "not options & (1 <<1)" : null;
1701 try (final Cursor cursor =
1702 db.query(Account.TABLENAME, columns, where, null, null, null, null)) {
1703 while (cursor != null && cursor.moveToNext()) {
1704 jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
1705 }
1706 } catch (final Exception e) {
1707 return jids;
1708 }
1709 return jids;
1710 }
1711
1712 private List<Account> getAccounts(SQLiteDatabase db) {
1713 final List<Account> list = new ArrayList<>();
1714 try (final Cursor cursor =
1715 db.query(Account.TABLENAME, null, null, null, null, null, null)) {
1716 while (cursor != null && cursor.moveToNext()) {
1717 list.add(Account.fromCursor(cursor));
1718 }
1719 }
1720 return list;
1721 }
1722
1723 public boolean updateAccount(Account account) {
1724 final var db = this.getWritableDatabase();
1725 final String[] args = {account.getUuid()};
1726 final int rows =
1727 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
1728 return rows == 1;
1729 }
1730
1731 public boolean deleteAccount(final Account account) {
1732 final var db = this.getWritableDatabase();
1733 final String[] args = {account.getUuid()};
1734 final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
1735 return rows == 1;
1736 }
1737
1738 public boolean updateMessage(final Message message, final boolean includeBody) {
1739 final var db = this.getWritableDatabase();
1740 final String[] args = {message.getUuid()};
1741 final var contentValues = message.getContentValues();
1742 contentValues.remove(Message.UUID);
1743 if (!includeBody) {
1744 contentValues.remove(Message.BODY);
1745 }
1746 final int rows = db.update(Message.TABLENAME, contentValues, Message.UUID + "=?", args);
1747 return rows == 1;
1748 }
1749
1750 public boolean updateMessage(final Message message, final String uuid) {
1751 final var db = this.getWritableDatabase();
1752 final String[] args = {uuid};
1753 final int rows =
1754 db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args);
1755 return rows == 1;
1756 }
1757
1758 public void readRoster(Roster roster) {
1759 final SQLiteDatabase db = this.getReadableDatabase();
1760 final String[] args = {roster.getAccount().getUuid()};
1761 try (final Cursor cursor =
1762 db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null)) {
1763 while (cursor.moveToNext()) {
1764 roster.initContact(Contact.fromCursor(cursor));
1765 }
1766 }
1767 }
1768
1769 public void writeRoster(final Roster roster) {
1770 long start = SystemClock.elapsedRealtime();
1771 final Account account = roster.getAccount();
1772 final SQLiteDatabase db = this.getWritableDatabase();
1773 db.beginTransaction();
1774 for (Contact contact : roster.getContacts()) {
1775 if (contact.getOption(Contact.Options.IN_ROSTER)
1776 || contact.hasAvatarOrPresenceName()
1777 || contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1778 db.insert(Contact.TABLENAME, null, contact.getContentValues());
1779 } else {
1780 String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
1781 String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
1782 db.delete(Contact.TABLENAME, where, whereArgs);
1783 }
1784 }
1785 db.setTransactionSuccessful();
1786 db.endTransaction();
1787 account.setRosterVersion(roster.getVersion());
1788 updateAccount(account);
1789 long duration = SystemClock.elapsedRealtime() - start;
1790 Log.d(
1791 Config.LOGTAG,
1792 account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
1793 }
1794
1795 public void deleteMessagesInConversation(Conversation conversation) {
1796 long start = SystemClock.elapsedRealtime();
1797 final SQLiteDatabase db = this.getWritableDatabase();
1798 db.beginTransaction();
1799 final String[] args = {conversation.getUuid()};
1800 int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
1801 db.setTransactionSuccessful();
1802 db.endTransaction();
1803 Log.d(
1804 Config.LOGTAG,
1805 "deleted "
1806 + num
1807 + " messages for "
1808 + conversation.getJid().asBareJid()
1809 + " in "
1810 + (SystemClock.elapsedRealtime() - start)
1811 + "ms");
1812 }
1813
1814 public void expireOldMessages(long timestamp) {
1815 final String[] args = {String.valueOf(timestamp)};
1816 SQLiteDatabase db = this.getReadableDatabase();
1817 db.beginTransaction();
1818 db.delete(Message.TABLENAME, "timeSent<?", args);
1819 db.setTransactionSuccessful();
1820 db.endTransaction();
1821 }
1822
1823 public MamReference getLastMessageReceived(Account account) {
1824 Cursor cursor = null;
1825 try {
1826 SQLiteDatabase db = this.getReadableDatabase();
1827 String sql =
1828 "select messages.timeSent,messages.serverMsgId from accounts join conversations"
1829 + " on accounts.uuid=conversations.accountUuid join messages on"
1830 + " conversations.uuid=messages.conversationUuid where accounts.uuid=? and"
1831 + " (messages.status=0 or messages.carbon=1 or messages.serverMsgId not"
1832 + " null) and (conversations.mode=0 or (messages.serverMsgId not null and"
1833 + " messages.type=4)) order by messages.timesent desc limit 1";
1834 String[] args = {account.getUuid()};
1835 cursor = db.rawQuery(sql, args);
1836 if (cursor.getCount() == 0) {
1837 return null;
1838 } else {
1839 cursor.moveToFirst();
1840 return new MamReference(cursor.getLong(0), cursor.getString(1));
1841 }
1842 } catch (Exception e) {
1843 return null;
1844 } finally {
1845 if (cursor != null) {
1846 cursor.close();
1847 }
1848 }
1849 }
1850
1851 public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
1852 String SQL =
1853 "select messages.timeSent from accounts join conversations on"
1854 + " accounts.uuid=conversations.accountUuid join messages on"
1855 + " conversations.uuid=messages.conversationUuid where accounts.uuid=? and"
1856 + " messages.axolotl_fingerprint=? order by messages.timesent desc limit 1";
1857 String[] args = {account.getUuid(), fingerprint};
1858 Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
1859 long time;
1860 if (cursor.moveToFirst()) {
1861 time = cursor.getLong(0);
1862 } else {
1863 time = 0;
1864 }
1865 cursor.close();
1866 return time;
1867 }
1868
1869 public MamReference getLastClearDate(Account account) {
1870 SQLiteDatabase db = this.getReadableDatabase();
1871 String[] columns = {Conversation.ATTRIBUTES};
1872 String selection = Conversation.ACCOUNT + "=?";
1873 String[] args = {account.getUuid()};
1874 Cursor cursor =
1875 db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
1876 MamReference maxClearDate = new MamReference(0);
1877 while (cursor.moveToNext()) {
1878 try {
1879 final JSONObject o = new JSONObject(cursor.getString(0));
1880 maxClearDate =
1881 MamReference.max(
1882 maxClearDate,
1883 MamReference.fromAttribute(
1884 o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
1885 } catch (Exception e) {
1886 // ignored
1887 }
1888 }
1889 cursor.close();
1890 return maxClearDate;
1891 }
1892
1893 private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
1894 final SQLiteDatabase db = this.getReadableDatabase();
1895 String[] selectionArgs = {
1896 account.getUuid(), contact.getName(), Integer.toString(contact.getDeviceId())
1897 };
1898 return db.query(
1899 SQLiteAxolotlStore.SESSION_TABLENAME,
1900 null,
1901 SQLiteAxolotlStore.ACCOUNT
1902 + " = ? AND "
1903 + SQLiteAxolotlStore.NAME
1904 + " = ? AND "
1905 + SQLiteAxolotlStore.DEVICE_ID
1906 + " = ? ",
1907 selectionArgs,
1908 null,
1909 null,
1910 null);
1911 }
1912
1913 public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
1914 SessionRecord session = null;
1915 Cursor cursor = getCursorForSession(account, contact);
1916 if (cursor.getCount() != 0) {
1917 cursor.moveToFirst();
1918 try {
1919 session =
1920 new SessionRecord(
1921 Base64.decode(
1922 cursor.getString(
1923 cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
1924 Base64.DEFAULT));
1925 } catch (IOException e) {
1926 cursor.close();
1927 throw new AssertionError(e);
1928 }
1929 }
1930 cursor.close();
1931 return session;
1932 }
1933
1934 public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1935 final SQLiteDatabase db = this.getReadableDatabase();
1936 return getSubDeviceSessions(db, account, contact);
1937 }
1938
1939 private List<Integer> getSubDeviceSessions(
1940 SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1941 List<Integer> devices = new ArrayList<>();
1942 String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1943 String[] selectionArgs = {account.getUuid(), contact.getName()};
1944 Cursor cursor =
1945 db.query(
1946 SQLiteAxolotlStore.SESSION_TABLENAME,
1947 columns,
1948 SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.NAME + " = ?",
1949 selectionArgs,
1950 null,
1951 null,
1952 null);
1953
1954 while (cursor.moveToNext()) {
1955 devices.add(cursor.getInt(cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1956 }
1957
1958 cursor.close();
1959 return devices;
1960 }
1961
1962 public List<String> getKnownSignalAddresses(Account account) {
1963 List<String> addresses = new ArrayList<>();
1964 String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1965 String[] selectionArgs = {account.getUuid()};
1966 Cursor cursor =
1967 getReadableDatabase()
1968 .query(
1969 SQLiteAxolotlStore.SESSION_TABLENAME,
1970 colums,
1971 SQLiteAxolotlStore.ACCOUNT + " = ?",
1972 selectionArgs,
1973 null,
1974 null,
1975 null);
1976 while (cursor.moveToNext()) {
1977 addresses.add(cursor.getString(0));
1978 }
1979 cursor.close();
1980 return addresses;
1981 }
1982
1983 public boolean containsSession(Account account, SignalProtocolAddress contact) {
1984 Cursor cursor = getCursorForSession(account, contact);
1985 int count = cursor.getCount();
1986 cursor.close();
1987 return count != 0;
1988 }
1989
1990 public void storeSession(
1991 Account account, SignalProtocolAddress contact, SessionRecord session) {
1992 SQLiteDatabase db = this.getWritableDatabase();
1993 ContentValues values = new ContentValues();
1994 values.put(SQLiteAxolotlStore.NAME, contact.getName());
1995 values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1996 values.put(
1997 SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1998 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1999 db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
2000 }
2001
2002 public void deleteSession(Account account, SignalProtocolAddress contact) {
2003 SQLiteDatabase db = this.getWritableDatabase();
2004 deleteSession(db, account, contact);
2005 }
2006
2007 private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
2008 String[] args = {
2009 account.getUuid(), contact.getName(), Integer.toString(contact.getDeviceId())
2010 };
2011 db.delete(
2012 SQLiteAxolotlStore.SESSION_TABLENAME,
2013 SQLiteAxolotlStore.ACCOUNT
2014 + " = ? AND "
2015 + SQLiteAxolotlStore.NAME
2016 + " = ? AND "
2017 + SQLiteAxolotlStore.DEVICE_ID
2018 + " = ? ",
2019 args);
2020 }
2021
2022 public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
2023 SQLiteDatabase db = this.getWritableDatabase();
2024 String[] args = {account.getUuid(), contact.getName()};
2025 db.delete(
2026 SQLiteAxolotlStore.SESSION_TABLENAME,
2027 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + " = ?",
2028 args);
2029 }
2030
2031 private Cursor getCursorForPreKey(Account account, int preKeyId) {
2032 SQLiteDatabase db = this.getReadableDatabase();
2033 String[] columns = {SQLiteAxolotlStore.KEY};
2034 String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
2035 Cursor cursor =
2036 db.query(
2037 SQLiteAxolotlStore.PREKEY_TABLENAME,
2038 columns,
2039 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2040 selectionArgs,
2041 null,
2042 null,
2043 null);
2044
2045 return cursor;
2046 }
2047
2048 public PreKeyRecord loadPreKey(Account account, int preKeyId) {
2049 PreKeyRecord record = null;
2050 Cursor cursor = getCursorForPreKey(account, preKeyId);
2051 if (cursor.getCount() != 0) {
2052 cursor.moveToFirst();
2053 try {
2054 record =
2055 new PreKeyRecord(
2056 Base64.decode(
2057 cursor.getString(
2058 cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2059 Base64.DEFAULT));
2060 } catch (IOException e) {
2061 throw new AssertionError(e);
2062 }
2063 }
2064 cursor.close();
2065 return record;
2066 }
2067
2068 public boolean containsPreKey(Account account, int preKeyId) {
2069 Cursor cursor = getCursorForPreKey(account, preKeyId);
2070 int count = cursor.getCount();
2071 cursor.close();
2072 return count != 0;
2073 }
2074
2075 public void storePreKey(Account account, PreKeyRecord record) {
2076 SQLiteDatabase db = this.getWritableDatabase();
2077 ContentValues values = new ContentValues();
2078 values.put(SQLiteAxolotlStore.ID, record.getId());
2079 values.put(
2080 SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
2081 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2082 db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
2083 }
2084
2085 public int deletePreKey(Account account, int preKeyId) {
2086 SQLiteDatabase db = this.getWritableDatabase();
2087 String[] args = {account.getUuid(), Integer.toString(preKeyId)};
2088 return db.delete(
2089 SQLiteAxolotlStore.PREKEY_TABLENAME,
2090 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2091 args);
2092 }
2093
2094 private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
2095 SQLiteDatabase db = this.getReadableDatabase();
2096 String[] columns = {SQLiteAxolotlStore.KEY};
2097 String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
2098 Cursor cursor =
2099 db.query(
2100 SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2101 columns,
2102 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2103 selectionArgs,
2104 null,
2105 null,
2106 null);
2107
2108 return cursor;
2109 }
2110
2111 public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
2112 SignedPreKeyRecord record = null;
2113 Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
2114 if (cursor.getCount() != 0) {
2115 cursor.moveToFirst();
2116 try {
2117 record =
2118 new SignedPreKeyRecord(
2119 Base64.decode(
2120 cursor.getString(
2121 cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2122 Base64.DEFAULT));
2123 } catch (IOException e) {
2124 throw new AssertionError(e);
2125 }
2126 }
2127 cursor.close();
2128 return record;
2129 }
2130
2131 public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
2132 List<SignedPreKeyRecord> prekeys = new ArrayList<>();
2133 SQLiteDatabase db = this.getReadableDatabase();
2134 String[] columns = {SQLiteAxolotlStore.KEY};
2135 String[] selectionArgs = {account.getUuid()};
2136 Cursor cursor =
2137 db.query(
2138 SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2139 columns,
2140 SQLiteAxolotlStore.ACCOUNT + "=?",
2141 selectionArgs,
2142 null,
2143 null,
2144 null);
2145
2146 while (cursor.moveToNext()) {
2147 try {
2148 prekeys.add(
2149 new SignedPreKeyRecord(
2150 Base64.decode(
2151 cursor.getString(
2152 cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2153 Base64.DEFAULT)));
2154 } catch (IOException ignored) {
2155 }
2156 }
2157 cursor.close();
2158 return prekeys;
2159 }
2160
2161 public int getSignedPreKeysCount(Account account) {
2162 String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
2163 String[] selectionArgs = {account.getUuid()};
2164 SQLiteDatabase db = this.getReadableDatabase();
2165 Cursor cursor =
2166 db.query(
2167 SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2168 columns,
2169 SQLiteAxolotlStore.ACCOUNT + "=?",
2170 selectionArgs,
2171 null,
2172 null,
2173 null);
2174 final int count;
2175 if (cursor.moveToFirst()) {
2176 count = cursor.getInt(0);
2177 } else {
2178 count = 0;
2179 }
2180 cursor.close();
2181 return count;
2182 }
2183
2184 public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
2185 Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
2186 int count = cursor.getCount();
2187 cursor.close();
2188 return count != 0;
2189 }
2190
2191 public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
2192 SQLiteDatabase db = this.getWritableDatabase();
2193 ContentValues values = new ContentValues();
2194 values.put(SQLiteAxolotlStore.ID, record.getId());
2195 values.put(
2196 SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
2197 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2198 db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
2199 }
2200
2201 public void deleteSignedPreKey(Account account, int signedPreKeyId) {
2202 SQLiteDatabase db = this.getWritableDatabase();
2203 String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
2204 db.delete(
2205 SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2206 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
2207 args);
2208 }
2209
2210 private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
2211 final SQLiteDatabase db = this.getReadableDatabase();
2212 return getIdentityKeyCursor(db, account, name, own);
2213 }
2214
2215 private Cursor getIdentityKeyCursor(
2216 SQLiteDatabase db, Account account, String name, boolean own) {
2217 return getIdentityKeyCursor(db, account, name, own, null);
2218 }
2219
2220 private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
2221 final SQLiteDatabase db = this.getReadableDatabase();
2222 return getIdentityKeyCursor(db, account, fingerprint);
2223 }
2224
2225 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
2226 return getIdentityKeyCursor(db, account, null, null, fingerprint);
2227 }
2228
2229 private Cursor getIdentityKeyCursor(
2230 SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
2231 String[] columns = {
2232 SQLiteAxolotlStore.TRUST,
2233 SQLiteAxolotlStore.ACTIVE,
2234 SQLiteAxolotlStore.LAST_ACTIVATION,
2235 SQLiteAxolotlStore.KEY
2236 };
2237 ArrayList<String> selectionArgs = new ArrayList<>(4);
2238 selectionArgs.add(account.getUuid());
2239 String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
2240 if (name != null) {
2241 selectionArgs.add(name);
2242 selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
2243 }
2244 if (fingerprint != null) {
2245 selectionArgs.add(fingerprint);
2246 selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
2247 }
2248 if (own != null) {
2249 selectionArgs.add(own ? "1" : "0");
2250 selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
2251 }
2252 Cursor cursor =
2253 db.query(
2254 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2255 columns,
2256 selectionString,
2257 selectionArgs.toArray(new String[selectionArgs.size()]),
2258 null,
2259 null,
2260 null);
2261
2262 return cursor;
2263 }
2264
2265 public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
2266 SQLiteDatabase db = getReadableDatabase();
2267 return loadOwnIdentityKeyPair(db, account);
2268 }
2269
2270 private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
2271 String name = account.getJid().asBareJid().toString();
2272 IdentityKeyPair identityKeyPair = null;
2273 Cursor cursor = getIdentityKeyCursor(db, account, name, true);
2274 if (cursor.getCount() != 0) {
2275 cursor.moveToFirst();
2276 try {
2277 identityKeyPair =
2278 new IdentityKeyPair(
2279 Base64.decode(
2280 cursor.getString(
2281 cursor.getColumnIndex(SQLiteAxolotlStore.KEY)),
2282 Base64.DEFAULT));
2283 } catch (InvalidKeyException e) {
2284 Log.d(
2285 Config.LOGTAG,
2286 AxolotlService.getLogprefix(account)
2287 + "Encountered invalid IdentityKey in database for account"
2288 + account.getJid().asBareJid()
2289 + ", address: "
2290 + name);
2291 }
2292 }
2293 cursor.close();
2294
2295 return identityKeyPair;
2296 }
2297
2298 public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
2299 return loadIdentityKeys(account, name, null);
2300 }
2301
2302 public Set<IdentityKey> loadIdentityKeys(
2303 Account account, String name, FingerprintStatus status) {
2304 Set<IdentityKey> identityKeys = new HashSet<>();
2305 Cursor cursor = getIdentityKeyCursor(account, name, false);
2306
2307 while (cursor.moveToNext()) {
2308 if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
2309 continue;
2310 }
2311 try {
2312 String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
2313 if (key != null) {
2314 identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
2315 } else {
2316 Log.d(
2317 Config.LOGTAG,
2318 AxolotlService.getLogprefix(account)
2319 + "Missing key (possibly preverified) in database for account"
2320 + account.getJid().asBareJid()
2321 + ", address: "
2322 + name);
2323 }
2324 } catch (InvalidKeyException e) {
2325 Log.d(
2326 Config.LOGTAG,
2327 AxolotlService.getLogprefix(account)
2328 + "Encountered invalid IdentityKey in database for account"
2329 + account.getJid().asBareJid()
2330 + ", address: "
2331 + name);
2332 }
2333 }
2334 cursor.close();
2335
2336 return identityKeys;
2337 }
2338
2339 public long numTrustedKeys(Account account, String name) {
2340 SQLiteDatabase db = getReadableDatabase();
2341 String[] args = {
2342 account.getUuid(),
2343 name,
2344 FingerprintStatus.Trust.TRUSTED.toString(),
2345 FingerprintStatus.Trust.VERIFIED.toString(),
2346 FingerprintStatus.Trust.VERIFIED_X509.toString()
2347 };
2348 return DatabaseUtils.queryNumEntries(
2349 db,
2350 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2351 SQLiteAxolotlStore.ACCOUNT
2352 + " = ?"
2353 + " AND "
2354 + SQLiteAxolotlStore.NAME
2355 + " = ?"
2356 + " AND ("
2357 + SQLiteAxolotlStore.TRUST
2358 + " = ? OR "
2359 + SQLiteAxolotlStore.TRUST
2360 + " = ? OR "
2361 + SQLiteAxolotlStore.TRUST
2362 + " = ?)"
2363 + " AND "
2364 + SQLiteAxolotlStore.ACTIVE
2365 + " > 0",
2366 args);
2367 }
2368
2369 private void storeIdentityKey(
2370 Account account,
2371 String name,
2372 boolean own,
2373 String fingerprint,
2374 String base64Serialized,
2375 FingerprintStatus status) {
2376 SQLiteDatabase db = this.getWritableDatabase();
2377 ContentValues values = new ContentValues();
2378 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2379 values.put(SQLiteAxolotlStore.NAME, name);
2380 values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
2381 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
2382 values.put(SQLiteAxolotlStore.KEY, base64Serialized);
2383 values.putAll(status.toContentValues());
2384 String where =
2385 SQLiteAxolotlStore.ACCOUNT
2386 + "=? AND "
2387 + SQLiteAxolotlStore.NAME
2388 + "=? AND "
2389 + SQLiteAxolotlStore.FINGERPRINT
2390 + " =?";
2391 String[] whereArgs = {account.getUuid(), name, fingerprint};
2392 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
2393 if (rows == 0) {
2394 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
2395 }
2396 }
2397
2398 public void storePreVerification(
2399 Account account, String name, String fingerprint, FingerprintStatus status) {
2400 SQLiteDatabase db = this.getWritableDatabase();
2401 ContentValues values = new ContentValues();
2402 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
2403 values.put(SQLiteAxolotlStore.NAME, name);
2404 values.put(SQLiteAxolotlStore.OWN, 0);
2405 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
2406 values.putAll(status.toContentValues());
2407 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
2408 }
2409
2410 public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
2411 Cursor cursor = getIdentityKeyCursor(account, fingerprint);
2412 final FingerprintStatus status;
2413 if (cursor.getCount() > 0) {
2414 cursor.moveToFirst();
2415 status = FingerprintStatus.fromCursor(cursor);
2416 } else {
2417 status = null;
2418 }
2419 cursor.close();
2420 return status;
2421 }
2422
2423 public boolean setIdentityKeyTrust(
2424 Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
2425 SQLiteDatabase db = this.getWritableDatabase();
2426 return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
2427 }
2428
2429 private boolean setIdentityKeyTrust(
2430 SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
2431 String[] selectionArgs = {account.getUuid(), fingerprint};
2432 int rows =
2433 db.update(
2434 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2435 status.toContentValues(),
2436 SQLiteAxolotlStore.ACCOUNT
2437 + " = ? AND "
2438 + SQLiteAxolotlStore.FINGERPRINT
2439 + " = ? ",
2440 selectionArgs);
2441 return rows == 1;
2442 }
2443
2444 public boolean setIdentityKeyCertificate(
2445 Account account, String fingerprint, X509Certificate x509Certificate) {
2446 SQLiteDatabase db = this.getWritableDatabase();
2447 String[] selectionArgs = {account.getUuid(), fingerprint};
2448 try {
2449 ContentValues values = new ContentValues();
2450 values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
2451 return db.update(
2452 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2453 values,
2454 SQLiteAxolotlStore.ACCOUNT
2455 + " = ? AND "
2456 + SQLiteAxolotlStore.FINGERPRINT
2457 + " = ? ",
2458 selectionArgs)
2459 == 1;
2460 } catch (CertificateEncodingException e) {
2461 Log.d(Config.LOGTAG, "could not encode certificate");
2462 return false;
2463 }
2464 }
2465
2466 public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
2467 SQLiteDatabase db = this.getReadableDatabase();
2468 String[] selectionArgs = {account.getUuid(), fingerprint};
2469 String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
2470 String selection =
2471 SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
2472 Cursor cursor =
2473 db.query(
2474 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2475 colums,
2476 selection,
2477 selectionArgs,
2478 null,
2479 null,
2480 null);
2481 if (cursor.getCount() < 1) {
2482 return null;
2483 } else {
2484 cursor.moveToFirst();
2485 byte[] certificate =
2486 cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
2487 cursor.close();
2488 if (certificate == null || certificate.length == 0) {
2489 return null;
2490 }
2491 try {
2492 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
2493 return (X509Certificate)
2494 certificateFactory.generateCertificate(
2495 new ByteArrayInputStream(certificate));
2496 } catch (CertificateException e) {
2497 Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
2498 return null;
2499 }
2500 }
2501 }
2502
2503 public void storeIdentityKey(
2504 Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
2505 storeIdentityKey(
2506 account,
2507 name,
2508 false,
2509 CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()),
2510 Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT),
2511 status);
2512 }
2513
2514 public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
2515 storeIdentityKey(
2516 account,
2517 account.getJid().asBareJid().toString(),
2518 true,
2519 CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()),
2520 Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT),
2521 FingerprintStatus.createActiveVerified(false));
2522 }
2523
2524 private void recreateAxolotlDb(SQLiteDatabase db) {
2525 Log.d(
2526 Config.LOGTAG,
2527 AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
2528 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
2529 db.execSQL(CREATE_SESSIONS_STATEMENT);
2530 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
2531 db.execSQL(CREATE_PREKEYS_STATEMENT);
2532 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
2533 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
2534 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
2535 db.execSQL(CREATE_IDENTITIES_STATEMENT);
2536 }
2537
2538 public void wipeAxolotlDb(Account account) {
2539 String accountName = account.getUuid();
2540 Log.d(
2541 Config.LOGTAG,
2542 AxolotlService.getLogprefix(account)
2543 + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT "
2544 + accountName
2545 + " <<<");
2546 SQLiteDatabase db = this.getWritableDatabase();
2547 String[] deleteArgs = {accountName};
2548 db.delete(
2549 SQLiteAxolotlStore.SESSION_TABLENAME,
2550 SQLiteAxolotlStore.ACCOUNT + " = ?",
2551 deleteArgs);
2552 db.delete(
2553 SQLiteAxolotlStore.PREKEY_TABLENAME,
2554 SQLiteAxolotlStore.ACCOUNT + " = ?",
2555 deleteArgs);
2556 db.delete(
2557 SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
2558 SQLiteAxolotlStore.ACCOUNT + " = ?",
2559 deleteArgs);
2560 db.delete(
2561 SQLiteAxolotlStore.IDENTITIES_TABLENAME,
2562 SQLiteAxolotlStore.ACCOUNT + " = ?",
2563 deleteArgs);
2564 }
2565
2566 public List<ShortcutService.FrequentContact> getFrequentContacts(final int days) {
2567 final var db = this.getReadableDatabase();
2568 final String SQL =
2569 "select "
2570 + Conversation.TABLENAME
2571 + "."
2572 + Conversation.UUID
2573 + ","
2574 + Conversation.TABLENAME
2575 + "."
2576 + Conversation.ACCOUNT
2577 + ","
2578 + Conversation.TABLENAME
2579 + "."
2580 + Conversation.CONTACTJID
2581 + " from "
2582 + Conversation.TABLENAME
2583 + " join "
2584 + Message.TABLENAME
2585 + " on conversations.uuid=messages.conversationUuid where"
2586 + " messages.status!=0 and carbon==0 and conversations.mode=0 and"
2587 + " messages.timeSent>=? group by conversations.uuid order by count(body)"
2588 + " desc limit 4;";
2589 String[] whereArgs =
2590 new String[] {
2591 String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))
2592 };
2593 Cursor cursor = db.rawQuery(SQL, whereArgs);
2594 ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
2595 while (cursor.moveToNext()) {
2596 try {
2597 contacts.add(
2598 new ShortcutService.FrequentContact(
2599 cursor.getString(0),
2600 cursor.getString(1),
2601 Jid.of(cursor.getString(2))));
2602 } catch (final Exception e) {
2603 Log.e(Config.LOGTAG, "could not create frequent contact", e);
2604 }
2605 }
2606 cursor.close();
2607 return contacts;
2608 }
2609}