DatabaseBackend.java

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