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