MessagingController.java revision 85e4c101b014857fe40f87c3837b82564cfc5b6c
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email;
18
19import com.android.email.mail.Sender;
20import com.android.email.mail.Store;
21import com.android.emailcommon.Logging;
22import com.android.emailcommon.internet.MimeBodyPart;
23import com.android.emailcommon.internet.MimeHeader;
24import com.android.emailcommon.internet.MimeMultipart;
25import com.android.emailcommon.internet.MimeUtility;
26import com.android.emailcommon.mail.AuthenticationFailedException;
27import com.android.emailcommon.mail.FetchProfile;
28import com.android.emailcommon.mail.Flag;
29import com.android.emailcommon.mail.Folder;
30import com.android.emailcommon.mail.Folder.FolderType;
31import com.android.emailcommon.mail.Folder.MessageRetrievalListener;
32import com.android.emailcommon.mail.Folder.MessageUpdateCallbacks;
33import com.android.emailcommon.mail.Folder.OpenMode;
34import com.android.emailcommon.mail.Message;
35import com.android.emailcommon.mail.MessagingException;
36import com.android.emailcommon.mail.Part;
37import com.android.emailcommon.provider.EmailContent;
38import com.android.emailcommon.provider.EmailContent.Account;
39import com.android.emailcommon.provider.EmailContent.Attachment;
40import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
41import com.android.emailcommon.provider.EmailContent.MailboxColumns;
42import com.android.emailcommon.provider.EmailContent.MessageColumns;
43import com.android.emailcommon.provider.EmailContent.SyncColumns;
44import com.android.emailcommon.provider.Mailbox;
45import com.android.emailcommon.utility.AttachmentUtilities;
46import com.android.emailcommon.utility.ConversionUtilities;
47import com.android.emailcommon.utility.Utility;
48
49import android.content.ContentResolver;
50import android.content.ContentUris;
51import android.content.ContentValues;
52import android.content.Context;
53import android.database.Cursor;
54import android.net.Uri;
55import android.os.Process;
56import android.util.Log;
57
58import java.io.IOException;
59import java.util.ArrayList;
60import java.util.Date;
61import java.util.HashMap;
62import java.util.HashSet;
63import java.util.concurrent.BlockingQueue;
64import java.util.concurrent.LinkedBlockingQueue;
65
66/**
67 * Starts a long running (application) Thread that will run through commands
68 * that require remote mailbox access. This class is used to serialize and
69 * prioritize these commands. Each method that will submit a command requires a
70 * MessagingListener instance to be provided. It is expected that that listener
71 * has also been added as a registered listener using addListener(). When a
72 * command is to be executed, if the listener that was provided with the command
73 * is no longer registered the command is skipped. The design idea for the above
74 * is that when an Activity starts it registers as a listener. When it is paused
75 * it removes itself. Thus, any commands that that activity submitted are
76 * removed from the queue once the activity is no longer active.
77 */
78public class MessagingController implements Runnable {
79
80    /**
81     * The maximum message size that we'll consider to be "small". A small message is downloaded
82     * in full immediately instead of in pieces. Anything over this size will be downloaded in
83     * pieces with attachments being left off completely and downloaded on demand.
84     *
85     *
86     * 25k for a "small" message was picked by educated trial and error.
87     * http://answers.google.com/answers/threadview?id=312463 claims that the
88     * average size of an email is 59k, which I feel is too large for our
89     * blind download. The following tests were performed on a download of
90     * 25 random messages.
91     * <pre>
92     * 5k - 61 seconds,
93     * 25k - 51 seconds,
94     * 55k - 53 seconds,
95     * </pre>
96     * So 25k gives good performance and a reasonable data footprint. Sounds good to me.
97     */
98    private static final int MAX_SMALL_MESSAGE_SIZE = (25 * 1024);
99
100    private static final Flag[] FLAG_LIST_SEEN = new Flag[] { Flag.SEEN };
101    private static final Flag[] FLAG_LIST_FLAGGED = new Flag[] { Flag.FLAGGED };
102
103    /**
104     * We write this into the serverId field of messages that will never be upsynced.
105     */
106    private static final String LOCAL_SERVERID_PREFIX = "Local-";
107
108    private static final ContentValues PRUNE_ATTACHMENT_CV = new ContentValues();
109    static {
110        PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI);
111    }
112
113    private static MessagingController sInstance = null;
114    private final BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
115    private final Thread mThread;
116
117    /**
118     * All access to mListeners *must* be synchronized
119     */
120    private final GroupMessagingListener mListeners = new GroupMessagingListener();
121    private boolean mBusy;
122    private final Context mContext;
123    private final Controller mController;
124
125    protected MessagingController(Context _context, Controller _controller) {
126        mContext = _context.getApplicationContext();
127        mController = _controller;
128        mThread = new Thread(this);
129        mThread.start();
130    }
131
132    /**
133     * Gets or creates the singleton instance of MessagingController. Application is used to
134     * provide a Context to classes that need it.
135     */
136    public synchronized static MessagingController getInstance(Context _context,
137            Controller _controller) {
138        if (sInstance == null) {
139            sInstance = new MessagingController(_context, _controller);
140        }
141        return sInstance;
142    }
143
144    /**
145     * Inject a mock controller.  Used only for testing.  Affects future calls to getInstance().
146     */
147    public static void injectMockController(MessagingController mockController) {
148        sInstance = mockController;
149    }
150
151    // TODO: seems that this reading of mBusy isn't thread-safe
152    public boolean isBusy() {
153        return mBusy;
154    }
155
156    public void run() {
157        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
158        // TODO: add an end test to this infinite loop
159        while (true) {
160            Command command;
161            try {
162                command = mCommands.take();
163            } catch (InterruptedException e) {
164                continue; //re-test the condition on the eclosing while
165            }
166            if (command.listener == null || isActiveListener(command.listener)) {
167                mBusy = true;
168                command.runnable.run();
169                mListeners.controllerCommandCompleted(mCommands.size() > 0);
170            }
171            mBusy = false;
172        }
173    }
174
175    private void put(String description, MessagingListener listener, Runnable runnable) {
176        try {
177            Command command = new Command();
178            command.listener = listener;
179            command.runnable = runnable;
180            command.description = description;
181            mCommands.add(command);
182        }
183        catch (IllegalStateException ie) {
184            throw new Error(ie);
185        }
186    }
187
188    public void addListener(MessagingListener listener) {
189        mListeners.addListener(listener);
190    }
191
192    public void removeListener(MessagingListener listener) {
193        mListeners.removeListener(listener);
194    }
195
196    private boolean isActiveListener(MessagingListener listener) {
197        return mListeners.isActiveListener(listener);
198    }
199
200    private static final int MAILBOX_COLUMN_ID = 0;
201    private static final int MAILBOX_COLUMN_SERVER_ID = 1;
202    private static final int MAILBOX_COLUMN_TYPE = 2;
203
204    /** Small projection for just the columns required for a sync. */
205    private static final String[] MAILBOX_PROJECTION = new String[] {
206        MailboxColumns.ID,
207        MailboxColumns.SERVER_ID,
208        MailboxColumns.TYPE,
209    };
210
211    /**
212     * Synchronize the folder list with the remote server. Synchronization occurs in the
213     * background and results are passed through the {@link MessagingListener}. If the
214     * given listener is not {@code null}, it must have been previously added to the set
215     * of listeners using the {@link #addListener(MessagingListener)}. Otherwise, no
216     * actions will be performed.
217     *
218     * TODO this needs to cache the remote folder list
219     * TODO break out an inner listFoldersSynchronized which could simplify checkMail
220     *
221     * @param accountId ID of the account for which to list the folders
222     * @param listener A listener to notify
223     */
224    void listFolders(final long accountId, MessagingListener listener) {
225        final Account account = Account.restoreAccountWithId(mContext, accountId);
226        if (account == null) {
227            Log.i(Logging.LOG_TAG, "Could not load account id " + accountId
228                    + ". Has it been removed?");
229            return;
230        }
231        mListeners.listFoldersStarted(accountId);
232        put("listFolders", listener, new Runnable() {
233            // TODO For now, mailbox addition occurs in the server-dependent store implementation,
234            // but, mailbox removal occurs here. Instead, each store should be responsible for
235            // content synchronization (addition AND removal) since each store will likely need
236            // to implement it's own, unique synchronization methodology.
237            public void run() {
238                Cursor localFolderCursor = null;
239                try {
240                    // Step 1: Get remote mailboxes
241                    Store store = Store.getInstance(account, mContext, null);
242                    Folder[] remoteFolders = store.updateFolders();
243                    HashSet<String> remoteFolderNames = new HashSet<String>();
244                    for (int i = 0, count = remoteFolders.length; i < count; i++) {
245                        remoteFolderNames.add(remoteFolders[i].getName());
246                    }
247
248                    // Step 2: Get local mailboxes
249                    localFolderCursor = mContext.getContentResolver().query(
250                            Mailbox.CONTENT_URI,
251                            MAILBOX_PROJECTION,
252                            EmailContent.MailboxColumns.ACCOUNT_KEY + "=?",
253                            new String[] { String.valueOf(account.mId) },
254                            null);
255
256                    // Step 3: Remove any local mailbox not on the remote list
257                    while (localFolderCursor.moveToNext()) {
258                        String mailboxPath = localFolderCursor.getString(MAILBOX_COLUMN_SERVER_ID);
259                        // Short circuit if we have a remote mailbox with the same name
260                        if (remoteFolderNames.contains(mailboxPath)) {
261                            continue;
262                        }
263
264                        int mailboxType = localFolderCursor.getInt(MAILBOX_COLUMN_TYPE);
265                        long mailboxId = localFolderCursor.getLong(MAILBOX_COLUMN_ID);
266                        switch (mailboxType) {
267                            case Mailbox.TYPE_INBOX:
268                            case Mailbox.TYPE_DRAFTS:
269                            case Mailbox.TYPE_OUTBOX:
270                            case Mailbox.TYPE_SENT:
271                            case Mailbox.TYPE_TRASH:
272                                // Never, ever delete special mailboxes
273                                break;
274                            default:
275                                // Drop all attachment files related to this mailbox
276                                AttachmentUtilities.deleteAllMailboxAttachmentFiles(
277                                        mContext, accountId, mailboxId);
278                                // Delete the mailbox; database triggers take care of related
279                                // Message, Body and Attachment records
280                                Uri uri = ContentUris.withAppendedId(
281                                        Mailbox.CONTENT_URI, mailboxId);
282                                mContext.getContentResolver().delete(uri, null, null);
283                                break;
284                        }
285                    }
286                    mListeners.listFoldersFinished(accountId);
287                } catch (Exception e) {
288                    mListeners.listFoldersFailed(accountId, e.toString());
289                } finally {
290                    if (localFolderCursor != null) {
291                        localFolderCursor.close();
292                    }
293                }
294            }
295        });
296    }
297
298    /**
299     * Start background synchronization of the specified folder.
300     * @param account
301     * @param folder
302     * @param listener
303     */
304    public void synchronizeMailbox(final EmailContent.Account account,
305            final Mailbox folder, MessagingListener listener) {
306        /*
307         * We don't ever sync the Outbox.
308         */
309        if (folder.mType == Mailbox.TYPE_OUTBOX) {
310            return;
311        }
312        mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
313        put("synchronizeMailbox", listener, new Runnable() {
314            public void run() {
315                synchronizeMailboxSynchronous(account, folder);
316            }
317        });
318    }
319
320    /**
321     * Start foreground synchronization of the specified folder. This is called by
322     * synchronizeMailbox or checkMail.
323     * TODO this should use ID's instead of fully-restored objects
324     * @param account
325     * @param folder
326     */
327    private void synchronizeMailboxSynchronous(final EmailContent.Account account,
328            final Mailbox folder) {
329        mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
330        if ((folder.mFlags & Mailbox.FLAG_HOLDS_MAIL) == 0) {
331            // We don't hold messages, so, nothing to synchronize
332            mListeners.synchronizeMailboxFinished(account.mId, folder.mId, 0, 0, null);
333            return;
334        }
335        NotificationController nc = NotificationController.getInstance(mContext);
336        try {
337            processPendingActionsSynchronous(account);
338
339            // Select generic sync or store-specific sync
340            SyncResults results = synchronizeMailboxGeneric(account, folder);
341            mListeners.synchronizeMailboxFinished(account.mId, folder.mId,
342                                                  results.mTotalMessages,
343                                                  results.mAddedMessages.size(),
344                                                  results.mAddedMessages);
345            // Clear authentication notification for this account
346            nc.cancelLoginFailedNotification(account.mId);
347        } catch (MessagingException e) {
348            if (Logging.LOGD) {
349                Log.v(Logging.LOG_TAG, "synchronizeMailbox", e);
350            }
351            if (e instanceof AuthenticationFailedException) {
352                // Generate authentication notification
353                nc.showLoginFailedNotification(account.mId);
354            }
355            mListeners.synchronizeMailboxFailed(account.mId, folder.mId, e);
356        }
357    }
358
359    /**
360     * Lightweight record for the first pass of message sync, where I'm just seeing if
361     * the local message requires sync.  Later (for messages that need syncing) we'll do a full
362     * readout from the DB.
363     */
364    private static class LocalMessageInfo {
365        private static final int COLUMN_ID = 0;
366        private static final int COLUMN_FLAG_READ = 1;
367        private static final int COLUMN_FLAG_FAVORITE = 2;
368        private static final int COLUMN_FLAG_LOADED = 3;
369        private static final int COLUMN_SERVER_ID = 4;
370        private static final String[] PROJECTION = new String[] {
371            EmailContent.RECORD_ID,
372            MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_LOADED,
373            SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY
374        };
375
376        final long mId;
377        final boolean mFlagRead;
378        final boolean mFlagFavorite;
379        final int mFlagLoaded;
380        final String mServerId;
381
382        public LocalMessageInfo(Cursor c) {
383            mId = c.getLong(COLUMN_ID);
384            mFlagRead = c.getInt(COLUMN_FLAG_READ) != 0;
385            mFlagFavorite = c.getInt(COLUMN_FLAG_FAVORITE) != 0;
386            mFlagLoaded = c.getInt(COLUMN_FLAG_LOADED);
387            mServerId = c.getString(COLUMN_SERVER_ID);
388            // Note: mailbox key and account key not needed - they are projected for the SELECT
389        }
390    }
391
392    private void saveOrUpdate(EmailContent content, Context context) {
393        if (content.isSaved()) {
394            content.update(context, content.toContentValues());
395        } else {
396            content.save(context);
397        }
398    }
399
400    /**
401     * Generic synchronizer - used for POP3 and IMAP.
402     *
403     * TODO Break this method up into smaller chunks.
404     *
405     * @param account the account to sync
406     * @param folder the mailbox to sync
407     * @return results of the sync pass
408     * @throws MessagingException
409     */
410    private SyncResults synchronizeMailboxGeneric(
411            final EmailContent.Account account, final Mailbox folder)
412            throws MessagingException {
413
414        /*
415         * A list of IDs for messages that were downloaded and did not have the seen flag set.
416         * This serves as the "true" new message count reported to the user via notification.
417         */
418        final ArrayList<Long> unseenMessages = new ArrayList<Long>();
419
420        Log.d(Logging.LOG_TAG, "*** synchronizeMailboxGeneric ***");
421        ContentResolver resolver = mContext.getContentResolver();
422
423        // 0.  We do not ever sync DRAFTS or OUTBOX (down or up)
424        if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
425            int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
426            return new SyncResults(totalMessages, unseenMessages);
427        }
428
429        // 1.  Get the message list from the local store and create an index of the uids
430
431        Cursor localUidCursor = null;
432        HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
433
434        try {
435            localUidCursor = resolver.query(
436                    EmailContent.Message.CONTENT_URI,
437                    LocalMessageInfo.PROJECTION,
438                    EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
439                    " AND " + MessageColumns.MAILBOX_KEY + "=?",
440                    new String[] {
441                            String.valueOf(account.mId),
442                            String.valueOf(folder.mId)
443                    },
444                    null);
445            while (localUidCursor.moveToNext()) {
446                LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
447                localMessageMap.put(info.mServerId, info);
448            }
449        } finally {
450            if (localUidCursor != null) {
451                localUidCursor.close();
452            }
453        }
454
455        // 1a. Count the unread messages before changing anything
456        int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
457                EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
458                " AND " + MessageColumns.MAILBOX_KEY + "=?" +
459                " AND " + MessageColumns.FLAG_READ + "=0",
460                new String[] {
461                        String.valueOf(account.mId),
462                        String.valueOf(folder.mId)
463                });
464
465        // 2.  Open the remote folder and create the remote folder if necessary
466
467        Store remoteStore = Store.getInstance(account, mContext, null);
468        Folder remoteFolder = remoteStore.getFolder(folder.mServerId);
469
470        /*
471         * If the folder is a "special" folder we need to see if it exists
472         * on the remote server. It if does not exist we'll try to create it. If we
473         * can't create we'll abort. This will happen on every single Pop3 folder as
474         * designed and on Imap folders during error conditions. This allows us
475         * to treat Pop3 and Imap the same in this code.
476         */
477        if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
478                || folder.mType == Mailbox.TYPE_DRAFTS) {
479            if (!remoteFolder.exists()) {
480                if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
481                    return new SyncResults(0, unseenMessages);
482                }
483            }
484        }
485
486        // 3, Open the remote folder. This pre-loads certain metadata like message count.
487        remoteFolder.open(OpenMode.READ_WRITE, null);
488
489        // 4. Trash any remote messages that are marked as trashed locally.
490        // TODO - this comment was here, but no code was here.
491
492        // 5. Get the remote message count.
493        int remoteMessageCount = remoteFolder.getMessageCount();
494
495        // 6. Determine the limit # of messages to download
496        int visibleLimit = folder.mVisibleLimit;
497        if (visibleLimit <= 0) {
498            visibleLimit = Email.VISIBLE_LIMIT_DEFAULT;
499        }
500
501        // 7.  Create a list of messages to download
502        Message[] remoteMessages = new Message[0];
503        final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
504        HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
505
506        int newMessageCount = 0;
507        if (remoteMessageCount > 0) {
508            /*
509             * Message numbers start at 1.
510             */
511            int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
512            int remoteEnd = remoteMessageCount;
513            remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
514            // TODO Why are we running through the list twice? Combine w/ for loop below
515            for (Message message : remoteMessages) {
516                remoteUidMap.put(message.getUid(), message);
517            }
518
519            /*
520             * Get a list of the messages that are in the remote list but not on the
521             * local store, or messages that are in the local store but failed to download
522             * on the last sync. These are the new messages that we will download.
523             * Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
524             * because they are locally deleted and we don't need or want the old message from
525             * the server.
526             */
527            for (Message message : remoteMessages) {
528                LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
529                if (localMessage == null) {
530                    newMessageCount++;
531                }
532                // localMessage == null -> message has never been created (not even headers)
533                // mFlagLoaded = UNLOADED -> message created, but none of body loaded
534                // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
535                // mFlagLoaded = COMPLETE -> message body has been completely loaded
536                // mFlagLoaded = DELETED -> message has been deleted
537                // Only the first two of these are "unsynced", so let's retrieve them
538                if (localMessage == null ||
539                        (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
540                    unsyncedMessages.add(message);
541                }
542            }
543        }
544
545        // 8.  Download basic info about the new/unloaded messages (if any)
546        /*
547         * Fetch the flags and envelope only of the new messages. This is intended to get us
548         * critical data as fast as possible, and then we'll fill in the details.
549         */
550        if (unsyncedMessages.size() > 0) {
551            FetchProfile fp = new FetchProfile();
552            fp.add(FetchProfile.Item.FLAGS);
553            fp.add(FetchProfile.Item.ENVELOPE);
554            final HashMap<String, LocalMessageInfo> localMapCopy =
555                new HashMap<String, LocalMessageInfo>(localMessageMap);
556
557            remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
558                    new MessageRetrievalListener() {
559                        public void messageRetrieved(Message message) {
560                            try {
561                                // Determine if the new message was already known (e.g. partial)
562                                // And create or reload the full message info
563                                LocalMessageInfo localMessageInfo =
564                                    localMapCopy.get(message.getUid());
565                                EmailContent.Message localMessage = null;
566                                if (localMessageInfo == null) {
567                                    localMessage = new EmailContent.Message();
568                                } else {
569                                    localMessage = EmailContent.Message.restoreMessageWithId(
570                                            mContext, localMessageInfo.mId);
571                                }
572
573                                if (localMessage != null) {
574                                    try {
575                                        // Copy the fields that are available into the message
576                                        LegacyConversions.updateMessageFields(localMessage,
577                                                message, account.mId, folder.mId);
578                                        // Commit the message to the local store
579                                        saveOrUpdate(localMessage, mContext);
580                                        // Track the "new" ness of the downloaded message
581                                        if (!message.isSet(Flag.SEEN)) {
582                                            unseenMessages.add(localMessage.mId);
583                                        }
584                                    } catch (MessagingException me) {
585                                        Log.e(Logging.LOG_TAG,
586                                                "Error while copying downloaded message." + me);
587                                    }
588
589                                }
590                            }
591                            catch (Exception e) {
592                                Log.e(Logging.LOG_TAG,
593                                        "Error while storing downloaded message." + e.toString());
594                            }
595                        }
596
597                        @Override
598                        public void loadAttachmentProgress(int progress) {
599                        }
600                    });
601        }
602
603        // 9. Refresh the flags for any messages in the local store that we didn't just download.
604        FetchProfile fp = new FetchProfile();
605        fp.add(FetchProfile.Item.FLAGS);
606        remoteFolder.fetch(remoteMessages, fp, null);
607        boolean remoteSupportsSeen = false;
608        boolean remoteSupportsFlagged = false;
609        for (Flag flag : remoteFolder.getPermanentFlags()) {
610            if (flag == Flag.SEEN) {
611                remoteSupportsSeen = true;
612            }
613            if (flag == Flag.FLAGGED) {
614                remoteSupportsFlagged = true;
615            }
616        }
617        // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
618        if (remoteSupportsSeen || remoteSupportsFlagged) {
619            for (Message remoteMessage : remoteMessages) {
620                LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
621                if (localMessageInfo == null) {
622                    continue;
623                }
624                boolean localSeen = localMessageInfo.mFlagRead;
625                boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
626                boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
627                boolean localFlagged = localMessageInfo.mFlagFavorite;
628                boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
629                boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
630                if (newSeen || newFlagged) {
631                    Uri uri = ContentUris.withAppendedId(
632                            EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
633                    ContentValues updateValues = new ContentValues();
634                    updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
635                    updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
636                    resolver.update(uri, updateValues, null, null);
637                }
638            }
639        }
640
641        // 10. Remove any messages that are in the local store but no longer on the remote store.
642        HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
643        localUidsToDelete.removeAll(remoteUidMap.keySet());
644        for (String uidToDelete : localUidsToDelete) {
645            LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
646
647            // Delete associated data (attachment files)
648            // Attachment & Body records are auto-deleted when we delete the Message record
649            AttachmentUtilities.deleteAllAttachmentFiles(mContext, account.mId,
650                    infoToDelete.mId);
651
652            // Delete the message itself
653            Uri uriToDelete = ContentUris.withAppendedId(
654                    EmailContent.Message.CONTENT_URI, infoToDelete.mId);
655            resolver.delete(uriToDelete, null, null);
656
657            // Delete extra rows (e.g. synced or deleted)
658            Uri syncRowToDelete = ContentUris.withAppendedId(
659                    EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
660            resolver.delete(syncRowToDelete, null, null);
661            Uri deletERowToDelete = ContentUris.withAppendedId(
662                    EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
663            resolver.delete(deletERowToDelete, null, null);
664        }
665
666        // 11. Divide the unsynced messages into small & large (by size)
667
668        // TODO doing this work here (synchronously) is problematic because it prevents the UI
669        // from affecting the order (e.g. download a message because the user requested it.)  Much
670        // of this logic should move out to a different sync loop that attempts to update small
671        // groups of messages at a time, as a background task.  However, we can't just return
672        // (yet) because POP messages don't have an envelope yet....
673
674        ArrayList<Message> largeMessages = new ArrayList<Message>();
675        ArrayList<Message> smallMessages = new ArrayList<Message>();
676        for (Message message : unsyncedMessages) {
677            if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
678                largeMessages.add(message);
679            } else {
680                smallMessages.add(message);
681            }
682        }
683
684        // 12. Download small messages
685
686        // TODO Problems with this implementation.  1. For IMAP, where we get a real envelope,
687        // this is going to be inefficient and duplicate work we've already done.  2.  It's going
688        // back to the DB for a local message that we already had (and discarded).
689
690        // For small messages, we specify "body", which returns everything (incl. attachments)
691        fp = new FetchProfile();
692        fp.add(FetchProfile.Item.BODY);
693        remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
694                new MessageRetrievalListener() {
695                    public void messageRetrieved(Message message) {
696                        // Store the updated message locally and mark it fully loaded
697                        copyOneMessageToProvider(message, account, folder,
698                                EmailContent.Message.FLAG_LOADED_COMPLETE);
699                    }
700
701                    @Override
702                    public void loadAttachmentProgress(int progress) {
703                    }
704        });
705
706        // 13. Download large messages.  We ask the server to give us the message structure,
707        // but not all of the attachments.
708        fp.clear();
709        fp.add(FetchProfile.Item.STRUCTURE);
710        remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
711        for (Message message : largeMessages) {
712            if (message.getBody() == null) {
713                // POP doesn't support STRUCTURE mode, so we'll just do a partial download
714                // (hopefully enough to see some/all of the body) and mark the message for
715                // further download.
716                fp.clear();
717                fp.add(FetchProfile.Item.BODY_SANE);
718                //  TODO a good optimization here would be to make sure that all Stores set
719                //  the proper size after this fetch and compare the before and after size. If
720                //  they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
721                remoteFolder.fetch(new Message[] { message }, fp, null);
722
723                // Store the partially-loaded message and mark it partially loaded
724                copyOneMessageToProvider(message, account, folder,
725                        EmailContent.Message.FLAG_LOADED_PARTIAL);
726            } else {
727                // We have a structure to deal with, from which
728                // we can pull down the parts we want to actually store.
729                // Build a list of parts we are interested in. Text parts will be downloaded
730                // right now, attachments will be left for later.
731                ArrayList<Part> viewables = new ArrayList<Part>();
732                ArrayList<Part> attachments = new ArrayList<Part>();
733                MimeUtility.collectParts(message, viewables, attachments);
734                // Download the viewables immediately
735                for (Part part : viewables) {
736                    fp.clear();
737                    fp.add(part);
738                    // TODO what happens if the network connection dies? We've got partial
739                    // messages with incorrect status stored.
740                    remoteFolder.fetch(new Message[] { message }, fp, null);
741                }
742                // Store the updated message locally and mark it fully loaded
743                copyOneMessageToProvider(message, account, folder,
744                        EmailContent.Message.FLAG_LOADED_COMPLETE);
745            }
746        }
747
748        // 14. Clean up and report results
749        remoteFolder.close(false);
750
751        return new SyncResults(remoteMessageCount, unseenMessages);
752    }
753
754    /**
755     * Copy one downloaded message (which may have partially-loaded sections)
756     * into a newly created EmailProvider Message, given the account and mailbox
757     *
758     * @param message the remote message we've just downloaded
759     * @param account the account it will be stored into
760     * @param folder the mailbox it will be stored into
761     * @param loadStatus when complete, the message will be marked with this status (e.g.
762     *        EmailContent.Message.LOADED)
763     */
764    public void copyOneMessageToProvider(Message message, EmailContent.Account account,
765            Mailbox folder, int loadStatus) {
766        EmailContent.Message localMessage = null;
767        Cursor c = null;
768        try {
769            c = mContext.getContentResolver().query(
770                    EmailContent.Message.CONTENT_URI,
771                    EmailContent.Message.CONTENT_PROJECTION,
772                    EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
773                    " AND " + MessageColumns.MAILBOX_KEY + "=?" +
774                    " AND " + SyncColumns.SERVER_ID + "=?",
775                    new String[] {
776                            String.valueOf(account.mId),
777                            String.valueOf(folder.mId),
778                            String.valueOf(message.getUid())
779                    },
780                    null);
781            if (c.moveToNext()) {
782                localMessage = EmailContent.getContent(c, EmailContent.Message.class);
783                localMessage.mMailboxKey = folder.mId;
784                localMessage.mAccountKey = account.mId;
785                copyOneMessageToProvider(message, localMessage, loadStatus, mContext);
786            }
787        } finally {
788            if (c != null) {
789                c.close();
790            }
791        }
792    }
793
794    /**
795     * Copy one downloaded message (which may have partially-loaded sections)
796     * into an already-created EmailProvider Message
797     *
798     * @param message the remote message we've just downloaded
799     * @param localMessage the EmailProvider Message, already created
800     * @param loadStatus when complete, the message will be marked with this status (e.g.
801     *        EmailContent.Message.LOADED)
802     * @param context the context to be used for EmailProvider
803     */
804    public void copyOneMessageToProvider(Message message, EmailContent.Message localMessage,
805            int loadStatus, Context context) {
806        try {
807
808            EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(context,
809                    localMessage.mId);
810            if (body == null) {
811                body = new EmailContent.Body();
812            }
813            try {
814                // Copy the fields that are available into the message object
815                LegacyConversions.updateMessageFields(localMessage, message,
816                        localMessage.mAccountKey, localMessage.mMailboxKey);
817
818                // Now process body parts & attachments
819                ArrayList<Part> viewables = new ArrayList<Part>();
820                ArrayList<Part> attachments = new ArrayList<Part>();
821                MimeUtility.collectParts(message, viewables, attachments);
822
823                ConversionUtilities.updateBodyFields(body, localMessage, viewables);
824
825                // Commit the message & body to the local store immediately
826                saveOrUpdate(localMessage, context);
827                saveOrUpdate(body, context);
828
829                // process (and save) attachments
830                LegacyConversions.updateAttachments(context, localMessage, attachments);
831
832                // One last update of message with two updated flags
833                localMessage.mFlagLoaded = loadStatus;
834
835                ContentValues cv = new ContentValues();
836                cv.put(EmailContent.MessageColumns.FLAG_ATTACHMENT, localMessage.mFlagAttachment);
837                cv.put(EmailContent.MessageColumns.FLAG_LOADED, localMessage.mFlagLoaded);
838                Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI,
839                        localMessage.mId);
840                context.getContentResolver().update(uri, cv, null, null);
841
842            } catch (MessagingException me) {
843                Log.e(Logging.LOG_TAG, "Error while copying downloaded message." + me);
844            }
845
846        } catch (RuntimeException rte) {
847            Log.e(Logging.LOG_TAG, "Error while storing downloaded message." + rte.toString());
848        } catch (IOException ioe) {
849            Log.e(Logging.LOG_TAG, "Error while storing attachment." + ioe.toString());
850        }
851    }
852
853    public void processPendingActions(final long accountId) {
854        put("processPendingActions", null, new Runnable() {
855            public void run() {
856                try {
857                    EmailContent.Account account =
858                        EmailContent.Account.restoreAccountWithId(mContext, accountId);
859                    if (account == null) {
860                        return;
861                    }
862                    processPendingActionsSynchronous(account);
863                }
864                catch (MessagingException me) {
865                    if (Logging.LOGD) {
866                        Log.v(Logging.LOG_TAG, "processPendingActions", me);
867                    }
868                    /*
869                     * Ignore any exceptions from the commands. Commands will be processed
870                     * on the next round.
871                     */
872                }
873            }
874        });
875    }
876
877    /**
878     * Find messages in the updated table that need to be written back to server.
879     *
880     * Handles:
881     *   Read/Unread
882     *   Flagged
883     *   Append (upload)
884     *   Move To Trash
885     *   Empty trash
886     * TODO:
887     *   Move
888     *
889     * @param account the account to scan for pending actions
890     * @throws MessagingException
891     */
892    private void processPendingActionsSynchronous(EmailContent.Account account)
893           throws MessagingException {
894        ContentResolver resolver = mContext.getContentResolver();
895        String[] accountIdArgs = new String[] { Long.toString(account.mId) };
896
897        // Handle deletes first, it's always better to get rid of things first
898        processPendingDeletesSynchronous(account, resolver, accountIdArgs);
899
900        // Handle uploads (currently, only to sent messages)
901        processPendingUploadsSynchronous(account, resolver, accountIdArgs);
902
903        // Now handle updates / upsyncs
904        processPendingUpdatesSynchronous(account, resolver, accountIdArgs);
905    }
906
907    /**
908     * Scan for messages that are in the Message_Deletes table, look for differences that
909     * we can deal with, and do the work.
910     *
911     * @param account
912     * @param resolver
913     * @param accountIdArgs
914     */
915    private void processPendingDeletesSynchronous(EmailContent.Account account,
916            ContentResolver resolver, String[] accountIdArgs) {
917        Cursor deletes = resolver.query(EmailContent.Message.DELETED_CONTENT_URI,
918                EmailContent.Message.CONTENT_PROJECTION,
919                EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
920                EmailContent.MessageColumns.MAILBOX_KEY);
921        long lastMessageId = -1;
922        try {
923            // Defer setting up the store until we know we need to access it
924            Store remoteStore = null;
925            // Demand load mailbox (note order-by to reduce thrashing here)
926            Mailbox mailbox = null;
927            // loop through messages marked as deleted
928            while (deletes.moveToNext()) {
929                boolean deleteFromTrash = false;
930
931                EmailContent.Message oldMessage =
932                        EmailContent.getContent(deletes, EmailContent.Message.class);
933
934                if (oldMessage != null) {
935                    lastMessageId = oldMessage.mId;
936                    if (mailbox == null || mailbox.mId != oldMessage.mMailboxKey) {
937                        mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
938                        if (mailbox == null) {
939                            continue; // Mailbox removed. Move to the next message.
940                        }
941                    }
942                    deleteFromTrash = mailbox.mType == Mailbox.TYPE_TRASH;
943                }
944
945                // Load the remote store if it will be needed
946                if (remoteStore == null && deleteFromTrash) {
947                    remoteStore = Store.getInstance(account, mContext, null);
948                }
949
950                // Dispatch here for specific change types
951                if (deleteFromTrash) {
952                    // Move message to trash
953                    processPendingDeleteFromTrash(remoteStore, account, mailbox, oldMessage);
954                }
955
956                // Finally, delete the update
957                Uri uri = ContentUris.withAppendedId(EmailContent.Message.DELETED_CONTENT_URI,
958                        oldMessage.mId);
959                resolver.delete(uri, null, null);
960            }
961
962        } catch (MessagingException me) {
963            // Presumably an error here is an account connection failure, so there is
964            // no point in continuing through the rest of the pending updates.
965            if (Email.DEBUG) {
966                Log.d(Logging.LOG_TAG, "Unable to process pending delete for id="
967                            + lastMessageId + ": " + me);
968            }
969        } finally {
970            deletes.close();
971        }
972    }
973
974    /**
975     * Scan for messages that are in Sent, and are in need of upload,
976     * and send them to the server.  "In need of upload" is defined as:
977     *  serverId == null (no UID has been assigned)
978     * or
979     *  message is in the updated list
980     *
981     * Note we also look for messages that are moving from drafts->outbox->sent.  They never
982     * go through "drafts" or "outbox" on the server, so we hang onto these until they can be
983     * uploaded directly to the Sent folder.
984     *
985     * @param account
986     * @param resolver
987     * @param accountIdArgs
988     */
989    private void processPendingUploadsSynchronous(EmailContent.Account account,
990            ContentResolver resolver, String[] accountIdArgs) {
991        // Find the Sent folder (since that's all we're uploading for now
992        Cursor mailboxes = resolver.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
993                MailboxColumns.ACCOUNT_KEY + "=?"
994                + " and " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_SENT,
995                accountIdArgs, null);
996        long lastMessageId = -1;
997        try {
998            // Defer setting up the store until we know we need to access it
999            Store remoteStore = null;
1000            while (mailboxes.moveToNext()) {
1001                long mailboxId = mailboxes.getLong(Mailbox.ID_PROJECTION_COLUMN);
1002                String[] mailboxKeyArgs = new String[] { Long.toString(mailboxId) };
1003                // Demand load mailbox
1004                Mailbox mailbox = null;
1005
1006                // First handle the "new" messages (serverId == null)
1007                Cursor upsyncs1 = resolver.query(EmailContent.Message.CONTENT_URI,
1008                        EmailContent.Message.ID_PROJECTION,
1009                        EmailContent.Message.MAILBOX_KEY + "=?"
1010                        + " and (" + EmailContent.Message.SERVER_ID + " is null"
1011                        + " or " + EmailContent.Message.SERVER_ID + "=''" + ")",
1012                        mailboxKeyArgs,
1013                        null);
1014                try {
1015                    while (upsyncs1.moveToNext()) {
1016                        // Load the remote store if it will be needed
1017                        if (remoteStore == null) {
1018                            remoteStore =
1019                                Store.getInstance(account, mContext, null);
1020                        }
1021                        // Load the mailbox if it will be needed
1022                        if (mailbox == null) {
1023                            mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
1024                            if (mailbox == null) {
1025                                continue; // Mailbox removed. Move to the next message.
1026                            }
1027                        }
1028                        // upsync the message
1029                        long id = upsyncs1.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
1030                        lastMessageId = id;
1031                        processUploadMessage(resolver, remoteStore, account, mailbox, id);
1032                    }
1033                } finally {
1034                    if (upsyncs1 != null) {
1035                        upsyncs1.close();
1036                    }
1037                }
1038
1039                // Next, handle any updates (e.g. edited in place, although this shouldn't happen)
1040                Cursor upsyncs2 = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
1041                        EmailContent.Message.ID_PROJECTION,
1042                        EmailContent.MessageColumns.MAILBOX_KEY + "=?", mailboxKeyArgs,
1043                        null);
1044                try {
1045                    while (upsyncs2.moveToNext()) {
1046                        // Load the remote store if it will be needed
1047                        if (remoteStore == null) {
1048                            remoteStore =
1049                                Store.getInstance(account, mContext, null);
1050                        }
1051                        // Load the mailbox if it will be needed
1052                        if (mailbox == null) {
1053                            mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
1054                            if (mailbox == null) {
1055                                continue; // Mailbox removed. Move to the next message.
1056                            }
1057                        }
1058                        // upsync the message
1059                        long id = upsyncs2.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
1060                        lastMessageId = id;
1061                        processUploadMessage(resolver, remoteStore, account, mailbox, id);
1062                    }
1063                } finally {
1064                    if (upsyncs2 != null) {
1065                        upsyncs2.close();
1066                    }
1067                }
1068            }
1069        } catch (MessagingException me) {
1070            // Presumably an error here is an account connection failure, so there is
1071            // no point in continuing through the rest of the pending updates.
1072            if (Email.DEBUG) {
1073                Log.d(Logging.LOG_TAG, "Unable to process pending upsync for id="
1074                        + lastMessageId + ": " + me);
1075            }
1076        } finally {
1077            if (mailboxes != null) {
1078                mailboxes.close();
1079            }
1080        }
1081    }
1082
1083    /**
1084     * Scan for messages that are in the Message_Updates table, look for differences that
1085     * we can deal with, and do the work.
1086     *
1087     * @param account
1088     * @param resolver
1089     * @param accountIdArgs
1090     */
1091    private void processPendingUpdatesSynchronous(EmailContent.Account account,
1092            ContentResolver resolver, String[] accountIdArgs) {
1093        Cursor updates = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
1094                EmailContent.Message.CONTENT_PROJECTION,
1095                EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
1096                EmailContent.MessageColumns.MAILBOX_KEY);
1097        long lastMessageId = -1;
1098        try {
1099            // Defer setting up the store until we know we need to access it
1100            Store remoteStore = null;
1101            // Demand load mailbox (note order-by to reduce thrashing here)
1102            Mailbox mailbox = null;
1103            // loop through messages marked as needing updates
1104            while (updates.moveToNext()) {
1105                boolean changeMoveToTrash = false;
1106                boolean changeRead = false;
1107                boolean changeFlagged = false;
1108                boolean changeMailbox = false;
1109
1110                EmailContent.Message oldMessage =
1111                    EmailContent.getContent(updates, EmailContent.Message.class);
1112                lastMessageId = oldMessage.mId;
1113                EmailContent.Message newMessage =
1114                    EmailContent.Message.restoreMessageWithId(mContext, oldMessage.mId);
1115                if (newMessage != null) {
1116                    if (mailbox == null || mailbox.mId != newMessage.mMailboxKey) {
1117                        mailbox = Mailbox.restoreMailboxWithId(mContext, newMessage.mMailboxKey);
1118                        if (mailbox == null) {
1119                            continue; // Mailbox removed. Move to the next message.
1120                        }
1121                    }
1122                    if (oldMessage.mMailboxKey != newMessage.mMailboxKey) {
1123                        if (mailbox.mType == Mailbox.TYPE_TRASH) {
1124                            changeMoveToTrash = true;
1125                        } else {
1126                            changeMailbox = true;
1127                        }
1128                    }
1129                    changeRead = oldMessage.mFlagRead != newMessage.mFlagRead;
1130                    changeFlagged = oldMessage.mFlagFavorite != newMessage.mFlagFavorite;
1131               }
1132
1133                // Load the remote store if it will be needed
1134                if (remoteStore == null &&
1135                        (changeMoveToTrash || changeRead || changeFlagged || changeMailbox)) {
1136                    remoteStore = Store.getInstance(account, mContext, null);
1137                }
1138
1139                // Dispatch here for specific change types
1140                if (changeMoveToTrash) {
1141                    // Move message to trash
1142                    processPendingMoveToTrash(remoteStore, account, mailbox, oldMessage,
1143                            newMessage);
1144                } else if (changeRead || changeFlagged || changeMailbox) {
1145                    processPendingDataChange(remoteStore, mailbox, changeRead, changeFlagged,
1146                            changeMailbox, oldMessage, newMessage);
1147                }
1148
1149                // Finally, delete the update
1150                Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI,
1151                        oldMessage.mId);
1152                resolver.delete(uri, null, null);
1153            }
1154
1155        } catch (MessagingException me) {
1156            // Presumably an error here is an account connection failure, so there is
1157            // no point in continuing through the rest of the pending updates.
1158            if (Email.DEBUG) {
1159                Log.d(Logging.LOG_TAG, "Unable to process pending update for id="
1160                            + lastMessageId + ": " + me);
1161            }
1162        } finally {
1163            updates.close();
1164        }
1165    }
1166
1167    /**
1168     * Upsync an entire message.  This must also unwind whatever triggered it (either by
1169     * updating the serverId, or by deleting the update record, or it's going to keep happening
1170     * over and over again.
1171     *
1172     * Note:  If the message is being uploaded into an unexpected mailbox, we *do not* upload.
1173     * This is to avoid unnecessary uploads into the trash.  Although the caller attempts to select
1174     * only the Drafts and Sent folders, this can happen when the update record and the current
1175     * record mismatch.  In this case, we let the update record remain, because the filters
1176     * in processPendingUpdatesSynchronous() will pick it up as a move and handle it (or drop it)
1177     * appropriately.
1178     *
1179     * @param resolver
1180     * @param remoteStore
1181     * @param account
1182     * @param mailbox the actual mailbox
1183     * @param messageId
1184     */
1185    private void processUploadMessage(ContentResolver resolver, Store remoteStore,
1186            EmailContent.Account account, Mailbox mailbox, long messageId)
1187            throws MessagingException {
1188        EmailContent.Message newMessage =
1189            EmailContent.Message.restoreMessageWithId(mContext, messageId);
1190        boolean deleteUpdate = false;
1191        if (newMessage == null) {
1192            deleteUpdate = true;
1193            Log.d(Logging.LOG_TAG, "Upsync failed for null message, id=" + messageId);
1194        } else if (mailbox.mType == Mailbox.TYPE_DRAFTS) {
1195            deleteUpdate = false;
1196            Log.d(Logging.LOG_TAG, "Upsync skipped for mailbox=drafts, id=" + messageId);
1197        } else if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
1198            deleteUpdate = false;
1199            Log.d(Logging.LOG_TAG, "Upsync skipped for mailbox=outbox, id=" + messageId);
1200        } else if (mailbox.mType == Mailbox.TYPE_TRASH) {
1201            deleteUpdate = false;
1202            Log.d(Logging.LOG_TAG, "Upsync skipped for mailbox=trash, id=" + messageId);
1203        } else if (newMessage != null && newMessage.mMailboxKey != mailbox.mId) {
1204            deleteUpdate = false;
1205            Log.d(Logging.LOG_TAG, "Upsync skipped; mailbox changed, id=" + messageId);
1206        } else {
1207            Log.d(Logging.LOG_TAG, "Upsyc triggered for message id=" + messageId);
1208            deleteUpdate = processPendingAppend(remoteStore, account, mailbox, newMessage);
1209        }
1210        if (deleteUpdate) {
1211            // Finally, delete the update (if any)
1212            Uri uri = ContentUris.withAppendedId(
1213                    EmailContent.Message.UPDATED_CONTENT_URI, messageId);
1214            resolver.delete(uri, null, null);
1215        }
1216    }
1217
1218    /**
1219     * Upsync changes to read, flagged, or mailbox
1220     *
1221     * @param remoteStore the remote store for this mailbox
1222     * @param mailbox the mailbox the message is stored in
1223     * @param changeRead whether the message's read state has changed
1224     * @param changeFlagged whether the message's flagged state has changed
1225     * @param changeMailbox whether the message's mailbox has changed
1226     * @param oldMessage the message in it's pre-change state
1227     * @param newMessage the current version of the message
1228     */
1229    private void processPendingDataChange(Store remoteStore, Mailbox mailbox, boolean changeRead,
1230            boolean changeFlagged, boolean changeMailbox, EmailContent.Message oldMessage,
1231            final EmailContent.Message newMessage) throws MessagingException {
1232        Mailbox newMailbox = null;
1233
1234        // 0. No remote update if the message is local-only
1235        if (newMessage.mServerId == null || newMessage.mServerId.equals("")
1236                || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX) || (mailbox == null)) {
1237            return;
1238        }
1239
1240        // 0.5 If the mailbox has changed, use the original mailbox for operations
1241        // After any flag changes (which we execute in the original mailbox), we then
1242        // copy the message to the new mailbox
1243        if (changeMailbox) {
1244            newMailbox = mailbox;
1245            mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
1246        }
1247
1248        if (mailbox == null) {
1249            return;
1250        }
1251
1252        // 1. No remote update for DRAFTS or OUTBOX
1253        if (mailbox.mType == Mailbox.TYPE_DRAFTS || mailbox.mType == Mailbox.TYPE_OUTBOX) {
1254            return;
1255        }
1256
1257        // 2. Open the remote store & folder
1258        Folder remoteFolder = remoteStore.getFolder(mailbox.mServerId);
1259        if (!remoteFolder.exists()) {
1260            return;
1261        }
1262        remoteFolder.open(OpenMode.READ_WRITE, null);
1263        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1264            return;
1265        }
1266
1267        // 3. Finally, apply the changes to the message
1268        Message remoteMessage = remoteFolder.getMessage(newMessage.mServerId);
1269        if (remoteMessage == null) {
1270            return;
1271        }
1272        if (Email.DEBUG) {
1273            Log.d(Logging.LOG_TAG,
1274                    "Update for msg id=" + newMessage.mId
1275                    + " read=" + newMessage.mFlagRead
1276                    + " flagged=" + newMessage.mFlagFavorite
1277                    + " new mailbox=" + newMessage.mMailboxKey);
1278        }
1279        Message[] messages = new Message[] { remoteMessage };
1280        if (changeRead) {
1281            remoteFolder.setFlags(messages, FLAG_LIST_SEEN, newMessage.mFlagRead);
1282        }
1283        if (changeFlagged) {
1284            remoteFolder.setFlags(messages, FLAG_LIST_FLAGGED, newMessage.mFlagFavorite);
1285        }
1286        if (changeMailbox) {
1287            Folder toFolder = remoteStore.getFolder(newMailbox.mServerId);
1288            if (!remoteFolder.exists()) {
1289                return;
1290            }
1291            // We may need the message id to search for the message in the destination folder
1292            remoteMessage.setMessageId(newMessage.mMessageId);
1293            // Copy the message to its new folder
1294            remoteFolder.copyMessages(messages, toFolder, new MessageUpdateCallbacks() {
1295                @Override
1296                public void onMessageUidChange(Message message, String newUid) {
1297                    ContentValues cv = new ContentValues();
1298                    cv.put(EmailContent.Message.SERVER_ID, newUid);
1299                    // We only have one message, so, any updates _must_ be for it. Otherwise,
1300                    // we'd have to cycle through to find the one with the same server ID.
1301                    mContext.getContentResolver().update(ContentUris.withAppendedId(
1302                            EmailContent.Message.CONTENT_URI, newMessage.mId), cv, null, null);
1303                }
1304                @Override
1305                public void onMessageNotFound(Message message) {
1306                }
1307            });
1308            // Delete the message from the remote source folder
1309            remoteMessage.setFlag(Flag.DELETED, true);
1310            remoteFolder.expunge();
1311        }
1312        remoteFolder.close(false);
1313    }
1314
1315    /**
1316     * Process a pending trash message command.
1317     *
1318     * @param remoteStore the remote store we're working in
1319     * @param account The account in which we are working
1320     * @param newMailbox The local trash mailbox
1321     * @param oldMessage The message copy that was saved in the updates shadow table
1322     * @param newMessage The message that was moved to the mailbox
1323     */
1324    private void processPendingMoveToTrash(Store remoteStore,
1325            EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage,
1326            final EmailContent.Message newMessage) throws MessagingException {
1327
1328        // 0. No remote move if the message is local-only
1329        if (newMessage.mServerId == null || newMessage.mServerId.equals("")
1330                || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
1331            return;
1332        }
1333
1334        // 1. Escape early if we can't find the local mailbox
1335        // TODO smaller projection here
1336        Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
1337        if (oldMailbox == null) {
1338            // can't find old mailbox, it may have been deleted.  just return.
1339            return;
1340        }
1341        // 2. We don't support delete-from-trash here
1342        if (oldMailbox.mType == Mailbox.TYPE_TRASH) {
1343            return;
1344        }
1345
1346        // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return
1347        //
1348        // This sentinel takes the place of the server-side message, and locally "deletes" it
1349        // by inhibiting future sync or display of the message.  It will eventually go out of
1350        // scope when it becomes old, or is deleted on the server, and the regular sync code
1351        // will clean it up for us.
1352        if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
1353            EmailContent.Message sentinel = new EmailContent.Message();
1354            sentinel.mAccountKey = oldMessage.mAccountKey;
1355            sentinel.mMailboxKey = oldMessage.mMailboxKey;
1356            sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
1357            sentinel.mFlagRead = true;
1358            sentinel.mServerId = oldMessage.mServerId;
1359            sentinel.save(mContext);
1360
1361            return;
1362        }
1363
1364        // The rest of this method handles server-side deletion
1365
1366        // 4.  Find the remote mailbox (that we deleted from), and open it
1367        Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId);
1368        if (!remoteFolder.exists()) {
1369            return;
1370        }
1371
1372        remoteFolder.open(OpenMode.READ_WRITE, null);
1373        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1374            remoteFolder.close(false);
1375            return;
1376        }
1377
1378        // 5. Find the remote original message
1379        Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId);
1380        if (remoteMessage == null) {
1381            remoteFolder.close(false);
1382            return;
1383        }
1384
1385        // 6. Find the remote trash folder, and create it if not found
1386        Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId);
1387        if (!remoteTrashFolder.exists()) {
1388            /*
1389             * If the remote trash folder doesn't exist we try to create it.
1390             */
1391            remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
1392        }
1393
1394        // 7.  Try to copy the message into the remote trash folder
1395        // Note, this entire section will be skipped for POP3 because there's no remote trash
1396        if (remoteTrashFolder.exists()) {
1397            /*
1398             * Because remoteTrashFolder may be new, we need to explicitly open it
1399             */
1400            remoteTrashFolder.open(OpenMode.READ_WRITE, null);
1401            if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
1402                remoteFolder.close(false);
1403                remoteTrashFolder.close(false);
1404                return;
1405            }
1406
1407            remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
1408                    new Folder.MessageUpdateCallbacks() {
1409                public void onMessageUidChange(Message message, String newUid) {
1410                    // update the UID in the local trash folder, because some stores will
1411                    // have to change it when copying to remoteTrashFolder
1412                    ContentValues cv = new ContentValues();
1413                    cv.put(EmailContent.Message.SERVER_ID, newUid);
1414                    mContext.getContentResolver().update(newMessage.getUri(), cv, null, null);
1415                }
1416
1417                /**
1418                 * This will be called if the deleted message doesn't exist and can't be
1419                 * deleted (e.g. it was already deleted from the server.)  In this case,
1420                 * attempt to delete the local copy as well.
1421                 */
1422                public void onMessageNotFound(Message message) {
1423                    mContext.getContentResolver().delete(newMessage.getUri(), null, null);
1424                }
1425            });
1426            remoteTrashFolder.close(false);
1427        }
1428
1429        // 8. Delete the message from the remote source folder
1430        remoteMessage.setFlag(Flag.DELETED, true);
1431        remoteFolder.expunge();
1432        remoteFolder.close(false);
1433    }
1434
1435    /**
1436     * Process a pending trash message command.
1437     *
1438     * @param remoteStore the remote store we're working in
1439     * @param account The account in which we are working
1440     * @param oldMailbox The local trash mailbox
1441     * @param oldMessage The message that was deleted from the trash
1442     */
1443    private void processPendingDeleteFromTrash(Store remoteStore,
1444            EmailContent.Account account, Mailbox oldMailbox, EmailContent.Message oldMessage)
1445            throws MessagingException {
1446
1447        // 1. We only support delete-from-trash here
1448        if (oldMailbox.mType != Mailbox.TYPE_TRASH) {
1449            return;
1450        }
1451
1452        // 2.  Find the remote trash folder (that we are deleting from), and open it
1453        Folder remoteTrashFolder = remoteStore.getFolder(oldMailbox.mServerId);
1454        if (!remoteTrashFolder.exists()) {
1455            return;
1456        }
1457
1458        remoteTrashFolder.open(OpenMode.READ_WRITE, null);
1459        if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
1460            remoteTrashFolder.close(false);
1461            return;
1462        }
1463
1464        // 3. Find the remote original message
1465        Message remoteMessage = remoteTrashFolder.getMessage(oldMessage.mServerId);
1466        if (remoteMessage == null) {
1467            remoteTrashFolder.close(false);
1468            return;
1469        }
1470
1471        // 4. Delete the message from the remote trash folder
1472        remoteMessage.setFlag(Flag.DELETED, true);
1473        remoteTrashFolder.expunge();
1474        remoteTrashFolder.close(false);
1475    }
1476
1477    /**
1478     * Process a pending append message command. This command uploads a local message to the
1479     * server, first checking to be sure that the server message is not newer than
1480     * the local message.
1481     *
1482     * @param remoteStore the remote store we're working in
1483     * @param account The account in which we are working
1484     * @param newMailbox The mailbox we're appending to
1485     * @param message The message we're appending
1486     * @return true if successfully uploaded
1487     */
1488    private boolean processPendingAppend(Store remoteStore, EmailContent.Account account,
1489            Mailbox newMailbox, EmailContent.Message message)
1490            throws MessagingException {
1491
1492        boolean updateInternalDate = false;
1493        boolean updateMessage = false;
1494        boolean deleteMessage = false;
1495
1496        // 1. Find the remote folder that we're appending to and create and/or open it
1497        Folder remoteFolder = remoteStore.getFolder(newMailbox.mServerId);
1498        if (!remoteFolder.exists()) {
1499            if (!remoteFolder.canCreate(FolderType.HOLDS_MESSAGES)) {
1500                // This is POP3, we cannot actually upload.  Instead, we'll update the message
1501                // locally with a fake serverId (so we don't keep trying here) and return.
1502                if (message.mServerId == null || message.mServerId.length() == 0) {
1503                    message.mServerId = LOCAL_SERVERID_PREFIX + message.mId;
1504                    Uri uri =
1505                        ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
1506                    ContentValues cv = new ContentValues();
1507                    cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
1508                    mContext.getContentResolver().update(uri, cv, null, null);
1509                }
1510                return true;
1511            }
1512            if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
1513                // This is a (hopefully) transient error and we return false to try again later
1514                return false;
1515            }
1516        }
1517        remoteFolder.open(OpenMode.READ_WRITE, null);
1518        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1519            return false;
1520        }
1521
1522        // 2. If possible, load a remote message with the matching UID
1523        Message remoteMessage = null;
1524        if (message.mServerId != null && message.mServerId.length() > 0) {
1525            remoteMessage = remoteFolder.getMessage(message.mServerId);
1526        }
1527
1528        // 3. If a remote message could not be found, upload our local message
1529        if (remoteMessage == null) {
1530            // 3a. Create a legacy message to upload
1531            Message localMessage = LegacyConversions.makeMessage(mContext, message);
1532
1533            // 3b. Upload it
1534            FetchProfile fp = new FetchProfile();
1535            fp.add(FetchProfile.Item.BODY);
1536            remoteFolder.appendMessages(new Message[] { localMessage });
1537
1538            // 3b. And record the UID from the server
1539            message.mServerId = localMessage.getUid();
1540            updateInternalDate = true;
1541            updateMessage = true;
1542        } else {
1543            // 4. If the remote message exists we need to determine which copy to keep.
1544            FetchProfile fp = new FetchProfile();
1545            fp.add(FetchProfile.Item.ENVELOPE);
1546            remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
1547            Date localDate = new Date(message.mServerTimeStamp);
1548            Date remoteDate = remoteMessage.getInternalDate();
1549            if (remoteDate != null && remoteDate.compareTo(localDate) > 0) {
1550                // 4a. If the remote message is newer than ours we'll just
1551                // delete ours and move on. A sync will get the server message
1552                // if we need to be able to see it.
1553                deleteMessage = true;
1554            } else {
1555                // 4b. Otherwise we'll upload our message and then delete the remote message.
1556
1557                // Create a legacy message to upload
1558                Message localMessage = LegacyConversions.makeMessage(mContext, message);
1559
1560                // 4c. Upload it
1561                fp.clear();
1562                fp = new FetchProfile();
1563                fp.add(FetchProfile.Item.BODY);
1564                remoteFolder.appendMessages(new Message[] { localMessage });
1565
1566                // 4d. Record the UID and new internalDate from the server
1567                message.mServerId = localMessage.getUid();
1568                updateInternalDate = true;
1569                updateMessage = true;
1570
1571                // 4e. And delete the old copy of the message from the server
1572                remoteMessage.setFlag(Flag.DELETED, true);
1573            }
1574        }
1575
1576        // 5. If requested, Best-effort to capture new "internaldate" from the server
1577        if (updateInternalDate && message.mServerId != null) {
1578            try {
1579                Message remoteMessage2 = remoteFolder.getMessage(message.mServerId);
1580                if (remoteMessage2 != null) {
1581                    FetchProfile fp2 = new FetchProfile();
1582                    fp2.add(FetchProfile.Item.ENVELOPE);
1583                    remoteFolder.fetch(new Message[] { remoteMessage2 }, fp2, null);
1584                    message.mServerTimeStamp = remoteMessage2.getInternalDate().getTime();
1585                    updateMessage = true;
1586                }
1587            } catch (MessagingException me) {
1588                // skip it - we can live without this
1589            }
1590        }
1591
1592        // 6. Perform required edits to local copy of message
1593        if (deleteMessage || updateMessage) {
1594            Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
1595            ContentResolver resolver = mContext.getContentResolver();
1596            if (deleteMessage) {
1597                resolver.delete(uri, null, null);
1598            } else if (updateMessage) {
1599                ContentValues cv = new ContentValues();
1600                cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
1601                cv.put(EmailContent.Message.SERVER_TIMESTAMP, message.mServerTimeStamp);
1602                resolver.update(uri, cv, null, null);
1603            }
1604        }
1605
1606        return true;
1607    }
1608
1609    /**
1610     * Finish loading a message that have been partially downloaded.
1611     *
1612     * @param messageId the message to load
1613     * @param listener the callback by which results will be reported
1614     */
1615    public void loadMessageForView(final long messageId, MessagingListener listener) {
1616        mListeners.loadMessageForViewStarted(messageId);
1617        put("loadMessageForViewRemote", listener, new Runnable() {
1618            public void run() {
1619                try {
1620                    // 1. Resample the message, in case it disappeared or synced while
1621                    // this command was in queue
1622                    EmailContent.Message message =
1623                        EmailContent.Message.restoreMessageWithId(mContext, messageId);
1624                    if (message == null) {
1625                        mListeners.loadMessageForViewFailed(messageId, "Unknown message");
1626                        return;
1627                    }
1628                    if (message.mFlagLoaded == EmailContent.Message.FLAG_LOADED_COMPLETE) {
1629                        mListeners.loadMessageForViewFinished(messageId);
1630                        return;
1631                    }
1632
1633                    // 2. Open the remote folder.
1634                    // TODO all of these could be narrower projections
1635                    // TODO combine with common code in loadAttachment
1636                    EmailContent.Account account =
1637                        EmailContent.Account.restoreAccountWithId(mContext, message.mAccountKey);
1638                    Mailbox mailbox =
1639                        Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
1640                    if (account == null || mailbox == null) {
1641                        mListeners.loadMessageForViewFailed(messageId, "null account or mailbox");
1642                        return;
1643                    }
1644
1645                    Store remoteStore =
1646                        Store.getInstance(account, mContext, null);
1647                    Folder remoteFolder = remoteStore.getFolder(mailbox.mServerId);
1648                    remoteFolder.open(OpenMode.READ_WRITE, null);
1649
1650                    // 3. Not supported, because IMAP & POP don't use it: structure prefetch
1651//                  if (remoteStore.requireStructurePrefetch()) {
1652//                  // For remote stores that require it, prefetch the message structure.
1653//                  FetchProfile fp = new FetchProfile();
1654//                  fp.add(FetchProfile.Item.STRUCTURE);
1655//                  localFolder.fetch(new Message[] { message }, fp, null);
1656//
1657//                  ArrayList<Part> viewables = new ArrayList<Part>();
1658//                  ArrayList<Part> attachments = new ArrayList<Part>();
1659//                  MimeUtility.collectParts(message, viewables, attachments);
1660//                  fp.clear();
1661//                  for (Part part : viewables) {
1662//                      fp.add(part);
1663//                  }
1664//
1665//                  remoteFolder.fetch(new Message[] { message }, fp, null);
1666//
1667//                  // Store the updated message locally
1668//                  localFolder.updateMessage((LocalMessage)message);
1669
1670                    // 4. Set up to download the entire message
1671                    Message remoteMessage = remoteFolder.getMessage(message.mServerId);
1672                    FetchProfile fp = new FetchProfile();
1673                    fp.add(FetchProfile.Item.BODY);
1674                    remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
1675
1676                    // 5. Write to provider
1677                    copyOneMessageToProvider(remoteMessage, account, mailbox,
1678                            EmailContent.Message.FLAG_LOADED_COMPLETE);
1679
1680                    // 6. Notify UI
1681                    mListeners.loadMessageForViewFinished(messageId);
1682
1683                } catch (MessagingException me) {
1684                    if (Logging.LOGD) Log.v(Logging.LOG_TAG, "", me);
1685                    mListeners.loadMessageForViewFailed(messageId, me.getMessage());
1686                } catch (RuntimeException rte) {
1687                    mListeners.loadMessageForViewFailed(messageId, rte.getMessage());
1688                }
1689            }
1690        });
1691    }
1692
1693    /**
1694     * Attempts to load the attachment specified by id from the given account and message.
1695     */
1696    public void loadAttachment(final long accountId, final long messageId, final long mailboxId,
1697            final long attachmentId, MessagingListener listener, final boolean background) {
1698        mListeners.loadAttachmentStarted(accountId, messageId, attachmentId, true);
1699
1700        put("loadAttachment", listener, new Runnable() {
1701            public void run() {
1702                try {
1703                    //1. Check if the attachment is already here and return early in that case
1704                    Attachment attachment =
1705                        Attachment.restoreAttachmentWithId(mContext, attachmentId);
1706                    if (attachment == null) {
1707                        mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
1708                                   new MessagingException("The attachment is null"),
1709                                   background);
1710                        return;
1711                    }
1712                    if (Utility.attachmentExists(mContext, attachment)) {
1713                        mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
1714                        return;
1715                    }
1716
1717                    // 2. Open the remote folder.
1718                    // TODO all of these could be narrower projections
1719                    EmailContent.Account account =
1720                        EmailContent.Account.restoreAccountWithId(mContext, accountId);
1721                    Mailbox mailbox =
1722                        Mailbox.restoreMailboxWithId(mContext, mailboxId);
1723                    EmailContent.Message message =
1724                        EmailContent.Message.restoreMessageWithId(mContext, messageId);
1725
1726                    if (account == null || mailbox == null || message == null) {
1727                        mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
1728                                new MessagingException(
1729                                        "Account, mailbox, message or attachment are null"),
1730                                background);
1731                        return;
1732                    }
1733
1734                    Store remoteStore =
1735                        Store.getInstance(account, mContext, null);
1736                    Folder remoteFolder = remoteStore.getFolder(mailbox.mServerId);
1737                    remoteFolder.open(OpenMode.READ_WRITE, null);
1738
1739                    // 3. Generate a shell message in which to retrieve the attachment,
1740                    // and a shell BodyPart for the attachment.  Then glue them together.
1741                    Message storeMessage = remoteFolder.createMessage(message.mServerId);
1742                    MimeBodyPart storePart = new MimeBodyPart();
1743                    storePart.setSize((int)attachment.mSize);
1744                    storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA,
1745                            attachment.mLocation);
1746                    storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
1747                            String.format("%s;\n name=\"%s\"",
1748                            attachment.mMimeType,
1749                            attachment.mFileName));
1750                    // TODO is this always true for attachments?  I think we dropped the
1751                    // true encoding along the way
1752                    storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
1753
1754                    MimeMultipart multipart = new MimeMultipart();
1755                    multipart.setSubType("mixed");
1756                    multipart.addBodyPart(storePart);
1757
1758                    storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
1759                    storeMessage.setBody(multipart);
1760
1761                    // 4. Now ask for the attachment to be fetched
1762                    FetchProfile fp = new FetchProfile();
1763                    fp.add(storePart);
1764                    remoteFolder.fetch(new Message[] { storeMessage }, fp,
1765                            mController.new MessageRetrievalListenerBridge(
1766                                    messageId, attachmentId));
1767
1768                    // If we failed to load the attachment, throw an Exception here, so that
1769                    // AttachmentDownloadService knows that we failed
1770                    if (storePart.getBody() == null) {
1771                        throw new MessagingException("Attachment not loaded.");
1772                    }
1773
1774                    // 5. Save the downloaded file and update the attachment as necessary
1775                    LegacyConversions.saveAttachmentBody(mContext, storePart, attachment,
1776                            accountId);
1777
1778                    // 6. Report success
1779                    mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
1780                }
1781                catch (MessagingException me) {
1782                    if (Logging.LOGD) Log.v(Logging.LOG_TAG, "", me);
1783                    mListeners.loadAttachmentFailed(
1784                            accountId, messageId, attachmentId, me, background);
1785                } catch (IOException ioe) {
1786                    Log.e(Logging.LOG_TAG, "Error while storing attachment." + ioe.toString());
1787                }
1788            }});
1789    }
1790
1791    /**
1792     * Attempt to send any messages that are sitting in the Outbox.
1793     * @param account
1794     * @param listener
1795     */
1796    public void sendPendingMessages(final EmailContent.Account account, final long sentFolderId,
1797            MessagingListener listener) {
1798        put("sendPendingMessages", listener, new Runnable() {
1799            public void run() {
1800                sendPendingMessagesSynchronous(account, sentFolderId);
1801            }
1802        });
1803    }
1804
1805    /**
1806     * Attempt to send all messages sitting in the given account's outbox. Optionally,
1807     * if the server requires it, the message will be moved to the given sent folder.
1808     */
1809    public void sendPendingMessagesSynchronous(final EmailContent.Account account,
1810            long sentFolderId) {
1811        NotificationController nc = NotificationController.getInstance(mContext);
1812        // 1.  Loop through all messages in the account's outbox
1813        long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
1814        if (outboxId == Mailbox.NO_MAILBOX) {
1815            return;
1816        }
1817        ContentResolver resolver = mContext.getContentResolver();
1818        Cursor c = resolver.query(EmailContent.Message.CONTENT_URI,
1819                EmailContent.Message.ID_COLUMN_PROJECTION,
1820                EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) },
1821                null);
1822        try {
1823            // 2.  exit early
1824            if (c.getCount() <= 0) {
1825                return;
1826            }
1827            // 3. do one-time setup of the Sender & other stuff
1828            mListeners.sendPendingMessagesStarted(account.mId, -1);
1829
1830            Sender sender = Sender.getInstance(mContext, account);
1831            Store remoteStore = Store.getInstance(account, mContext, null);
1832            boolean requireMoveMessageToSentFolder = remoteStore.requireCopyMessageToSentFolder();
1833            ContentValues moveToSentValues = null;
1834            if (requireMoveMessageToSentFolder) {
1835                moveToSentValues = new ContentValues();
1836                moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolderId);
1837            }
1838
1839            // 4.  loop through the available messages and send them
1840            while (c.moveToNext()) {
1841                long messageId = -1;
1842                try {
1843                    messageId = c.getLong(0);
1844                    mListeners.sendPendingMessagesStarted(account.mId, messageId);
1845                    // Don't send messages with unloaded attachments
1846                    if (Utility.hasUnloadedAttachments(mContext, messageId)) {
1847                        if (Email.DEBUG) {
1848                            Log.d(Logging.LOG_TAG, "Can't send #" + messageId +
1849                                    "; unloaded attachments");
1850                        }
1851                        continue;
1852                    }
1853                    sender.sendMessage(messageId);
1854                } catch (MessagingException me) {
1855                    // report error for this message, but keep trying others
1856                    if (me instanceof AuthenticationFailedException) {
1857                        nc.showLoginFailedNotification(account.mId);
1858                    }
1859                    mListeners.sendPendingMessagesFailed(account.mId, messageId, me);
1860                    continue;
1861                }
1862                // 5. move to sent, or delete
1863                Uri syncedUri =
1864                    ContentUris.withAppendedId(EmailContent.Message.SYNCED_CONTENT_URI, messageId);
1865                if (requireMoveMessageToSentFolder) {
1866                    // If this is a forwarded message and it has attachments, delete them, as they
1867                    // duplicate information found elsewhere (on the server).  This saves storage.
1868                    EmailContent.Message msg =
1869                        EmailContent.Message.restoreMessageWithId(mContext, messageId);
1870                    if (msg != null &&
1871                            ((msg.mFlags & EmailContent.Message.FLAG_TYPE_FORWARD) != 0)) {
1872                        AttachmentUtilities.deleteAllAttachmentFiles(mContext, account.mId,
1873                                messageId);
1874                    }
1875                    resolver.update(syncedUri, moveToSentValues, null, null);
1876                } else {
1877                    AttachmentUtilities.deleteAllAttachmentFiles(mContext, account.mId,
1878                            messageId);
1879                    Uri uri =
1880                        ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId);
1881                    resolver.delete(uri, null, null);
1882                    resolver.delete(syncedUri, null, null);
1883                }
1884            }
1885            // 6. report completion/success
1886            mListeners.sendPendingMessagesCompleted(account.mId);
1887            nc.cancelLoginFailedNotification(account.mId);
1888        } catch (MessagingException me) {
1889            if (me instanceof AuthenticationFailedException) {
1890                nc.showLoginFailedNotification(account.mId);
1891            }
1892            mListeners.sendPendingMessagesFailed(account.mId, -1, me);
1893        } finally {
1894            c.close();
1895        }
1896    }
1897
1898    /**
1899     * Checks mail for an account.
1900     * This entry point is for use by the mail checking service only, because it
1901     * gives slightly different callbacks (so the service doesn't get confused by callbacks
1902     * triggered by/for the foreground UI.
1903     *
1904     * TODO clean up the execution model which is unnecessarily threaded due to legacy code
1905     *
1906     * @param accountId the account to check
1907     * @param listener
1908     */
1909    public void checkMail(final long accountId, final long tag, final MessagingListener listener) {
1910        mListeners.checkMailStarted(mContext, accountId, tag);
1911
1912        // This puts the command on the queue (not synchronous)
1913        listFolders(accountId, null);
1914
1915        // Put this on the queue as well so it follows listFolders
1916        put("checkMail", listener, new Runnable() {
1917            public void run() {
1918                // send any pending outbound messages.  note, there is a slight race condition
1919                // here if we somehow don't have a sent folder, but this should never happen
1920                // because the call to sendMessage() would have built one previously.
1921                long inboxId = -1;
1922                EmailContent.Account account =
1923                    EmailContent.Account.restoreAccountWithId(mContext, accountId);
1924                if (account != null) {
1925                    long sentboxId = Mailbox.findMailboxOfType(mContext, accountId,
1926                            Mailbox.TYPE_SENT);
1927                    if (sentboxId != Mailbox.NO_MAILBOX) {
1928                        sendPendingMessagesSynchronous(account, sentboxId);
1929                    }
1930                    // find mailbox # for inbox and sync it.
1931                    // TODO we already know this in Controller, can we pass it in?
1932                    inboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX);
1933                    if (inboxId != Mailbox.NO_MAILBOX) {
1934                        Mailbox mailbox =
1935                            Mailbox.restoreMailboxWithId(mContext, inboxId);
1936                        if (mailbox != null) {
1937                            synchronizeMailboxSynchronous(account, mailbox);
1938                        }
1939                    }
1940                }
1941                mListeners.checkMailFinished(mContext, accountId, inboxId, tag);
1942            }
1943        });
1944    }
1945
1946    private static class Command {
1947        public Runnable runnable;
1948
1949        public MessagingListener listener;
1950
1951        public String description;
1952
1953        @Override
1954        public String toString() {
1955            return description;
1956        }
1957    }
1958
1959    /** Results of the latest synchronization. */
1960    private static class SyncResults {
1961        /** The total # of messages in the folder */
1962        public final int mTotalMessages;
1963        /** A list of new message IDs; must not be {@code null} */
1964        public final ArrayList<Long> mAddedMessages;
1965
1966        public SyncResults(int totalMessages, ArrayList<Long> addedMessages) {
1967            if (addedMessages == null) {
1968                throw new IllegalArgumentException("addedMessages must not be null");
1969            }
1970            mTotalMessages = totalMessages;
1971            mAddedMessages = addedMessages;
1972        }
1973    }
1974}
1975