Search in sources :

Example 1 with Preferences

use of org.orcid.jaxb.model.record_rc2.Preferences in project k-9 by k9mail.

the class MessagingController method checkMail.

/**
     * Checks mail for one or multiple accounts. If account is null all accounts
     * are checked.
     */
public void checkMail(final Context context, final Account account, final boolean ignoreLastCheckedTime, final boolean useManualWakeLock, final MessagingListener listener) {
    TracingWakeLock twakeLock = null;
    if (useManualWakeLock) {
        TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
        twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
        twakeLock.setReferenceCounted(false);
        twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
    }
    final TracingWakeLock wakeLock = twakeLock;
    for (MessagingListener l : getListeners()) {
        l.checkMailStarted(context, account);
    }
    putBackground("checkMail", listener, new Runnable() {

        @Override
        public void run() {
            try {
                Timber.i("Starting mail check");
                Preferences prefs = Preferences.getPreferences(context);
                Collection<Account> accounts;
                if (account != null) {
                    accounts = new ArrayList<>(1);
                    accounts.add(account);
                } else {
                    accounts = prefs.getAvailableAccounts();
                }
                for (final Account account : accounts) {
                    checkMailForAccount(context, account, ignoreLastCheckedTime, listener);
                }
            } catch (Exception e) {
                Timber.e(e, "Unable to synchronize mail");
                addErrorMessage(account, null, e);
            }
            putBackground("finalize sync", null, new Runnable() {

                @Override
                public void run() {
                    Timber.i("Finished mail sync");
                    if (wakeLock != null) {
                        wakeLock.release();
                    }
                    for (MessagingListener l : getListeners()) {
                        l.checkMailFinished(context, account);
                    }
                }
            });
        }
    });
}
Also used : SearchAccount(com.fsck.k9.search.SearchAccount) Account(com.fsck.k9.Account) TracingPowerManager(com.fsck.k9.mail.power.TracingPowerManager) ArrayList(java.util.ArrayList) Collection(java.util.Collection) Preferences(com.fsck.k9.Preferences) TracingWakeLock(com.fsck.k9.mail.power.TracingPowerManager.TracingWakeLock) CertificateValidationException(com.fsck.k9.mail.CertificateValidationException) UnavailableStorageException(com.fsck.k9.mailstore.UnavailableStorageException) IOException(java.io.IOException) MessagingException(com.fsck.k9.mail.MessagingException) AuthenticationFailedException(com.fsck.k9.mail.AuthenticationFailedException)

Example 2 with Preferences

use of org.orcid.jaxb.model.record_rc2.Preferences 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 3 with Preferences

use of org.orcid.jaxb.model.record_rc2.Preferences in project k-9 by k9mail.

the class SettingsExporter method exportPreferences.

static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException {
    try {
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(os, "UTF-8");
        serializer.startDocument(null, Boolean.TRUE);
        // Output with indentation
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.startTag(null, ROOT_ELEMENT);
        serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION));
        serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION));
        Timber.i("Exporting preferences");
        Preferences preferences = Preferences.getPreferences(context);
        Storage storage = preferences.getStorage();
        Set<String> exportAccounts;
        if (accountUuids == null) {
            List<Account> accounts = preferences.getAccounts();
            exportAccounts = new HashSet<>();
            for (Account account : accounts) {
                exportAccounts.add(account.getUuid());
            }
        } else {
            exportAccounts = accountUuids;
        }
        Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll());
        if (includeGlobals) {
            serializer.startTag(null, GLOBAL_ELEMENT);
            writeSettings(serializer, prefs);
            serializer.endTag(null, GLOBAL_ELEMENT);
        }
        serializer.startTag(null, ACCOUNTS_ELEMENT);
        for (String accountUuid : exportAccounts) {
            Account account = preferences.getAccount(accountUuid);
            writeAccount(serializer, account, prefs);
        }
        serializer.endTag(null, ACCOUNTS_ELEMENT);
        serializer.endTag(null, ROOT_ELEMENT);
        serializer.endDocument();
        serializer.flush();
    } catch (Exception e) {
        throw new SettingsImportExportException(e.getLocalizedMessage(), e);
    }
}
Also used : Account(com.fsck.k9.Account) TreeMap(java.util.TreeMap) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException) Preferences(com.fsck.k9.Preferences) XmlSerializer(org.xmlpull.v1.XmlSerializer)

Example 4 with Preferences

use of org.orcid.jaxb.model.record_rc2.Preferences in project k-9 by k9mail.

the class RemoteControlService method startService.

