Search in sources :

Example 16 with Callback

use of com.fsck.k9.message.MessageBuilder.Callback in project k-9 by k9mail.

the class MessageBuilderTest method build_withMessageAttachment_shouldAttachAsMessageRfc822.

@Test
public void build_withMessageAttachment_shouldAttachAsMessageRfc822() throws Exception {
    MessageBuilder messageBuilder = createSimpleMessageBuilder();
    Attachment attachment = createAttachmentWithContent("message/rfc822", "attach.txt", TEST_ATTACHMENT_TEXT);
    messageBuilder.setAttachments(Collections.singletonList(attachment));
    messageBuilder.buildAsync(callback);
    MimeMessage message = getMessageFromCallback();
    assertEquals(MESSAGE_HEADERS + MESSAGE_CONTENT_WITH_MESSAGE_ATTACH, getMessageContents(message));
}
Also used : MimeMessage(com.fsck.k9.mail.internet.MimeMessage) RobolectricTest(com.fsck.k9.RobolectricTest) Test(org.junit.Test)

Example 17 with Callback

use of com.fsck.k9.message.MessageBuilder.Callback in project k-9 by k9mail.

the class ImapFolder method fetch.

@Override
public void fetch(List<ImapMessage> messages, FetchProfile fetchProfile, MessageRetrievalListener<ImapMessage> listener) throws MessagingException {
    if (messages == null || messages.isEmpty()) {
        return;
    }
    checkOpen();
    List<String> uids = new ArrayList<>(messages.size());
    HashMap<String, Message> messageMap = new HashMap<>();
    for (Message message : messages) {
        String uid = message.getUid();
        uids.add(uid);
        messageMap.put(uid, message);
    }
    Set<String> fetchFields = new LinkedHashSet<>();
    fetchFields.add("UID");
    if (fetchProfile.contains(FetchProfile.Item.FLAGS)) {
        fetchFields.add("FLAGS");
    }
    if (fetchProfile.contains(FetchProfile.Item.ENVELOPE)) {
        fetchFields.add("INTERNALDATE");
        fetchFields.add("RFC822.SIZE");
        fetchFields.add("BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc " + "reply-to message-id references in-reply-to " + K9MailLib.IDENTITY_HEADER + ")]");
    }
    if (fetchProfile.contains(FetchProfile.Item.STRUCTURE)) {
        fetchFields.add("BODYSTRUCTURE");
    }
    if (fetchProfile.contains(FetchProfile.Item.BODY_SANE)) {
        int maximumAutoDownloadMessageSize = store.getStoreConfig().getMaximumAutoDownloadMessageSize();
        if (maximumAutoDownloadMessageSize > 0) {
            fetchFields.add(String.format(Locale.US, "BODY.PEEK[]<0.%d>", maximumAutoDownloadMessageSize));
        } else {
            fetchFields.add("BODY.PEEK[]");
        }
    }
    if (fetchProfile.contains(FetchProfile.Item.BODY)) {
        fetchFields.add("BODY.PEEK[]");
    }
    String spaceSeparatedFetchFields = combine(fetchFields.toArray(new String[fetchFields.size()]), ' ');
    for (int windowStart = 0; windowStart < messages.size(); windowStart += (FETCH_WINDOW_SIZE)) {
        int windowEnd = Math.min(windowStart + FETCH_WINDOW_SIZE, messages.size());
        List<String> uidWindow = uids.subList(windowStart, windowEnd);
        try {
            String commaSeparatedUids = combine(uidWindow.toArray(new String[uidWindow.size()]), ',');
            String command = String.format("UID FETCH %s (%s)", commaSeparatedUids, spaceSeparatedFetchFields);
            connection.sendCommand(command, false);
            ImapResponse response;
            int messageNumber = 0;
            ImapResponseCallback callback = null;
            if (fetchProfile.contains(FetchProfile.Item.BODY) || fetchProfile.contains(FetchProfile.Item.BODY_SANE)) {
                callback = new FetchBodyCallback(messageMap);
            }
            do {
                response = connection.readResponse(callback);
                if (response.getTag() == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) {
                    ImapList fetchList = (ImapList) response.getKeyedValue("FETCH");
                    String uid = fetchList.getKeyedString("UID");
                    long msgSeq = response.getLong(0);
                    if (uid != null) {
                        try {
                            msgSeqUidMap.put(msgSeq, uid);
                            if (K9MailLib.isDebug()) {
                                Log.v(LOG_TAG, "Stored uid '" + uid + "' for msgSeq " + msgSeq + " into map");
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Unable to store uid '" + uid + "' for msgSeq " + msgSeq);
                        }
                    }
                    Message message = messageMap.get(uid);
                    if (message == null) {
                        if (K9MailLib.isDebug()) {
                            Log.d(LOG_TAG, "Do not have message in messageMap for UID " + uid + " for " + getLogId());
                        }
                        handleUntaggedResponse(response);
                        continue;
                    }
                    if (listener != null) {
                        listener.messageStarted(uid, messageNumber++, messageMap.size());
                    }
                    ImapMessage imapMessage = (ImapMessage) message;
                    Object literal = handleFetchResponse(imapMessage, fetchList);
                    if (literal != null) {
                        if (literal instanceof String) {
                            String bodyString = (String) literal;
                            InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes());
                            imapMessage.parse(bodyStream);
                        } else if (literal instanceof Integer) {
                        // All the work was done in FetchBodyCallback.foundLiteral()
                        } else {
                            // This shouldn't happen
                            throw new MessagingException("Got FETCH response with bogus parameters");
                        }
                    }
                    if (listener != null) {
                        listener.messageFinished(imapMessage, messageNumber, messageMap.size());
                    }
                } else {
                    handleUntaggedResponse(response);
                }
            } while (response.getTag() == null);
        } catch (IOException ioe) {
            throw ioExceptionHandler(connection, ioe);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Message(com.fsck.k9.mail.Message) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MessagingException(com.fsck.k9.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) MessagingException(com.fsck.k9.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 18 with Callback

use of com.fsck.k9.message.MessageBuilder.Callback in project k-9 by k9mail.

the class PgpMessageBuilderTest method buildEncryptWithAttach__withInlineEnabled__shouldThrow.

@Test
public void buildEncryptWithAttach__withInlineEnabled__shouldThrow() throws MessagingException {
    ComposeCryptoStatus cryptoStatus = cryptoStatusBuilder.setCryptoMode(CryptoMode.OPPORTUNISTIC).setEnablePgpInline(true).build();
    pgpMessageBuilder.setCryptoStatus(cryptoStatus);
    pgpMessageBuilder.setAttachments(Collections.singletonList(Attachment.createAttachment(null, 0, null)));
    Callback mockCallback = mock(Callback.class);
    pgpMessageBuilder.buildAsync(mockCallback);
    verify(mockCallback).onMessageBuildException(any(MessagingException.class));
    verifyNoMoreInteractions(mockCallback);
    verifyNoMoreInteractions(openPgpApi);
}
Also used : Callback(com.fsck.k9.message.MessageBuilder.Callback) MessagingException(com.fsck.k9.mail.MessagingException) ComposeCryptoStatus(com.fsck.k9.activity.compose.ComposeCryptoStatus) Test(org.junit.Test)

Example 19 with Callback

use of com.fsck.k9.message.MessageBuilder.Callback in project k-9 by k9mail.

the class PgpMessageBuilderTest method buildSign__withDetachedSignatureInResult__shouldSucceed.

@Test
public void buildSign__withDetachedSignatureInResult__shouldSucceed() throws MessagingException {
    cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY);
    pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build());
    ArgumentCaptor<Intent> capturedApiIntent = ArgumentCaptor.forClass(Intent.class);
    Intent returnIntent = new Intent();
    returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS);
    returnIntent.putExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE, new byte[] { 1, 2, 3 });
    when(openPgpApi.executeApi(capturedApiIntent.capture(), any(OpenPgpDataSource.class), any(OutputStream.class))).thenReturn(returnIntent);
    Callback mockCallback = mock(Callback.class);
    pgpMessageBuilder.buildAsync(mockCallback);
    Intent expectedIntent = new Intent(OpenPgpApi.ACTION_DETACHED_SIGN);
    expectedIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_SIGN_KEY_ID);
    expectedIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
    assertIntentEqualsActionAndExtras(expectedIntent, capturedApiIntent.getValue());
    ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
    verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false));
    verifyNoMoreInteractions(mockCallback);
    MimeMessage message = captor.getValue();
    Assert.assertEquals("message must be multipart/signed", "multipart/signed", message.getMimeType());
    MimeMultipart multipart = (MimeMultipart) message.getBody();
    Assert.assertEquals("multipart/signed must consist of two parts", 2, multipart.getCount());
    BodyPart contentBodyPart = multipart.getBodyPart(0);
    Assert.assertEquals("first part must have content type text/plain", "text/plain", MimeUtility.getHeaderParameter(contentBodyPart.getContentType(), null));
    Assert.assertTrue("signed message body must be TextBody", contentBodyPart.getBody() instanceof TextBody);
    Assert.assertEquals(MimeUtil.ENC_QUOTED_PRINTABLE, ((TextBody) contentBodyPart.getBody()).getEncoding());
    assertContentOfBodyPartEquals("content must match the message text", contentBodyPart, TEST_MESSAGE_TEXT);
    BodyPart signatureBodyPart = multipart.getBodyPart(1);
    String contentType = signatureBodyPart.getContentType();
    Assert.assertEquals("second part must be pgp signature", "application/pgp-signature", MimeUtility.getHeaderParameter(contentType, null));
    Assert.assertEquals("second part must be called signature.asc", "signature.asc", MimeUtility.getHeaderParameter(contentType, "name"));
    assertContentOfBodyPartEquals("content must match the supplied detached signature", signatureBodyPart, new byte[] { 1, 2, 3 });
}
Also used : TextBody(com.fsck.k9.mail.internet.TextBody) BodyPart(com.fsck.k9.mail.BodyPart) Callback(com.fsck.k9.message.MessageBuilder.Callback) MimeMessage(com.fsck.k9.mail.internet.MimeMessage) MimeMultipart(com.fsck.k9.mail.internet.MimeMultipart) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) OpenPgpDataSource(org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource) Test(org.junit.Test)

