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 org.json.JSONObject;
15import org.whispersystems.libsignal.SignalProtocolAddress;
16import org.whispersystems.libsignal.IdentityKey;
17import org.whispersystems.libsignal.IdentityKeyPair;
18import org.whispersystems.libsignal.InvalidKeyException;
19import org.whispersystems.libsignal.state.PreKeyRecord;
20import org.whispersystems.libsignal.state.SessionRecord;
21import org.whispersystems.libsignal.state.SignedPreKeyRecord;
22
23import java.io.ByteArrayInputStream;
24import java.io.File;
25import java.io.IOException;
26import java.security.cert.CertificateEncodingException;
27import java.security.cert.CertificateException;
28import java.security.cert.CertificateFactory;
29import java.security.cert.X509Certificate;
30import java.util.ArrayList;
31import java.util.HashMap;
32import java.util.HashSet;
33import java.util.Iterator;
34import java.util.List;
35import java.util.Map;
36import java.util.Set;
37import java.util.concurrent.CopyOnWriteArrayList;
38
39import org.json.JSONException;
40
41import eu.siacs.conversations.Config;
42import eu.siacs.conversations.crypto.axolotl.AxolotlService;
43import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
44import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
45import eu.siacs.conversations.entities.Account;
46import eu.siacs.conversations.entities.Contact;
47import eu.siacs.conversations.entities.Conversation;
48import eu.siacs.conversations.entities.Message;
49import eu.siacs.conversations.entities.PresenceTemplate;
50import eu.siacs.conversations.entities.Roster;
51import eu.siacs.conversations.entities.ServiceDiscoveryResult;
52import eu.siacs.conversations.services.ShortcutService;
53import eu.siacs.conversations.utils.CryptoHelper;
54import eu.siacs.conversations.utils.FtsUtils;
55import eu.siacs.conversations.utils.MimeUtils;
56import eu.siacs.conversations.utils.Resolver;
57import eu.siacs.conversations.xmpp.InvalidJid;
58import eu.siacs.conversations.xmpp.mam.MamReference;
59import rocks.xmpp.addr.Jid;
60
61public class DatabaseBackend extends SQLiteOpenHelper {
62
63 private static final String DATABASE_NAME = "history";
64 private static final int DATABASE_VERSION = 42;
65 private static DatabaseBackend instance = null;
66 private static String CREATE_CONTATCS_STATEMENT = "create table "
67 + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
68 + Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
69 + Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
70 + Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
71 + Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
72 + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
73 + Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
74 + Account.TABLENAME + "(" + Account.UUID
75 + ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
76 + Contact.JID + ") ON CONFLICT REPLACE);";
77
78 private static String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
79 + ServiceDiscoveryResult.TABLENAME + "("
80 + ServiceDiscoveryResult.HASH + " TEXT, "
81 + ServiceDiscoveryResult.VER + " TEXT, "
82 + ServiceDiscoveryResult.RESULT + " TEXT, "
83 + "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
84 + ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
85
86 private static String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
87 + PresenceTemplate.TABELNAME + "("
88 + PresenceTemplate.UUID + " TEXT, "
89 + PresenceTemplate.LAST_USED + " NUMBER,"
90 + PresenceTemplate.MESSAGE + " TEXT,"
91 + PresenceTemplate.STATUS + " TEXT,"
92 + "UNIQUE(" + PresenceTemplate.MESSAGE + "," + PresenceTemplate.STATUS + ") ON CONFLICT REPLACE);";
93
94 private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
95 + SQLiteAxolotlStore.PREKEY_TABLENAME + "("
96 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
97 + SQLiteAxolotlStore.ID + " INTEGER, "
98 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
99 + SQLiteAxolotlStore.ACCOUNT
100 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
101 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
102 + SQLiteAxolotlStore.ID
103 + ") ON CONFLICT REPLACE"
104 + ");";
105
106 private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
107 + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
108 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
109 + SQLiteAxolotlStore.ID + " INTEGER, "
110 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
111 + SQLiteAxolotlStore.ACCOUNT
112 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
113 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
114 + SQLiteAxolotlStore.ID
115 + ") ON CONFLICT REPLACE" +
116 ");";
117
118 private static String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
119 + SQLiteAxolotlStore.SESSION_TABLENAME + "("
120 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
121 + SQLiteAxolotlStore.NAME + " TEXT, "
122 + SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
123 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
124 + SQLiteAxolotlStore.ACCOUNT
125 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
126 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
127 + SQLiteAxolotlStore.NAME + ", "
128 + SQLiteAxolotlStore.DEVICE_ID
129 + ") ON CONFLICT REPLACE"
130 + ");";
131
132 private static String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
133 + SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
134 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
135 + SQLiteAxolotlStore.NAME + " TEXT, "
136 + SQLiteAxolotlStore.OWN + " INTEGER, "
137 + SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
138 + SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
139 + SQLiteAxolotlStore.TRUST + " TEXT, "
140 + SQLiteAxolotlStore.ACTIVE + " NUMBER, "
141 + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
142 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
143 + SQLiteAxolotlStore.ACCOUNT
144 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
145 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
146 + SQLiteAxolotlStore.NAME + ", "
147 + SQLiteAxolotlStore.FINGERPRINT
148 + ") ON CONFLICT IGNORE"
149 + ");";
150
151 private static String RESOLVER_RESULTS_TABLENAME = "resolver_results";
152
153 private static String CREATE_RESOLVER_RESULTS_TABLE = "create table " + RESOLVER_RESULTS_TABLENAME + "("
154 + Resolver.Result.DOMAIN + " TEXT,"
155 + Resolver.Result.HOSTNAME + " TEXT,"
156 + Resolver.Result.IP + " BLOB,"
157 + Resolver.Result.PRIORITY + " NUMBER,"
158 + Resolver.Result.DIRECT_TLS + " NUMBER,"
159 + Resolver.Result.AUTHENTICATED + " NUMBER,"
160 + Resolver.Result.PORT + " NUMBER,"
161 + "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
162 + ");";
163
164 private static String CREATE_MESSAGE_TIME_INDEX = "create INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
165 private static String CREATE_MESSAGE_CONVERSATION_INDEX = "create INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
166
167 private static String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING FTS4(uuid TEXT PRIMARY KEY, body TEXT)";
168 private static String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index (uuid,body) VALUES (new.uuid,new.body); END;";
169 private static 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 uuid=old.uuid; END;";
170 private static String COPY_PREEXISTING_ENTRIES = "INSERT into messages_index(uuid,body) select uuid,body FROM " + Message.TABLENAME + ";";
171
172 private DatabaseBackend(Context context) {
173 super(context, DATABASE_NAME, null, DATABASE_VERSION);
174 }
175
176 private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
177 ContentValues values = new ContentValues();
178 values.put(SQLiteAxolotlStore.TRUST, trust.toString());
179 values.put(SQLiteAxolotlStore.ACTIVE, active ? 1 : 0);
180 return values;
181 }
182
183 public static synchronized DatabaseBackend getInstance(Context context) {
184 if (instance == null) {
185 instance = new DatabaseBackend(context);
186 }
187 return instance;
188 }
189
190 @Override
191 public void onConfigure(SQLiteDatabase db) {
192 db.execSQL("PRAGMA foreign_keys=ON");
193 }
194
195 @Override
196 public void onCreate(SQLiteDatabase db) {
197 db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID + " TEXT PRIMARY KEY,"
198 + Account.USERNAME + " TEXT,"
199 + Account.SERVER + " TEXT,"
200 + Account.PASSWORD + " TEXT,"
201 + Account.DISPLAY_NAME + " TEXT, "
202 + Account.STATUS + " TEXT,"
203 + Account.STATUS_MESSAGE + " TEXT,"
204 + Account.ROSTERVERSION + " TEXT,"
205 + Account.OPTIONS + " NUMBER, "
206 + Account.AVATAR + " TEXT, "
207 + Account.KEYS + " TEXT, "
208 + Account.HOSTNAME + " TEXT, "
209 + Account.RESOURCE + " TEXT,"
210 + Account.PORT + " NUMBER DEFAULT 5222)");
211 db.execSQL("create table " + Conversation.TABLENAME + " ("
212 + Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
213 + " TEXT, " + Conversation.CONTACT + " TEXT, "
214 + Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
215 + " TEXT, " + Conversation.CREATED + " NUMBER, "
216 + Conversation.STATUS + " NUMBER, " + Conversation.MODE
217 + " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
218 + Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
219 + "(" + Account.UUID + ") ON DELETE CASCADE);");
220 db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
221 + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
222 + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
223 + " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
224 + Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
225 + Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
226 + Message.RELATIVE_FILE_PATH + " TEXT, "
227 + Message.SERVER_MSG_ID + " TEXT, "
228 + Message.FINGERPRINT + " TEXT, "
229 + Message.CARBON + " INTEGER, "
230 + Message.EDITED + " TEXT, "
231 + Message.READ + " NUMBER DEFAULT 1, "
232 + Message.OOB + " INTEGER, "
233 + Message.ERROR_MESSAGE + " TEXT,"
234 + Message.READ_BY_MARKERS + " TEXT,"
235 + Message.MARKABLE + " NUMBER DEFAULT 0,"
236 + Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
237 + Message.CONVERSATION + ") REFERENCES "
238 + Conversation.TABLENAME + "(" + Conversation.UUID
239 + ") ON DELETE CASCADE);");
240 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
241 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
242 db.execSQL(CREATE_CONTATCS_STATEMENT);
243 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
244 db.execSQL(CREATE_SESSIONS_STATEMENT);
245 db.execSQL(CREATE_PREKEYS_STATEMENT);
246 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
247 db.execSQL(CREATE_IDENTITIES_STATEMENT);
248 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
249 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
250 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
251 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
252 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
253 }
254
255 @Override
256 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
257 if (oldVersion < 2 && newVersion >= 2) {
258 db.execSQL("update " + Account.TABLENAME + " set "
259 + Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
260 }
261 if (oldVersion < 3 && newVersion >= 3) {
262 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
263 + Message.TYPE + " NUMBER");
264 }
265 if (oldVersion < 5 && newVersion >= 5) {
266 db.execSQL("DROP TABLE " + Contact.TABLENAME);
267 db.execSQL(CREATE_CONTATCS_STATEMENT);
268 db.execSQL("UPDATE " + Account.TABLENAME + " SET "
269 + Account.ROSTERVERSION + " = NULL");
270 }
271 if (oldVersion < 6 && newVersion >= 6) {
272 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
273 + Message.TRUE_COUNTERPART + " TEXT");
274 }
275 if (oldVersion < 7 && newVersion >= 7) {
276 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
277 + Message.REMOTE_MSG_ID + " TEXT");
278 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
279 + Contact.AVATAR + " TEXT");
280 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
281 + Account.AVATAR + " TEXT");
282 }
283 if (oldVersion < 8 && newVersion >= 8) {
284 db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
285 + Conversation.ATTRIBUTES + " TEXT");
286 }
287 if (oldVersion < 9 && newVersion >= 9) {
288 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
289 + Contact.LAST_TIME + " NUMBER");
290 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
291 + Contact.LAST_PRESENCE + " TEXT");
292 }
293 if (oldVersion < 10 && newVersion >= 10) {
294 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
295 + Message.RELATIVE_FILE_PATH + " TEXT");
296 }
297 if (oldVersion < 11 && newVersion >= 11) {
298 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
299 + Contact.GROUPS + " TEXT");
300 db.execSQL("delete from " + Contact.TABLENAME);
301 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
302 }
303 if (oldVersion < 12 && newVersion >= 12) {
304 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
305 + Message.SERVER_MSG_ID + " TEXT");
306 }
307 if (oldVersion < 13 && newVersion >= 13) {
308 db.execSQL("delete from " + Contact.TABLENAME);
309 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
310 }
311 if (oldVersion < 14 && newVersion >= 14) {
312 canonicalizeJids(db);
313 }
314 if (oldVersion < 15 && newVersion >= 15) {
315 recreateAxolotlDb(db);
316 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
317 + Message.FINGERPRINT + " TEXT");
318 }
319 if (oldVersion < 16 && newVersion >= 16) {
320 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
321 + Message.CARBON + " INTEGER");
322 }
323 if (oldVersion < 19 && newVersion >= 19) {
324 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
325 }
326 if (oldVersion < 20 && newVersion >= 20) {
327 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
328 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
329 }
330 if (oldVersion < 26 && newVersion >= 26) {
331 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
332 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
333 }
334 if (oldVersion < 40 && newVersion >= 40) {
335 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.RESOURCE + " TEXT");
336 }
337 /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
338 * depends on account de-serialization.
339 */
340 if (oldVersion < 17 && newVersion >= 17 && newVersion < 31) {
341 List<Account> accounts = getAccounts(db);
342 for (Account account : accounts) {
343 String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
344 if (ownDeviceIdString == null) {
345 continue;
346 }
347 int ownDeviceId = Integer.valueOf(ownDeviceIdString);
348 SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownDeviceId);
349 deleteSession(db, account, ownAddress);
350 IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
351 if (identityKeyPair != null) {
352 String[] selectionArgs = {
353 account.getUuid(),
354 CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize())
355 };
356 ContentValues values = new ContentValues();
357 values.put(SQLiteAxolotlStore.TRUSTED, 2);
358 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
359 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
360 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
361 selectionArgs);
362 } else {
363 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not load own identity key pair");
364 }
365 }
366 }
367 if (oldVersion < 18 && newVersion >= 18) {
368 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
369 }
370
371 if (oldVersion < 21 && newVersion >= 21) {
372 List<Account> accounts = getAccounts(db);
373 for (Account account : accounts) {
374 account.unsetPgpSignature();
375 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
376 + "=?", new String[]{account.getUuid()});
377 }
378 }
379
380 if (oldVersion >= 15 && oldVersion < 22 && newVersion >= 22) {
381 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
382 }
383
384 if (oldVersion < 23 && newVersion >= 23) {
385 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
386 }
387
388 if (oldVersion < 24 && newVersion >= 24) {
389 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
390 }
391
392 if (oldVersion < 25 && newVersion >= 25) {
393 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
394 }
395
396 if (oldVersion < 26 && newVersion >= 26) {
397 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
398 }
399
400 if (oldVersion < 27 && newVersion >= 27) {
401 db.execSQL("DELETE FROM " + ServiceDiscoveryResult.TABLENAME);
402 }
403
404 if (oldVersion < 28 && newVersion >= 28) {
405 canonicalizeJids(db);
406 }
407
408 if (oldVersion < 29 && newVersion >= 29) {
409 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
410 }
411 if (oldVersion >= 15 && oldVersion < 31 && newVersion >= 31) {
412 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.TRUST + " TEXT");
413 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.ACTIVE + " NUMBER");
414 HashMap<Integer, ContentValues> migration = new HashMap<>();
415 migration.put(0, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
416 migration.put(1, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
417 migration.put(2, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
418 migration.put(3, createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
419 migration.put(4, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
420 migration.put(5, createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
421 migration.put(6, createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
422 migration.put(7, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
423 migration.put(8, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
424 for (Map.Entry<Integer, ContentValues> entry : migration.entrySet()) {
425 String whereClause = SQLiteAxolotlStore.TRUSTED + "=?";
426 String[] where = {String.valueOf(entry.getKey())};
427 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, entry.getValue(), whereClause, where);
428 }
429
430 }
431 if (oldVersion >= 15 && oldVersion < 32 && newVersion >= 32) {
432 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
433 ContentValues defaults = new ContentValues();
434 defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION, System.currentTimeMillis());
435 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, defaults, null, null);
436 }
437 if (oldVersion >= 15 && oldVersion < 33 && newVersion >= 33) {
438 String whereClause = SQLiteAxolotlStore.OWN + "=1";
439 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED, true), whereClause, null);
440 }
441
442 if (oldVersion < 34 && newVersion >= 34) {
443 db.execSQL(CREATE_MESSAGE_TIME_INDEX);
444
445 final File oldPicturesDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Conversations/");
446 final File oldFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/");
447 final File newFilesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Files/");
448 final File newVideosDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Videos/");
449 if (oldPicturesDirectory.exists() && oldPicturesDirectory.isDirectory()) {
450 final File newPicturesDirectory = new File(Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations Images/");
451 newPicturesDirectory.getParentFile().mkdirs();
452 if (oldPicturesDirectory.renameTo(newPicturesDirectory)) {
453 Log.d(Config.LOGTAG, "moved " + oldPicturesDirectory.getAbsolutePath() + " to " + newPicturesDirectory.getAbsolutePath());
454 }
455 }
456 if (oldFilesDirectory.exists() && oldFilesDirectory.isDirectory()) {
457 newFilesDirectory.mkdirs();
458 newVideosDirectory.mkdirs();
459 final File[] files = oldFilesDirectory.listFiles();
460 if (files == null) {
461 return;
462 }
463 for (File file : files) {
464 if (file.getName().equals(".nomedia")) {
465 if (file.delete()) {
466 Log.d(Config.LOGTAG, "deleted nomedia file in " + oldFilesDirectory.getAbsolutePath());
467 }
468 } else if (file.isFile()) {
469 final String name = file.getName();
470 boolean isVideo = false;
471 int start = name.lastIndexOf('.') + 1;
472 if (start < name.length()) {
473 String mime = MimeUtils.guessMimeTypeFromExtension(name.substring(start));
474 isVideo = mime != null && mime.startsWith("video/");
475 }
476 File dst = new File((isVideo ? newVideosDirectory : newFilesDirectory).getAbsolutePath() + "/" + file.getName());
477 if (file.renameTo(dst)) {
478 Log.d(Config.LOGTAG, "moved " + file + " to " + dst);
479 }
480 }
481 }
482 }
483 }
484 if (oldVersion < 35 && newVersion >= 35) {
485 db.execSQL(CREATE_MESSAGE_CONVERSATION_INDEX);
486 }
487 if (oldVersion < 36 && newVersion >= 36) {
488 List<Account> accounts = getAccounts(db);
489 for (Account account : accounts) {
490 account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true);
491 account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, false);
492 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
493 + "=?", new String[]{account.getUuid()});
494 }
495 }
496
497 if (oldVersion < 37 && newVersion >= 37) {
498 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ_BY_MARKERS + " TEXT");
499 }
500
501 if (oldVersion < 38 && newVersion >= 38) {
502 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0");
503 }
504
505 if (oldVersion < 39 && newVersion >= 39) {
506 db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
507 }
508
509 if (oldVersion < 41 && newVersion >= 41) {
510 db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
511 db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
512 db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
513 db.execSQL(COPY_PREEXISTING_ENTRIES);
514 }
515
516 if (oldVersion < 42 && newVersion >= 42) {
517 db.execSQL("DROP TRIGGER IF EXISTS after_message_delete");
518 }
519 }
520
521 private void canonicalizeJids(SQLiteDatabase db) {
522 // migrate db to new, canonicalized JID domainpart representation
523
524 // Conversation table
525 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
526 while (cursor.moveToNext()) {
527 String newJid;
528 try {
529 newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))).toString();
530 } catch (IllegalArgumentException ignored) {
531 Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
532 + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
533 + ": " + ignored + ". Skipping...");
534 continue;
535 }
536
537 String updateArgs[] = {
538 newJid,
539 cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
540 };
541 db.execSQL("update " + Conversation.TABLENAME
542 + " set " + Conversation.CONTACTJID + " = ? "
543 + " where " + Conversation.UUID + " = ?", updateArgs);
544 }
545 cursor.close();
546
547 // Contact table
548 cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
549 while (cursor.moveToNext()) {
550 String newJid;
551 try {
552 newJid = Jid.of(cursor.getString(cursor.getColumnIndex(Contact.JID))).toString();
553 } catch (IllegalArgumentException ignored) {
554 Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
555 + cursor.getString(cursor.getColumnIndex(Contact.JID))
556 + ": " + ignored + ". Skipping...");
557 continue;
558 }
559
560 String updateArgs[] = {
561 newJid,
562 cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
563 cursor.getString(cursor.getColumnIndex(Contact.JID)),
564 };
565 db.execSQL("update " + Contact.TABLENAME
566 + " set " + Contact.JID + " = ? "
567 + " where " + Contact.ACCOUNT + " = ? "
568 + " AND " + Contact.JID + " = ?", updateArgs);
569 }
570 cursor.close();
571
572 // Account table
573 cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
574 while (cursor.moveToNext()) {
575 String newServer;
576 try {
577 newServer = Jid.of(
578 cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
579 cursor.getString(cursor.getColumnIndex(Account.SERVER)),
580 null
581 ).getDomain();
582 } catch (IllegalArgumentException ignored) {
583 Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
584 + cursor.getString(cursor.getColumnIndex(Account.SERVER))
585 + ": " + ignored + ". Skipping...");
586 continue;
587 }
588
589 String updateArgs[] = {
590 newServer,
591 cursor.getString(cursor.getColumnIndex(Account.UUID)),
592 };
593 db.execSQL("update " + Account.TABLENAME
594 + " set " + Account.SERVER + " = ? "
595 + " where " + Account.UUID + " = ?", updateArgs);
596 }
597 cursor.close();
598 }
599
600 public void createConversation(Conversation conversation) {
601 SQLiteDatabase db = this.getWritableDatabase();
602 db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
603 }
604
605 public void createMessage(Message message) {
606 SQLiteDatabase db = this.getWritableDatabase();
607 db.insert(Message.TABLENAME, null, message.getContentValues());
608 }
609
610 public void createAccount(Account account) {
611 SQLiteDatabase db = this.getWritableDatabase();
612 db.insert(Account.TABLENAME, null, account.getContentValues());
613 }
614
615 public void insertDiscoveryResult(ServiceDiscoveryResult result) {
616 SQLiteDatabase db = this.getWritableDatabase();
617 db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
618 }
619
620 public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
621 SQLiteDatabase db = this.getReadableDatabase();
622 String[] selectionArgs = {hash, ver};
623 Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
624 ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
625 selectionArgs, null, null, null);
626 if (cursor.getCount() == 0) {
627 cursor.close();
628 return null;
629 }
630 cursor.moveToFirst();
631
632 ServiceDiscoveryResult result = null;
633 try {
634 result = new ServiceDiscoveryResult(cursor);
635 } catch (JSONException e) { /* result is still null */ }
636
637 cursor.close();
638 return result;
639 }
640
641 public void saveResolverResult(String domain, Resolver.Result result) {
642 SQLiteDatabase db = this.getWritableDatabase();
643 ContentValues contentValues = result.toContentValues();
644 contentValues.put(Resolver.Result.DOMAIN, domain);
645 db.insert(RESOLVER_RESULTS_TABLENAME, null, contentValues);
646 }
647
648 public Resolver.Result findResolverResult(String domain) {
649 SQLiteDatabase db = this.getReadableDatabase();
650 String where = Resolver.Result.DOMAIN + "=?";
651 String[] whereArgs = {domain};
652 Cursor cursor = db.query(RESOLVER_RESULTS_TABLENAME, null, where, whereArgs, null, null, null);
653 Resolver.Result result = null;
654 if (cursor != null) {
655 if (cursor.moveToFirst()) {
656 result = Resolver.Result.fromCursor(cursor);
657 }
658 cursor.close();
659 }
660 return result;
661 }
662
663 public void insertPresenceTemplate(PresenceTemplate template) {
664 SQLiteDatabase db = this.getWritableDatabase();
665 String whereToDelete = PresenceTemplate.MESSAGE + "=?";
666 String[] whereToDeleteArgs = {template.getStatusMessage()};
667 db.delete(PresenceTemplate.TABELNAME, whereToDelete, whereToDeleteArgs);
668 db.delete(PresenceTemplate.TABELNAME, PresenceTemplate.UUID + " not in (select " + PresenceTemplate.UUID + " from " + PresenceTemplate.TABELNAME + " order by " + PresenceTemplate.LAST_USED + " desc limit 9)", null);
669 db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
670 }
671
672 public List<PresenceTemplate> getPresenceTemplates() {
673 ArrayList<PresenceTemplate> templates = new ArrayList<>();
674 SQLiteDatabase db = this.getReadableDatabase();
675 Cursor cursor = db.query(PresenceTemplate.TABELNAME, null, null, null, null, null, PresenceTemplate.LAST_USED + " desc");
676 while (cursor.moveToNext()) {
677 templates.add(PresenceTemplate.fromCursor(cursor));
678 }
679 cursor.close();
680 return templates;
681 }
682
683 public CopyOnWriteArrayList<Conversation> getConversations(int status) {
684 CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
685 SQLiteDatabase db = this.getReadableDatabase();
686 String[] selectionArgs = {Integer.toString(status)};
687 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
688 + " where " + Conversation.STATUS + " = ? and " + Conversation.CONTACTJID + " is not null order by "
689 + Conversation.CREATED + " desc", selectionArgs);
690 while (cursor.moveToNext()) {
691 final Conversation conversation = Conversation.fromCursor(cursor);
692 if (conversation.getJid() instanceof InvalidJid) {
693 continue;
694 }
695 list.add(conversation);
696 }
697 cursor.close();
698 return list;
699 }
700
701 public ArrayList<Message> getMessages(Conversation conversations, int limit) {
702 return getMessages(conversations, limit, -1);
703 }
704
705 public ArrayList<Message> getMessages(Conversation conversation, int limit, long timestamp) {
706 ArrayList<Message> list = new ArrayList<>();
707 SQLiteDatabase db = this.getReadableDatabase();
708 Cursor cursor;
709 if (timestamp == -1) {
710 String[] selectionArgs = {conversation.getUuid()};
711 cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
712 + "=?", selectionArgs, null, null, Message.TIME_SENT
713 + " DESC", String.valueOf(limit));
714 } else {
715 String[] selectionArgs = {conversation.getUuid(),
716 Long.toString(timestamp)};
717 cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
718 + "=? and " + Message.TIME_SENT + "<?", selectionArgs,
719 null, null, Message.TIME_SENT + " DESC",
720 String.valueOf(limit));
721 }
722 if (cursor.getCount() > 0) {
723 cursor.moveToLast();
724 do {
725 Message message = Message.fromCursor(cursor, conversation);
726 if (message != null) {
727 list.add(message);
728 }
729 } while (cursor.moveToPrevious());
730 }
731 cursor.close();
732 return list;
733 }
734
735 public Cursor getMessageSearchCursor(List<String> term) {
736 SQLiteDatabase db = this.getReadableDatabase();
737 String SQL = "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.uuid=messages.uuid where " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + ',' + Message.ENCRYPTION_PGP + ',' + Message.ENCRYPTION_DECRYPTION_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + ',' + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ? ORDER BY " + Message.TIME_SENT + " DESC limit " + Config.MAX_SEARCH_RESULTS;
738 Log.d(Config.LOGTAG, "search term: " + FtsUtils.toMatchString(term));
739 return db.rawQuery(SQL, new String[]{FtsUtils.toMatchString(term)});
740 }
741
742 public Iterable<Message> getMessagesIterable(final Conversation conversation) {
743 return () -> {
744 class MessageIterator implements Iterator<Message> {
745 private SQLiteDatabase db = getReadableDatabase();
746 private String[] selectionArgs = {conversation.getUuid()};
747 private Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
748 + "=?", selectionArgs, null, null, Message.TIME_SENT
749 + " ASC", null);
750
751 private MessageIterator() {
752 cursor.moveToFirst();
753 }
754
755 @Override
756 public boolean hasNext() {
757 return !cursor.isAfterLast();
758 }
759
760 @Override
761 public Message next() {
762 Message message = Message.fromCursor(cursor, conversation);
763 cursor.moveToNext();
764 return message;
765 }
766
767 @Override
768 public void remove() {
769 throw new UnsupportedOperationException();
770 }
771 }
772 return new MessageIterator();
773 };
774 }
775
776 public Conversation findConversation(final Account account, final Jid contactJid) {
777 SQLiteDatabase db = this.getReadableDatabase();
778 String[] selectionArgs = {account.getUuid(),
779 contactJid.asBareJid().toString() + "/%",
780 contactJid.asBareJid().toString()
781 };
782 Cursor cursor = db.query(Conversation.TABLENAME, null,
783 Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
784 + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
785 if (cursor.getCount() == 0) {
786 cursor.close();
787 return null;
788 }
789 cursor.moveToFirst();
790 Conversation conversation = Conversation.fromCursor(cursor);
791 cursor.close();
792 if (conversation.getJid() instanceof InvalidJid) {
793 return null;
794 }
795 return conversation;
796 }
797
798 public void updateConversation(final Conversation conversation) {
799 final SQLiteDatabase db = this.getWritableDatabase();
800 final String[] args = {conversation.getUuid()};
801 db.update(Conversation.TABLENAME, conversation.getContentValues(),
802 Conversation.UUID + "=?", args);
803 }
804
805 public List<Account> getAccounts() {
806 SQLiteDatabase db = this.getReadableDatabase();
807 return getAccounts(db);
808 }
809
810 public List<Jid> getAccountJids() {
811 SQLiteDatabase db = this.getReadableDatabase();
812 final List<Jid> jids = new ArrayList<>();
813 final String[] columns = new String[]{Account.USERNAME, Account.SERVER};
814 String where = "not options & (1 <<1)";
815 Cursor cursor = db.query(Account.TABLENAME, columns, where, null, null, null, null);
816 try {
817 while (cursor.moveToNext()) {
818 jids.add(Jid.of(cursor.getString(0), cursor.getString(1), null));
819 }
820 return jids;
821 } catch (Exception e) {
822 return jids;
823 } finally {
824 if (cursor != null) {
825 cursor.close();
826 }
827 }
828 }
829
830 private List<Account> getAccounts(SQLiteDatabase db) {
831 List<Account> list = new ArrayList<>();
832 Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
833 null, null);
834 while (cursor.moveToNext()) {
835 list.add(Account.fromCursor(cursor));
836 }
837 cursor.close();
838 return list;
839 }
840
841 public boolean updateAccount(Account account) {
842 SQLiteDatabase db = this.getWritableDatabase();
843 String[] args = {account.getUuid()};
844 final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
845 return rows == 1;
846 }
847
848 public boolean deleteAccount(Account account) {
849 SQLiteDatabase db = this.getWritableDatabase();
850 String[] args = {account.getUuid()};
851 final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
852 return rows == 1;
853 }
854
855 public boolean updateMessage(Message message, boolean includeBody) {
856 SQLiteDatabase db = this.getWritableDatabase();
857 String[] args = {message.getUuid()};
858 ContentValues contentValues = message.getContentValues();
859 contentValues.remove(Message.UUID);
860 if (!includeBody) {
861 contentValues.remove(Message.BODY);
862 }
863 return db.update(Message.TABLENAME, message.getContentValues(), Message.UUID + "=?", args) == 1;
864 }
865
866 public void updateMessage(Message message, String uuid) {
867 SQLiteDatabase db = this.getWritableDatabase();
868 String[] args = {uuid};
869 db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
870 + "=?", args);
871 }
872
873 public void readRoster(Roster roster) {
874 SQLiteDatabase db = this.getReadableDatabase();
875 Cursor cursor;
876 String args[] = {roster.getAccount().getUuid()};
877 cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
878 while (cursor.moveToNext()) {
879 roster.initContact(Contact.fromCursor(cursor));
880 }
881 cursor.close();
882 }
883
884 public void writeRoster(final Roster roster) {
885 long start = SystemClock.elapsedRealtime();
886 final Account account = roster.getAccount();
887 final SQLiteDatabase db = this.getWritableDatabase();
888 db.beginTransaction();
889 for (Contact contact : roster.getContacts()) {
890 if (contact.getOption(Contact.Options.IN_ROSTER)) {
891 db.insert(Contact.TABLENAME, null, contact.getContentValues());
892 } else {
893 String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
894 String[] whereArgs = {account.getUuid(), contact.getJid().toString()};
895 db.delete(Contact.TABLENAME, where, whereArgs);
896 }
897 }
898 db.setTransactionSuccessful();
899 db.endTransaction();
900 account.setRosterVersion(roster.getVersion());
901 updateAccount(account);
902 long duration = SystemClock.elapsedRealtime() - start;
903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisted roster in " + duration + "ms");
904 }
905
906 public void deleteMessagesInConversation(Conversation conversation) {
907 long start = SystemClock.elapsedRealtime();
908 final SQLiteDatabase db = this.getWritableDatabase();
909 db.beginTransaction();
910 String[] args = {conversation.getUuid()};
911 db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
912 int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
913 db.setTransactionSuccessful();
914 db.endTransaction();
915 Log.d(Config.LOGTAG, "deleted " + num + " messages for " + conversation.getJid().asBareJid() + " in " + (SystemClock.elapsedRealtime() - start) + "ms");
916 }
917
918 public void expireOldMessages(long timestamp) {
919 final String[] args = {String.valueOf(timestamp)};
920 SQLiteDatabase db = this.getReadableDatabase();
921 db.beginTransaction();
922 db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
923 db.delete(Message.TABLENAME, "timeSent<?", args);
924 db.setTransactionSuccessful();
925 db.endTransaction();
926 }
927
928 public MamReference getLastMessageReceived(Account account) {
929 Cursor cursor = null;
930 try {
931 SQLiteDatabase db = this.getReadableDatabase();
932 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";
933 String[] args = {account.getUuid()};
934 cursor = db.rawQuery(sql, args);
935 if (cursor.getCount() == 0) {
936 return null;
937 } else {
938 cursor.moveToFirst();
939 return new MamReference(cursor.getLong(0), cursor.getString(1));
940 }
941 } catch (Exception e) {
942 return null;
943 } finally {
944 if (cursor != null) {
945 cursor.close();
946 }
947 }
948 }
949
950 public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
951 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";
952 String[] args = {account.getUuid(), fingerprint};
953 Cursor cursor = getReadableDatabase().rawQuery(SQL, args);
954 long time;
955 if (cursor.moveToFirst()) {
956 time = cursor.getLong(0);
957 } else {
958 time = 0;
959 }
960 cursor.close();
961 return time;
962 }
963
964 public MamReference getLastClearDate(Account account) {
965 SQLiteDatabase db = this.getReadableDatabase();
966 String[] columns = {Conversation.ATTRIBUTES};
967 String selection = Conversation.ACCOUNT + "=?";
968 String[] args = {account.getUuid()};
969 Cursor cursor = db.query(Conversation.TABLENAME, columns, selection, args, null, null, null);
970 MamReference maxClearDate = new MamReference(0);
971 while (cursor.moveToNext()) {
972 try {
973 final JSONObject o = new JSONObject(cursor.getString(0));
974 maxClearDate = MamReference.max(maxClearDate, MamReference.fromAttribute(o.getString(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY)));
975 } catch (Exception e) {
976 //ignored
977 }
978 }
979 cursor.close();
980 return maxClearDate;
981 }
982
983 private Cursor getCursorForSession(Account account, SignalProtocolAddress contact) {
984 final SQLiteDatabase db = this.getReadableDatabase();
985 String[] selectionArgs = {account.getUuid(),
986 contact.getName(),
987 Integer.toString(contact.getDeviceId())};
988 return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
989 null,
990 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
991 + SQLiteAxolotlStore.NAME + " = ? AND "
992 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
993 selectionArgs,
994 null, null, null);
995 }
996
997 public SessionRecord loadSession(Account account, SignalProtocolAddress contact) {
998 SessionRecord session = null;
999 Cursor cursor = getCursorForSession(account, contact);
1000 if (cursor.getCount() != 0) {
1001 cursor.moveToFirst();
1002 try {
1003 session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1004 } catch (IOException e) {
1005 cursor.close();
1006 throw new AssertionError(e);
1007 }
1008 }
1009 cursor.close();
1010 return session;
1011 }
1012
1013 public List<Integer> getSubDeviceSessions(Account account, SignalProtocolAddress contact) {
1014 final SQLiteDatabase db = this.getReadableDatabase();
1015 return getSubDeviceSessions(db, account, contact);
1016 }
1017
1018 private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1019 List<Integer> devices = new ArrayList<>();
1020 String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
1021 String[] selectionArgs = {account.getUuid(),
1022 contact.getName()};
1023 Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
1024 columns,
1025 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1026 + SQLiteAxolotlStore.NAME + " = ?",
1027 selectionArgs,
1028 null, null, null);
1029
1030 while (cursor.moveToNext()) {
1031 devices.add(cursor.getInt(
1032 cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
1033 }
1034
1035 cursor.close();
1036 return devices;
1037 }
1038
1039 public List<String> getKnownSignalAddresses(Account account) {
1040 List<String> addresses = new ArrayList<>();
1041 String[] colums = {"DISTINCT " + SQLiteAxolotlStore.NAME};
1042 String[] selectionArgs = {account.getUuid()};
1043 Cursor cursor = getReadableDatabase().query(SQLiteAxolotlStore.SESSION_TABLENAME,
1044 colums,
1045 SQLiteAxolotlStore.ACCOUNT + " = ?",
1046 selectionArgs,
1047 null, null, null
1048 );
1049 while (cursor.moveToNext()) {
1050 addresses.add(cursor.getString(0));
1051 }
1052 cursor.close();
1053 return addresses;
1054 }
1055
1056 public boolean containsSession(Account account, SignalProtocolAddress contact) {
1057 Cursor cursor = getCursorForSession(account, contact);
1058 int count = cursor.getCount();
1059 cursor.close();
1060 return count != 0;
1061 }
1062
1063 public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
1064 SQLiteDatabase db = this.getWritableDatabase();
1065 ContentValues values = new ContentValues();
1066 values.put(SQLiteAxolotlStore.NAME, contact.getName());
1067 values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
1068 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
1069 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1070 db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
1071 }
1072
1073 public void deleteSession(Account account, SignalProtocolAddress contact) {
1074 SQLiteDatabase db = this.getWritableDatabase();
1075 deleteSession(db, account, contact);
1076 }
1077
1078 private void deleteSession(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
1079 String[] args = {account.getUuid(),
1080 contact.getName(),
1081 Integer.toString(contact.getDeviceId())};
1082 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1083 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1084 + SQLiteAxolotlStore.NAME + " = ? AND "
1085 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
1086 args);
1087 }
1088
1089 public void deleteAllSessions(Account account, SignalProtocolAddress contact) {
1090 SQLiteDatabase db = this.getWritableDatabase();
1091 String[] args = {account.getUuid(), contact.getName()};
1092 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1093 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1094 + SQLiteAxolotlStore.NAME + " = ?",
1095 args);
1096 }
1097
1098 private Cursor getCursorForPreKey(Account account, int preKeyId) {
1099 SQLiteDatabase db = this.getReadableDatabase();
1100 String[] columns = {SQLiteAxolotlStore.KEY};
1101 String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
1102 Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
1103 columns,
1104 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1105 + SQLiteAxolotlStore.ID + "=?",
1106 selectionArgs,
1107 null, null, null);
1108
1109 return cursor;
1110 }
1111
1112 public PreKeyRecord loadPreKey(Account account, int preKeyId) {
1113 PreKeyRecord record = null;
1114 Cursor cursor = getCursorForPreKey(account, preKeyId);
1115 if (cursor.getCount() != 0) {
1116 cursor.moveToFirst();
1117 try {
1118 record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1119 } catch (IOException e) {
1120 throw new AssertionError(e);
1121 }
1122 }
1123 cursor.close();
1124 return record;
1125 }
1126
1127 public boolean containsPreKey(Account account, int preKeyId) {
1128 Cursor cursor = getCursorForPreKey(account, preKeyId);
1129 int count = cursor.getCount();
1130 cursor.close();
1131 return count != 0;
1132 }
1133
1134 public void storePreKey(Account account, PreKeyRecord record) {
1135 SQLiteDatabase db = this.getWritableDatabase();
1136 ContentValues values = new ContentValues();
1137 values.put(SQLiteAxolotlStore.ID, record.getId());
1138 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1139 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1140 db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
1141 }
1142
1143 public void deletePreKey(Account account, int preKeyId) {
1144 SQLiteDatabase db = this.getWritableDatabase();
1145 String[] args = {account.getUuid(), Integer.toString(preKeyId)};
1146 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1147 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1148 + SQLiteAxolotlStore.ID + "=?",
1149 args);
1150 }
1151
1152 private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
1153 SQLiteDatabase db = this.getReadableDatabase();
1154 String[] columns = {SQLiteAxolotlStore.KEY};
1155 String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
1156 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1157 columns,
1158 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
1159 selectionArgs,
1160 null, null, null);
1161
1162 return cursor;
1163 }
1164
1165 public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
1166 SignedPreKeyRecord record = null;
1167 Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
1168 if (cursor.getCount() != 0) {
1169 cursor.moveToFirst();
1170 try {
1171 record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1172 } catch (IOException e) {
1173 throw new AssertionError(e);
1174 }
1175 }
1176 cursor.close();
1177 return record;
1178 }
1179
1180 public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1181 List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1182 SQLiteDatabase db = this.getReadableDatabase();
1183 String[] columns = {SQLiteAxolotlStore.KEY};
1184 String[] selectionArgs = {account.getUuid()};
1185 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1186 columns,
1187 SQLiteAxolotlStore.ACCOUNT + "=?",
1188 selectionArgs,
1189 null, null, null);
1190
1191 while (cursor.moveToNext()) {
1192 try {
1193 prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1194 } catch (IOException ignored) {
1195 }
1196 }
1197 cursor.close();
1198 return prekeys;
1199 }
1200
1201 public int getSignedPreKeysCount(Account account) {
1202 String[] columns = {"count(" + SQLiteAxolotlStore.KEY + ")"};
1203 String[] selectionArgs = {account.getUuid()};
1204 SQLiteDatabase db = this.getReadableDatabase();
1205 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1206 columns,
1207 SQLiteAxolotlStore.ACCOUNT + "=?",
1208 selectionArgs,
1209 null, null, null);
1210 final int count;
1211 if (cursor.moveToFirst()) {
1212 count = cursor.getInt(0);
1213 } else {
1214 count = 0;
1215 }
1216 cursor.close();
1217 return count;
1218 }
1219
1220 public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1221 Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1222 int count = cursor.getCount();
1223 cursor.close();
1224 return count != 0;
1225 }
1226
1227 public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1228 SQLiteDatabase db = this.getWritableDatabase();
1229 ContentValues values = new ContentValues();
1230 values.put(SQLiteAxolotlStore.ID, record.getId());
1231 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1232 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1233 db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1234 }
1235
1236 public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1237 SQLiteDatabase db = this.getWritableDatabase();
1238 String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1239 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1240 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1241 + SQLiteAxolotlStore.ID + "=?",
1242 args);
1243 }
1244
1245 private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1246 final SQLiteDatabase db = this.getReadableDatabase();
1247 return getIdentityKeyCursor(db, account, name, own);
1248 }
1249
1250 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1251 return getIdentityKeyCursor(db, account, name, own, null);
1252 }
1253
1254 private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1255 final SQLiteDatabase db = this.getReadableDatabase();
1256 return getIdentityKeyCursor(db, account, fingerprint);
1257 }
1258
1259 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1260 return getIdentityKeyCursor(db, account, null, null, fingerprint);
1261 }
1262
1263 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1264 String[] columns = {SQLiteAxolotlStore.TRUST,
1265 SQLiteAxolotlStore.ACTIVE,
1266 SQLiteAxolotlStore.LAST_ACTIVATION,
1267 SQLiteAxolotlStore.KEY};
1268 ArrayList<String> selectionArgs = new ArrayList<>(4);
1269 selectionArgs.add(account.getUuid());
1270 String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1271 if (name != null) {
1272 selectionArgs.add(name);
1273 selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1274 }
1275 if (fingerprint != null) {
1276 selectionArgs.add(fingerprint);
1277 selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1278 }
1279 if (own != null) {
1280 selectionArgs.add(own ? "1" : "0");
1281 selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1282 }
1283 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1284 columns,
1285 selectionString,
1286 selectionArgs.toArray(new String[selectionArgs.size()]),
1287 null, null, null);
1288
1289 return cursor;
1290 }
1291
1292 public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1293 SQLiteDatabase db = getReadableDatabase();
1294 return loadOwnIdentityKeyPair(db, account);
1295 }
1296
1297 private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1298 String name = account.getJid().asBareJid().toString();
1299 IdentityKeyPair identityKeyPair = null;
1300 Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1301 if (cursor.getCount() != 0) {
1302 cursor.moveToFirst();
1303 try {
1304 identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1305 } catch (InvalidKeyException e) {
1306 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1307 }
1308 }
1309 cursor.close();
1310
1311 return identityKeyPair;
1312 }
1313
1314 public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1315 return loadIdentityKeys(account, name, null);
1316 }
1317
1318 public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1319 Set<IdentityKey> identityKeys = new HashSet<>();
1320 Cursor cursor = getIdentityKeyCursor(account, name, false);
1321
1322 while (cursor.moveToNext()) {
1323 if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1324 continue;
1325 }
1326 try {
1327 String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1328 if (key != null) {
1329 identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1330 } else {
1331 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
1332 }
1333 } catch (InvalidKeyException e) {
1334 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
1335 }
1336 }
1337 cursor.close();
1338
1339 return identityKeys;
1340 }
1341
1342 public long numTrustedKeys(Account account, String name) {
1343 SQLiteDatabase db = getReadableDatabase();
1344 String[] args = {
1345 account.getUuid(),
1346 name,
1347 FingerprintStatus.Trust.TRUSTED.toString(),
1348 FingerprintStatus.Trust.VERIFIED.toString(),
1349 FingerprintStatus.Trust.VERIFIED_X509.toString()
1350 };
1351 return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1352 SQLiteAxolotlStore.ACCOUNT + " = ?"
1353 + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1354 + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ?)"
1355 + " AND " + SQLiteAxolotlStore.ACTIVE + " > 0",
1356 args
1357 );
1358 }
1359
1360 private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1361 SQLiteDatabase db = this.getWritableDatabase();
1362 ContentValues values = new ContentValues();
1363 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1364 values.put(SQLiteAxolotlStore.NAME, name);
1365 values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1366 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1367 values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1368 values.putAll(status.toContentValues());
1369 String where = SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.NAME + "=? AND " + SQLiteAxolotlStore.FINGERPRINT + " =?";
1370 String[] whereArgs = {account.getUuid(), name, fingerprint};
1371 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values, where, whereArgs);
1372 if (rows == 0) {
1373 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1374 }
1375 }
1376
1377 public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1378 SQLiteDatabase db = this.getWritableDatabase();
1379 ContentValues values = new ContentValues();
1380 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1381 values.put(SQLiteAxolotlStore.NAME, name);
1382 values.put(SQLiteAxolotlStore.OWN, 0);
1383 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1384 values.putAll(status.toContentValues());
1385 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1386 }
1387
1388 public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1389 Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1390 final FingerprintStatus status;
1391 if (cursor.getCount() > 0) {
1392 cursor.moveToFirst();
1393 status = FingerprintStatus.fromCursor(cursor);
1394 } else {
1395 status = null;
1396 }
1397 cursor.close();
1398 return status;
1399 }
1400
1401 public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1402 SQLiteDatabase db = this.getWritableDatabase();
1403 return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1404 }
1405
1406 private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1407 String[] selectionArgs = {
1408 account.getUuid(),
1409 fingerprint
1410 };
1411 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1412 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1413 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1414 selectionArgs);
1415 return rows == 1;
1416 }
1417
1418 public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1419 SQLiteDatabase db = this.getWritableDatabase();
1420 String[] selectionArgs = {
1421 account.getUuid(),
1422 fingerprint
1423 };
1424 try {
1425 ContentValues values = new ContentValues();
1426 values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1427 return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1428 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1429 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1430 selectionArgs) == 1;
1431 } catch (CertificateEncodingException e) {
1432 Log.d(Config.LOGTAG, "could not encode certificate");
1433 return false;
1434 }
1435 }
1436
1437 public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1438 SQLiteDatabase db = this.getReadableDatabase();
1439 String[] selectionArgs = {
1440 account.getUuid(),
1441 fingerprint
1442 };
1443 String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1444 String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1445 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1446 if (cursor.getCount() < 1) {
1447 return null;
1448 } else {
1449 cursor.moveToFirst();
1450 byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1451 cursor.close();
1452 if (certificate == null || certificate.length == 0) {
1453 return null;
1454 }
1455 try {
1456 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1457 return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1458 } catch (CertificateException e) {
1459 Log.d(Config.LOGTAG, "certificate exception " + e.getMessage());
1460 return null;
1461 }
1462 }
1463 }
1464
1465 public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1466 storeIdentityKey(account, name, false, CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1467 }
1468
1469 public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1470 storeIdentityKey(account, account.getJid().asBareJid().toString(), true, CryptoHelper.bytesToHex(identityKeyPair.getPublicKey().serialize()), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1471 }
1472
1473
1474 private void recreateAxolotlDb(SQLiteDatabase db) {
1475 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1476 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1477 db.execSQL(CREATE_SESSIONS_STATEMENT);
1478 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1479 db.execSQL(CREATE_PREKEYS_STATEMENT);
1480 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1481 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1482 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1483 db.execSQL(CREATE_IDENTITIES_STATEMENT);
1484 }
1485
1486 public void wipeAxolotlDb(Account account) {
1487 String accountName = account.getUuid();
1488 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1489 SQLiteDatabase db = this.getWritableDatabase();
1490 String[] deleteArgs = {
1491 accountName
1492 };
1493 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1494 SQLiteAxolotlStore.ACCOUNT + " = ?",
1495 deleteArgs);
1496 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1497 SQLiteAxolotlStore.ACCOUNT + " = ?",
1498 deleteArgs);
1499 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1500 SQLiteAxolotlStore.ACCOUNT + " = ?",
1501 deleteArgs);
1502 db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1503 SQLiteAxolotlStore.ACCOUNT + " = ?",
1504 deleteArgs);
1505 }
1506
1507 public List<ShortcutService.FrequentContact> getFrequentContacts(int days) {
1508 SQLiteDatabase db = this.getReadableDatabase();
1509 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;";
1510 String[] whereArgs = new String[]{String.valueOf(System.currentTimeMillis() - (Config.MILLISECONDS_IN_DAY * days))};
1511 Cursor cursor = db.rawQuery(SQL, whereArgs);
1512 ArrayList<ShortcutService.FrequentContact> contacts = new ArrayList<>();
1513 while (cursor.moveToNext()) {
1514 try {
1515 contacts.add(new ShortcutService.FrequentContact(cursor.getString(0), Jid.of(cursor.getString(1))));
1516 } catch (Exception e) {
1517 Log.d(Config.LOGTAG, e.getMessage());
1518 }
1519 }
1520 cursor.close();
1521 return contacts;
1522 }
1523}