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