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