Search in sources :

Example 56 with SQLiteDatabase

use of net.sqlcipher.database.SQLiteDatabase in project Zom-Android by zom.

the class ImpsProvider method deleteInternal.

private int deleteInternal(Uri url, String userWhere, String[] whereArgs) {
    String tableToChange;
    // In some cases a given url requires that we delete rows from more than one
    // table.  The motivating example is deleting messages from both the on disk
    // and in memory messages tables.
    String tableToChange2 = null;
    String idColumnName = null;
    String changedItemId = null;
    String provider = null;
    String accountStr = null;
    long account = 0;
    String contact = null;
    long threadId = 0;
    StringBuilder whereClause = new StringBuilder();
    if (userWhere != null) {
        whereClause.append(userWhere);
    }
    boolean notifyMessagesContentUri = false;
    boolean notifyMessagesByContactContentUri = false;
    boolean notifyMessagesByThreadIdContentUri = false;
    boolean notifyContactListContentUri = false;
    boolean notifyProviderAccountContentUri = false;
    int match = mUrlMatcher.match(url);
    boolean contactDeleted = false;
    long deletedContactId = 0;
    boolean backfillQuickSwitchSlots = false;
    final SQLiteDatabase db = getDBHelper().getWritableDatabase();
    switch(match) {
        case MATCH_PROVIDERS_BY_ID:
            changedItemId = url.getPathSegments().get(1);
        // fall through
        case MATCH_PROVIDERS:
            tableToChange = TABLE_PROVIDERS;
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_ACCOUNTS_BY_ID:
            changedItemId = url.getPathSegments().get(1);
        // fall through
        case MATCH_ACCOUNTS:
            tableToChange = TABLE_ACCOUNTS;
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_ACCOUNT_STATUS:
            changedItemId = url.getPathSegments().get(1);
        // fall through
        case MATCH_ACCOUNTS_STATUS:
            tableToChange = TABLE_ACCOUNT_STATUS;
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_CONTACTS:
        case MATCH_CONTACTS_BAREBONE:
            tableToChange = TABLE_CONTACTS;
            contactDeleted = true;
            break;
        case MATCH_CONTACT:
            tableToChange = TABLE_CONTACTS;
            changedItemId = url.getPathSegments().get(1);
            try {
                deletedContactId = Long.parseLong(changedItemId);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException();
            }
            contactDeleted = true;
            break;
        case MATCH_CONTACTS_BY_PROVIDER:
            tableToChange = TABLE_CONTACTS;
            appendWhere(whereClause, Imps.Contacts.ACCOUNT, "=", url.getPathSegments().get(2));
            contactDeleted = true;
            break;
        case MATCH_CONTACTLISTS_BY_PROVIDER:
            appendWhere(whereClause, Imps.ContactList.ACCOUNT, "=", url.getPathSegments().get(2));
        // fall through
        case MATCH_CONTACTLISTS:
            tableToChange = TABLE_CONTACT_LIST;
            notifyContactListContentUri = true;
            break;
        case MATCH_CONTACTLIST:
            tableToChange = TABLE_CONTACT_LIST;
            changedItemId = url.getPathSegments().get(1);
            break;
        case MATCH_BLOCKEDLIST:
            tableToChange = TABLE_BLOCKED_LIST;
            break;
        case MATCH_BLOCKEDLIST_BY_PROVIDER:
            tableToChange = TABLE_BLOCKED_LIST;
            appendWhere(whereClause, Imps.BlockedList.ACCOUNT, "=", url.getPathSegments().get(2));
            break;
        case MATCH_CONTACTS_ETAGS:
            tableToChange = TABLE_CONTACTS_ETAG;
            break;
        case MATCH_CONTACTS_ETAG:
            tableToChange = TABLE_CONTACTS_ETAG;
            changedItemId = url.getPathSegments().get(1);
            break;
        case MATCH_MESSAGES:
            tableToChange = TABLE_MESSAGES;
            break;
        case MATCH_MESSAGES_BY_CONTACT:
            tableToChange = TABLE_MESSAGES;
            tableToChange2 = TABLE_IN_MEMORY_MESSAGES;
            accountStr = decodeURLSegment(url.getPathSegments().get(1));
            try {
                account = Long.parseLong(accountStr);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException();
            }
            contact = decodeURLSegment(url.getPathSegments().get(2));
            appendWhere(whereClause, Imps.Messages.THREAD_ID, "=", getContactId(db, accountStr, contact));
            notifyMessagesContentUri = true;
            break;
        case MATCH_MESSAGES_BY_THREAD_ID:
            tableToChange = TABLE_MESSAGES;
            tableToChange2 = TABLE_IN_MEMORY_MESSAGES;
            try {
                threadId = Long.parseLong(decodeURLSegment(url.getPathSegments().get(1)));
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException();
            }
            appendWhere(whereClause, Imps.Messages.THREAD_ID, "=", threadId);
            notifyMessagesContentUri = true;
            break;
        case MATCH_MESSAGES_BY_PACKET_ID:
            String packetId = decodeURLSegment(url.getPathSegments().get(1));
            // FIXME these should be going to memory but they do not
            tableToChange = TABLE_MESSAGES;
            appendWhere(whereClause, Imps.Messages.PACKET_ID, "=", packetId);
            notifyMessagesContentUri = true;
            notifyMessagesByThreadIdContentUri = true;
            break;
        case MATCH_OTR_MESSAGES_BY_PACKET_ID:
            String packetIdOtr = decodeURLSegment(url.getPathSegments().get(1));
            // FIXME these should be going to memory but they do not
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            appendWhere(whereClause, Imps.Messages.PACKET_ID, "=", packetIdOtr);
            notifyMessagesContentUri = true;
            notifyMessagesByThreadIdContentUri = true;
            break;
        case MATCH_MESSAGES_BY_PROVIDER:
            tableToChange = TABLE_MESSAGES;
            provider = decodeURLSegment(url.getPathSegments().get(1));
            appendWhere(whereClause, buildContactIdSelection(Imps.Messages.THREAD_ID, Imps.Contacts.PROVIDER + "='" + provider + "'"));
            notifyMessagesContentUri = true;
            break;
        case MATCH_MESSAGES_BY_ACCOUNT:
            tableToChange = TABLE_MESSAGES;
            accountStr = decodeURLSegment(url.getPathSegments().get(1));
            appendWhere(whereClause, buildContactIdSelection(Imps.Messages.THREAD_ID, Imps.Contacts.ACCOUNT + "='" + accountStr + "'"));
            notifyMessagesContentUri = true;
            break;
        case MATCH_MESSAGE:
            tableToChange = TABLE_MESSAGES;
            changedItemId = url.getPathSegments().get(1);
            notifyMessagesContentUri = true;
            break;
        case MATCH_OTR_MESSAGES:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            break;
        case MATCH_OTR_MESSAGES_BY_CONTACT:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            accountStr = decodeURLSegment(url.getPathSegments().get(1));
            try {
                account = Long.parseLong(accountStr);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException();
            }
            contact = decodeURLSegment(url.getPathSegments().get(2));
            appendWhere(whereClause, Imps.Messages.THREAD_ID, "=", getContactId(db, accountStr, contact));
            notifyMessagesByContactContentUri = true;
            break;
        case MATCH_OTR_MESSAGES_BY_THREAD_ID:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            try {
                threadId = Long.parseLong(decodeURLSegment(url.getPathSegments().get(1)));
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException();
            }
            appendWhere(whereClause, Imps.Messages.THREAD_ID, "=", threadId);
            notifyMessagesByThreadIdContentUri = true;
            break;
        case MATCH_OTR_MESSAGES_BY_PROVIDER:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            provider = decodeURLSegment(url.getPathSegments().get(1));
            appendWhere(whereClause, buildContactIdSelection(Imps.Messages.THREAD_ID, Imps.Contacts.PROVIDER + "='" + provider + "'"));
            log("delete (MATCH_OTR_MESSAGES_BY_PROVIDER) sel => " + whereClause);
            notifyMessagesContentUri = true;
            break;
        case MATCH_OTR_MESSAGES_BY_ACCOUNT:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            accountStr = decodeURLSegment(url.getPathSegments().get(1));
            appendWhere(whereClause, buildContactIdSelection(Imps.Messages.THREAD_ID, Imps.Contacts.ACCOUNT + "='" + accountStr + "'"));
            log("delete (MATCH_OTR_MESSAGES_BY_ACCOUNT) sel => " + whereClause);
            notifyMessagesContentUri = true;
            break;
        case MATCH_OTR_MESSAGE:
            tableToChange = TABLE_IN_MEMORY_MESSAGES;
            changedItemId = url.getPathSegments().get(1);
            notifyMessagesContentUri = true;
            break;
        case MATCH_GROUP_MEMBERS:
            tableToChange = TABLE_GROUP_MEMBERS;
            break;
        case MATCH_GROUP_MEMBERS_BY_GROUP:
            tableToChange = TABLE_GROUP_MEMBERS;
            appendWhere(whereClause, Imps.GroupMembers.GROUP, "=", url.getPathSegments().get(1));
            break;
        case MATCH_INVITATIONS:
            tableToChange = TABLE_INVITATIONS;
            break;
        case MATCH_INVITATION:
            tableToChange = TABLE_INVITATIONS;
            changedItemId = url.getPathSegments().get(1);
            break;
        case MATCH_AVATARS:
            tableToChange = TABLE_AVATARS;
            break;
        case MATCH_AVATAR:
            tableToChange = TABLE_AVATARS;
            changedItemId = url.getPathSegments().get(1);
            break;
        case MATCH_AVATAR_BY_PROVIDER:
            tableToChange = TABLE_AVATARS;
            changedItemId = url.getPathSegments().get(2);
            idColumnName = Imps.Avatars.ACCOUNT;
            break;
        case MATCH_CHATS:
            tableToChange = TABLE_CHATS;
            backfillQuickSwitchSlots = true;
            // For updating account stats in account list
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_CHATS_BY_ACCOUNT:
            tableToChange = TABLE_CHATS;
            accountStr = decodeURLSegment(url.getLastPathSegment());
            appendWhere(whereClause, buildContactIdSelection(Imps.Chats.CONTACT_ID, Imps.Contacts.ACCOUNT + "='" + accountStr + "'"));
            log("delete (MATCH_CHATS_BY_ACCOUNT) sel => " + whereClause);
            changedItemId = null;
            // For updating account stats in account list
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_CHATS_ID:
            tableToChange = TABLE_CHATS;
            changedItemId = url.getPathSegments().get(1);
            idColumnName = Imps.Chats.CONTACT_ID;
            // For updating account stats in account list
            notifyProviderAccountContentUri = true;
            break;
        case MATCH_PRESENCE:
            tableToChange = TABLE_PRESENCE;
            break;
        case MATCH_PRESENCE_ID:
            tableToChange = TABLE_PRESENCE;
            changedItemId = url.getPathSegments().get(1);
            idColumnName = Imps.Presence.CONTACT_ID;
            break;
        case MATCH_PRESENCE_BY_ACCOUNT:
            tableToChange = TABLE_PRESENCE;
            accountStr = decodeURLSegment(url.getLastPathSegment());
            appendWhere(whereClause, buildContactIdSelection(Imps.Presence.CONTACT_ID, Imps.Contacts.ACCOUNT + "='" + accountStr + "'"));
            log("delete (MATCH_PRESENCE_BY_ACCOUNT): sel => " + whereClause);
            changedItemId = null;
            break;
        case MATCH_SESSIONS:
            tableToChange = TABLE_SESSION_COOKIES;
            break;
        case MATCH_SESSIONS_BY_PROVIDER:
            tableToChange = TABLE_SESSION_COOKIES;
            changedItemId = url.getPathSegments().get(2);
            idColumnName = Imps.SessionCookies.ACCOUNT;
            break;
        case MATCH_PROVIDER_SETTINGS_BY_ID:
            tableToChange = TABLE_PROVIDER_SETTINGS;
            changedItemId = url.getPathSegments().get(1);
            idColumnName = Imps.ProviderSettings.PROVIDER;
            break;
        case MATCH_PROVIDER_SETTINGS_BY_ID_AND_NAME:
            tableToChange = TABLE_PROVIDER_SETTINGS;
            String providerId = url.getPathSegments().get(1);
            String name = url.getPathSegments().get(2);
            appendWhere(whereClause, Imps.ProviderSettings.PROVIDER, "=", providerId);
            appendWhere(whereClause, Imps.ProviderSettings.NAME, "=", name);
            break;
        case MATCH_BRANDING_RESOURCE_MAP_CACHE:
            tableToChange = TABLE_BRANDING_RESOURCE_MAP_CACHE;
            break;
        // mcs/rmq stuff
        case MATCH_OUTGOING_RMQ_MESSAGES:
            tableToChange = TABLE_OUTGOING_RMQ_MESSAGES;
            break;
        case MATCH_LAST_RMQ_ID:
            tableToChange = TABLE_LAST_RMQ_ID;
            break;
        case MATCH_S2D_RMQ_IDS:
            tableToChange = TABLE_S2D_RMQ_IDS;
            break;
        // ChatSecure-Push
        case MATCH_CSP_ACCOUNTS:
            tableToChange = TABLE_CSP_ACCOUNTS;
            break;
        case MATCH_CSP_DEVICES:
            tableToChange = TABLE_CSP_DEVICES;
            break;
        case MATCH_CSP_TOKENS:
            tableToChange = TABLE_CSP_TOKENS;
            break;
        default:
            throw new UnsupportedOperationException("Cannot delete that URL: " + url);
    }
    if (idColumnName == null) {
        idColumnName = "_id";
    }
    if (changedItemId != null) {
        appendWhere(whereClause, idColumnName, "=", changedItemId);
    }
    log("delete from " + url + " WHERE  " + whereClause);
    int count = db.delete(tableToChange, whereClause.toString(), whereArgs);
    // see the comment at the declaration of tableToChange2 for an explanation
    if (tableToChange2 != null) {
        count += db.delete(tableToChange2, whereClause.toString(), whereArgs);
    }
    if (contactDeleted && count > 0) {
        // since the contact cleanup triggers no longer work for cross database tables,
        // we have to do it by hand here.
        performContactRemovalCleanup(deletedContactId);
    }
    if (count > 0) {
        ContentResolver resolver = getContext().getContentResolver();
        // we should also notify that contacts changes when presence or chats changed.
        if (match == MATCH_CHATS || match == MATCH_CHATS_ID || match == MATCH_PRESENCE || match == MATCH_PRESENCE_ID || match == MATCH_CONTACTS_BAREBONE) {
            resolver.notifyChange(Imps.Contacts.CONTENT_URI, null);
        }
        if (notifyMessagesContentUri) {
            resolver.notifyChange(Imps.Messages.CONTENT_URI, null);
        }
        if (notifyMessagesByContactContentUri) {
            resolver.notifyChange(Imps.Messages.CONTENT_URI, null);
            resolver.notifyChange(Imps.Messages.getContentUriByContact(account, contact), null);
        }
        if (notifyMessagesByThreadIdContentUri) {
            resolver.notifyChange(Imps.Messages.CONTENT_URI, null);
            resolver.notifyChange(Imps.Messages.getContentUriByThreadId(threadId), null);
        }
        if (notifyContactListContentUri) {
            resolver.notifyChange(Imps.ContactList.CONTENT_URI, null);
        }
        if (notifyProviderAccountContentUri) {
            log("notify delete for " + Imps.Provider.CONTENT_URI_WITH_ACCOUNT);
            resolver.notifyChange(Imps.Provider.CONTENT_URI_WITH_ACCOUNT, null);
        }
        if (backfillQuickSwitchSlots) {
            backfillQuickSwitchSlots();
        }
    }
    return count;
}
Also used : SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) ContentResolver(android.content.ContentResolver)

