Search in sources :

Example 6 with Storage

use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.

the class SettingsImporter method importSettings.

/**
     * Reads an import {@link InputStream} and imports the global settings and/or account
     * configurations specified by the arguments.
     *
     * @param context
     *         A {@link Context} instance.
     * @param inputStream
     *         The {@code InputStream} to read the settings from.
     * @param globalSettings
     *         {@code true} if global settings should be imported from the file.
     * @param accountUuids
     *         A list of UUIDs of the accounts that should be imported.
     * @param overwrite
     *         {@code true} if existing accounts should be overwritten when an account with the
     *         same UUID is found in the settings file.<br>
     *         <strong>Note:</strong> This can have side-effects we currently don't handle, e.g.
     *         changing the account type from IMAP to POP3. So don't use this for now!
     *
     * @return An {@link ImportResults} instance containing information about errors and
     *         successfully imported accounts.
     *
     * @throws SettingsImportExportException
     *         In case of an error.
     */
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException {
    try {
        boolean globalSettingsImported = false;
        List<AccountDescriptionPair> importedAccounts = new ArrayList<>();
        List<AccountDescription> erroneousAccounts = new ArrayList<>();
        Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false);
        Preferences preferences = Preferences.getPreferences(context);
        Storage storage = preferences.getStorage();
        if (globalSettings) {
            try {
                StorageEditor editor = storage.edit();
                if (imported.globalSettings != null) {
                    importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings);
                } else {
                    Timber.w("Was asked to import global settings but none found.");
                }
                if (editor.commit()) {
                    Timber.v("Committed global settings to the preference storage.");
                    globalSettingsImported = true;
                } else {
                    Timber.v("Failed to commit global settings to the preference storage");
                }
            } catch (Exception e) {
                Timber.e(e, "Exception while importing global settings");
            }
        }
        if (accountUuids != null && accountUuids.size() > 0) {
            if (imported.accounts != null) {
                for (String accountUuid : accountUuids) {
                    if (imported.accounts.containsKey(accountUuid)) {
                        ImportedAccount account = imported.accounts.get(accountUuid);
                        try {
                            StorageEditor editor = storage.edit();
                            AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite);
                            if (editor.commit()) {
                                Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name);
                                // account UUIDs
                                if (!importResult.overwritten) {
                                    editor = storage.edit();
                                    String newUuid = importResult.imported.uuid;
                                    String oldAccountUuids = storage.getString("accountUuids", "");
                                    String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid;
                                    putString(editor, "accountUuids", newAccountUuids);
                                    if (!editor.commit()) {
                                        throw new SettingsImportExportException("Failed to set account UUID list");
                                    }
                                }
                                // Reload accounts
                                preferences.loadAccounts();
                                importedAccounts.add(importResult);
                            } else {
                                Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name);
                                erroneousAccounts.add(importResult.original);
                            }
                        } catch (InvalidSettingValueException e) {
                            Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name);
                            erroneousAccounts.add(new AccountDescription(account.name, account.uuid));
                        } catch (Exception e) {
                            Timber.e(e, "Exception while importing account \"%s\"", account.name);
                            erroneousAccounts.add(new AccountDescription(account.name, account.uuid));
                        }
                    } else {
                        Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid);
                    }
                }
                StorageEditor editor = storage.edit();
                String defaultAccountUuid = storage.getString("defaultAccountUuid", null);
                if (defaultAccountUuid == null) {
                    putString(editor, "defaultAccountUuid", accountUuids.get(0));
                }
                if (!editor.commit()) {
                    throw new SettingsImportExportException("Failed to set default account");
                }
            } else {
                Timber.w("Was asked to import at least one account but none found.");
            }
        }
        preferences.loadAccounts();
        K9.loadPrefs(preferences);
        K9.setServicesEnabled(context);
        return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts);
    } catch (SettingsImportExportException e) {
        throw e;
    } catch (Exception e) {
        throw new SettingsImportExportException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) SharedPreferences(android.content.SharedPreferences) Preferences(com.fsck.k9.Preferences)

Example 7 with Storage

use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.

the class EmailProvider method getAccountStats.