@Override
public int startService(final Intent intent, final int startId) {
    Timber.i("RemoteControlService started with startId = %d", startId);
    final Preferences preferences = Preferences.getPreferences(this);
    if (RESCHEDULE_ACTION.equals(intent.getAction())) {
        Timber.i("RemoteControlService requesting MailService poll reschedule");
        MailService.actionReschedulePoll(this, null);
    }
    if (PUSH_RESTART_ACTION.equals(intent.getAction())) {
        Timber.i("RemoteControlService requesting MailService push restart");
        MailService.actionRestartPushers(this, null);
    } else if (RemoteControlService.SET_ACTION.equals(intent.getAction())) {
        Timber.i("RemoteControlService got request to change settings");
        execute(getApplication(), new Runnable() {

            public void run() {
                try {
                    boolean needsReschedule = false;
                    boolean needsPushRestart = false;
                    String uuid = intent.getStringExtra(K9_ACCOUNT_UUID);
                    boolean allAccounts = intent.getBooleanExtra(K9_ALL_ACCOUNTS, false);
                    if (allAccounts) {
                        Timber.i("RemoteControlService changing settings for all accounts");
                    } else {
                        Timber.i("RemoteControlService changing settings for account with UUID %s", uuid);
                    }
                    List<Account> accounts = preferences.getAccounts();
                    for (Account account : accounts) {
                        //warning: account may not be isAvailable()
                        if (allAccounts || account.getUuid().equals(uuid)) {
                            Timber.i("RemoteControlService changing settings for account %s", account.getDescription());
                            String notificationEnabled = intent.getStringExtra(K9_NOTIFICATION_ENABLED);
                            String ringEnabled = intent.getStringExtra(K9_RING_ENABLED);
                            String vibrateEnabled = intent.getStringExtra(K9_VIBRATE_ENABLED);
                            String pushClasses = intent.getStringExtra(K9_PUSH_CLASSES);
                            String pollClasses = intent.getStringExtra(K9_POLL_CLASSES);
                            String pollFrequency = intent.getStringExtra(K9_POLL_FREQUENCY);
                            if (notificationEnabled != null) {
                                account.setNotifyNewMail(Boolean.parseBoolean(notificationEnabled));
                            }
                            if (ringEnabled != null) {
                                account.getNotificationSetting().setRing(Boolean.parseBoolean(ringEnabled));
                            }
                            if (vibrateEnabled != null) {
                                account.getNotificationSetting().setVibrate(Boolean.parseBoolean(vibrateEnabled));
                            }
                            if (pushClasses != null) {
                                needsPushRestart |= account.setFolderPushMode(FolderMode.valueOf(pushClasses));
                            }
                            if (pollClasses != null) {
                                needsReschedule |= account.setFolderSyncMode(FolderMode.valueOf(pollClasses));
                            }
                            if (pollFrequency != null) {
                                String[] allowedFrequencies = getResources().getStringArray(R.array.account_settings_check_frequency_values);
                                for (String allowedFrequency : allowedFrequencies) {
                                    if (allowedFrequency.equals(pollFrequency)) {
                                        Integer newInterval = Integer.parseInt(allowedFrequency);
                                        needsReschedule |= account.setAutomaticCheckIntervalMinutes(newInterval);
                                    }
                                }
                            }
                            account.save(Preferences.getPreferences(RemoteControlService.this));
                        }
                    }
                    Timber.i("RemoteControlService changing global settings");
                    String backgroundOps = intent.getStringExtra(K9_BACKGROUND_OPERATIONS);
                    if (K9RemoteControl.K9_BACKGROUND_OPERATIONS_ALWAYS.equals(backgroundOps) || K9RemoteControl.K9_BACKGROUND_OPERATIONS_NEVER.equals(backgroundOps) || K9RemoteControl.K9_BACKGROUND_OPERATIONS_WHEN_CHECKED_AUTO_SYNC.equals(backgroundOps)) {
                        BACKGROUND_OPS newBackgroundOps = BACKGROUND_OPS.valueOf(backgroundOps);
                        boolean needsReset = K9.setBackgroundOps(newBackgroundOps);
                        needsPushRestart |= needsReset;
                        needsReschedule |= needsReset;
                    }
                    String theme = intent.getStringExtra(K9_THEME);
                    if (theme != null) {
                        K9.setK9Theme(K9RemoteControl.K9_THEME_DARK.equals(theme) ? K9.Theme.DARK : K9.Theme.LIGHT);
                    }
                    Storage storage = preferences.getStorage();
                    StorageEditor editor = storage.edit();
                    K9.save(editor);
                    editor.commit();
                    if (needsReschedule) {
                        Intent i = new Intent(RemoteControlService.this, RemoteControlService.class);
                        i.setAction(RESCHEDULE_ACTION);
                        long nextTime = System.currentTimeMillis() + 10000;
                        BootReceiver.scheduleIntent(RemoteControlService.this, nextTime, i);
                    }
                    if (needsPushRestart) {
                        Intent i = new Intent(RemoteControlService.this, RemoteControlService.class);
                        i.setAction(PUSH_RESTART_ACTION);
                        long nextTime = System.currentTimeMillis() + 10000;
                        BootReceiver.scheduleIntent(RemoteControlService.this, nextTime, i);
                    }
                } catch (Exception e) {
                    Timber.e(e, "Could not handle K9_SET");
                    Toast toast = Toast.makeText(RemoteControlService.this, e.getMessage(), Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        }, RemoteControlService.REMOTE_CONTROL_SERVICE_WAKE_LOCK_TIMEOUT, startId);
    }
    return START_NOT_STICKY;
}
Also used : Account(com.fsck.k9.Account) Intent(android.content.Intent) StorageEditor(com.fsck.k9.preferences.StorageEditor) BACKGROUND_OPS(com.fsck.k9.K9.BACKGROUND_OPS) Storage(com.fsck.k9.preferences.Storage) Toast(android.widget.Toast) Preferences(com.fsck.k9.Preferences)

Example 5 with Preferences

use of org.orcid.jaxb.model.record_rc2.Preferences in project k-9 by k9mail.

the class MailService method reschedulePoll.

private void reschedulePoll(final boolean hasConnectivity, final boolean doBackground, boolean considerLastCheckEnd) {
    if (!(hasConnectivity && doBackground)) {
        Timber.i("No connectivity, canceling check for %s", getApplication().getPackageName());
        nextCheck = -1;
        cancel();
        return;
    }
    Preferences prefs = Preferences.getPreferences(MailService.this);
    Storage storage = prefs.getStorage();
    int previousInterval = storage.getInt(PREVIOUS_INTERVAL, -1);
    long lastCheckEnd = storage.getLong(LAST_CHECK_END, -1);
    long now = System.currentTimeMillis();
    if (lastCheckEnd > now) {
        Timber.i("The database claims that the last time mail was checked was in the future (%tc). To try to get " + "things back to normal, the last check time has been reset to: %tc", lastCheckEnd, now);
        lastCheckEnd = now;
    }
    int shortestInterval = -1;
    for (Account account : prefs.getAvailableAccounts()) {
        if (account.getAutomaticCheckIntervalMinutes() != -1 && account.getFolderSyncMode() != FolderMode.NONE && (account.getAutomaticCheckIntervalMinutes() < shortestInterval || shortestInterval == -1)) {
            shortestInterval = account.getAutomaticCheckIntervalMinutes();
        }
    }
    StorageEditor editor = storage.edit();
    editor.putInt(PREVIOUS_INTERVAL, shortestInterval);
    editor.commit();
    if (shortestInterval == -1) {
        Timber.i("No next check scheduled for package %s", getApplication().getPackageName());
        nextCheck = -1;
        pollingRequested = false;
        cancel();
    } else {
        long delay = (shortestInterval * (60 * 1000));
        long base = (previousInterval == -1 || lastCheckEnd == -1 || !considerLastCheckEnd ? System.currentTimeMillis() : lastCheckEnd);
        long nextTime = base + delay;
        Timber.i("previousInterval = %d, shortestInterval = %d, lastCheckEnd = %tc, considerLastCheckEnd = %b", previousInterval, shortestInterval, lastCheckEnd, considerLastCheckEnd);
        nextCheck = nextTime;
        pollingRequested = true;
        try {
            Timber.i("Next check for package %s scheduled for %tc", getApplication().getPackageName(), nextTime);
        } catch (Exception e) {
            // I once got a NullPointerException deep in new Date();
            Timber.e(e, "Exception while logging");
        }
        Intent i = new Intent(this, MailService.class);
        i.setAction(ACTION_CHECK_MAIL);
        BootReceiver.scheduleIntent(MailService.this, nextTime, i);
    }
}
Also used : Account(com.fsck.k9.Account) Storage(com.fsck.k9.preferences.Storage) Intent(android.content.Intent) Preferences(com.fsck.k9.Preferences) StorageEditor(com.fsck.k9.preferences.StorageEditor)

Aggregations

Preferences (com.fsck.k9.Preferences)17 Account (com.fsck.k9.Account)13 Test (org.junit.Test)12 Preferences (org.apereo.portal.soffit.model.v1_0.Preferences)5 Preferences (org.orcid.jaxb.model.record_v2.Preferences)5 StorageEditor (com.fsck.k9.preferences.StorageEditor)4 SearchAccount (com.fsck.k9.search.SearchAccount)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 InvalidSettingValueException (com.fsck.k9.preferences.Settings.InvalidSettingValueException)3 Storage (com.fsck.k9.preferences.Storage)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Bearer (org.apereo.portal.soffit.model.v1_0.Bearer)3 Definition (org.apereo.portal.soffit.model.v1_0.Definition)3 PortalRequest (org.apereo.portal.soffit.model.v1_0.PortalRequest)3 Intent (android.content.Intent)2 SharedPreferences (android.content.SharedPreferences)2 Uri (android.net.Uri)2 UnavailableStorageException (com.fsck.k9.mailstore.UnavailableStorageException)2