Search in sources :

Example 36 with LocalMessage

use of com.fsck.k9.mailstore.LocalMessage in project k-9 by k9mail.

the class MessagingController method loadMessageRemoteSynchronous.

private boolean loadMessageRemoteSynchronous(final Account account, final String folder, final String uid, final MessagingListener listener, final boolean loadPartialFromSearch) {
    Folder remoteFolder = null;
    LocalFolder localFolder = null;
    try {
        LocalStore localStore = account.getLocalStore();
        localFolder = localStore.getFolder(folder);
        localFolder.open(Folder.OPEN_MODE_RW);
        LocalMessage message = localFolder.getMessage(uid);
        if (uid.startsWith(K9.LOCAL_UID_PREFIX)) {
            Timber.w("Message has local UID so cannot download fully.");
            // ASH move toast
            android.widget.Toast.makeText(context, "Message has local UID so cannot download fully", android.widget.Toast.LENGTH_LONG).show();
            // TODO: Using X_DOWNLOADED_FULL is wrong because it's only a partial message. But
            // one we can't download completely. Maybe add a new flag; X_PARTIAL_MESSAGE ?
            message.setFlag(Flag.X_DOWNLOADED_FULL, true);
            message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
        }
        /* commented out because this was pulled from another unmerged branch:
            } else if (localFolder.isLocalOnly() && !force) {
                Log.w(K9.LOG_TAG, "Message in local-only folder so cannot download fully.");
                // ASH move toast
                android.widget.Toast.makeText(mApplication,
                        "Message in local-only folder so cannot download fully",
                        android.widget.Toast.LENGTH_LONG).show();
                message.setFlag(Flag.X_DOWNLOADED_FULL, true);
                message.setFlag(Flag.X_DOWNLOADED_PARTIAL, false);
            }*/
        /*if (!message.isSet(Flag.X_DOWNLOADED_FULL)) */
        {
            /*
                 * At this point the message is not available, so we need to download it
                 * fully if possible.
                 */
            Store remoteStore = account.getRemoteStore();
            remoteFolder = remoteStore.getFolder(folder);
            remoteFolder.open(Folder.OPEN_MODE_RW);
            // Get the remote message and fully download it
            Message remoteMessage = remoteFolder.getMessage(uid);
            if (loadPartialFromSearch) {
                downloadMessages(account, remoteFolder, localFolder, Collections.singletonList(remoteMessage), false, false);
            } else {
                FetchProfile fp = new FetchProfile();
                fp.add(FetchProfile.Item.BODY);
                remoteFolder.fetch(Collections.singletonList(remoteMessage), fp, null);
                localFolder.appendMessages(Collections.singletonList(remoteMessage));
            }
            message = localFolder.getMessage(uid);
            if (!loadPartialFromSearch) {
                message.setFlag(Flag.X_DOWNLOADED_FULL, true);
            }
        }
        // Mark that this message is now fully synched
        if (account.isMarkMessageAsReadOnView()) {
            message.setFlag(Flag.SEEN, true);
        }
        // now that we have the full message, refresh the headers
        for (MessagingListener l : getListeners(listener)) {
            l.loadMessageRemoteFinished(account, folder, uid);
        }
        return true;
    } catch (Exception e) {
        for (MessagingListener l : getListeners(listener)) {
            l.loadMessageRemoteFailed(account, folder, uid, e);
        }
        notifyUserIfCertificateProblem(account, e, true);
        addErrorMessage(account, null, e);
        return false;
    } finally {
        closeFolder(remoteFolder);
        closeFolder(localFolder);
    }
}
Also used : LocalFolder(com.fsck.k9.mailstore.LocalFolder) LocalMessage(com.fsck.k9.mailstore.LocalMessage) FetchProfile(com.fsck.k9.mail.FetchProfile) LocalMessage(com.fsck.k9.mailstore.LocalMessage) MimeMessage(com.fsck.k9.mail.internet.MimeMessage) Message(com.fsck.k9.mail.Message) LocalStore(com.fsck.k9.mailstore.LocalStore) Store(com.fsck.k9.mail.Store) Pop3Store(com.fsck.k9.mail.store.pop3.Pop3Store) LocalStore(com.fsck.k9.mailstore.LocalStore) Folder(com.fsck.k9.mail.Folder) LocalFolder(com.fsck.k9.mailstore.LocalFolder) 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 37 with LocalMessage

