1/* Copyright (C) 2012 The Android Open Source Project
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package com.android.email.service;
17
18import android.content.ContentResolver;
19import android.content.ContentUris;
20import android.content.ContentValues;
21import android.content.Context;
22import android.database.Cursor;
23import android.net.TrafficStats;
24import android.net.Uri;
25import android.os.Bundle;
26import android.os.RemoteException;
27import android.text.TextUtils;
28
29import com.android.email.NotificationController;
30import com.android.email.mail.Sender;
31import com.android.email.mail.Store;
32import com.android.email.provider.AccountReconciler;
33import com.android.email.provider.Utilities;
34import com.android.email.service.EmailServiceUtils.EmailServiceInfo;
35import com.android.email2.ui.MailActivityEmail;
36import com.android.emailcommon.Api;
37import com.android.emailcommon.Logging;
38import com.android.emailcommon.TrafficFlags;
39import com.android.emailcommon.internet.MimeBodyPart;
40import com.android.emailcommon.internet.MimeHeader;
41import com.android.emailcommon.internet.MimeMultipart;
42import com.android.emailcommon.mail.AuthenticationFailedException;
43import com.android.emailcommon.mail.FetchProfile;
44import com.android.emailcommon.mail.Folder;
45import com.android.emailcommon.mail.Folder.MessageRetrievalListener;
46import com.android.emailcommon.mail.Folder.OpenMode;
47import com.android.emailcommon.mail.Message;
48import com.android.emailcommon.mail.MessagingException;
49import com.android.emailcommon.provider.Account;
50import com.android.emailcommon.provider.EmailContent;
51import com.android.emailcommon.provider.EmailContent.Attachment;
52import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
53import com.android.emailcommon.provider.EmailContent.Body;
54import com.android.emailcommon.provider.EmailContent.BodyColumns;
55import com.android.emailcommon.provider.EmailContent.MailboxColumns;
56import com.android.emailcommon.provider.EmailContent.MessageColumns;
57import com.android.emailcommon.provider.HostAuth;
58import com.android.emailcommon.provider.Mailbox;
59import com.android.emailcommon.service.EmailServiceStatus;
60import com.android.emailcommon.service.IEmailService;
61import com.android.emailcommon.service.IEmailServiceCallback;
62import com.android.emailcommon.service.SearchParams;
63import com.android.emailcommon.utility.AttachmentUtilities;
64import com.android.emailcommon.utility.Utility;
65import com.android.mail.providers.UIProvider;
66import com.android.mail.providers.UIProvider.DraftType;
67import com.android.mail.utils.LogUtils;
68
69import java.util.HashSet;
70
71/**
72 * EmailServiceStub is an abstract class representing an EmailService
73 *
74 * This class provides legacy support for a few methods that are common to both
75 * IMAP and POP3, including startSync, loadMore, loadAttachment, and sendMail
76 */
77public abstract class EmailServiceStub extends IEmailService.Stub implements IEmailService {
78
79    private static final int MAILBOX_COLUMN_ID = 0;
80    private static final int MAILBOX_COLUMN_SERVER_ID = 1;
81    private static final int MAILBOX_COLUMN_TYPE = 2;
82
83    /** Small projection for just the columns required for a sync. */
84    private static final String[] MAILBOX_PROJECTION = new String[] {
85        MailboxColumns.ID,
86        MailboxColumns.SERVER_ID,
87        MailboxColumns.TYPE,
88    };
89
90    protected Context mContext;
91
92    protected void init(Context context) {
93        mContext = context;
94    }
95
96    @Override
97    public Bundle validate(HostAuth hostauth) throws RemoteException {
98        // TODO Auto-generated method stub
99        return null;
100    }
101
102    @Deprecated
103    @Override
104    public void startSync(long mailboxId, boolean userRequest, int deltaMessageCount)
105            throws RemoteException {
106        final Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
107        if (mailbox == null) return;
108        final Account account = Account.restoreAccountWithId(mContext, mailbox.mAccountKey);
109        if (account == null) return;
110        final EmailServiceInfo info =
111                EmailServiceUtils.getServiceInfoForAccount(mContext, account.mId);
112        final android.accounts.Account acct = new android.accounts.Account(account.mEmailAddress,
113                info.accountType);
114        final Bundle extras = Mailbox.createSyncBundle(mailboxId);
115        if (userRequest) {
116            extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
117            extras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
118            extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
119        }
120        if (deltaMessageCount != 0) {
121            extras.putInt(Mailbox.SYNC_EXTRA_DELTA_MESSAGE_COUNT, deltaMessageCount);
122        }
123        ContentResolver.requestSync(acct, EmailContent.AUTHORITY, extras);
124        LogUtils.i(Logging.LOG_TAG, "requestSync EmailServiceStub startSync %s, %s",
125                account.toString(), extras.toString());
126    }
127
128    @Override
129    public void stopSync(long mailboxId) throws RemoteException {
130        // Not required
131    }
132
133    @Override
134    public void loadMore(long messageId) throws RemoteException {
135        // Load a message for view...
136        try {
137            // 1. Resample the message, in case it disappeared or synced while
138            // this command was in queue
139            final EmailContent.Message message =
140                EmailContent.Message.restoreMessageWithId(mContext, messageId);
141            if (message == null) {
142                return;
143            }
144            if (message.mFlagLoaded == EmailContent.Message.FLAG_LOADED_COMPLETE) {
145                // We should NEVER get here
146                return;
147            }
148
149            // 2. Open the remote folder.
150            // TODO combine with common code in loadAttachment
151            final Account account = Account.restoreAccountWithId(mContext, message.mAccountKey);
152            final Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
153            if (account == null || mailbox == null) {
154                //mListeners.loadMessageForViewFailed(messageId, "null account or mailbox");
155                return;
156            }
157            TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(mContext, account));
158
159            final Store remoteStore = Store.getInstance(account, mContext);
160            final String remoteServerId;
161            // If this is a search result, use the protocolSearchInfo field to get the
162            // correct remote location
163            if (!TextUtils.isEmpty(message.mProtocolSearchInfo)) {
164                remoteServerId = message.mProtocolSearchInfo;
165            } else {
166                remoteServerId = mailbox.mServerId;
167            }
168            final Folder remoteFolder = remoteStore.getFolder(remoteServerId);
169            remoteFolder.open(OpenMode.READ_WRITE);
170
171            // 3. Set up to download the entire message
172            final Message remoteMessage = remoteFolder.getMessage(message.mServerId);
173            final FetchProfile fp = new FetchProfile();
174            fp.add(FetchProfile.Item.BODY);
175            remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
176
177            // 4. Write to provider
178            Utilities.copyOneMessageToProvider(mContext, remoteMessage, account, mailbox,
179                    EmailContent.Message.FLAG_LOADED_COMPLETE);
180        } catch (MessagingException me) {
181            if (Logging.LOGD) LogUtils.v(Logging.LOG_TAG, "", me);
182
183        } catch (RuntimeException rte) {
184            LogUtils.d(Logging.LOG_TAG, "RTE During loadMore");
185        }
186    }
187
188    @Override
189    public void loadAttachment(final IEmailServiceCallback cb, final long attachmentId,
190            final boolean background) throws RemoteException {
191        Folder remoteFolder = null;
192        try {
193            //1. Check if the attachment is already here and return early in that case
194            Attachment attachment =
195                Attachment.restoreAttachmentWithId(mContext, attachmentId);
196            if (attachment == null) {
197                cb.loadAttachmentStatus(0, attachmentId,
198                        EmailServiceStatus.ATTACHMENT_NOT_FOUND, 0);
199                return;
200            }
201            final long messageId = attachment.mMessageKey;
202
203            final EmailContent.Message message =
204                    EmailContent.Message.restoreMessageWithId(mContext, attachment.mMessageKey);
205            if (message == null) {
206                cb.loadAttachmentStatus(messageId, attachmentId,
207                        EmailServiceStatus.MESSAGE_NOT_FOUND, 0);
208                return;
209            }
210
211            // If the message is loaded, just report that we're finished
212            if (Utility.attachmentExists(mContext, attachment)
213                    && attachment.mUiState == UIProvider.AttachmentState.SAVED) {
214                cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.SUCCESS,
215                        0);
216                return;
217            }
218
219            // Say we're starting...
220            cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.IN_PROGRESS, 0);
221
222            // 2. Open the remote folder.
223            final Account account = Account.restoreAccountWithId(mContext, message.mAccountKey);
224            Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
225
226            if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
227                long sourceId = Utility.getFirstRowLong(mContext, Body.CONTENT_URI,
228                        new String[] {BodyColumns.SOURCE_MESSAGE_KEY},
229                        BodyColumns.MESSAGE_KEY + "=?",
230                        new String[] {Long.toString(messageId)}, null, 0, -1L);
231                if (sourceId != -1 ) {
232                    EmailContent.Message sourceMsg =
233                            EmailContent.Message.restoreMessageWithId(mContext, sourceId);
234                    if (sourceMsg != null) {
235                        mailbox = Mailbox.restoreMailboxWithId(mContext, sourceMsg.mMailboxKey);
236                        message.mServerId = sourceMsg.mServerId;
237                    }
238                }
239            }
240
241            if (account == null || mailbox == null) {
242                // If the account/mailbox are gone, just report success; the UI handles this
243                cb.loadAttachmentStatus(messageId, attachmentId,
244                        EmailServiceStatus.SUCCESS, 0);
245                return;
246            }
247            TrafficStats.setThreadStatsTag(
248                    TrafficFlags.getAttachmentFlags(mContext, account));
249
250            final Store remoteStore = Store.getInstance(account, mContext);
251            remoteFolder = remoteStore.getFolder(mailbox.mServerId);
252            remoteFolder.open(OpenMode.READ_WRITE);
253
254            // 3. Generate a shell message in which to retrieve the attachment,
255            // and a shell BodyPart for the attachment.  Then glue them together.
256            final Message storeMessage = remoteFolder.createMessage(message.mServerId);
257            final MimeBodyPart storePart = new MimeBodyPart();
258            storePart.setSize((int)attachment.mSize);
259            storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA,
260                    attachment.mLocation);
261            storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
262                    String.format("%s;\n name=\"%s\"",
263                    attachment.mMimeType,
264                    attachment.mFileName));
265            // TODO is this always true for attachments?  I think we dropped the
266            // true encoding along the way
267            storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
268
269            final MimeMultipart multipart = new MimeMultipart();
270            multipart.setSubType("mixed");
271            multipart.addBodyPart(storePart);
272
273            storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
274            storeMessage.setBody(multipart);
275
276            // 4. Now ask for the attachment to be fetched
277            final FetchProfile fp = new FetchProfile();
278            fp.add(storePart);
279            remoteFolder.fetch(new Message[] { storeMessage }, fp,
280                    new MessageRetrievalListenerBridge(messageId, attachmentId, cb));
281
282            // If we failed to load the attachment, throw an Exception here, so that
283            // AttachmentDownloadService knows that we failed
284            if (storePart.getBody() == null) {
285                throw new MessagingException("Attachment not loaded.");
286            }
287
288            // Save the attachment to wherever it's going
289            AttachmentUtilities.saveAttachment(mContext, storePart.getBody().getInputStream(),
290                    attachment);
291
292            // 6. Report success
293            cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.SUCCESS, 0);
294
295        } catch (MessagingException me) {
296            LogUtils.i(Logging.LOG_TAG, me, "Error loading attachment");
297
298            final ContentValues cv = new ContentValues(1);
299            cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
300            final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId);
301            mContext.getContentResolver().update(uri, cv, null, null);
302
303            cb.loadAttachmentStatus(0, attachmentId, EmailServiceStatus.CONNECTION_ERROR, 0);
304        } finally {
305            if (remoteFolder != null) {
306                remoteFolder.close(false);
307            }
308        }
309
310    }
311
312    /**
313     * Bridge to intercept {@link MessageRetrievalListener#loadAttachmentProgress} and
314     * pass down to {@link IEmailServiceCallback}.
315     */
316    public class MessageRetrievalListenerBridge implements MessageRetrievalListener {
317        private final long mMessageId;
318        private final long mAttachmentId;
319        private final IEmailServiceCallback mCallback;
320
321
322        public MessageRetrievalListenerBridge(final long messageId, final long attachmentId,
323                final IEmailServiceCallback callback) {
324            mMessageId = messageId;
325            mAttachmentId = attachmentId;
326            mCallback = callback;
327        }
328
329        @Override
330        public void loadAttachmentProgress(int progress) {
331            try {
332                mCallback.loadAttachmentStatus(mMessageId, mAttachmentId,
333                        EmailServiceStatus.IN_PROGRESS, progress);
334            } catch (final RemoteException e) {
335                // No danger if the client is no longer around
336            }
337        }
338
339        @Override
340        public void messageRetrieved(com.android.emailcommon.mail.Message message) {
341        }
342    }
343
344    @Override
345    public void updateFolderList(long accountId) throws RemoteException {
346        final Account account = Account.restoreAccountWithId(mContext, accountId);
347        if (account == null) return;
348        long inboxId = -1;
349        TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(mContext, account));
350        Cursor localFolderCursor = null;
351        try {
352            // Step 0: Make sure the default system mailboxes exist.
353            for (final int type : Mailbox.REQUIRED_FOLDER_TYPES) {
354                if (Mailbox.findMailboxOfType(mContext, accountId, type) == Mailbox.NO_MAILBOX) {
355                    final Mailbox mailbox = Mailbox.newSystemMailbox(mContext, accountId, type);
356                    mailbox.save(mContext);
357                    if (type == Mailbox.TYPE_INBOX) {
358                        inboxId = mailbox.mId;
359                    }
360                }
361            }
362
363            // Step 1: Get remote mailboxes
364            final Store store = Store.getInstance(account, mContext);
365            final Folder[] remoteFolders = store.updateFolders();
366            final HashSet<String> remoteFolderNames = new HashSet<String>();
367            for (final Folder remoteFolder : remoteFolders) {
368                remoteFolderNames.add(remoteFolder.getName());
369            }
370
371            // Step 2: Get local mailboxes
372            localFolderCursor = mContext.getContentResolver().query(
373                    Mailbox.CONTENT_URI,
374                    MAILBOX_PROJECTION,
375                    EmailContent.MailboxColumns.ACCOUNT_KEY + "=?",
376                    new String[] { String.valueOf(account.mId) },
377                    null);
378
379            // Step 3: Remove any local mailbox not on the remote list
380            while (localFolderCursor.moveToNext()) {
381                final String mailboxPath = localFolderCursor.getString(MAILBOX_COLUMN_SERVER_ID);
382                // Short circuit if we have a remote mailbox with the same name
383                if (remoteFolderNames.contains(mailboxPath)) {
384                    continue;
385                }
386
387                final int mailboxType = localFolderCursor.getInt(MAILBOX_COLUMN_TYPE);
388                final long mailboxId = localFolderCursor.getLong(MAILBOX_COLUMN_ID);
389                switch (mailboxType) {
390                    case Mailbox.TYPE_INBOX:
391                    case Mailbox.TYPE_DRAFTS:
392                    case Mailbox.TYPE_OUTBOX:
393                    case Mailbox.TYPE_SENT:
394                    case Mailbox.TYPE_TRASH:
395                    case Mailbox.TYPE_SEARCH:
396                        // Never, ever delete special mailboxes
397                        break;
398                    default:
399                        // Drop all attachment files related to this mailbox
400                        AttachmentUtilities.deleteAllMailboxAttachmentFiles(
401                                mContext, accountId, mailboxId);
402                        // Delete the mailbox; database triggers take care of related
403                        // Message, Body and Attachment records
404                        Uri uri = ContentUris.withAppendedId(
405                                Mailbox.CONTENT_URI, mailboxId);
406                        mContext.getContentResolver().delete(uri, null, null);
407                        break;
408                }
409            }
410        } catch (MessagingException me) {
411            LogUtils.i(Logging.LOG_TAG, me, "Error in updateFolderList");
412            // We'll hope this is temporary
413        } finally {
414            if (localFolderCursor != null) {
415                localFolderCursor.close();
416            }
417            // If we just created the inbox, sync it
418            if (inboxId != -1) {
419                startSync(inboxId, true, 0);
420            }
421        }
422    }
423
424    @Override
425    public boolean createFolder(long accountId, String name) throws RemoteException {
426        // Not required
427        return false;
428    }
429
430    @Override
431    public boolean deleteFolder(long accountId, String name) throws RemoteException {
432        // Not required
433        return false;
434    }
435
436    @Override
437    public boolean renameFolder(long accountId, String oldName, String newName)
438            throws RemoteException {
439        // Not required
440        return false;
441    }
442
443    @Override
444    public void setLogging(int on) throws RemoteException {
445        // Not required
446    }
447
448    @Override
449    public void hostChanged(long accountId) throws RemoteException {
450        // Not required
451    }
452
453    @Override
454    public Bundle autoDiscover(String userName, String password) throws RemoteException {
455        // Not required
456       return null;
457    }
458
459    @Override
460    public void sendMeetingResponse(long messageId, int response) throws RemoteException {
461        // Not required
462    }
463
464    @Override
465    public void deleteAccountPIMData(final String emailAddress) throws RemoteException {
466        AccountReconciler.reconcileAccounts(mContext);
467    }
468
469    @Override
470    public int getApiLevel() throws RemoteException {
471        return Api.LEVEL;
472    }
473
474    @Override
475    public int searchMessages(long accountId, SearchParams params, long destMailboxId)
476            throws RemoteException {
477        // Not required
478        return 0;
479    }
480
481    @Override
482    public void sendMail(long accountId) throws RemoteException {
483        sendMailImpl(mContext, accountId);
484    }
485
486    public static void sendMailImpl(Context context, long accountId) {
487        final Account account = Account.restoreAccountWithId(context, accountId);
488        TrafficStats.setThreadStatsTag(TrafficFlags.getSmtpFlags(context, account));
489        final NotificationController nc = NotificationController.getInstance(context);
490        // 1.  Loop through all messages in the account's outbox
491        final long outboxId = Mailbox.findMailboxOfType(context, account.mId, Mailbox.TYPE_OUTBOX);
492        if (outboxId == Mailbox.NO_MAILBOX) {
493            return;
494        }
495        final ContentResolver resolver = context.getContentResolver();
496        final Cursor c = resolver.query(EmailContent.Message.CONTENT_URI,
497                EmailContent.Message.ID_COLUMN_PROJECTION,
498                EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) },
499                null);
500        try {
501            // 2.  exit early
502            if (c.getCount() <= 0) {
503                return;
504            }
505            final Sender sender = Sender.getInstance(context, account);
506            final Store remoteStore = Store.getInstance(account, context);
507            final ContentValues moveToSentValues;
508            if (remoteStore.requireCopyMessageToSentFolder()) {
509                Mailbox sentFolder =
510                    Mailbox.restoreMailboxOfType(context, accountId, Mailbox.TYPE_SENT);
511                moveToSentValues = new ContentValues();
512                moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolder.mId);
513            } else {
514                moveToSentValues = null;
515            }
516
517            // 3.  loop through the available messages and send them
518            while (c.moveToNext()) {
519                final long messageId;
520                if (moveToSentValues != null) {
521                    moveToSentValues.remove(EmailContent.MessageColumns.FLAGS);
522                }
523                try {
524                    messageId = c.getLong(0);
525                    // Don't send messages with unloaded attachments
526                    if (Utility.hasUnloadedAttachments(context, messageId)) {
527                        if (MailActivityEmail.DEBUG) {
528                            LogUtils.d(Logging.LOG_TAG, "Can't send #" + messageId +
529                                    "; unloaded attachments");
530                        }
531                        continue;
532                    }
533                    sender.sendMessage(messageId);
534                } catch (MessagingException me) {
535                    // report error for this message, but keep trying others
536                    if (me instanceof AuthenticationFailedException) {
537                        nc.showLoginFailedNotification(account.mId);
538                    }
539                    continue;
540                }
541                // 4. move to sent, or delete
542                final Uri syncedUri =
543                    ContentUris.withAppendedId(EmailContent.Message.SYNCED_CONTENT_URI, messageId);
544                // Delete all cached files
545                AttachmentUtilities.deleteAllCachedAttachmentFiles(context, account.mId, messageId);
546                if (moveToSentValues != null) {
547                    // If this is a forwarded message and it has attachments, delete them, as they
548                    // duplicate information found elsewhere (on the server).  This saves storage.
549                    final EmailContent.Message msg =
550                        EmailContent.Message.restoreMessageWithId(context, messageId);
551                    if ((msg.mFlags & EmailContent.Message.FLAG_TYPE_FORWARD) != 0) {
552                        AttachmentUtilities.deleteAllAttachmentFiles(context, account.mId,
553                                messageId);
554                    }
555                    final int flags = msg.mFlags & ~(EmailContent.Message.FLAG_TYPE_REPLY |
556                            EmailContent.Message.FLAG_TYPE_FORWARD |
557                            EmailContent.Message.FLAG_TYPE_REPLY_ALL |
558                            EmailContent.Message.FLAG_TYPE_ORIGINAL);
559
560                    moveToSentValues.put(EmailContent.MessageColumns.FLAGS, flags);
561                    resolver.update(syncedUri, moveToSentValues, null, null);
562                } else {
563                    AttachmentUtilities.deleteAllAttachmentFiles(context, account.mId,
564                            messageId);
565                    final Uri uri =
566                        ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId);
567                    resolver.delete(uri, null, null);
568                    resolver.delete(syncedUri, null, null);
569                }
570            }
571            nc.cancelLoginFailedNotification(account.mId);
572        } catch (MessagingException me) {
573            if (me instanceof AuthenticationFailedException) {
574                nc.showLoginFailedNotification(account.mId);
575            }
576        } finally {
577            c.close();
578        }
579
580    }
581}
582