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