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