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