1/*
2 * Copyright (C) 2010 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.service;
18
19import android.app.Service;
20import android.content.AbstractThreadedSyncAdapter;
21import android.content.ContentProviderClient;
22import android.content.ContentResolver;
23import android.content.ContentUris;
24import android.content.ContentValues;
25import android.content.Context;
26import android.content.Intent;
27import android.content.SyncResult;
28import android.database.Cursor;
29import android.net.Uri;
30import android.os.Bundle;
31import android.os.IBinder;
32
33import com.android.email.R;
34import com.android.emailcommon.TempDirectory;
35import com.android.emailcommon.mail.MessagingException;
36import com.android.emailcommon.provider.Account;
37import com.android.emailcommon.provider.EmailContent;
38import com.android.emailcommon.provider.EmailContent.AccountColumns;
39import com.android.emailcommon.provider.EmailContent.Message;
40import com.android.emailcommon.provider.EmailContent.MessageColumns;
41import com.android.emailcommon.provider.Mailbox;
42import com.android.emailcommon.service.EmailServiceProxy;
43import com.android.emailcommon.service.EmailServiceStatus;
44import com.android.mail.providers.UIProvider;
45import com.android.mail.utils.LogUtils;
46
47import java.util.ArrayList;
48
49public class PopImapSyncAdapterService extends Service {
50    private static final String TAG = "PopImapSyncService";
51    private SyncAdapterImpl mSyncAdapter = null;
52
53    public PopImapSyncAdapterService() {
54        super();
55    }
56
57    private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
58        public SyncAdapterImpl(Context context) {
59            super(context, true /* autoInitialize */);
60        }
61
62        @Override
63        public void onPerformSync(android.accounts.Account account, Bundle extras,
64                String authority, ContentProviderClient provider, SyncResult syncResult) {
65            PopImapSyncAdapterService.performSync(getContext(), account, extras, provider,
66                    syncResult);
67        }
68    }
69
70    @Override
71    public void onCreate() {
72        super.onCreate();
73        mSyncAdapter = new SyncAdapterImpl(getApplicationContext());
74    }
75
76    @Override
77    public IBinder onBind(Intent intent) {
78        return mSyncAdapter.getSyncAdapterBinder();
79    }
80
81    /**
82     * @return whether or not this mailbox retrieves its data from the server (as opposed to just
83     *     a local mailbox that is never synced).
84     */
85    private static boolean loadsFromServer(Context context, Mailbox m, String protocol) {
86        String legacyImapProtocol = context.getString(R.string.protocol_legacy_imap);
87        String pop3Protocol = context.getString(R.string.protocol_pop3);
88        if (legacyImapProtocol.equals(protocol)) {
89            // TODO: actually use a sync flag when creating the mailboxes. Right now we use an
90            // approximation for IMAP.
91            return m.mType != Mailbox.TYPE_DRAFTS
92                    && m.mType != Mailbox.TYPE_OUTBOX
93                    && m.mType != Mailbox.TYPE_SEARCH;
94
95        } else if (pop3Protocol.equals(protocol)) {
96            return Mailbox.TYPE_INBOX == m.mType;
97        }
98
99        return false;
100    }
101
102    private static void sync(final Context context, final long mailboxId,
103            final Bundle extras, final SyncResult syncResult, final boolean uiRefresh,
104            final int deltaMessageCount) {
105        TempDirectory.setTempDirectory(context);
106        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
107        if (mailbox == null) return;
108        Account account = Account.restoreAccountWithId(context, mailbox.mAccountKey);
109        if (account == null) return;
110        ContentResolver resolver = context.getContentResolver();
111        String protocol = account.getProtocol(context);
112        if ((mailbox.mType != Mailbox.TYPE_OUTBOX) &&
113                !loadsFromServer(context, mailbox, protocol)) {
114            // This is an update to a message in a non-syncing mailbox; delete this from the
115            // updates table and return
116            resolver.delete(Message.UPDATED_CONTENT_URI, MessageColumns.MAILBOX_KEY + "=?",
117                    new String[] {Long.toString(mailbox.mId)});
118            return;
119        }
120        LogUtils.d(TAG, "About to sync mailbox: " + mailbox.mDisplayName);
121
122        Uri mailboxUri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
123        ContentValues values = new ContentValues();
124        // Set mailbox sync state
125        values.put(Mailbox.UI_SYNC_STATUS,
126                uiRefresh ? EmailContent.SYNC_STATUS_USER : EmailContent.SYNC_STATUS_BACKGROUND);
127        resolver.update(mailboxUri, values, null, null);
128        try {
129            try {
130                String legacyImapProtocol = context.getString(R.string.protocol_legacy_imap);
131                if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
132                    EmailServiceStub.sendMailImpl(context, account.mId);
133                } else {
134                    EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId,
135                            EmailServiceStatus.IN_PROGRESS, 0, UIProvider.LastSyncResult.SUCCESS);
136                    final int status;
137                    if (protocol.equals(legacyImapProtocol)) {
138                        status = ImapService.synchronizeMailboxSynchronous(context, account,
139                                mailbox, deltaMessageCount != 0, uiRefresh);
140                    } else {
141                        status = Pop3Service.synchronizeMailboxSynchronous(context, account,
142                                mailbox, deltaMessageCount);
143                    }
144                    EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId, status, 0,
145                            UIProvider.LastSyncResult.SUCCESS);
146                }
147            } catch (MessagingException e) {
148                final int type = e.getExceptionType();
149                // type must be translated into the domain of values used by EmailServiceStatus
150                switch(type) {
151                    case MessagingException.IOERROR:
152                        EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId, type, 0,
153                                UIProvider.LastSyncResult.CONNECTION_ERROR);
154                        syncResult.stats.numIoExceptions++;
155                        break;
156                    case MessagingException.AUTHENTICATION_FAILED:
157                        EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId, type, 0,
158                                UIProvider.LastSyncResult.AUTH_ERROR);
159                        syncResult.stats.numAuthExceptions++;
160                        break;
161                    case MessagingException.SERVER_ERROR:
162                        EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId, type, 0,
163                                UIProvider.LastSyncResult.SERVER_ERROR);
164                        break;
165
166                    default:
167                        EmailServiceStatus.syncMailboxStatus(resolver, extras, mailboxId, type, 0,
168                                UIProvider.LastSyncResult.INTERNAL_ERROR);
169                }
170            }
171        } finally {
172            // Always clear our sync state and update sync time.
173            values.put(Mailbox.UI_SYNC_STATUS, EmailContent.SYNC_STATUS_NONE);
174            values.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
175            resolver.update(mailboxUri, values, null, null);
176        }
177    }
178
179    /**
180     * Partial integration with system SyncManager; we initiate manual syncs upon request
181     */
182    private static void performSync(Context context, android.accounts.Account account,
183            Bundle extras, ContentProviderClient provider, SyncResult syncResult) {
184        // Find an EmailProvider account with the Account's email address
185        Cursor c = null;
186        try {
187            c = provider.query(com.android.emailcommon.provider.Account.CONTENT_URI,
188                    Account.CONTENT_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
189                    new String[] {account.name}, null);
190            if (c != null && c.moveToNext()) {
191                Account acct = new Account();
192                acct.restore(c);
193                if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) {
194                    LogUtils.d(TAG, "Upload sync request for " + acct.mDisplayName);
195                    // See if any boxes have mail...
196                    ArrayList<Long> mailboxesToUpdate;
197                    Cursor updatesCursor = provider.query(Message.UPDATED_CONTENT_URI,
198                            new String[] {MessageColumns.MAILBOX_KEY},
199                            MessageColumns.ACCOUNT_KEY + "=?",
200                            new String[] {Long.toString(acct.mId)},
201                            null);
202                    try {
203                        if ((updatesCursor == null) || (updatesCursor.getCount() == 0)) return;
204                        mailboxesToUpdate = new ArrayList<Long>();
205                        while (updatesCursor.moveToNext()) {
206                            Long mailboxId = updatesCursor.getLong(0);
207                            if (!mailboxesToUpdate.contains(mailboxId)) {
208                                mailboxesToUpdate.add(mailboxId);
209                            }
210                        }
211                    } finally {
212                        if (updatesCursor != null) {
213                            updatesCursor.close();
214                        }
215                    }
216                    for (long mailboxId: mailboxesToUpdate) {
217                        sync(context, mailboxId, extras, syncResult, false, 0);
218                    }
219                } else {
220                    LogUtils.d(TAG, "Sync request for " + acct.mDisplayName);
221                    LogUtils.d(TAG, extras.toString());
222
223                    // We update our folder structure on every sync.
224                    final EmailServiceProxy service =
225                            EmailServiceUtils.getServiceForAccount(context, acct.mId);
226                    service.updateFolderList(acct.mId);
227
228                    // Get the id for the mailbox we want to sync.
229                    long [] mailboxIds = Mailbox.getMailboxIdsFromBundle(extras);
230                    if (mailboxIds == null || mailboxIds.length == 0) {
231                        // No mailbox specified, just sync the inbox.
232                        // TODO: IMAP may eventually want to allow multiple auto-sync mailboxes.
233                        final long inboxId = Mailbox.findMailboxOfType(context, acct.mId,
234                                Mailbox.TYPE_INBOX);
235                        if (inboxId != Mailbox.NO_MAILBOX) {
236                            mailboxIds = new long[1];
237                            mailboxIds[0] = inboxId;
238                        }
239                    }
240
241                    if (mailboxIds != null) {
242                        boolean uiRefresh =
243                            extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
244                        int deltaMessageCount =
245                                extras.getInt(Mailbox.SYNC_EXTRA_DELTA_MESSAGE_COUNT, 0);
246                        for (long mailboxId : mailboxIds) {
247                            sync(context, mailboxId, extras, syncResult, uiRefresh,
248                                    deltaMessageCount);
249                        }
250                    }
251                }
252            }
253        } catch (Exception e) {
254            e.printStackTrace();
255        } finally {
256            if (c != null) {
257                c.close();
258            }
259        }
260    }
261}
262