private Cursor getAccountStats(String accountUuid, String[] columns, final String selection, final String[] selectionArgs) {
    Account account = getAccount(accountUuid);
    LockableDatabase database = getDatabase(account);
    // Use default projection if none was given
    String[] sourceProjection = (columns == null) ? STATS_DEFAULT_PROJECTION : columns;
    // Create SQL query string
    final StringBuilder sql = new StringBuilder();
    sql.append("SELECT ");
    // Append projection for the database query
    // e.g. "SUM(read=0) AS unread_count, SUM(flagged) AS flagged_count"
    boolean first = true;
    for (String columnName : sourceProjection) {
        if (!first) {
            sql.append(',');
        } else {
            first = false;
        }
        if (StatsColumns.UNREAD_COUNT.equals(columnName)) {
            sql.append("SUM(" + MessageColumns.READ + "=0) AS " + StatsColumns.UNREAD_COUNT);
        } else if (StatsColumns.FLAGGED_COUNT.equals(columnName)) {
            sql.append("SUM(" + MessageColumns.FLAGGED + ") AS " + StatsColumns.FLAGGED_COUNT);
        } else {
            throw new IllegalArgumentException("Column name not allowed: " + columnName);
        }
    }
    // Table selection
    sql.append(" FROM messages");
    if (containsAny(selection, FOLDERS_COLUMNS)) {
        sql.append(" JOIN folders ON (folders.id = messages.folder_id)");
    }
    // WHERE clause
    sql.append(" WHERE (deleted = 0 AND empty = 0)");
    if (!TextUtils.isEmpty(selection)) {
        sql.append(" AND (");
        sql.append(selection);
        sql.append(")");
    }
    // Query the database and return the result cursor
    try {
        return database.execute(false, new DbCallback<Cursor>() {

            @Override
            public Cursor doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
                return db.rawQuery(sql.toString(), selectionArgs);
            }
        });
    } catch (UnavailableStorageException e) {
        throw new RuntimeException("Storage not available", e);
    } catch (MessagingException e) {
        throw new RuntimeException("messaging exception", e);
    }
}
Also used : Account(com.fsck.k9.Account) WrappedException(com.fsck.k9.mailstore.LockableDatabase.WrappedException) MessagingException(com.fsck.k9.mail.MessagingException) UnavailableStorageException(com.fsck.k9.mailstore.UnavailableStorageException) EmailProviderCacheCursor(com.fsck.k9.cache.EmailProviderCacheCursor) Cursor(android.database.Cursor) LockableDatabase(com.fsck.k9.mailstore.LockableDatabase) SQLiteDatabase(android.database.sqlite.SQLiteDatabase)

Example 8 with Storage

use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.

the class EmailProvider method getMessages.

protected Cursor getMessages(String accountUuid, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) {
    Account account = getAccount(accountUuid);
    LockableDatabase database = getDatabase(account);
    try {
        return database.execute(false, new DbCallback<Cursor>() {

            @Override
            public Cursor doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
                String where;
                if (TextUtils.isEmpty(selection)) {
                    where = InternalMessageColumns.DELETED + " = 0 AND " + InternalMessageColumns.EMPTY + " = 0";
                } else {
                    where = "(" + selection + ") AND " + InternalMessageColumns.DELETED + " = 0 AND " + InternalMessageColumns.EMPTY + " = 0";
                }
                final Cursor cursor;
                if (Utility.arrayContainsAny(projection, (Object[]) FOLDERS_COLUMNS)) {
                    StringBuilder query = new StringBuilder();
                    query.append("SELECT ");
                    boolean first = true;
                    for (String columnName : projection) {
                        if (!first) {
                            query.append(",");
                        } else {
                            first = false;
                        }
                        if (MessageColumns.ID.equals(columnName)) {
                            query.append("m.");
                            query.append(MessageColumns.ID);
                            query.append(" AS ");
                            query.append(MessageColumns.ID);
                        } else {
                            query.append(columnName);
                        }
                    }
                    query.append(" FROM messages m " + "JOIN threads t ON (t.message_id = m.id) " + "LEFT JOIN folders f ON (m.folder_id = f.id) " + "WHERE ");
                    query.append(SqlQueryBuilder.addPrefixToSelection(FIXUP_MESSAGES_COLUMNS, "m.", where));
                    query.append(" ORDER BY ");
                    query.append(SqlQueryBuilder.addPrefixToSelection(FIXUP_MESSAGES_COLUMNS, "m.", sortOrder));
                    cursor = db.rawQuery(query.toString(), selectionArgs);
                } else {
                    cursor = db.query(MESSAGES_TABLE, projection, where, selectionArgs, null, null, sortOrder);
                }
                return cursor;
            }
        });
    } catch (UnavailableStorageException e) {
        throw new RuntimeException("Storage not available", e);
    } catch (MessagingException e) {
        throw new RuntimeException("messaging exception", e);
    }
}
Also used : Account(com.fsck.k9.Account) WrappedException(com.fsck.k9.mailstore.LockableDatabase.WrappedException) LockableDatabase(com.fsck.k9.mailstore.LockableDatabase) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) MessagingException(com.fsck.k9.mail.MessagingException) UnavailableStorageException(com.fsck.k9.mailstore.UnavailableStorageException) EmailProviderCacheCursor(com.fsck.k9.cache.EmailProviderCacheCursor) Cursor(android.database.Cursor)

Example 9 with Storage

use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.

the class EmailProvider method getThread.