use of com.fsck.k9.mailstore.LocalMessage in project k-9 by k9mail.

the class LocalFolder method changeUid.

/**
     * Changes the stored uid of the given message (using it's internal id as a key) to
     * the uid in the message.
     * @throws com.fsck.k9.mail.MessagingException
     */
public void changeUid(final LocalMessage message) throws MessagingException {
    open(OPEN_MODE_RW);
    final ContentValues cv = new ContentValues();
    cv.put("uid", message.getUid());
    this.localStore.database.execute(false, new DbCallback<Void>() {

        @Override
        public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException {
            db.update("messages", cv, "id = ?", new String[] { Long.toString(message.getId()) });
            return null;
        }
    });
    //TODO: remove this once the UI code exclusively uses the database id
    this.localStore.notifyChange();
}
Also used : ContentValues(android.content.ContentValues) WrappedException(com.fsck.k9.mailstore.LockableDatabase.WrappedException) SQLiteDatabase(android.database.sqlite.SQLiteDatabase)

Example 38 with LocalMessage

use of com.fsck.k9.mailstore.LocalMessage in project k-9 by k9mail.

the class LocalFolder method saveMessage.

protected void saveMessage(SQLiteDatabase db, Message message, boolean copy, Map<String, String> uidMap) throws MessagingException {
    if (!(message instanceof MimeMessage)) {
        throw new Error("LocalStore can only store Messages that extend MimeMessage");
    }
    long oldMessageId = -1;
    String uid = message.getUid();
    boolean shouldCreateNewMessage = uid == null || copy;
    if (shouldCreateNewMessage) {
        String randomLocalUid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString();
        if (copy) {
            // Save mapping: source UID -> target UID
            uidMap.put(uid, randomLocalUid);
        } else {
            // Modify the Message instance to reference the new UID
            message.setUid(randomLocalUid);
        }
        // The message will be saved with the newly generated UID
        uid = randomLocalUid;
    } else {
        LocalMessage oldMessage = getMessage(uid);
        if (oldMessage != null) {
            oldMessageId = oldMessage.getId();
            long oldRootMessagePartId = oldMessage.getMessagePartId();
            deleteMessagePartsAndDataFromDisk(oldRootMessagePartId);
        }
    }
    long rootId = -1;
    long parentId = -1;
    long msgId;
    if (oldMessageId == -1) {
        // This is a new message. Do the message threading.
        ThreadInfo threadInfo = doMessageThreading(db, message);
        oldMessageId = threadInfo.msgId;
        rootId = threadInfo.rootId;
        parentId = threadInfo.parentId;
    }
    try {
        MessagePreviewCreator previewCreator = localStore.getMessagePreviewCreator();
        PreviewResult previewResult = previewCreator.createPreview(message);
        PreviewType previewType = previewResult.getPreviewType();
        DatabasePreviewType databasePreviewType = DatabasePreviewType.fromPreviewType(previewType);
        MessageFulltextCreator fulltextCreator = localStore.getMessageFulltextCreator();
        String fulltext = fulltextCreator.createFulltext(message);
        AttachmentCounter attachmentCounter = localStore.getAttachmentCounter();
        int attachmentCount = attachmentCounter.getAttachmentCount(message);
        long rootMessagePartId = saveMessageParts(db, message);
        ContentValues cv = new ContentValues();
        cv.put("message_part_id", rootMessagePartId);
        cv.put("uid", uid);
        cv.put("subject", message.getSubject());
        cv.put("sender_list", Address.pack(message.getFrom()));
        cv.put("date", message.getSentDate() == null ? System.currentTimeMillis() : message.getSentDate().getTime());
        cv.put("flags", this.localStore.serializeFlags(message.getFlags()));
        cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0);
        cv.put("read", message.isSet(Flag.SEEN) ? 1 : 0);
        cv.put("flagged", message.isSet(Flag.FLAGGED) ? 1 : 0);
        cv.put("answered", message.isSet(Flag.ANSWERED) ? 1 : 0);
        cv.put("forwarded", message.isSet(Flag.FORWARDED) ? 1 : 0);
        cv.put("folder_id", mFolderId);
        cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
        cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
        cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
        cv.put("reply_to_list", Address.pack(message.getReplyTo()));
        cv.put("attachment_count", attachmentCount);
        cv.put("internal_date", message.getInternalDate() == null ? System.currentTimeMillis() : message.getInternalDate().getTime());
        cv.put("mime_type", message.getMimeType());
        cv.put("empty", 0);
        cv.put("preview_type", databasePreviewType.getDatabaseValue());
        if (previewResult.isPreviewTextAvailable()) {
            cv.put("preview", previewResult.getPreviewText());
        } else {
            cv.putNull("preview");
        }
        String messageId = message.getMessageId();
        if (messageId != null) {
            cv.put("message_id", messageId);
        }
        if (oldMessageId == -1) {
            msgId = db.insert("messages", "uid", cv);
            // Create entry in 'threads' table
            cv.clear();
            cv.put("message_id", msgId);
            if (rootId != -1) {
                cv.put("root", rootId);
            }
            if (parentId != -1) {
                cv.put("parent", parentId);
            }
            db.insert("threads", null, cv);
        } else {
            msgId = oldMessageId;
            db.update("messages", cv, "id = ?", new String[] { Long.toString(oldMessageId) });
        }
        if (fulltext != null) {
            cv.clear();
            cv.put("docid", msgId);
            cv.put("fulltext", fulltext);
            db.replace("messages_fulltext", null, cv);
        }
    } catch (Exception e) {
        throw new MessagingException("Error appending message: " + message.getSubject(), e);
    }
}
Also used : ContentValues(android.content.ContentValues) MessageFulltextCreator(com.fsck.k9.message.extractors.MessageFulltextCreator) MessagingException(com.fsck.k9.mail.MessagingException) AttachmentCounter(com.fsck.k9.message.extractors.AttachmentCounter) PreviewResult(com.fsck.k9.message.extractors.PreviewResult) MessagePreviewCreator(com.fsck.k9.message.extractors.MessagePreviewCreator) WrappedException(com.fsck.k9.mailstore.LockableDatabase.WrappedException) IOException(java.io.IOException) MessagingException(com.fsck.k9.mail.MessagingException) PreviewType(com.fsck.k9.message.extractors.PreviewResult.PreviewType) MimeMessage(com.fsck.k9.mail.internet.MimeMessage)

