use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.
the class PgpMessageBuilder method launchOpenPgpApiIntent.
private PendingIntent launchOpenPgpApiIntent(@NonNull Intent openPgpIntent, boolean captureOutputPart, boolean capturedOutputPartIs7Bit, boolean writeBodyContentOnly) throws MessagingException {
final MimeBodyPart bodyPart = currentProcessedMimeMessage.toBodyPart();
String[] contentType = currentProcessedMimeMessage.getHeader(MimeHeader.HEADER_CONTENT_TYPE);
if (contentType.length > 0) {
bodyPart.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType[0]);
}
OpenPgpDataSource dataSource = createOpenPgpDataSourceFromBodyPart(bodyPart, writeBodyContentOnly);
BinaryTempFileBody pgpResultTempBody = null;
OutputStream outputStream = null;
if (captureOutputPart) {
try {
pgpResultTempBody = new BinaryTempFileBody(capturedOutputPartIs7Bit ? MimeUtil.ENC_7BIT : MimeUtil.ENC_8BIT);
outputStream = pgpResultTempBody.getOutputStream();
// OpenKeychain/BouncyCastle at this point use the system newline for formatting, which is LF on android.
// we need this to be CRLF, so we convert the data after receiving.
outputStream = new EOLConvertingOutputStream(outputStream);
} catch (IOException e) {
throw new MessagingException("could not allocate temp file for storage!", e);
}
}
Intent result = openPgpApi.executeApi(openPgpIntent, dataSource, outputStream);
switch(result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS:
mimeBuildMessage(result, bodyPart, pgpResultTempBody);
return null;
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
PendingIntent returnedPendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
if (returnedPendingIntent == null) {
throw new MessagingException("openpgp api needs user interaction, but returned no pendingintent!");
}
return returnedPendingIntent;
case OpenPgpApi.RESULT_CODE_ERROR:
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
if (error == null) {
throw new MessagingException("internal openpgp api error");
}
boolean isOpportunisticError = error.getErrorId() == OpenPgpError.OPPORTUNISTIC_MISSING_KEYS;
if (isOpportunisticError) {
if (!cryptoStatus.isEncryptionOpportunistic()) {
throw new IllegalStateException("Got opportunistic error, but encryption wasn't supposed to be opportunistic!");
}
Timber.d("Skipping encryption due to opportunistic mode");
return null;
}
throw new MessagingException(error.getMessage());
}
throw new IllegalStateException("unreachable code segment reached");
}
use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.
the class SettingsExporter method writeFolder.
private static void writeFolder(XmlSerializer serializer, String accountUuid, String folder, Map<String, Object> prefs) throws IOException {
serializer.startTag(null, FOLDER_ELEMENT);
serializer.attribute(null, NAME_ATTRIBUTE, folder);
// Write folder settings
for (Map.Entry<String, Object> entry : prefs.entrySet()) {
String key = entry.getKey();
String valueString = entry.getValue().toString();
int indexOfFirstDot = key.indexOf('.');
int indexOfLastDot = key.lastIndexOf('.');
if (indexOfFirstDot == -1 || indexOfLastDot == -1 || indexOfFirstDot == indexOfLastDot) {
// Skip non-folder config entries
continue;
}
String keyUuid = key.substring(0, indexOfFirstDot);
String folderName = key.substring(indexOfFirstDot + 1, indexOfLastDot);
String folderKey = key.substring(indexOfLastDot + 1);
if (!keyUuid.equals(accountUuid) || !folderName.equals(folder)) {
// Skip entries that belong to another folder
continue;
}
TreeMap<Integer, SettingsDescription> versionedSetting = FolderSettings.SETTINGS.get(folderKey);
if (versionedSetting != null) {
Integer highestVersion = versionedSetting.lastKey();
SettingsDescription setting = versionedSetting.get(highestVersion);
if (setting != null) {
// Only write settings that have an entry in FolderSettings.SETTINGS
try {
writeKeyAndPrettyValueFromSetting(serializer, folderKey, setting, valueString);
} catch (InvalidSettingValueException e) {
Timber.w("Folder setting \"%s\" has invalid value \"%s\" in preference storage. " + "This shouldn't happen!", folderKey, valueString);
}
}
}
}
serializer.endTag(null, FOLDER_ELEMENT);
}
use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.
the class MessageCompose method createMessageBuilder.
@Nullable
private MessageBuilder createMessageBuilder(boolean isDraft) {
MessageBuilder builder;
recipientPresenter.updateCryptoStatus();
ComposeCryptoStatus cryptoStatus = recipientPresenter.getCurrentCryptoStatus();
// TODO encrypt drafts for storage
if (!isDraft && cryptoStatus.shouldUsePgpMessageBuilder()) {
SendErrorState maybeSendErrorState = cryptoStatus.getSendErrorStateOrNull();
if (maybeSendErrorState != null) {
recipientPresenter.showPgpSendError(maybeSendErrorState);
return null;
}
PgpMessageBuilder pgpBuilder = PgpMessageBuilder.newInstance();
recipientPresenter.builderSetProperties(pgpBuilder);
builder = pgpBuilder;
} else {
builder = SimpleMessageBuilder.newInstance();
}
builder.setSubject(Utility.stripNewLines(subjectView.getText().toString())).setSentDate(new Date()).setHideTimeZone(K9.hideTimeZone()).setTo(recipientPresenter.getToAddresses()).setCc(recipientPresenter.getCcAddresses()).setBcc(recipientPresenter.getBccAddresses()).setInReplyTo(repliedToMessageId).setReferences(referencedMessageIds).setRequestReadReceipt(requestReadReceipt).setIdentity(identity).setMessageFormat(currentMessageFormat).setText(messageContentView.getCharacters()).setAttachments(attachmentPresenter.createAttachmentList()).setSignature(signatureView.getCharacters()).setSignatureBeforeQuotedText(account.isSignatureBeforeQuotedText()).setIdentityChanged(identityChanged).setSignatureChanged(signatureChanged).setCursorPosition(messageContentView.getSelectionStart()).setMessageReference(relatedMessageReference).setDraft(isDraft).setIsPgpInlineEnabled(cryptoStatus.isPgpInlineModeEnabled());
quotedMessagePresenter.builderSetProperties(builder);
return builder;
}
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();
}
}
use of com.fsck.k9.preferences.Storage in project k-9 by k9mail.
the class MessagingController method moveOrCopyMessageSynchronous.
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final List<? extends Message> inMessages, final String destFolder, final boolean isCopy) {
try {
LocalStore localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (!isCopy && (!remoteStore.isMoveCapable() || !localStore.isMoveCapable())) {
return;
}
if (isCopy && (!remoteStore.isCopyCapable() || !localStore.isCopyCapable())) {
return;
}
LocalFolder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
boolean unreadCountAffected = false;
List<String> uids = new LinkedList<>();
for (Message message : inMessages) {
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX)) {
uids.add(uid);
}
if (!unreadCountAffected && !message.isSet(Flag.SEEN)) {
unreadCountAffected = true;
}
}
List<LocalMessage> messages = localSrcFolder.getMessagesByUids(uids);
if (messages.size() > 0) {
Map<String, Message> origUidMap = new HashMap<>();
for (Message message : messages) {
origUidMap.put(message.getUid(), message);
}
Timber.i("moveOrCopyMessageSynchronous: source folder = %s, %d messages, destination folder = %s, " + "isCopy = %s", srcFolder, messages.size(), destFolder, isCopy);
Map<String, String> uidMap;
if (isCopy) {
FetchProfile fp = new FetchProfile();
fp.add(Item.ENVELOPE);
fp.add(Item.BODY);
localSrcFolder.fetch(messages, fp, null);
uidMap = localSrcFolder.copyMessages(messages, localDestFolder);
if (unreadCountAffected) {
// If this copy operation changes the unread count in the destination
// folder, notify the listeners.
int unreadMessageCount = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, destFolder, unreadMessageCount);
}
}
} else {
uidMap = localSrcFolder.moveMessages(messages, localDestFolder);
for (Entry<String, Message> entry : origUidMap.entrySet()) {
String origUid = entry.getKey();
Message message = entry.getValue();
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
}
unsuppressMessages(account, messages);
if (unreadCountAffected) {
// If this move operation changes the unread count, notify the listeners
// that the unread count changed in both the source and destination folder.
int unreadMessageCountSrc = localSrcFolder.getUnreadMessageCount();
int unreadMessageCountDest = localDestFolder.getUnreadMessageCount();
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, srcFolder, unreadMessageCountSrc);
l.folderStatusChanged(account, destFolder, unreadMessageCountDest);
}
}
}
List<String> origUidKeys = new ArrayList<>(origUidMap.keySet());
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidKeys, uidMap);
}
processPendingCommands(account);
} catch (UnavailableStorageException e) {
Timber.i("Failed to move/copy message because storage is not available - trying again later.");
throw new UnavailableAccountException(e);
} catch (MessagingException me) {
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
Aggregations