Search in sources :

Example 26 with Storage

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

the class Account method loadAccount.

/**
     * Load stored settings for this account.
     */
private synchronized void loadAccount(Preferences preferences) {
    Storage storage = preferences.getStorage();
    mStoreUri = Base64.decode(storage.getString(mUuid + ".storeUri", null));
    mLocalStorageProviderId = storage.getString(mUuid + ".localStorageProvider", StorageManager.getInstance(K9.app).getDefaultProviderId());
    mTransportUri = Base64.decode(storage.getString(mUuid + ".transportUri", null));
    mDescription = storage.getString(mUuid + ".description", null);
    mAlwaysBcc = storage.getString(mUuid + ".alwaysBcc", mAlwaysBcc);
    mAutomaticCheckIntervalMinutes = storage.getInt(mUuid + ".automaticCheckIntervalMinutes", -1);
    mIdleRefreshMinutes = storage.getInt(mUuid + ".idleRefreshMinutes", 24);
    mPushPollOnConnect = storage.getBoolean(mUuid + ".pushPollOnConnect", true);
    mDisplayCount = storage.getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT);
    if (mDisplayCount < 0) {
        mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
    }
    mLatestOldMessageSeenTime = storage.getLong(mUuid + ".latestOldMessageSeenTime", 0);
    mNotifyNewMail = storage.getBoolean(mUuid + ".notifyNewMail", false);
    mFolderNotifyNewMailMode = getEnumStringPref(storage, mUuid + ".folderNotifyNewMailMode", FolderMode.ALL);
    mNotifySelfNewMail = storage.getBoolean(mUuid + ".notifySelfNewMail", true);
    mNotifyContactsMailOnly = storage.getBoolean(mUuid + ".notifyContactsMailOnly", false);
    mNotifySync = storage.getBoolean(mUuid + ".notifyMailCheck", false);
    mDeletePolicy = DeletePolicy.fromInt(storage.getInt(mUuid + ".deletePolicy", DeletePolicy.NEVER.setting));
    mInboxFolderName = storage.getString(mUuid + ".inboxFolderName", INBOX);
    mDraftsFolderName = storage.getString(mUuid + ".draftsFolderName", "Drafts");
    mSentFolderName = storage.getString(mUuid + ".sentFolderName", "Sent");
    mTrashFolderName = storage.getString(mUuid + ".trashFolderName", "Trash");
    mArchiveFolderName = storage.getString(mUuid + ".archiveFolderName", "Archive");
    mSpamFolderName = storage.getString(mUuid + ".spamFolderName", "Spam");
    mExpungePolicy = getEnumStringPref(storage, mUuid + ".expungePolicy", Expunge.EXPUNGE_IMMEDIATELY);
    mSyncRemoteDeletions = storage.getBoolean(mUuid + ".syncRemoteDeletions", true);
    mMaxPushFolders = storage.getInt(mUuid + ".maxPushFolders", 10);
    goToUnreadMessageSearch = storage.getBoolean(mUuid + ".goToUnreadMessageSearch", false);
    subscribedFoldersOnly = storage.getBoolean(mUuid + ".subscribedFoldersOnly", false);
    maximumPolledMessageAge = storage.getInt(mUuid + ".maximumPolledMessageAge", -1);
    maximumAutoDownloadMessageSize = storage.getInt(mUuid + ".maximumAutoDownloadMessageSize", 32768);
    mMessageFormat = getEnumStringPref(storage, mUuid + ".messageFormat", DEFAULT_MESSAGE_FORMAT);
    mMessageFormatAuto = storage.getBoolean(mUuid + ".messageFormatAuto", DEFAULT_MESSAGE_FORMAT_AUTO);
    if (mMessageFormatAuto && mMessageFormat == MessageFormat.TEXT) {
        mMessageFormat = MessageFormat.AUTO;
    }
    mMessageReadReceipt = storage.getBoolean(mUuid + ".messageReadReceipt", DEFAULT_MESSAGE_READ_RECEIPT);
    mQuoteStyle = getEnumStringPref(storage, mUuid + ".quoteStyle", DEFAULT_QUOTE_STYLE);
    mQuotePrefix = storage.getString(mUuid + ".quotePrefix", DEFAULT_QUOTE_PREFIX);
    mDefaultQuotedTextShown = storage.getBoolean(mUuid + ".defaultQuotedTextShown", DEFAULT_QUOTED_TEXT_SHOWN);
    mReplyAfterQuote = storage.getBoolean(mUuid + ".replyAfterQuote", DEFAULT_REPLY_AFTER_QUOTE);
    mStripSignature = storage.getBoolean(mUuid + ".stripSignature", DEFAULT_STRIP_SIGNATURE);
    for (NetworkType type : NetworkType.values()) {
        Boolean useCompression = storage.getBoolean(mUuid + ".useCompression." + type, true);
        compressionMap.put(type, useCompression);
    }
    mAutoExpandFolderName = storage.getString(mUuid + ".autoExpandFolderName", INBOX);
    mAccountNumber = storage.getInt(mUuid + ".accountNumber", 0);
    mChipColor = storage.getInt(mUuid + ".chipColor", ColorPicker.getRandomColor());
    mSortType = getEnumStringPref(storage, mUuid + ".sortTypeEnum", SortType.SORT_DATE);
    mSortAscending.put(mSortType, storage.getBoolean(mUuid + ".sortAscending", false));
    mShowPictures = getEnumStringPref(storage, mUuid + ".showPicturesEnum", ShowPictures.NEVER);
    mNotificationSetting.setVibrate(storage.getBoolean(mUuid + ".vibrate", false));
    mNotificationSetting.setVibratePattern(storage.getInt(mUuid + ".vibratePattern", 0));
    mNotificationSetting.setVibrateTimes(storage.getInt(mUuid + ".vibrateTimes", 5));
    mNotificationSetting.setRing(storage.getBoolean(mUuid + ".ring", true));
    mNotificationSetting.setRingtone(storage.getString(mUuid + ".ringtone", "content://settings/system/notification_sound"));
    mNotificationSetting.setLed(storage.getBoolean(mUuid + ".led", true));
    mNotificationSetting.setLedColor(storage.getInt(mUuid + ".ledColor", mChipColor));
    mFolderDisplayMode = getEnumStringPref(storage, mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS);
    mFolderSyncMode = getEnumStringPref(storage, mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS);
    mFolderPushMode = getEnumStringPref(storage, mUuid + ".folderPushMode", FolderMode.FIRST_CLASS);
    mFolderTargetMode = getEnumStringPref(storage, mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS);
    searchableFolders = getEnumStringPref(storage, mUuid + ".searchableFolders", Searchable.ALL);
    mIsSignatureBeforeQuotedText = storage.getBoolean(mUuid + ".signatureBeforeQuotedText", false);
    identities = loadIdentities(storage);
    mCryptoKey = storage.getLong(mUuid + ".cryptoKey", NO_OPENPGP_KEY);
    mAllowRemoteSearch = storage.getBoolean(mUuid + ".allowRemoteSearch", false);
    mRemoteSearchFullText = storage.getBoolean(mUuid + ".remoteSearchFullText", false);
    mRemoteSearchNumResults = storage.getInt(mUuid + ".remoteSearchNumResults", DEFAULT_REMOTE_SEARCH_NUM_RESULTS);
    mEnabled = storage.getBoolean(mUuid + ".enabled", true);
    mMarkMessageAsReadOnView = storage.getBoolean(mUuid + ".markMessageAsReadOnView", true);
    mAlwaysShowCcBcc = storage.getBoolean(mUuid + ".alwaysShowCcBcc", false);
    cacheChips();
    // Use email address as account description if necessary
    if (mDescription == null) {
        mDescription = getEmail();
    }
}
Also used : Storage(com.fsck.k9.preferences.Storage) NetworkType(com.fsck.k9.mail.NetworkType)

