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