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