Example 27 with Storage

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

the class EmailProvider method getThreadedMessages.

protected Cursor getThreadedMessages(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 {
                StringBuilder query = new StringBuilder();
                query.append("SELECT ");
                boolean first = true;
                for (String columnName : projection) {
                    if (!first) {
                        query.append(",");
                    } else {
                        first = false;
                    }
                    final String aggregationFunc = THREAD_AGGREGATION_FUNCS.get(columnName);
                    if (MessageColumns.ID.equals(columnName)) {
                        query.append("m." + MessageColumns.ID + " AS " + MessageColumns.ID);
                    } else if (aggregationFunc != null) {
                        query.append("a.");
                        query.append(columnName);
                        query.append(" AS ");
                        query.append(columnName);
                    } else {
                        query.append(columnName);
                    }
                }
                query.append(" FROM (");
                createThreadedSubQuery(projection, selection, query);
                query.append(") a ");
                query.append("JOIN " + THREADS_TABLE + " t " + "ON (t." + ThreadColumns.ROOT + " = a.thread_root) " + "JOIN " + MESSAGES_TABLE + " m " + "ON (m." + MessageColumns.ID + " = t." + ThreadColumns.MESSAGE_ID + " AND " + "m." + InternalMessageColumns.EMPTY + "=0 AND " + "m." + InternalMessageColumns.DELETED + "=0 AND " + "m." + MessageColumns.DATE + " = a." + MessageColumns.DATE + ") ");
                if (Utility.arrayContainsAny(projection, (Object[]) FOLDERS_COLUMNS)) {
                    query.append("JOIN " + FOLDERS_TABLE + " f " + "ON (m." + MessageColumns.FOLDER_ID + " = f." + FolderColumns.ID + ") ");
                }
                query.append(" GROUP BY " + ThreadColumns.ROOT);
                if (!TextUtils.isEmpty(sortOrder)) {
                    query.append(" ORDER BY ");
                    query.append(SqlQueryBuilder.addPrefixToSelection(FIXUP_AGGREGATED_MESSAGES_COLUMNS, "a.", sortOrder));
                }
                return db.rawQuery(query.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) 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 28 with Storage

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

the class SettingsImporter method importAccount.

private static AccountDescriptionPair importAccount(Context context, StorageEditor editor, int contentVersion, ImportedAccount account, boolean overwrite) throws InvalidSettingValueException {
    AccountDescription original = new AccountDescription(account.name, account.uuid);
    Preferences prefs = Preferences.getPreferences(context);
    List<Account> accounts = prefs.getAccounts();
    String uuid = account.uuid;
    Account existingAccount = prefs.getAccount(uuid);
    boolean mergeImportedAccount = (overwrite && existingAccount != null);
    if (!overwrite && existingAccount != null) {
        // An account with this UUID already exists, but we're not allowed to overwrite it.
        // So generate a new UUID.
        uuid = UUID.randomUUID().toString();
    }
    // Make sure the account name is unique
    String accountName = account.name;
    if (isAccountNameUsed(accountName, accounts)) {
        // number >= 1 that results in an unused account name.
        for (int i = 1; i <= accounts.size(); i++) {
            accountName = account.name + " (" + i + ")";
            if (!isAccountNameUsed(accountName, accounts)) {
                break;
            }
        }
    }
    // Write account name
    String accountKeyPrefix = uuid + ".";
    putString(editor, accountKeyPrefix + Account.ACCOUNT_DESCRIPTION_KEY, accountName);
    if (account.incoming == null) {
        // We don't import accounts without incoming server settings
        throw new InvalidSettingValueException();
    }
    // Write incoming server settings (storeUri)
    ServerSettings incoming = new ImportedServerSettings(account.incoming);
    String storeUri = RemoteStore.createStoreUri(incoming);
    putString(editor, accountKeyPrefix + Account.STORE_URI_KEY, Base64.encode(storeUri));
    // Mark account as disabled if the AuthType isn't EXTERNAL and the
    // settings file didn't contain a password
    boolean createAccountDisabled = AuthType.EXTERNAL != incoming.authenticationType && (incoming.password == null || incoming.password.isEmpty());
    if (account.outgoing == null && !ServerSettings.Type.WebDAV.name().equals(account.incoming.type)) {
        // All account types except WebDAV need to provide outgoing server settings
        throw new InvalidSettingValueException();
    }
    if (account.outgoing != null) {
        // Write outgoing server settings (transportUri)
        ServerSettings outgoing = new ImportedServerSettings(account.outgoing);
        String transportUri = Transport.createTransportUri(outgoing);
        putString(editor, accountKeyPrefix + Account.TRANSPORT_URI_KEY, Base64.encode(transportUri));
        /*
             * Mark account as disabled if the settings file contained a username but no password. However, no password
             * is required for the outgoing server for WebDAV accounts, because incoming and outgoing servers are 
             * identical for this account type. Nor is a password required if the AuthType is EXTERNAL.
             */
        boolean outgoingPasswordNeeded = AuthType.EXTERNAL != outgoing.authenticationType && !(ServerSettings.Type.WebDAV == outgoing.type) && outgoing.username != null && !outgoing.username.isEmpty() && (outgoing.password == null || outgoing.password.isEmpty());
        createAccountDisabled = outgoingPasswordNeeded || createAccountDisabled;
    }
    // Write key to mark account as disabled if necessary
    if (createAccountDisabled) {
        editor.putBoolean(accountKeyPrefix + "enabled", false);
    }
    // Validate account settings
    Map<String, Object> validatedSettings = AccountSettings.validate(contentVersion, account.settings.settings, !mergeImportedAccount);
    // Upgrade account settings to current content version
    if (contentVersion != Settings.VERSION) {
        AccountSettings.upgrade(contentVersion, validatedSettings);
    }
    // Convert account settings to the string representation used in preference storage
    Map<String, String> stringSettings = AccountSettings.convert(validatedSettings);
    // Merge account settings if necessary
    Map<String, String> writeSettings;
    if (mergeImportedAccount) {
        writeSettings = new HashMap<>(AccountSettings.getAccountSettings(prefs.getStorage(), uuid));
        writeSettings.putAll(stringSettings);
    } else {
        writeSettings = stringSettings;
    }
    // Write account settings
    for (Map.Entry<String, String> setting : writeSettings.entrySet()) {
        String key = accountKeyPrefix + setting.getKey();
        String value = setting.getValue();
        putString(editor, key, value);
    }
    // If it's a new account generate and write a new "accountNumber"
    if (!mergeImportedAccount) {
        int newAccountNumber = Account.generateAccountNumber(prefs);
        putString(editor, accountKeyPrefix + "accountNumber", Integer.toString(newAccountNumber));
    }
    // Write identities
    if (account.identities != null) {
        importIdentities(editor, contentVersion, uuid, account, overwrite, existingAccount, prefs);
    } else if (!mergeImportedAccount) {
        // Require accounts to at least have one identity
        throw new InvalidSettingValueException();
    }
    // Write folder settings
    if (account.folders != null) {
        for (ImportedFolder folder : account.folders) {
            importFolder(editor, contentVersion, uuid, folder, mergeImportedAccount, prefs);
        }
    }
    //TODO: sync folder settings with localstore?
    AccountDescription imported = new AccountDescription(accountName, uuid);
    return new AccountDescriptionPair(original, imported, mergeImportedAccount);
}
Also used : Account(com.fsck.k9.Account) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) ServerSettings(com.fsck.k9.mail.ServerSettings) SharedPreferences(android.content.SharedPreferences) Preferences(com.fsck.k9.Preferences) HashMap(java.util.HashMap) Map(java.util.Map)

Example 29 with Storage

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

the class MailService method saveLastCheckEnd.

public static void saveLastCheckEnd(Context context) {
    long lastCheckEnd = System.currentTimeMillis();
    Timber.i("Saving lastCheckEnd = %tc", lastCheckEnd);
    Preferences prefs = Preferences.getPreferences(context);
    Storage storage = prefs.getStorage();
    StorageEditor editor = storage.edit();
    editor.putLong(LAST_CHECK_END, lastCheckEnd);
    editor.commit();
}
Also used : Storage(com.fsck.k9.preferences.Storage) Preferences(com.fsck.k9.Preferences) StorageEditor(com.fsck.k9.preferences.StorageEditor)

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