Example 39 with LocalMessage

use of com.fsck.k9.mailstore.LocalMessage in project k-9 by k9mail.

the class LocalFolder method getMessagesByReference.

public List<LocalMessage> getMessagesByReference(@NonNull List<MessageReference> messageReferences) throws MessagingException {
    open(OPEN_MODE_RW);
    String accountUuid = getAccountUuid();
    String folderName = getName();
    List<LocalMessage> messages = new ArrayList<>();
    for (MessageReference messageReference : messageReferences) {
        if (!accountUuid.equals(messageReference.getAccountUuid())) {
            throw new IllegalArgumentException("all message references must belong to this Account!");
        }
        if (!folderName.equals(messageReference.getFolderName())) {
            throw new IllegalArgumentException("all message references must belong to this LocalFolder!");
        }
        LocalMessage message = getMessage(messageReference.getUid());
        if (message != null) {
            messages.add(message);
        }
    }
    return messages;
}
Also used : ArrayList(java.util.ArrayList) MessageReference(com.fsck.k9.activity.MessageReference)

Example 40 with LocalMessage

use of com.fsck.k9.mailstore.LocalMessage in project k-9 by k9mail.

the class LocalFolder method loadMessagePart.

private void loadMessagePart(LocalMessage message, Map<Long, Part> partById, Cursor cursor) throws MessagingException {
    long id = cursor.getLong(0);
    long parentId = cursor.getLong(2);
    String mimeType = cursor.getString(3);
    long size = cursor.getLong(4);
    byte[] header = cursor.getBlob(6);
    int dataLocation = cursor.getInt(9);
    String serverExtra = cursor.getString(15);
    // TODO we don't currently cache much of the part data which is computed with AttachmentInfoExtractor,
    // TODO might want to do that at a later point?
    // String displayName = cursor.getString(5);
    // int type = cursor.getInt(1);
    // boolean inlineAttachment = (type == MessagePartType.HIDDEN_ATTACHMENT);
    final Part part;
    if (id == message.getMessagePartId()) {
        part = message;
    } else {
        Part parentPart = partById.get(parentId);
        if (parentPart == null) {
            throw new IllegalStateException("Parent part not found");
        }
        String parentMimeType = parentPart.getMimeType();
        if (MimeUtility.isMultipart(parentMimeType)) {
            BodyPart bodyPart = new LocalBodyPart(getAccountUuid(), message, id, size);
            ((Multipart) parentPart.getBody()).addBodyPart(bodyPart);
            part = bodyPart;
        } else if (MimeUtility.isMessage(parentMimeType)) {
            Message innerMessage = new LocalMimeMessage(getAccountUuid(), message, id);
            parentPart.setBody(innerMessage);
            part = innerMessage;
        } else {
            throw new IllegalStateException("Parent is neither a multipart nor a message");
        }
        parseHeaderBytes(part, header);
    }
    partById.put(id, part);
    part.setServerExtra(serverExtra);
    if (MimeUtility.isMultipart(mimeType)) {
        byte[] preamble = cursor.getBlob(11);
        byte[] epilogue = cursor.getBlob(12);
        String boundary = cursor.getString(13);
        MimeMultipart multipart = new MimeMultipart(mimeType, boundary);
        part.setBody(multipart);
        multipart.setPreamble(preamble);
        multipart.setEpilogue(epilogue);
    } else if (dataLocation == DataLocation.IN_DATABASE) {
        String encoding = cursor.getString(7);
        byte[] data = cursor.getBlob(10);
        Body body = new BinaryMemoryBody(data, encoding);
        part.setBody(body);
    } else if (dataLocation == DataLocation.ON_DISK) {
        String encoding = cursor.getString(7);
        File file = localStore.getAttachmentFile(Long.toString(id));
        if (file.exists()) {
            Body body = new FileBackedBody(file, encoding);
            part.setBody(body);
        }
    }
}
Also used : BodyPart(com.fsck.k9.mail.BodyPart) Multipart(com.fsck.k9.mail.Multipart) MimeMultipart(com.fsck.k9.mail.internet.MimeMultipart) MimeMessage(com.fsck.k9.mail.internet.MimeMessage) Message(com.fsck.k9.mail.Message) MimeMultipart(com.fsck.k9.mail.internet.MimeMultipart) BodyPart(com.fsck.k9.mail.BodyPart) Part(com.fsck.k9.mail.Part) Body(com.fsck.k9.mail.Body) BinaryTempFileBody(com.fsck.k9.mail.internet.BinaryTempFileBody) File(java.io.File)

Aggregations

LocalMessage (com.fsck.k9.mailstore.LocalMessage)42 Test (org.junit.Test)23 FetchProfile (com.fsck.k9.mail.FetchProfile)19 Message (com.fsck.k9.mail.Message)19 MimeMessage (com.fsck.k9.mail.internet.MimeMessage)19 MessagingException (com.fsck.k9.mail.MessagingException)15 LocalFolder (com.fsck.k9.mailstore.LocalFolder)13 LocalStore (com.fsck.k9.mailstore.LocalStore)12 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)10 ArrayList (java.util.ArrayList)9 Notification (android.app.Notification)8 Part (com.fsck.k9.mail.Part)8 MessageReference (com.fsck.k9.activity.MessageReference)7 Multipart (com.fsck.k9.mail.Multipart)7 Date (java.util.Date)7 HashMap (java.util.HashMap)7 SuppressLint (android.annotation.SuppressLint)6 UnavailableStorageException (com.fsck.k9.mailstore.UnavailableStorageException)6 IOException (java.io.IOException)6 AuthenticationFailedException (com.fsck.k9.mail.AuthenticationFailedException)5