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