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