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