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