MessagingController.java revision 4b41bae270ea4c49ec8403084db43ee9b37cdda4
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.BodyPart;
20import com.android.email.mail.FetchProfile;
21import com.android.email.mail.Flag;
22import com.android.email.mail.Folder;
23import com.android.email.mail.Message;
24import com.android.email.mail.MessageRetrievalListener;
25import com.android.email.mail.MessagingException;
26import com.android.email.mail.Part;
27import com.android.email.mail.Sender;
28import com.android.email.mail.Store;
29import com.android.email.mail.StoreSynchronizer;
30import com.android.email.mail.Folder.FolderType;
31import com.android.email.mail.Folder.OpenMode;
32import com.android.email.mail.internet.MimeBodyPart;
33import com.android.email.mail.internet.MimeHeader;
34import com.android.email.mail.internet.MimeMultipart;
35import com.android.email.mail.internet.MimeUtility;
36import com.android.email.mail.store.LocalStore;
37import com.android.email.mail.store.LocalStore.LocalFolder;
38import com.android.email.mail.store.LocalStore.LocalMessage;
39import com.android.email.mail.store.LocalStore.PendingCommand;
40import com.android.email.provider.AttachmentProvider;
41import com.android.email.provider.EmailContent;
42import com.android.email.provider.EmailContent.Attachment;
43import com.android.email.provider.EmailContent.AttachmentColumns;
44import com.android.email.provider.EmailContent.Mailbox;
45import com.android.email.provider.EmailContent.MailboxColumns;
46import com.android.email.provider.EmailContent.MessageColumns;
47import com.android.email.provider.EmailContent.SyncColumns;
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.File;
59import java.io.IOException;
60import java.util.ArrayList;
61import java.util.Date;
62import java.util.HashMap;
63import java.util.HashSet;
64import java.util.concurrent.BlockingQueue;
65import java.util.concurrent.LinkedBlockingQueue;
66
67/**
68 * Starts a long running (application) Thread that will run through commands
69 * that require remote mailbox access. This class is used to serialize and
70 * prioritize these commands. Each method that will submit a command requires a
71 * MessagingListener instance to be provided. It is expected that that listener
72 * has also been added as a registered listener using addListener(). When a
73 * command is to be executed, if the listener that was provided with the command
74 * is no longer registered the command is skipped. The design idea for the above
75 * is that when an Activity starts it registers as a listener. When it is paused
76 * it removes itself. Thus, any commands that that activity submitted are
77 * removed from the queue once the activity is no longer active.
78 */
79public class MessagingController implements Runnable {
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 String PENDING_COMMAND_TRASH =
101        "com.android.email.MessagingController.trash";
102    private static final String PENDING_COMMAND_MARK_READ =
103        "com.android.email.MessagingController.markRead";
104    private static final String PENDING_COMMAND_APPEND =
105        "com.android.email.MessagingController.append";
106
107    /**
108     * Projections & CVs used by pruneCachedAttachments
109     */
110    private static String[] PRUNE_ATTACHMENT_PROJECTION = new String[] {
111        AttachmentColumns.LOCATION
112    };
113    private static ContentValues PRUNE_ATTACHMENT_CV = new ContentValues();
114    static {
115        PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI);
116    }
117
118    private static MessagingController inst = null;
119    private BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
120    private Thread mThread;
121
122    /**
123     * All access to mListeners *must* be synchronized
124     */
125    private GroupMessagingListener mListeners = new GroupMessagingListener();
126    private boolean mBusy;
127    private Context mContext;
128
129    protected MessagingController(Context _context) {
130        mContext = _context;
131        mThread = new Thread(this);
132        mThread.start();
133    }
134
135    /**
136     * Gets or creates the singleton instance of MessagingController. Application is used to
137     * provide a Context to classes that need it.
138     * @param application
139     * @return
140     */
141    public synchronized static MessagingController getInstance(Context _context) {
142        if (inst == null) {
143            inst = new MessagingController(_context);
144        }
145        return inst;
146    }
147
148    /**
149     * Inject a mock controller.  Used only for testing.  Affects future calls to getInstance().
150     */
151    public static void injectMockController(MessagingController mockController) {
152        inst = mockController;
153    }
154
155    // TODO: seems that this reading of mBusy isn't thread-safe
156    public boolean isBusy() {
157        return mBusy;
158    }
159
160    public void run() {
161        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
162        // TODO: add an end test to this infinite loop
163        while (true) {
164            Command command;
165            try {
166                command = mCommands.take();
167            } catch (InterruptedException e) {
168                continue; //re-test the condition on the eclosing while
169            }
170            if (command.listener == null || isActiveListener(command.listener)) {
171                mBusy = true;
172                command.runnable.run();
173                mListeners.controllerCommandCompleted(mCommands.size() > 0);
174            }
175            mBusy = false;
176        }
177    }
178
179    private void put(String description, MessagingListener listener, Runnable runnable) {
180        try {
181            Command command = new Command();
182            command.listener = listener;
183            command.runnable = runnable;
184            command.description = description;
185            mCommands.add(command);
186        }
187        catch (IllegalStateException ie) {
188            throw new Error(ie);
189        }
190    }
191
192    public void addListener(MessagingListener listener) {
193        mListeners.addListener(listener);
194    }
195
196    public void removeListener(MessagingListener listener) {
197        mListeners.removeListener(listener);
198    }
199
200    private boolean isActiveListener(MessagingListener listener) {
201        return mListeners.isActiveListener(listener);
202    }
203
204    /**
205     * Lightweight class for capturing local mailboxes in an account.  Just the columns
206     * necessary for a sync.
207     */
208    private static class LocalMailboxInfo {
209        private static final int COLUMN_ID = 0;
210        private static final int COLUMN_DISPLAY_NAME = 1;
211        private static final int COLUMN_ACCOUNT_KEY = 2;
212
213        private static final String[] PROJECTION = new String[] {
214            EmailContent.RECORD_ID,
215            MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY,
216        };
217
218        long mId;
219        String mDisplayName;
220        long mAccountKey;
221
222        public LocalMailboxInfo(Cursor c) {
223            mId = c.getLong(COLUMN_ID);
224            mDisplayName = c.getString(COLUMN_DISPLAY_NAME);
225            mAccountKey = c.getLong(COLUMN_ACCOUNT_KEY);
226        }
227    }
228
229    /**
230     * Lists folders that are available locally and remotely. This method calls
231     * listFoldersCallback for local folders before it returns, and then for
232     * remote folders at some later point. If there are no local folders
233     * includeRemote is forced by this method. This method should be called from
234     * a Thread as it may take several seconds to list the local folders.
235     *
236     * TODO this needs to cache the remote folder list
237     * TODO break out an inner listFoldersSynchronized which could simplify checkMail
238     *
239     * @param account
240     * @param listener
241     * @throws MessagingException
242     */
243    public void listFolders(long accountId, MessagingListener listener) {
244        final EmailContent.Account account =
245                EmailContent.Account.restoreAccountWithId(mContext, accountId);
246        mListeners.listFoldersStarted(account);
247        put("listFolders", listener, new Runnable() {
248            public void run() {
249                Cursor localFolderCursor = null;
250                try {
251                    // Step 1:  Get remote folders, make a list, and add any local folders
252                    // that don't already exist.
253
254                    Store store = Store.getInstance(account.getStoreUri(mContext), mContext, null);
255
256                    Folder[] remoteFolders = store.getPersonalNamespaces();
257                    updateAccountFolderNames(account, remoteFolders);
258
259                    HashSet<String> remoteFolderNames = new HashSet<String>();
260                    for (int i = 0, count = remoteFolders.length; i < count; i++) {
261                        remoteFolderNames.add(remoteFolders[i].getName());
262                    }
263
264                    HashMap<String, LocalMailboxInfo> localFolders =
265                        new HashMap<String, LocalMailboxInfo>();
266                    HashSet<String> localFolderNames = new HashSet<String>();
267                    localFolderCursor = mContext.getContentResolver().query(
268                            EmailContent.Mailbox.CONTENT_URI,
269                            LocalMailboxInfo.PROJECTION,
270                            EmailContent.MailboxColumns.ACCOUNT_KEY + "=?",
271                            new String[] { String.valueOf(account.mId) },
272                            null);
273                    while (localFolderCursor.moveToNext()) {
274                        LocalMailboxInfo info = new LocalMailboxInfo(localFolderCursor);
275                        localFolders.put(info.mDisplayName, info);
276                        localFolderNames.add(info.mDisplayName);
277                    }
278
279                    // Short circuit the rest if the sets are the same (the usual case)
280                    if (!remoteFolderNames.equals(localFolderNames)) {
281
282                        // They are different, so we have to do some adds and drops
283
284                        // Drops first, to make things smaller rather than larger
285                        HashSet<String> localsToDrop = new HashSet<String>(localFolderNames);
286                        localsToDrop.removeAll(remoteFolderNames);
287                        for (String localNameToDrop : localsToDrop) {
288                            LocalMailboxInfo localInfo = localFolders.get(localNameToDrop);
289                            Uri uri = ContentUris.withAppendedId(
290                                    EmailContent.Mailbox.CONTENT_URI, localInfo.mId);
291                            mContext.getContentResolver().delete(uri, null, null);
292                        }
293
294                        // Now do the adds
295                        remoteFolderNames.removeAll(localFolderNames);
296                        for (String remoteNameToAdd : remoteFolderNames) {
297                            EmailContent.Mailbox box = new EmailContent.Mailbox();
298                            box.mDisplayName = remoteNameToAdd;
299                            // box.mServerId;
300                            // box.mParentServerId;
301                            box.mAccountKey = account.mId;
302                            box.mType = inferMailboxTypeFromName(account, remoteNameToAdd);
303                            // box.mDelimiter;
304                            // box.mSyncKey;
305                            // box.mSyncLookback;
306                            // box.mSyncFrequency;
307                            // box.mSyncTime;
308                            // box.mUnreadCount;
309                            box.mFlagVisible = true;
310                            // box.mFlags;
311                            box.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT;
312                            box.save(mContext);
313                        }
314                    }
315                    mListeners.listFoldersFinished(account);
316                } catch (Exception e) {
317                    mListeners.listFoldersFailed(account, "");
318                } finally {
319                    if (localFolderCursor != null) {
320                        localFolderCursor.close();
321                    }
322                }
323            }
324        });
325    }
326
327    /**
328     * Temporarily:  Infer mailbox type from mailbox name.  This should probably be
329     * mutated into something that the stores can provide directly, instead of the two-step
330     * where we scan and report.
331     */
332    public int inferMailboxTypeFromName(EmailContent.Account account, String mailboxName) {
333        if (mailboxName == null || mailboxName.length() == 0) {
334            return EmailContent.Mailbox.TYPE_MAIL;
335        }
336        if (mailboxName.equals(Email.INBOX)) {
337            return EmailContent.Mailbox.TYPE_INBOX;
338        }
339        if (mailboxName.equals(account.getTrashFolderName(mContext))) {
340            return EmailContent.Mailbox.TYPE_TRASH;
341        }
342        if (mailboxName.equals(account.getOutboxFolderName(mContext))) {
343            return EmailContent.Mailbox.TYPE_OUTBOX;
344        }
345        if (mailboxName.equals(account.getDraftsFolderName(mContext))) {
346            return EmailContent.Mailbox.TYPE_DRAFTS;
347        }
348        if (mailboxName.equals(account.getSentFolderName(mContext))) {
349            return EmailContent.Mailbox.TYPE_SENT;
350        }
351
352        return EmailContent.Mailbox.TYPE_MAIL;
353    }
354
355    /**
356     * Asks the store for a list of server-specific folder names and, if provided, updates
357     * the account record for future getFolder() operations.
358     *
359     * NOTE:  Inbox is not queried, because we require it to be INBOX, and outbox is not
360     * queried, because outbox is local-only.
361     *
362     * TODO: Rewrite this to use simple folder tagging and none of this account nonsense
363     */
364    /* package */ void updateAccountFolderNames(EmailContent.Account account,
365            Folder[] remoteFolders) {
366        String trash = null;
367        String sent = null;
368        String drafts = null;
369
370        for (Folder folder : remoteFolders) {
371            Folder.FolderRole role = folder.getRole();
372            if (role == Folder.FolderRole.TRASH) {
373                trash = folder.getName();
374            } else if (role == Folder.FolderRole.SENT) {
375                sent = folder.getName();
376            } else if (role == Folder.FolderRole.DRAFTS) {
377                drafts = folder.getName();
378            }
379        }
380/*
381        // Do not update when null (defaults are already in place)
382        boolean commit = false;
383        if (trash != null && !trash.equals(account.getTrashFolderName(mContext))) {
384            account.setTrashFolderName(trash);
385            commit = true;
386        }
387        if (sent != null && !sent.equals(account.getSentFolderName(mContext))) {
388            account.setSentFolderName(sent);
389            commit = true;
390        }
391        if (drafts != null && !drafts.equals(account.getDraftsFolderName(mContext))) {
392            account.setDraftsFolderName(drafts);
393            commit = true;
394        }
395        if (commit) {
396            account.saveOrUpdate(mContext);
397        }
398*/
399    }
400
401    /**
402     * List the local message store for the given folder. This work is done
403     * synchronously.
404     *
405     * @param account
406     * @param folder
407     * @param listener
408     * @throws MessagingException
409     */
410/*
411    public void listLocalMessages(final EmailContent.Account account, final String folder,
412            MessagingListener listener) {
413        synchronized (mListeners) {
414            for (MessagingListener l : mListeners) {
415                l.listLocalMessagesStarted(account, folder);
416            }
417        }
418
419        try {
420            Store localStore = Store.getInstance(account.getLocalStoreUri(mContext), mContext,
421                    null);
422            Folder localFolder = localStore.getFolder(folder);
423            localFolder.open(OpenMode.READ_WRITE, null);
424            Message[] localMessages = localFolder.getMessages(null);
425            ArrayList<Message> messages = new ArrayList<Message>();
426            for (Message message : localMessages) {
427                if (!message.isSet(Flag.DELETED)) {
428                    messages.add(message);
429                }
430            }
431            synchronized (mListeners) {
432                for (MessagingListener l : mListeners) {
433                    l.listLocalMessages(account, folder, messages.toArray(new Message[0]));
434                }
435                for (MessagingListener l : mListeners) {
436                    l.listLocalMessagesFinished(account, folder);
437                }
438            }
439        }
440        catch (Exception e) {
441            synchronized (mListeners) {
442                for (MessagingListener l : mListeners) {
443                    l.listLocalMessagesFailed(account, folder, e.getMessage());
444                }
445            }
446        }
447    }
448*/
449
450    /**
451     * Increase the window size for a given mailbox, and load more from server.
452     */
453    public void loadMoreMessages(EmailContent.Account account, EmailContent.Mailbox folder,
454            MessagingListener listener) {
455
456        // TODO redo implementation
457/*
458        try {
459            Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
460                    mContext);
461            LocalStore localStore = (LocalStore) Store.getInstance(
462                    account.getLocalStoreUri(mContext), mContext, null);
463            LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
464            int oldLimit = localFolder.getVisibleLimit();
465            if (oldLimit <= 0) {
466                oldLimit = info.mVisibleLimitDefault;
467            }
468            localFolder.setVisibleLimit(oldLimit + info.mVisibleLimitIncrement);
469            synchronizeMailbox(account, folder, listener);
470        }
471        catch (MessagingException me) {
472            throw new RuntimeException("Unable to set visible limit on folder", me);
473        }
474*/
475    }
476
477    public void resetVisibleLimits(EmailContent.Account account) {
478        try {
479            Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
480                    mContext);
481            // check for null to handle semi-initialized accounts created during unit tests
482            // store info should not be null in production scenarios
483            if (info != null) {
484                LocalStore localStore = (LocalStore) Store.getInstance(
485                        account.getLocalStoreUri(mContext), mContext, null);
486                localStore.resetVisibleLimits(info.mVisibleLimitDefault);
487            }
488        }
489        catch (MessagingException e) {
490            Log.e(Email.LOG_TAG, "Unable to reset visible limits", e);
491        }
492    }
493
494    /**
495     * Start background synchronization of the specified folder.
496     * @param account
497     * @param folder
498     * @param listener
499     */
500    public void synchronizeMailbox(final EmailContent.Account account,
501            final EmailContent.Mailbox folder, MessagingListener listener) {
502        /*
503         * We don't ever sync the Outbox.
504         */
505        if (folder.mType == EmailContent.Mailbox.TYPE_OUTBOX) {
506            return;
507        }
508        mListeners.synchronizeMailboxStarted(account, folder);
509        put("synchronizeMailbox", listener, new Runnable() {
510            public void run() {
511                synchronizeMailboxSynchronous(account, folder);
512            }
513        });
514    }
515
516    /**
517     * Start foreground synchronization of the specified folder. This is called by
518     * synchronizeMailbox or checkMail.
519     * TODO this should use ID's instead of fully-restored objects
520     * @param account
521     * @param folder
522     * @param listener
523     */
524    private void synchronizeMailboxSynchronous(final EmailContent.Account account,
525            final EmailContent.Mailbox folder) {
526        mListeners.synchronizeMailboxStarted(account, folder);
527        try {
528            processPendingCommandsSynchronous(account);
529
530            StoreSynchronizer.SyncResults results;
531
532            // Select generic sync or store-specific sync
533            final LocalStore localStore =
534                (LocalStore) Store.getInstance(account.getLocalStoreUri(mContext), mContext, null);
535            Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext,
536                    localStore.getPersistentCallbacks());
537            StoreSynchronizer customSync = remoteStore.getMessageSynchronizer();
538            if (customSync == null) {
539                results = synchronizeMailboxGeneric(account, folder);
540            } else {
541                results = customSync.SynchronizeMessagesSynchronous(
542                        account, folder, mListeners, mContext);
543            }
544            mListeners.synchronizeMailboxFinished(account,
545                                                  folder,
546                                                  results.mTotalMessages,
547                                                  results.mNewMessages);
548        } catch (MessagingException e) {
549            if (Email.LOGD) {
550                Log.v(Email.LOG_TAG, "synchronizeMailbox", e);
551            }
552            mListeners.synchronizeMailboxFailed(account, folder, e);
553        }
554    }
555
556    /**
557     * Lightweight record for the first pass of message sync, where I'm just seeing if
558     * the local message requires sync.  Later (for messages that need syncing) we'll do a full
559     * readout from the DB.
560     */
561    private static class LocalMessageInfo {
562        private static final int COLUMN_ID = 0;
563        private static final int COLUMN_FLAG_READ = 1;
564        private static final int COLUMN_FLAG_LOADED = 2;
565        private static final int COLUMN_SERVER_ID = 3;
566        private static final int COLUMN_MAILBOX_KEY = 4;
567        private static final int COLUMN_ACCOUNT_KEY = 5;
568        private static final String[] PROJECTION = new String[] {
569            EmailContent.RECORD_ID,
570            MessageColumns.FLAG_READ, MessageColumns.FLAG_LOADED,
571            SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY
572        };
573
574        int mCursorIndex;
575        long mId;
576        boolean mFlagRead;
577        int mFlagLoaded;
578        String mServerId;
579
580        public LocalMessageInfo(Cursor c) {
581            mCursorIndex = c.getPosition();
582            mId = c.getLong(COLUMN_ID);
583            mFlagRead = c.getInt(COLUMN_FLAG_READ) != 0;
584            mFlagLoaded = c.getInt(COLUMN_FLAG_LOADED);
585            mServerId = c.getString(COLUMN_SERVER_ID);
586            // Note: mailbox key and account key not needed - they are projected for the SELECT
587        }
588    }
589
590    private void saveOrUpdate(EmailContent content) {
591        if (content.isSaved()) {
592            content.update(mContext, content.toContentValues());
593        } else {
594            content.save(mContext);
595        }
596    }
597
598    /**
599     * Generic synchronizer - used for POP3 and IMAP.
600     *
601     * TODO Break this method up into smaller chunks.
602     *
603     * @param account the account to sync
604     * @param folder the mailbox to sync
605     * @return results of the sync pass
606     * @throws MessagingException
607     */
608    private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
609            final EmailContent.Account account, final EmailContent.Mailbox folder)
610            throws MessagingException {
611
612        Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
613
614        // 1.  Get the message list from the local store and create an index of the uids
615
616        Cursor localUidCursor = null;
617        HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
618
619        try {
620            localUidCursor = mContext.getContentResolver().query(
621                    EmailContent.Message.CONTENT_URI,
622                    LocalMessageInfo.PROJECTION,
623                    EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
624                    " AND " + MessageColumns.MAILBOX_KEY + "=?",
625                    new String[] {
626                            String.valueOf(account.mId),
627                            String.valueOf(folder.mId)
628                    },
629                    null);
630            while (localUidCursor.moveToNext()) {
631                LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
632                localMessageMap.put(info.mServerId, info);
633            }
634        } finally {
635            if (localUidCursor != null) {
636                localUidCursor.close();
637            }
638        }
639
640        // 1a. Count the unread messages before changing anything
641        int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
642                EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
643                " AND " + MessageColumns.MAILBOX_KEY + "=?" +
644                " AND " + MessageColumns.FLAG_READ + "=0",
645                new String[] {
646                        String.valueOf(account.mId),
647                        String.valueOf(folder.mId)
648                });
649
650        // 2.  Open the remote folder and create the remote folder if necessary
651
652        Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
653        Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
654
655        /*
656         * If the folder is a "special" folder we need to see if it exists
657         * on the remote server. It if does not exist we'll try to create it. If we
658         * can't create we'll abort. This will happen on every single Pop3 folder as
659         * designed and on Imap folders during error conditions. This allows us
660         * to treat Pop3 and Imap the same in this code.
661         */
662        if (folder.equals(account.getTrashFolderName(mContext)) ||
663                folder.equals(account.getSentFolderName(mContext)) ||
664                folder.equals(account.getDraftsFolderName(mContext))) {
665            if (!remoteFolder.exists()) {
666                if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
667                    return new StoreSynchronizer.SyncResults(0, 0);
668                }
669            }
670        }
671
672        // 3, Open the remote folder. This pre-loads certain metadata like message count.
673        remoteFolder.open(OpenMode.READ_WRITE, null);
674
675        // 4. Trash any remote messages that are marked as trashed locally.
676        // TODO - this comment was here, but no code was here.
677
678        // 5. Get the remote message count.
679        int remoteMessageCount = remoteFolder.getMessageCount();
680
681        // 6. Determine the limit # of messages to download
682        // TODO decide where to persist the visible limit (account?) until we switch UI model
683        int visibleLimit = -1;  // localFolder.getVisibleLimit();
684        if (visibleLimit <= 0) {
685            Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
686                    mContext);
687            visibleLimit = info.mVisibleLimitDefault;
688            // localFolder.setVisibleLimit(visibleLimit);
689        }
690
691        // 7.  Create a list of messages to download
692        Message[] remoteMessages = new Message[0];
693        final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
694        HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
695
696        int newMessageCount = 0;
697        if (remoteMessageCount > 0) {
698            /*
699             * Message numbers start at 1.
700             */
701            int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
702            int remoteEnd = remoteMessageCount;
703            remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
704            for (Message message : remoteMessages) {
705                remoteUidMap.put(message.getUid(), message);
706            }
707
708            /*
709             * Get a list of the messages that are in the remote list but not on the
710             * local store, or messages that are in the local store but failed to download
711             * on the last sync. These are the new messages that we will download.
712             */
713            for (Message message : remoteMessages) {
714                LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
715                if (localMessage == null) {
716                    newMessageCount++;
717                }
718                if (localMessage == null ||
719                        localMessage.mFlagLoaded != EmailContent.Message.LOADED) {
720                    unsyncedMessages.add(message);
721                }
722            }
723        }
724
725        // 8.  Download basic info about the new/unloaded messages (if any)
726        /*
727         * A list of messages that were downloaded and which did not have the Seen flag set.
728         * This will serve to indicate the true "new" message count that will be reported to
729         * the user via notification.
730         */
731        final ArrayList<Message> newMessages = new ArrayList<Message>();
732
733        /*
734         * Fetch the flags and envelope only of the new messages. This is intended to get us
735         * critical data as fast as possible, and then we'll fill in the details.
736         */
737        if (unsyncedMessages.size() > 0) {
738            FetchProfile fp = new FetchProfile();
739            fp.add(FetchProfile.Item.FLAGS);
740            fp.add(FetchProfile.Item.ENVELOPE);
741            final HashMap<String, LocalMessageInfo> localMapCopy =
742                new HashMap<String, LocalMessageInfo>(localMessageMap);
743
744            remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
745                    new MessageRetrievalListener() {
746                        public void messageFinished(Message message, int number, int ofTotal) {
747                            try {
748                                // Determine if the new message was already known (e.g. partial)
749                                // And create or reload the full message info
750                                LocalMessageInfo localMessageInfo =
751                                    localMapCopy.get(message.getUid());
752                                EmailContent.Message localMessage = null;
753                                if (localMessageInfo == null) {
754                                    localMessage = new EmailContent.Message();
755                                } else {
756                                    localMessage = EmailContent.Message.restoreMessageWithId(
757                                            mContext, localMessageInfo.mId);
758                                }
759
760                                if (localMessage != null) {
761                                    try {
762                                        // Copy the fields that are available into the message
763                                        LegacyConversions.updateMessageFields(localMessage,
764                                                message, account.mId, folder.mId);
765                                        // Commit the message to the local store
766                                        saveOrUpdate(localMessage);
767                                        // Track the "new" ness of the downloaded message
768                                        if (!message.isSet(Flag.SEEN)) {
769                                            newMessages.add(message);
770                                        }
771                                    } catch (MessagingException me) {
772                                        Log.e(Email.LOG_TAG,
773                                                "Error while copying downloaded message." + me);
774                                    }
775
776                                }
777                            }
778                            catch (Exception e) {
779                                Log.e(Email.LOG_TAG,
780                                        "Error while storing downloaded message." + e.toString());
781                            }
782                        }
783
784                        public void messageStarted(String uid, int number, int ofTotal) {
785                        }
786                    });
787        }
788
789        // 9. Refresh the flags for any messages in the local store that we didn't just download.
790        FetchProfile fp = new FetchProfile();
791        fp.add(FetchProfile.Item.FLAGS);
792        remoteFolder.fetch(remoteMessages, fp, null);
793        boolean remoteSupportsSeenFlag = false;
794        for (Flag flag : remoteFolder.getPermanentFlags()) {
795            if (flag == Flag.SEEN) {
796                remoteSupportsSeenFlag = true;
797            }
798        }
799        // Update the SEEN flag (if supported remotely - e.g. not for POP3)
800        if (remoteSupportsSeenFlag) {
801            for (Message remoteMessage : remoteMessages) {
802                LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
803                if (localMessageInfo == null) {
804                    continue;
805                }
806                boolean localSeen = localMessageInfo.mFlagRead;
807                boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
808                if (remoteSeen != localSeen) {
809                    Uri uri = ContentUris.withAppendedId(
810                            EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
811                    ContentValues updateValues = new ContentValues();
812                    updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen ? 1 : 0);
813                    mContext.getContentResolver().update(uri, updateValues, null, null);
814                }
815            }
816        }
817
818        // 10. Compute and store the unread message count.
819        // -- no longer necessary - Provider uses DB triggers to keep track
820
821//        int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
822//        if (remoteUnreadMessageCount == -1) {
823//            if (remoteSupportsSeenFlag) {
824//                /*
825//                 * If remote folder doesn't supported unread message count but supports
826//                 * seen flag, use local folder's unread message count and the size of
827//                 * new messages. This mode is not used for POP3, or IMAP.
828//                 */
829//
830//                remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
831//            } else {
832//                /*
833//                 * If remote folder doesn't supported unread message count and doesn't
834//                 * support seen flag, use localUnreadCount and newMessageCount which
835//                 * don't rely on remote SEEN flag.  This mode is used by POP3.
836//                 */
837//                remoteUnreadMessageCount = localUnreadCount + newMessageCount;
838//            }
839//        } else {
840//            /*
841//             * If remote folder supports unread message count, use remoteUnreadMessageCount.
842//             * This mode is used by IMAP.
843//             */
844//         }
845//        Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
846//        ContentValues updateValues = new ContentValues();
847//        updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
848//        mContext.getContentResolver().update(uri, updateValues, null, null);
849
850        // 11. Remove any messages that are in the local store but no longer on the remote store.
851
852        HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
853        localUidsToDelete.removeAll(remoteUidMap.keySet());
854        for (String uidToDelete : localUidsToDelete) {
855            LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
856
857            Uri uriToDelete = ContentUris.withAppendedId(
858                    EmailContent.Message.CONTENT_URI, infoToDelete.mId);
859            mContext.getContentResolver().delete(uriToDelete, null, null);
860        }
861
862        // 12. Divide the unsynced messages into small & large (by size)
863
864        // TODO doing this work here (synchronously) is problematic because it prevents the UI
865        // from affecting the order (e.g. download a message because the user requested it.)  Much
866        // of this logic should move out to a different sync loop that attempts to update small
867        // groups of messages at a time, as a background task.  However, we can't just return
868        // (yet) because POP messages don't have an envelope yet....
869
870        ArrayList<Message> largeMessages = new ArrayList<Message>();
871        ArrayList<Message> smallMessages = new ArrayList<Message>();
872        for (Message message : unsyncedMessages) {
873            if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
874                largeMessages.add(message);
875            } else {
876                smallMessages.add(message);
877            }
878        }
879
880        // 13. Download small messages
881
882        // TODO Problems with this implementation.  1. For IMAP, where we get a real envelope,
883        // this is going to be inefficient and duplicate work we've already done.  2.  It's going
884        // back to the DB for a local message that we already had (and discarded).
885
886        // For small messages, we specify "body", which returns everything (incl. attachments)
887        fp = new FetchProfile();
888        fp.add(FetchProfile.Item.BODY);
889        remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
890                new MessageRetrievalListener() {
891                    public void messageFinished(Message message, int number, int ofTotal) {
892                        // Store the updated message locally and mark it fully loaded
893                        copyOneMessageToProvider(message, account, folder,
894                                EmailContent.Message.LOADED);
895                    }
896
897                    public void messageStarted(String uid, int number, int ofTotal) {
898                    }
899        });
900
901        // 14. Download large messages.  We ask the server to give us the message structure,
902        // but not all of the attachments.
903        fp.clear();
904        fp.add(FetchProfile.Item.STRUCTURE);
905        remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
906        for (Message message : largeMessages) {
907            if (message.getBody() == null) {
908                // POP doesn't support STRUCTURE mode, so we'll just do a partial download
909                // (hopefully enough to see some/all of the body) and mark the message for
910                // further download.
911                fp.clear();
912                fp.add(FetchProfile.Item.BODY_SANE);
913                //  TODO a good optimization here would be to make sure that all Stores set
914                //  the proper size after this fetch and compare the before and after size. If
915                //  they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
916                remoteFolder.fetch(new Message[] { message }, fp, null);
917
918                // Store the partially-loaded message and mark it partially loaded
919                copyOneMessageToProvider(message, account, folder,
920                        EmailContent.Message.PARTIALLY_LOADED);
921            } else {
922                // We have a structure to deal with, from which
923                // we can pull down the parts we want to actually store.
924                // Build a list of parts we are interested in. Text parts will be downloaded
925                // right now, attachments will be left for later.
926                ArrayList<Part> viewables = new ArrayList<Part>();
927                ArrayList<Part> attachments = new ArrayList<Part>();
928                MimeUtility.collectParts(message, viewables, attachments);
929                // Download the viewables immediately
930                for (Part part : viewables) {
931                    fp.clear();
932                    fp.add(part);
933                    // TODO what happens if the network connection dies? We've got partial
934                    // messages with incorrect status stored.
935                    remoteFolder.fetch(new Message[] { message }, fp, null);
936                }
937                // Store the updated message locally and mark it fully loaded
938                copyOneMessageToProvider(message, account, folder, EmailContent.Message.LOADED);
939            }
940        }
941
942        // 15. Clean up and report results
943
944        remoteFolder.close(false);
945        // TODO - more
946
947        // Original sync code.  Using for reference, will delete when done.
948        if (false) {
949        /*
950         * Now do the large messages that require more round trips.
951         */
952        fp.clear();
953        fp.add(FetchProfile.Item.STRUCTURE);
954        remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
955                fp, null);
956        for (Message message : largeMessages) {
957            if (message.getBody() == null) {
958                /*
959                 * The provider was unable to get the structure of the message, so
960                 * we'll download a reasonable portion of the messge and mark it as
961                 * incomplete so the entire thing can be downloaded later if the user
962                 * wishes to download it.
963                 */
964                fp.clear();
965                fp.add(FetchProfile.Item.BODY_SANE);
966                /*
967                 *  TODO a good optimization here would be to make sure that all Stores set
968                 *  the proper size after this fetch and compare the before and after size. If
969                 *  they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
970                 */
971
972                remoteFolder.fetch(new Message[] { message }, fp, null);
973                // Store the updated message locally
974//                localFolder.appendMessages(new Message[] {
975//                    message
976//                });
977
978//                Message localMessage = localFolder.getMessage(message.getUid());
979
980                // Set a flag indicating that the message has been partially downloaded and
981                // is ready for view.
982//                localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
983            } else {
984                /*
985                 * We have a structure to deal with, from which
986                 * we can pull down the parts we want to actually store.
987                 * Build a list of parts we are interested in. Text parts will be downloaded
988                 * right now, attachments will be left for later.
989                 */
990
991                ArrayList<Part> viewables = new ArrayList<Part>();
992                ArrayList<Part> attachments = new ArrayList<Part>();
993                MimeUtility.collectParts(message, viewables, attachments);
994
995                /*
996                 * Now download the parts we're interested in storing.
997                 */
998                for (Part part : viewables) {
999                    fp.clear();
1000                    fp.add(part);
1001                    // TODO what happens if the network connection dies? We've got partial
1002                    // messages with incorrect status stored.
1003                    remoteFolder.fetch(new Message[] { message }, fp, null);
1004                }
1005                // Store the updated message locally
1006//                localFolder.appendMessages(new Message[] {
1007//                    message
1008//                });
1009
1010//                Message localMessage = localFolder.getMessage(message.getUid());
1011
1012                // Set a flag indicating this message has been fully downloaded and can be
1013                // viewed.
1014//                localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
1015            }
1016
1017            // Update the listener with what we've found
1018//            synchronized (mListeners) {
1019//                for (MessagingListener l : mListeners) {
1020//                    l.synchronizeMailboxNewMessage(
1021//                            account,
1022//                            folder,
1023//                            localFolder.getMessage(message.getUid()));
1024//                }
1025//            }
1026        }
1027
1028
1029        /*
1030         * Report successful sync
1031         */
1032        StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
1033                remoteFolder.getMessageCount(), newMessages.size());
1034
1035        remoteFolder.close(false);
1036//        localFolder.close(false);
1037
1038        return results;
1039        }
1040
1041        return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
1042    }
1043
1044    /**
1045     * Copy one downloaded message (which may have partially-loaded sections)
1046     * into a provider message
1047     *
1048     * @param message the remote message we've just downloaded
1049     * @param account the account it will be stored into
1050     * @param folder the mailbox it will be stored into
1051     * @param loadStatus when complete, the message will be marked with this status (e.g.
1052     *        EmailContent.Message.LOADED)
1053     */
1054    private void copyOneMessageToProvider(Message message, EmailContent.Account account,
1055            EmailContent.Mailbox folder, int loadStatus) {
1056        try {
1057            EmailContent.Message localMessage = null;
1058            Cursor c = null;
1059            try {
1060                c = mContext.getContentResolver().query(
1061                        EmailContent.Message.CONTENT_URI,
1062                        EmailContent.Message.CONTENT_PROJECTION,
1063                        EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
1064                        " AND " + MessageColumns.MAILBOX_KEY + "=?" +
1065                        " AND " + SyncColumns.SERVER_ID + "=?",
1066                        new String[] {
1067                                String.valueOf(account.mId),
1068                                String.valueOf(folder.mId),
1069                                String.valueOf(message.getUid())
1070                        },
1071                        null);
1072                if (c.moveToNext()) {
1073                    localMessage = EmailContent.getContent(c, EmailContent.Message.class);
1074                }
1075            } finally {
1076                if (c != null) {
1077                    c.close();
1078                }
1079            }
1080            if (localMessage == null) {
1081                Log.d(Email.LOG_TAG, "Could not retrieve message from db, UUID="
1082                        + message.getUid());
1083                return;
1084            }
1085
1086            EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(mContext,
1087                    localMessage.mId);
1088            if (body == null) {
1089                body = new EmailContent.Body();
1090            }
1091            try {
1092                // Copy the fields that are available into the message object
1093                LegacyConversions.updateMessageFields(localMessage, message, account.mId,
1094                        folder.mId);
1095
1096                // Now process body parts & attachments
1097                ArrayList<Part> viewables = new ArrayList<Part>();
1098                ArrayList<Part> attachments = new ArrayList<Part>();
1099                MimeUtility.collectParts(message, viewables, attachments);
1100
1101                LegacyConversions.updateBodyFields(body, localMessage, viewables);
1102
1103                // Commit the message & body to the local store immediately
1104                saveOrUpdate(localMessage);
1105                saveOrUpdate(body);
1106
1107                // process (and save) attachments
1108                LegacyConversions.updateAttachments(mContext, localMessage,
1109                        attachments);
1110
1111                // One last update of message with two updated flags
1112                localMessage.mFlagLoaded = loadStatus;
1113
1114                ContentValues cv = new ContentValues();
1115                cv.put(EmailContent.MessageColumns.FLAG_ATTACHMENT, localMessage.mFlagAttachment);
1116                cv.put(EmailContent.MessageColumns.FLAG_LOADED, localMessage.mFlagLoaded);
1117                Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI,
1118                        localMessage.mId);
1119                mContext.getContentResolver().update(uri, cv, null, null);
1120
1121            } catch (MessagingException me) {
1122                Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me);
1123            }
1124
1125        } catch (RuntimeException rte) {
1126            Log.e(Email.LOG_TAG, "Error while storing downloaded message." + rte.toString());
1127        } catch (IOException ioe) {
1128            Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
1129        }
1130    }
1131
1132    private void queuePendingCommand(EmailContent.Account account, PendingCommand command) {
1133        try {
1134            LocalStore localStore = (LocalStore) Store.getInstance(
1135                    account.getLocalStoreUri(mContext), mContext, null);
1136            localStore.addPendingCommand(command);
1137        }
1138        catch (Exception e) {
1139            throw new RuntimeException("Unable to enqueue pending command", e);
1140        }
1141    }
1142
1143    private void processPendingCommands(final EmailContent.Account account) {
1144        put("processPendingCommands", null, new Runnable() {
1145            public void run() {
1146                try {
1147                    processPendingCommandsSynchronous(account);
1148                }
1149                catch (MessagingException me) {
1150                    if (Email.LOGD) {
1151                        Log.v(Email.LOG_TAG, "processPendingCommands", me);
1152                    }
1153                    /*
1154                     * Ignore any exceptions from the commands. Commands will be processed
1155                     * on the next round.
1156                     */
1157                }
1158            }
1159        });
1160    }
1161
1162    private void processPendingCommandsSynchronous(EmailContent.Account account)
1163            throws MessagingException {
1164        LocalStore localStore = (LocalStore) Store.getInstance(
1165                account.getLocalStoreUri(mContext), mContext, null);
1166        ArrayList<PendingCommand> commands = localStore.getPendingCommands();
1167        for (PendingCommand command : commands) {
1168            /*
1169             * We specifically do not catch any exceptions here. If a command fails it is
1170             * most likely due to a server or IO error and it must be retried before any
1171             * other command processes. This maintains the order of the commands.
1172             */
1173            if (PENDING_COMMAND_APPEND.equals(command.command)) {
1174                processPendingAppend(command, account);
1175            }
1176            else if (PENDING_COMMAND_MARK_READ.equals(command.command)) {
1177                processPendingMarkRead(command, account);
1178            }
1179            else if (PENDING_COMMAND_TRASH.equals(command.command)) {
1180                processPendingTrash(command, account);
1181            }
1182            localStore.removePendingCommand(command);
1183        }
1184    }
1185
1186    /**
1187     * Process a pending append message command. This command uploads a local message to the
1188     * server, first checking to be sure that the server message is not newer than
1189     * the local message. Once the local message is successfully processed it is deleted so
1190     * that the server message will be synchronized down without an additional copy being
1191     * created.
1192     * TODO update the local message UID instead of deleteing it
1193     *
1194     * @param command arguments = (String folder, String uid)
1195     * @param account
1196     * @throws MessagingException
1197     */
1198    private void processPendingAppend(PendingCommand command, EmailContent.Account account)
1199            throws MessagingException {
1200        String folder = command.arguments[0];
1201        String uid = command.arguments[1];
1202
1203        LocalStore localStore = (LocalStore) Store.getInstance(
1204                account.getLocalStoreUri(mContext), mContext, null);
1205        LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
1206        LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
1207
1208        if (localMessage == null) {
1209            return;
1210        }
1211
1212        Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext,
1213                localStore.getPersistentCallbacks());
1214        Folder remoteFolder = remoteStore.getFolder(folder);
1215        if (!remoteFolder.exists()) {
1216            if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
1217                return;
1218            }
1219        }
1220        remoteFolder.open(OpenMode.READ_WRITE, localFolder.getPersistentCallbacks());
1221        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1222            return;
1223        }
1224
1225        Message remoteMessage = null;
1226        if (!localMessage.getUid().startsWith("Local")
1227                && !localMessage.getUid().contains("-")) {
1228            remoteMessage = remoteFolder.getMessage(localMessage.getUid());
1229        }
1230
1231        if (remoteMessage == null) {
1232            /*
1233             * If the message does not exist remotely we just upload it and then
1234             * update our local copy with the new uid.
1235             */
1236            FetchProfile fp = new FetchProfile();
1237            fp.add(FetchProfile.Item.BODY);
1238            localFolder.fetch(new Message[] { localMessage }, fp, null);
1239            String oldUid = localMessage.getUid();
1240            remoteFolder.appendMessages(new Message[] { localMessage });
1241            localFolder.changeUid(localMessage);
1242            mListeners.messageUidChanged(account, folder, oldUid, localMessage.getUid());
1243        }
1244        else {
1245            /*
1246             * If the remote message exists we need to determine which copy to keep.
1247             */
1248            /*
1249             * See if the remote message is newer than ours.
1250             */
1251            FetchProfile fp = new FetchProfile();
1252            fp.add(FetchProfile.Item.ENVELOPE);
1253            remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
1254            Date localDate = localMessage.getInternalDate();
1255            Date remoteDate = remoteMessage.getInternalDate();
1256            if (remoteDate.compareTo(localDate) > 0) {
1257                /*
1258                 * If the remote message is newer than ours we'll just
1259                 * delete ours and move on. A sync will get the server message
1260                 * if we need to be able to see it.
1261                 */
1262                localMessage.setFlag(Flag.DELETED, true);
1263            }
1264            else {
1265                /*
1266                 * Otherwise we'll upload our message and then delete the remote message.
1267                 */
1268                fp.clear();
1269                fp = new FetchProfile();
1270                fp.add(FetchProfile.Item.BODY);
1271                localFolder.fetch(new Message[] { localMessage }, fp, null);
1272                String oldUid = localMessage.getUid();
1273                remoteFolder.appendMessages(new Message[] { localMessage });
1274                localFolder.changeUid(localMessage);
1275                mListeners.messageUidChanged(account, folder, oldUid, localMessage.getUid());
1276                remoteMessage.setFlag(Flag.DELETED, true);
1277            }
1278        }
1279    }
1280
1281    /**
1282     * Process a pending trash message command.
1283     *
1284     * @param command arguments = (String folder, String uid)
1285     * @param account
1286     * @throws MessagingException
1287     */
1288    private void processPendingTrash(PendingCommand command, final EmailContent.Account account)
1289            throws MessagingException {
1290        String folder = command.arguments[0];
1291        String uid = command.arguments[1];
1292
1293        final LocalStore localStore = (LocalStore) Store.getInstance(
1294                account.getLocalStoreUri(mContext), mContext, null);
1295        LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
1296
1297        Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext,
1298                localStore.getPersistentCallbacks());
1299        Folder remoteFolder = remoteStore.getFolder(folder);
1300        if (!remoteFolder.exists()) {
1301            return;
1302        }
1303        remoteFolder.open(OpenMode.READ_WRITE, localFolder.getPersistentCallbacks());
1304        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1305            remoteFolder.close(false);
1306            return;
1307        }
1308
1309        Message remoteMessage = null;
1310        if (!uid.startsWith("Local")) {
1311            remoteMessage = remoteFolder.getMessage(uid);
1312        }
1313        if (remoteMessage == null) {
1314            remoteFolder.close(false);
1315            return;
1316        }
1317
1318        Folder remoteTrashFolder = remoteStore.getFolder(account.getTrashFolderName(mContext));
1319        /*
1320         * Attempt to copy the remote message to the remote trash folder.
1321         */
1322        if (!remoteTrashFolder.exists()) {
1323            /*
1324             * If the remote trash folder doesn't exist we try to create it.
1325             */
1326            remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
1327        }
1328
1329        if (remoteTrashFolder.exists()) {
1330            /*
1331             * Because remoteTrashFolder may be new, we need to explicitly open it
1332             * and pass in the persistence callbacks.
1333             */
1334            final LocalFolder localTrashFolder =
1335                (LocalFolder) localStore.getFolder(account.getTrashFolderName(mContext));
1336            remoteTrashFolder.open(OpenMode.READ_WRITE, localTrashFolder.getPersistentCallbacks());
1337            if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
1338                remoteFolder.close(false);
1339                remoteTrashFolder.close(false);
1340                return;
1341            }
1342
1343            remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
1344                    new Folder.MessageUpdateCallbacks() {
1345                public void onMessageUidChange(Message message, String newUid)
1346                        throws MessagingException {
1347                    // update the UID in the local trash folder, because some stores will
1348                    // have to change it when copying to remoteTrashFolder
1349                    LocalMessage localMessage =
1350                        (LocalMessage) localTrashFolder.getMessage(message.getUid());
1351                    if(localMessage != null) {
1352                        localMessage.setUid(newUid);
1353                        localTrashFolder.updateMessage(localMessage);
1354                    }
1355                }
1356
1357                /**
1358                 * This will be called if the deleted message doesn't exist and can't be
1359                 * deleted (e.g. it was already deleted from the server.)  In this case,
1360                 * attempt to delete the local copy as well.
1361                 */
1362                public void onMessageNotFound(Message message) throws MessagingException {
1363                    LocalMessage localMessage =
1364                        (LocalMessage) localTrashFolder.getMessage(message.getUid());
1365                    if (localMessage != null) {
1366                        localMessage.setFlag(Flag.DELETED, true);
1367                    }
1368                }
1369
1370            }
1371            );
1372            remoteTrashFolder.close(false);
1373        }
1374
1375        remoteMessage.setFlag(Flag.DELETED, true);
1376        remoteFolder.expunge();
1377        remoteFolder.close(false);
1378    }
1379
1380    /**
1381     * Processes a pending mark read or unread command.
1382     *
1383     * @param command arguments = (String folder, String uid, boolean read)
1384     * @param account
1385     */
1386    private void processPendingMarkRead(PendingCommand command, EmailContent.Account account)
1387            throws MessagingException {
1388        String folder = command.arguments[0];
1389        String uid = command.arguments[1];
1390        boolean read = Boolean.parseBoolean(command.arguments[2]);
1391
1392        LocalStore localStore = (LocalStore) Store.getInstance(
1393                account.getLocalStoreUri(mContext), mContext, null);
1394        LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
1395
1396        Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext,
1397                localStore.getPersistentCallbacks());
1398        Folder remoteFolder = remoteStore.getFolder(folder);
1399        if (!remoteFolder.exists()) {
1400            return;
1401        }
1402        remoteFolder.open(OpenMode.READ_WRITE, localFolder.getPersistentCallbacks());
1403        if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
1404            return;
1405        }
1406        Message remoteMessage = null;
1407        if (!uid.startsWith("Local")
1408                && !uid.contains("-")) {
1409            remoteMessage = remoteFolder.getMessage(uid);
1410        }
1411        if (remoteMessage == null) {
1412            return;
1413        }
1414        remoteMessage.setFlag(Flag.SEEN, read);
1415    }
1416
1417    /**
1418     * Mark the message with the given account, folder and uid either Seen or not Seen.
1419     * @param account
1420     * @param folder
1421     * @param uid
1422     * @param seen
1423     */
1424    public void markMessageRead(
1425            final EmailContent.Account account,
1426            final String folder,
1427            final String uid,
1428            final boolean seen) {
1429        try {
1430            Store localStore = Store.getInstance(account.getLocalStoreUri(mContext), mContext,
1431                    null);
1432            Folder localFolder = localStore.getFolder(folder);
1433            localFolder.open(OpenMode.READ_WRITE, null);
1434
1435            Message message = localFolder.getMessage(uid);
1436            message.setFlag(Flag.SEEN, seen);
1437            PendingCommand command = new PendingCommand();
1438            command.command = PENDING_COMMAND_MARK_READ;
1439            command.arguments = new String[] { folder, uid, Boolean.toString(seen) };
1440            queuePendingCommand(account, command);
1441            processPendingCommands(account);
1442        }
1443        catch (MessagingException me) {
1444            throw new RuntimeException(me);
1445        }
1446    }
1447
1448    private void loadMessageForViewRemote(final EmailContent.Account account, final String folder,
1449            final String uid, MessagingListener listener) {
1450        put("loadMessageForViewRemote", listener, new Runnable() {
1451            public void run() {
1452                try {
1453                    LocalStore localStore = (LocalStore) Store.getInstance(
1454                            account.getLocalStoreUri(mContext), mContext, null);
1455                    LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
1456                    localFolder.open(OpenMode.READ_WRITE, null);
1457
1458                    Message message = localFolder.getMessage(uid);
1459
1460                    if (message.isSet(Flag.X_DOWNLOADED_FULL)) {
1461                        /*
1462                         * If the message has been synchronized since we were called we'll
1463                         * just hand it back cause it's ready to go.
1464                         */
1465                        FetchProfile fp = new FetchProfile();
1466                        fp.add(FetchProfile.Item.ENVELOPE);
1467                        fp.add(FetchProfile.Item.BODY);
1468                        localFolder.fetch(new Message[] { message }, fp, null);
1469
1470                        mListeners.loadMessageForViewBodyAvailable(account, folder, uid, message);
1471                        mListeners.loadMessageForViewFinished(account, folder, uid, message);
1472                        localFolder.close(false);
1473                        return;
1474                    }
1475
1476                    /*
1477                     * At this point the message is not available, so we need to download it
1478                     * fully if possible.
1479                     */
1480
1481                    Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext,
1482                            localStore.getPersistentCallbacks());
1483                    Folder remoteFolder = remoteStore.getFolder(folder);
1484                    remoteFolder.open(OpenMode.READ_WRITE, localFolder.getPersistentCallbacks());
1485
1486                    // Get the remote message and fully download it (and save into local store)
1487
1488                    if (remoteStore.requireStructurePrefetch()) {
1489                        // For remote stores that require it, prefetch the message structure.
1490                        FetchProfile fp = new FetchProfile();
1491                        fp.add(FetchProfile.Item.STRUCTURE);
1492                        localFolder.fetch(new Message[] { message }, fp, null);
1493
1494                        ArrayList<Part> viewables = new ArrayList<Part>();
1495                        ArrayList<Part> attachments = new ArrayList<Part>();
1496                        MimeUtility.collectParts(message, viewables, attachments);
1497                        fp.clear();
1498                        for (Part part : viewables) {
1499                            fp.add(part);
1500                        }
1501
1502                        remoteFolder.fetch(new Message[] { message }, fp, null);
1503
1504                        // Store the updated message locally
1505                        localFolder.updateMessage((LocalMessage)message);
1506
1507                    } else {
1508                        // Most remote stores can directly obtain the message using only uid
1509                        Message remoteMessage = remoteFolder.getMessage(uid);
1510                        FetchProfile fp = new FetchProfile();
1511                        fp.add(FetchProfile.Item.BODY);
1512                        remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
1513
1514                        // Store the message locally
1515                        localFolder.appendMessages(new Message[] { remoteMessage });
1516                    }
1517
1518                    // Now obtain the local copy for further access & manipulation
1519                    message = localFolder.getMessage(uid);
1520                    FetchProfile fp = new FetchProfile();
1521                    fp.add(FetchProfile.Item.BODY);
1522                    localFolder.fetch(new Message[] { message }, fp, null);
1523
1524                    // This is a view message request, so mark it read
1525                    if (!message.isSet(Flag.SEEN)) {
1526                        markMessageRead(account, folder, uid, true);
1527                    }
1528
1529                    // Mark that this message is now fully synched
1530                    message.setFlag(Flag.X_DOWNLOADED_FULL, true);
1531
1532                    mListeners.loadMessageForViewBodyAvailable(account, folder, uid, message);
1533                    mListeners.loadMessageForViewFinished(account, folder, uid, message);
1534                    remoteFolder.close(false);
1535                    localFolder.close(false);
1536                }
1537                catch (Exception e) {
1538                    mListeners.loadMessageForViewFailed(account, folder, uid, e.getMessage());
1539                }
1540            }
1541        });
1542    }
1543
1544    public void loadMessageForView(final EmailContent.Account account, final String folder,
1545            final String uid, MessagingListener listener) {
1546        mListeners.loadMessageForViewStarted(account, folder, uid);
1547        try {
1548            Store localStore = Store.getInstance(account.getLocalStoreUri(mContext), mContext,
1549                    null);
1550            LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
1551            localFolder.open(OpenMode.READ_WRITE, null);
1552
1553            Message message = localFolder.getMessage(uid);
1554            mListeners.loadMessageForViewHeadersAvailable(account, folder, uid, message);
1555            if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
1556                loadMessageForViewRemote(account, folder, uid, listener);
1557                localFolder.close(false);
1558                return;
1559            }
1560
1561            if (!message.isSet(Flag.SEEN)) {
1562                markMessageRead(account, folder, uid, true);
1563            }
1564
1565            FetchProfile fp = new FetchProfile();
1566            fp.add(FetchProfile.Item.ENVELOPE);
1567            fp.add(FetchProfile.Item.BODY);
1568            localFolder.fetch(new Message[] {
1569                message
1570            }, fp, null);
1571
1572            mListeners.loadMessageForViewBodyAvailable(account, folder, uid, message);
1573            mListeners.loadMessageForViewFinished(account, folder, uid, message);
1574            localFolder.close(false);
1575        }
1576        catch (Exception e) {
1577            mListeners.loadMessageForViewFailed(account, folder, uid, e.getMessage());
1578        }
1579    }
1580
1581    /**
1582     * Attempts to load the attachment specified by id from the given account and message.
1583     * @param account
1584     * @param message
1585     * @param part
1586     * @param listener
1587     */
1588    public void loadAttachment(final long accountId, final long messageId, final long mailboxId,
1589            final long attachmentId, MessagingListener listener) {
1590        mListeners.loadAttachmentStarted(accountId, messageId, attachmentId, true);
1591
1592        put("loadAttachment", listener, new Runnable() {
1593            public void run() {
1594                try {
1595                    // 1.  Pruning.  Policy is to have one downloaded attachment at a time,
1596                    // per account, to reduce disk storage pressure.
1597                    pruneCachedAttachments(accountId);
1598
1599                    // 2. Open the remote folder.
1600                    // TODO all of these could be narrower projections
1601                    EmailContent.Account account =
1602                        EmailContent.Account.restoreAccountWithId(mContext, accountId);
1603                    EmailContent.Mailbox mailbox =
1604                        EmailContent.Mailbox.restoreMailboxWithId(mContext, mailboxId);
1605                    EmailContent.Message message =
1606                        EmailContent.Message.restoreMessageWithId(mContext, messageId);
1607                    Attachment attachment =
1608                        Attachment.restoreAttachmentWithId(mContext, attachmentId);
1609
1610                    Store remoteStore =
1611                        Store.getInstance(account.getStoreUri(mContext), mContext, null);
1612                    Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
1613                    remoteFolder.open(OpenMode.READ_WRITE, null);
1614
1615                    // 3. Generate a shell message in which to retrieve the attachment,
1616                    // and a shell BodyPart for the attachment.  Then glue them together.
1617                    Message storeMessage = remoteFolder.createMessage(message.mServerId);
1618                    BodyPart storePart = new MimeBodyPart();
1619                    storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA,
1620                            attachment.mLocation);
1621                    storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
1622                            String.format("%s;\n name=\"%s\"",
1623                            attachment.mMimeType,
1624                            attachment.mFileName));
1625                    // TODO is this always true for attachments?  I think we dropped the
1626                    // true encoding along the way
1627                    storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
1628
1629                    MimeMultipart multipart = new MimeMultipart();
1630                    multipart.setSubType("mixed");
1631                    multipart.addBodyPart(storePart);
1632
1633                    storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
1634                    storeMessage.setBody(multipart);
1635
1636                    // 4. Now ask for the attachment to be fetched
1637                    FetchProfile fp = new FetchProfile();
1638                    fp.add(storePart);
1639                    remoteFolder.fetch(new Message[] { storeMessage }, fp, null);
1640
1641                    // 5. Save the downloaded file and update the attachment as necessary
1642                    LegacyConversions.saveAttachmentBody(mContext, storePart, attachment,
1643                            accountId);
1644
1645                    // 6. Report success
1646                    mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
1647                }
1648                catch (MessagingException me) {
1649                    if (Email.LOGD) Log.v(Email.LOG_TAG, "", me);
1650                    mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
1651                            me.getMessage());
1652                } catch (IOException ioe) {
1653                    Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
1654                }
1655            }});
1656    }
1657
1658    /**
1659     * Erase all stored attachments for a given account.  Rules:
1660     *   1.  All files in attachment directory are up for deletion
1661     *   2.  If filename does not match an known attachment id, it's deleted
1662     *   3.  If the attachment has location data (implying that it's reloadable), it's deleted
1663     */
1664    /* package */ void pruneCachedAttachments(long accountId) {
1665        ContentResolver resolver = mContext.getContentResolver();
1666        File cacheDir = AttachmentProvider.getAttachmentDirectory(mContext, accountId);
1667        for (File file : cacheDir.listFiles()) {
1668            if (file.exists()) {
1669                long id;
1670                try {
1671                    // the name of the file == the attachment id
1672                    id = Long.valueOf(file.getName());
1673                    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, id);
1674                    Cursor c = resolver.query(uri, PRUNE_ATTACHMENT_PROJECTION, null, null, null);
1675                    try {
1676                        if (c.moveToNext()) {
1677                            // if there is no way to reload the attachment, don't delete it
1678                            if (c.getString(0) == null) {
1679                                continue;
1680                            }
1681                        }
1682                    } finally {
1683                        c.close();
1684                    }
1685                    // Clear the content URI field since we're losing the attachment
1686                    resolver.update(uri, PRUNE_ATTACHMENT_CV, null, null);
1687                } catch (NumberFormatException nfe) {
1688                    // ignore filename != number error, and just delete it anyway
1689                }
1690                // This file can be safely deleted
1691                if (!file.delete()) {
1692                    file.deleteOnExit();
1693                }
1694            }
1695        }
1696    }
1697
1698    /**
1699     * Attempt to send any messages that are sitting in the Outbox.
1700     * @param account
1701     * @param listener
1702     */
1703    public void sendPendingMessages(final EmailContent.Account account, final long sentFolderId,
1704            MessagingListener listener) {
1705        put("sendPendingMessages", listener, new Runnable() {
1706            public void run() {
1707                sendPendingMessagesSynchronous(account, sentFolderId);
1708            }
1709        });
1710    }
1711
1712    /**
1713     * Attempt to send any messages that are sitting in the Outbox.
1714     *
1715     * @param account
1716     * @param listener
1717     */
1718    public void sendPendingMessagesSynchronous(final EmailContent.Account account,
1719            long sentFolderId) {
1720        // 1.  Loop through all messages in the account's outbox
1721        long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
1722        if (outboxId == Mailbox.NO_MAILBOX) {
1723            return;
1724        }
1725        ContentResolver resolver = mContext.getContentResolver();
1726        Cursor c = resolver.query(EmailContent.Message.CONTENT_URI,
1727                EmailContent.Message.ID_COLUMN_PROJECTION,
1728                EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) },
1729                null);
1730        try {
1731            // 2.  exit early
1732            if (c.getCount() <= 0) {
1733                return;
1734            }
1735            // 3. do one-time setup of the Sender & other stuff
1736            Sender sender = Sender.getInstance(mContext, account.getSenderUri(mContext));
1737            Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
1738            boolean requireMoveMessageToSentFolder = remoteStore.requireCopyMessageToSentFolder();
1739            ContentValues moveToSentValues = null;
1740            if (requireMoveMessageToSentFolder) {
1741                moveToSentValues = new ContentValues();
1742                moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolderId);
1743            }
1744
1745            // 4.  loop through the available messages and send them
1746            while (c.moveToNext()) {
1747                long messageId = -1;
1748                try {
1749                    messageId = c.getLong(0);
1750                    mListeners.sendPendingMessagesStarted(account.mId, messageId);
1751                    sender.sendMessage(messageId);
1752                } catch (MessagingException me) {
1753                    // report error for this message, but keep trying others
1754                    mListeners.sendPendingMessagesFailed(account.mId, messageId, me);
1755                    continue;
1756                }
1757                // 5. move to sent, or delete
1758                Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId);
1759                if (requireMoveMessageToSentFolder) {
1760                    resolver.update(uri, moveToSentValues, null, null);
1761                    // TODO: post for a pending upload
1762                } else {
1763                    AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, messageId);
1764                    resolver.delete(uri, null, null);
1765                }
1766            }
1767            // 6. report completion/success
1768            mListeners.sendPendingMessagesCompleted(account.mId);
1769
1770        } catch (MessagingException me) {
1771            mListeners.sendPendingMessagesFailed(account.mId, -1, me);
1772        } finally {
1773            c.close();
1774        }
1775    }
1776
1777    /**
1778     * We do the local portion of this synchronously because other activities may have to make
1779     * updates based on what happens here
1780     * @param account
1781     * @param folder
1782     * @param message
1783     * @param listener
1784     */
1785    public void deleteMessage(final EmailContent.Account account, final String folder,
1786            final Message message, MessagingListener listener) {
1787        if (folder.equals(account.getTrashFolderName(mContext))) {
1788            return;
1789        }
1790        try {
1791            Store localStore = Store.getInstance(account.getLocalStoreUri(mContext), mContext,
1792                    null);
1793            Folder localFolder = localStore.getFolder(folder);
1794            Folder localTrashFolder = localStore.getFolder(account.getTrashFolderName(mContext));
1795
1796            localFolder.copyMessages(new Message[] { message }, localTrashFolder, null);
1797            message.setFlag(Flag.DELETED, true);
1798
1799            if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) {
1800                PendingCommand command = new PendingCommand();
1801                command.command = PENDING_COMMAND_TRASH;
1802                command.arguments = new String[] { folder, message.getUid() };
1803                queuePendingCommand(account, command);
1804                processPendingCommands(account);
1805            }
1806        }
1807        catch (MessagingException me) {
1808            throw new RuntimeException("Error deleting message from local store.", me);
1809        }
1810    }
1811
1812    public void emptyTrash(final EmailContent.Account account, MessagingListener listener) {
1813        put("emptyTrash", listener, new Runnable() {
1814            public void run() {
1815                // TODO IMAP
1816                try {
1817                    Store localStore = Store.getInstance(
1818                            account.getLocalStoreUri(mContext), mContext, null);
1819                    Folder localFolder = localStore.getFolder(account.getTrashFolderName(mContext));
1820                    localFolder.open(OpenMode.READ_WRITE, null);
1821                    Message[] messages = localFolder.getMessages(null);
1822                    localFolder.setFlags(messages, new Flag[] {
1823                        Flag.DELETED
1824                    }, true);
1825                    localFolder.close(true);
1826                    mListeners.emptyTrashCompleted(account);
1827                }
1828                catch (Exception e) {
1829                    // TODO
1830                    if (Email.LOGD) {
1831                        Log.v(Email.LOG_TAG, "emptyTrash");
1832                    }
1833                }
1834            }
1835        });
1836    }
1837
1838    /**
1839     * Checks mail for one or multiple accounts. If account is null all accounts
1840     * are checked.  This entry point is for use by the mail checking service only, because it
1841     * gives slightly different callbacks (so the service doesn't get confused by callbacks
1842     * triggered by/for the foreground UI.
1843     *
1844     * TODO clean up the execution model which is unnecessarily threaded due to legacy code
1845     *
1846     * @param context
1847     * @param accountId the account to check
1848     * @param listener
1849     */
1850    public void checkMail(final long accountId, final long tag, final MessagingListener listener) {
1851        mListeners.checkMailStarted(mContext, accountId, tag);
1852
1853        // This puts the command on the queue (not synchronous)
1854        listFolders(accountId, null);
1855
1856        // Put this on the queue as well so it follows listFolders
1857        put("checkMail", listener, new Runnable() {
1858            public void run() {
1859                // send any pending outbound messages.  note, there is a slight race condition
1860                // here if we somehow don't have a sent folder, but this should never happen
1861                // because the call to sendMessage() would have built one previously.
1862                EmailContent.Account account =
1863                    EmailContent.Account.restoreAccountWithId(mContext, accountId);
1864                long sentboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_SENT);
1865                if (sentboxId != -1) {
1866                    sendPendingMessagesSynchronous(account, sentboxId);
1867                }
1868                // find mailbox # for inbox and sync it.
1869                // TODO we already know this in Controller, can we pass it in?
1870                long inboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX);
1871                EmailContent.Mailbox mailbox =
1872                    EmailContent.Mailbox.restoreMailboxWithId(mContext, inboxId);
1873                synchronizeMailboxSynchronous(account, mailbox);
1874
1875                mListeners.checkMailFinished(mContext, accountId, tag, inboxId);
1876            }
1877        });
1878    }
1879
1880    public void saveDraft(final EmailContent.Account account, final Message message) {
1881        try {
1882            Store localStore = Store.getInstance(account.getLocalStoreUri(mContext), mContext,
1883                    null);
1884            LocalFolder localFolder =
1885                (LocalFolder) localStore.getFolder(account.getDraftsFolderName(mContext));
1886            localFolder.open(OpenMode.READ_WRITE, null);
1887            localFolder.appendMessages(new Message[] {
1888                message
1889            });
1890            Message localMessage = localFolder.getMessage(message.getUid());
1891            localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
1892
1893            PendingCommand command = new PendingCommand();
1894            command.command = PENDING_COMMAND_APPEND;
1895            command.arguments = new String[] {
1896                    localFolder.getName(),
1897                    localMessage.getUid() };
1898            queuePendingCommand(account, command);
1899            processPendingCommands(account);
1900        }
1901        catch (MessagingException e) {
1902            Log.e(Email.LOG_TAG, "Unable to save message as draft.", e);
1903        }
1904    }
1905
1906    private static class Command {
1907        public Runnable runnable;
1908
1909        public MessagingListener listener;
1910
1911        public String description;
1912
1913        @Override
1914        public String toString() {
1915            return description;
1916        }
1917    }
1918}
1919