Example 57 with SQLiteDatabase

use of net.sqlcipher.database.SQLiteDatabase in project Zom-Android by zom.

the class ImpsProvider method seedInitialPresenceByAccount.

/**
 * make sure the presence for all contacts of a given account is set to
 * offline, and each contact has a presence row associated with it. However,
 * this method does not remove presences for which the corresponding
 * contacts no longer exist. That's probably ok since presence is kept in
 * memory, so it won't stay around for too long. Here is the algorithm.
 *
 * 1. for all presence that have a corresponding contact, make it OFFLINE.
 * This is one sqlite call. 2. query for all the contacts that don't have a
 * presence, and add a presence row for them.
 *
 * TODO simplify the presence management! The desire is to have a presence
 * row for each TODO contact in the database, so later we can just call
 * update() on the presence rows TODO instead of checking for the existence
 * of presence first. The assumption is we get TODO presence updates much
 * more frequently. However, the logic to maintain that goal is TODO overly
 * complicated. One possible solution is to use insert_or_replace the
 * presence rows TODO when updating the presence. That way we don't always
 * need to maintain an empty presence TODO row for each contact.
 *
 * @param account the account of the contacts for which we want to create
 *            seed presence rows.
 */
private void seedInitialPresenceByAccount(long account) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(TABLE_CONTACTS);
    qb.setProjectionMap(sContactsProjectionMap);
    mQueryContactIdSelectionArgs1[0] = String.valueOf(account);
    final SQLiteDatabase db = getDBHelper().getWritableDatabase();
    db.beginTransaction();
    Cursor c = null;
    try {
        ContentValues presenceValues = new ContentValues();
        presenceValues.put(Imps.Presence.PRESENCE_STATUS, Imps.Presence.OFFLINE);
        presenceValues.put(Imps.Presence.PRESENCE_CUSTOM_STATUS, "");
        // update all the presence for the account so they are offline
        StringBuilder buf = new StringBuilder();
        buf.append(Imps.Presence.CONTACT_ID);
        buf.append(" in (select ");
        buf.append(Imps.Contacts._ID);
        buf.append(" from ");
        buf.append(TABLE_CONTACTS);
        buf.append(" where ");
        buf.append(Imps.Contacts.ACCOUNT);
        buf.append("=?) ");
        String selection = buf.toString();
        log("seedInitialPresence: reset presence selection=" + selection);
        int count = db.update(TABLE_PRESENCE, presenceValues, selection, mQueryContactIdSelectionArgs1);
        log("seedInitialPresence: reset " + count + " presence rows to OFFLINE");
        // for in-memory presence table, add a presence row for each contact that
        // doesn't have a presence. in-memory presence table isn't reliable, and goes away
        // when device reboot or IMProvider process dies, so we can't rely on each contact
        // have a corresponding presence.
        {
            log("seedInitialPresence: contacts_with_no_presence_selection => " + CONTACTS_WITH_NO_PRESENCE_SELECTION);
        }
        c = qb.query(db, CONTACT_ID_PROJECTION, CONTACTS_WITH_NO_PRESENCE_SELECTION, mQueryContactIdSelectionArgs1, null, null, null, null);
        log("seedInitialPresence: found " + c.getCount() + " contacts w/o presence");
        count = 0;
        while (c.moveToNext()) {
            long id = c.getLong(CONTACT_ID_COLUMN);
            presenceValues.put(Imps.Presence.CONTACT_ID, id);
            try {
                if (db.insert(TABLE_PRESENCE, null, presenceValues) > 0) {
                    count++;
                }
            } catch (SQLiteConstraintException ex) {
                // we could possibly catch this exception, since there could be a presence
                // row with the same contact_id. That's fine, just ignore the error
                log("seedInitialPresence: insert presence for contact_id " + id + " failed, caught " + ex);
            }
        }
        log("seedInitialPresence: added " + count + " new presence rows");
        db.setTransactionSuccessful();
    } finally {
        if (c != null) {
            c.close();
        }
        db.endTransaction();
    }
}
Also used : ContentValues(android.content.ContentValues) SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) SQLiteConstraintException(net.sqlcipher.database.SQLiteConstraintException) Cursor(android.database.Cursor) SQLiteQueryBuilder(net.sqlcipher.database.SQLiteQueryBuilder)