protected Cursor getThread(String accountUuid, final String[] projection, final String threadId, final String sortOrder) {
    Account account = getAccount(accountUuid);
    LockableDatabase database = getDatabase(account);
    try {
        return database.execute(false, new DbCallback<Cursor>() {

            @Override
            public Cursor doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
                StringBuilder query = new StringBuilder();
                query.append("SELECT ");
                boolean first = true;
                for (String columnName : projection) {
                    if (!first) {
                        query.append(",");
                    } else {
                        first = false;
                    }
                    if (MessageColumns.ID.equals(columnName)) {
                        query.append("m." + MessageColumns.ID + " AS " + MessageColumns.ID);
                    } else {
                        query.append(columnName);
                    }
                }
                query.append(" FROM " + THREADS_TABLE + " t JOIN " + MESSAGES_TABLE + " m " + "ON (m." + MessageColumns.ID + " = t." + ThreadColumns.MESSAGE_ID + ") ");
                if (Utility.arrayContainsAny(projection, (Object[]) FOLDERS_COLUMNS)) {
                    query.append("LEFT JOIN " + FOLDERS_TABLE + " f " + "ON (m." + MessageColumns.FOLDER_ID + " = f." + FolderColumns.ID + ") ");
                }
                query.append("WHERE " + ThreadColumns.ROOT + " = ? AND " + InternalMessageColumns.DELETED + " = 0 AND " + InternalMessageColumns.EMPTY + " = 0");
                query.append(" ORDER BY ");
                query.append(SqlQueryBuilder.addPrefixToSelection(FIXUP_MESSAGES_COLUMNS, "m.", sortOrder));
                return db.rawQuery(query.toString(), new String[] { threadId });
            }
        });
    } catch (UnavailableStorageException e) {
        throw new RuntimeException("Storage not available", e);
    } catch (MessagingException e) {
        throw new RuntimeException("messaging exception", e);
    }
}
Also used : Account(com.fsck.k9.Account) WrappedException(com.fsck.k9.mailstore.LockableDatabase.WrappedException) LockableDatabase(com.fsck.k9.mailstore.LockableDatabase) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) MessagingException(com.fsck.k9.mail.MessagingException) UnavailableStorageException(com.fsck.k9.mailstore.UnavailableStorageException) EmailProviderCacheCursor(com.fsck.k9.cache.EmailProviderCacheCursor) Cursor(android.database.Cursor)

Example 10 with Storage

use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.

the class SettingsExporter method writeSettings.

private static void writeSettings(XmlSerializer serializer, Map<String, Object> prefs) throws IOException {
    for (Entry<String, TreeMap<Integer, SettingsDescription>> versionedSetting : GlobalSettings.SETTINGS.entrySet()) {
        String key = versionedSetting.getKey();
        String valueString = (String) prefs.get(key);
        TreeMap<Integer, SettingsDescription> versions = versionedSetting.getValue();
        Integer highestVersion = versions.lastKey();
        SettingsDescription setting = versions.get(highestVersion);
        if (setting == null) {
            // Setting was removed.
            continue;
        }
        if (valueString != null) {
            try {
                writeKeyAndPrettyValueFromSetting(serializer, key, setting, valueString);
            } catch (InvalidSettingValueException e) {
                Timber.w("Global setting \"%s\" has invalid value \"%s\" in preference storage. " + "This shouldn't happen!", key, valueString);
            }
        } else {
            Timber.d("Couldn't find key \"%s\" in preference storage. Using default value.", key);
            writeKeyAndDefaultValueFromSetting(serializer, key, setting);
        }
    }
}
Also used : SettingsDescription(com.fsck.k9.preferences.Settings.SettingsDescription) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) TreeMap(java.util.TreeMap)

Aggregations

MessagingException (com.fsck.k9.mail.MessagingException)12 Storage (com.fsck.k9.preferences.Storage)10 Account (com.fsck.k9.Account)9 UnavailableStorageException (com.fsck.k9.mailstore.UnavailableStorageException)8 InvalidSettingValueException (com.fsck.k9.preferences.Settings.InvalidSettingValueException)7 Preferences (com.fsck.k9.Preferences)6 StorageEditor (com.fsck.k9.preferences.StorageEditor)6 IOException (java.io.IOException)6 LocalFolder (com.fsck.k9.mailstore.LocalFolder)5 WrappedException (com.fsck.k9.mailstore.LockableDatabase.WrappedException)5 Cursor (android.database.Cursor)4 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 EmailProviderCacheCursor (com.fsck.k9.cache.EmailProviderCacheCursor)4 Folder (com.fsck.k9.mail.Folder)4 LocalMessage (com.fsck.k9.mailstore.LocalMessage)4 LocalStore (com.fsck.k9.mailstore.LocalStore)4 LockableDatabase (com.fsck.k9.mailstore.LockableDatabase)4 Map (java.util.Map)4 TreeMap (java.util.TreeMap)4 SuppressLint (android.annotation.SuppressLint)3