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