Example 20 with Callback

use of com.fsck.k9.message.MessageBuilder.Callback in project k-9 by k9mail.

the class PgpMessageBuilderTest method buildSign__withNoDetachedSignatureInResult__shouldThrow.

@Test
public void buildSign__withNoDetachedSignatureInResult__shouldThrow() throws MessagingException {
    cryptoStatusBuilder.setCryptoMode(CryptoMode.SIGN_ONLY);
    pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build());
    Intent returnIntent = new Intent();
    returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS);
    when(openPgpApi.executeApi(any(Intent.class), any(OpenPgpDataSource.class), any(OutputStream.class))).thenReturn(returnIntent);
    Callback mockCallback = mock(Callback.class);
    pgpMessageBuilder.buildAsync(mockCallback);
    verify(mockCallback).onMessageBuildException(any(MessagingException.class));
    verifyNoMoreInteractions(mockCallback);
}
Also used : Callback(com.fsck.k9.message.MessageBuilder.Callback) MessagingException(com.fsck.k9.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) OpenPgpDataSource(org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)23 MimeMessage (com.fsck.k9.mail.internet.MimeMessage)14 Callback (com.fsck.k9.message.MessageBuilder.Callback)14 MessagingException (com.fsck.k9.mail.MessagingException)11 RobolectricTest (com.fsck.k9.RobolectricTest)10 PendingIntent (android.app.PendingIntent)9 Intent (android.content.Intent)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 OutputStream (java.io.OutputStream)9 OpenPgpDataSource (org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource)9 ComposeCryptoStatus (com.fsck.k9.activity.compose.ComposeCryptoStatus)7 Recipient (com.fsck.k9.view.RecipientSelectView.Recipient)5 BodyPart (com.fsck.k9.mail.BodyPart)4 MimeMultipart (com.fsck.k9.mail.internet.MimeMultipart)4 IOException (java.io.IOException)3 BinaryTempFileBody (com.fsck.k9.mail.internet.BinaryTempFileBody)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 Activity (android.app.Activity)1