Example 58 with SQLiteDatabase

use of net.sqlcipher.database.SQLiteDatabase in project Android-Debug-Database by amitshekhariitbhu.

the class PersonDBHelper method getData.

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase(DB_PASSWORD);
    Cursor res = db.rawQuery("select * from person where id=" + id + "", null);
    return res;
}
Also used : SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) Cursor(android.database.Cursor)

Example 59 with SQLiteDatabase

use of net.sqlcipher.database.SQLiteDatabase in project storymaker by StoryMaker.

the class BaseHomeActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // copy index file
    // TODO: REPLACE THIS WITH INDEX DOWNLOAD (IF LOGGED IN) <- NEED TO COPY FILE FOR BASELINE CONTENT
    StorymakerIndexManager.copyAvailableIndex(this, false);
    // initialize db
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // version check (sqlite upgrade requires migration)
    int appMigrationVersion = preferences.getInt("APP_MIGRATION_VERSION", 0);
    Timber.d("MIGRATION CHECK: " + appMigrationVersion + " vs. " + Constants.APP_MIGRATION_VERSION);
    if (appMigrationVersion != Constants.APP_MIGRATION_VERSION) {
        Timber.d("MIGRATION REQUIRED, RE-ENCRYPTING DATABASE");
        final boolean[] dbStatus = { false };
        try {
            SQLiteDatabaseHook dbHook = new SQLiteDatabaseHook() {

                public void preKey(SQLiteDatabase database) {
                }

                public void postKey(SQLiteDatabase database) {
                    Cursor cursor = database.rawQuery("PRAGMA cipher_migrate", new String[] {});
                    String value = "";
                    if (cursor != null) {
                        cursor.moveToFirst();
                        value = cursor.getString(0);
                        cursor.close();
                    }
                    // this result is currently ignored, checking if db is null instead
                    dbStatus[0] = Integer.valueOf(value) == 0;
                }
            };
            File dbPath = getDatabasePath("sm.db");
            Timber.d("MIGRATING DATABASE AT " + dbPath.getPath());
            SQLiteDatabase sqldb = SQLiteDatabase.openOrCreateDatabase(dbPath, "foo", null, dbHook);
            if (sqldb != null) {
                Timber.d("MIGRATED DATABASE NOT NULL");
                sqldb.close();
                // update preferences if migration succeeded
                preferences.edit().putInt("APP_MIGRATION_VERSION", Constants.APP_MIGRATION_VERSION).commit();
            } else {
                Timber.e("MIGRATED DATABASE IS NULL");
            }
        } catch (Exception ex) {
            Timber.e("EXCEPTION WHILE MIGRATING DATABASE: " + ex.getMessage());
        }
    }
    int availableIndexVersion = preferences.getInt("AVAILABLE_INDEX_VERSION", 0);
    Timber.d("VERSION CHECK: " + availableIndexVersion + " vs. " + scal.io.liger.Constants.AVAILABLE_INDEX_VERSION);
    if (availableIndexVersion != scal.io.liger.Constants.AVAILABLE_INDEX_VERSION) {
        // load db from file
        HashMap<String, scal.io.liger.model.ExpansionIndexItem> availableItemsFromFile = scal.io.liger.IndexManager.loadAvailableIdIndex(this);
        if (availableItemsFromFile.size() == 0) {
            Timber.d("NOTHING LOADED FROM AVAILABLE FILE");
        } else {
            for (scal.io.liger.model.ExpansionIndexItem item : availableItemsFromFile.values()) {
                Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (AVAILABLE)");
                // replaces existing items, should trigger updates to installed items and table as needed
                availableIndexItemDao.addAvailableIndexItem(item, true);
                // ugly solution to deal with the fact that the popup menu assumes there will be threads for an item we tried to download/install
                ArrayList<Thread> noThreads = new ArrayList<Thread>();
                downloadThreads.put(item.getExpansionId(), noThreads);
            }
        }
        // the following migration stuff is currently piggy-backing on the index update stuff
        // if found, migrate installed index
        File installedFile = new File(StorageHelper.getActualStorageDirectory(this), "installed_index.json");
        if (installedFile.exists()) {
            HashMap<String, scal.io.liger.model.ExpansionIndexItem> installedItemsFromFile = scal.io.liger.IndexManager.loadInstalledIdIndex(this);
            if (installedItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTALLED INDEX FILE");
            } else {
                for (scal.io.liger.model.ExpansionIndexItem item : installedItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (INSTALLED)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    installedIndexItemDao.addInstalledIndexItem(item, true);
                }
            }
            installedFile.delete();
        } else {
            Timber.d("NO INSTALLED INDEX FILE");
        }
        // if found, migrate instance index
        File instanceFile = new File(StorageHelper.getActualStorageDirectory(this), "instance_index.json");
        if (instanceFile.exists()) {
            HashMap<String, scal.io.liger.model.InstanceIndexItem> instanceItemsFromFile = scal.io.liger.IndexManager.loadInstanceIndex(this);
            if (instanceItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTANCE INDEX FILE");
            } else {
                for (scal.io.liger.model.InstanceIndexItem item : instanceItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getInstanceFilePath() + " TO DATABASE (INSTANCE)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    instanceIndexItemDao.addInstanceIndexItem(item, true);
                }
            }
            instanceFile.delete();
        } else {
            Timber.d("NO INSTANCE INDEX FILE");
        }
        // update preferences
        preferences.edit().putInt("AVAILABLE_INDEX_VERSION", scal.io.liger.Constants.AVAILABLE_INDEX_VERSION).commit();
        if (getIntent() != null && getIntent().hasExtra("showlauncher")) {
            if (getIntent().getBooleanExtra("showlauncher", false)) {
                showLauncherIcon();
            }
        }
    }
    // dumb test
    // check values
    availableIndexItemDao.getAvailableIndexItems().take(1).subscribe(new Action1<List<AvailableIndexItem>>() {

        @Override
        public void call(List<AvailableIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("AVAILABLE ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    installedIndexItemDao.getInstalledIndexItems().take(1).subscribe(new Action1<List<InstalledIndexItem>>() {

        @Override
        public void call(List<InstalledIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("INSTALLED ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    // file cleanup
    File actualStorageDirectory = StorageHelper.getActualStorageDirectory(this);
    if (actualStorageDirectory != null) {
        JsonHelper.cleanup(actualStorageDirectory.getPath());
    } else {
    // this is an error, will deal with it below
    }
    // default
    loggedIn = false;
    if (actualStorageDirectory != null) {
        // NEW/TEMP
        // DOWNLOAD AVAILABE INDEX FOR CURRENT USER AND SAVE TO TARGET FILE
        // NEED TO ACCOUNT FOR POSSIBLE MISSING INDEX
        // force download at startup (maybe only force on a timetable?)
        IndexTask iTask = new IndexTask(this, true);
        iTask.execute();
    } else {
        // show storage error message
        new AlertDialog.Builder(this).setTitle(Utils.getAppName(this)).setIcon(android.R.drawable.ic_dialog_info).setMessage(R.string.err_storage_not_available).show();
    }
    // we want to grab required updates without restarting the app
    // integrate with index task
    // if (!DownloadHelper.checkAndDownload(this)) {
    // Toast.makeText(this, "Downloading content and/or updating installed files", Toast.LENGTH_LONG).show(); // FIXME move to strings.xml
    // }
    // i don't think we ever want to do this
    // IndexManager.copyInstalledIndex(this);
    // setContentView(R.layout.activity_home);
    // mRecyclerView = (RecyclerView) findViewById(scal.io.liger.R.id.recyclerView);
    // mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    // mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    // mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    // @Override
    // public void onRefresh() {
    // IndexTask iTask = new IndexTask(HomeActivity.this, true); // force download on manual refresh
    // iTask.execute();
    // }
    // });
    // mTabMenu = getMenu("home");
    // action bar stuff
    getActionBar().setDisplayHomeAsUpEnabled(true);
    checkForTor();
    checkForUpdates();
}
Also used : ArrayList(java.util.ArrayList) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) InstalledIndexItem(scal.io.liger.model.sqlbrite.InstalledIndexItem) Cursor(net.sqlcipher.Cursor) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) AvailableIndexItem(scal.io.liger.model.sqlbrite.AvailableIndexItem) List(java.util.List) ArrayList(java.util.ArrayList) SharedPreferences(android.content.SharedPreferences) IOException(java.io.IOException) SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) File(java.io.File) SQLiteDatabaseHook(net.sqlcipher.database.SQLiteDatabaseHook)

Example 60 with SQLiteDatabase

use of net.sqlcipher.database.SQLiteDatabase in project storymaker by StoryMaker.

the class ProjectsProvider method update.

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    mCacheWordHandler.connectToService();
    setTimer(60000);
    SQLiteDatabase db = getDB();
    if (db != null) {
        int uriType = sURIMatcher.match(uri);
        switch(uriType) {
            case PROJECTS:
            case PROJECT_ID:
                return (new ProjectTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case SCENES:
            case SCENE_ID:
                return (new SceneTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case LESSONS:
            case LESSON_ID:
                return (new LessonTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case MEDIA:
            case MEDIA_ID:
                return (new MediaTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case AUTH:
            case AUTH_ID:
                return (new AuthTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case TAGS:
            case TAG_ID:
            case DISTINCT_TAGS:
            case DISTINCT_TAG_ID:
                return (new TagTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case JOBS:
            case JOB_ID:
                return (new JobTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case PUBLISH_JOBS:
            case PUBLISH_JOB_ID:
                return (new PublishJobTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            case AUDIO_CLIPS:
            case AUDIO_CLIP_ID:
                return (new AudioClipTable(db)).update(getContext(), uri, values, selection, selectionArgs);
            default:
                throw new IllegalArgumentException("Unknown URI");
        }
    }
    return 0;
}
Also used : SceneTable(org.storymaker.app.model.SceneTable) PublishJobTable(org.storymaker.app.model.PublishJobTable) JobTable(org.storymaker.app.model.JobTable) PublishJobTable(org.storymaker.app.model.PublishJobTable) MediaTable(org.storymaker.app.model.MediaTable) SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) AudioClipTable(org.storymaker.app.model.AudioClipTable) AuthTable(org.storymaker.app.model.AuthTable) TagTable(org.storymaker.app.model.TagTable) ProjectTable(org.storymaker.app.model.ProjectTable) LessonTable(org.storymaker.app.model.LessonTable)

Aggregations

SQLiteDatabase (net.sqlcipher.database.SQLiteDatabase)124 Cursor (android.database.Cursor)37 ContentValues (android.content.ContentValues)32 IOException (java.io.IOException)15 LinkedList (java.util.LinkedList)12 NonNull (android.support.annotation.NonNull)7 MergeCursor (android.database.MergeCursor)6 Nullable (android.support.annotation.Nullable)6 Pair (android.util.Pair)6 File (java.io.File)5 SQLiteConstraintException (net.sqlcipher.database.SQLiteConstraintException)5 FileNotFoundException (java.io.FileNotFoundException)4 StreamCorruptedException (java.io.StreamCorruptedException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 AudioClipTable (org.storymaker.app.model.AudioClipTable)4 AuthTable (org.storymaker.app.model.AuthTable)4 JobTable (org.storymaker.app.model.JobTable)4 LessonTable (org.storymaker.app.model.LessonTable)4 MediaTable (org.storymaker.app.model.MediaTable)4 ProjectTable (org.storymaker.app.model.ProjectTable)4