LegacyConversions.java revision fab77f147f85766d2f75d8aece0aaa4ffb3838e8
1/* 2 * Copyright (C) 2009 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.Address; 20import com.android.email.mail.Body; 21import com.android.email.mail.Flag; 22import com.android.email.mail.Folder; 23import com.android.email.mail.Message; 24import com.android.email.mail.MessagingException; 25import com.android.email.mail.Part; 26import com.android.email.mail.Message.RecipientType; 27import com.android.email.mail.internet.MimeBodyPart; 28import com.android.email.mail.internet.MimeHeader; 29import com.android.email.mail.internet.MimeMessage; 30import com.android.email.mail.internet.MimeMultipart; 31import com.android.email.mail.internet.MimeUtility; 32import com.android.email.mail.internet.TextBody; 33import com.android.email.mail.store.LocalStore; 34import com.android.email.provider.AttachmentProvider; 35import com.android.email.provider.EmailContent; 36import com.android.email.provider.EmailContent.Attachment; 37import com.android.email.provider.EmailContent.AttachmentColumns; 38import com.android.email.provider.EmailContent.Mailbox; 39 40import org.apache.commons.io.IOUtils; 41 42import android.content.ContentUris; 43import android.content.ContentValues; 44import android.content.Context; 45import android.database.Cursor; 46import android.net.Uri; 47import android.provider.OpenableColumns; 48import android.text.TextUtils; 49import android.util.Log; 50 51import java.io.File; 52import java.io.FileOutputStream; 53import java.io.IOException; 54import java.io.InputStream; 55import java.util.ArrayList; 56import java.util.Date; 57import java.util.HashMap; 58 59public class LegacyConversions { 60 61 /** DO NOT CHECK IN "TRUE" */ 62 private static final boolean DEBUG_ATTACHMENTS = false; 63 64 /** Used for mapping folder names to type codes (e.g. inbox, drafts, trash) */ 65 private static final HashMap<String, Integer> 66 sServerMailboxNames = new HashMap<String, Integer>(); 67 68 /** 69 * Values for HEADER_ANDROID_BODY_QUOTED_PART to tag body parts 70 */ 71 /* package */ static final String BODY_QUOTED_PART_REPLY = "quoted-reply"; 72 /* package */ static final String BODY_QUOTED_PART_FORWARD = "quoted-forward"; 73 /* package */ static final String BODY_QUOTED_PART_INTRO = "quoted-intro"; 74 75 /** 76 * Standard columns for querying content providers 77 */ 78 private static final String[] ATTACHMENT_META_COLUMNS_PROJECTION = { 79 OpenableColumns.DISPLAY_NAME, 80 OpenableColumns.SIZE 81 }; 82 private static final int ATTACHMENT_META_COLUMNS_SIZE = 1; 83 84 /** 85 * Copy field-by-field from a "store" message to a "provider" message 86 * @param message The message we've just downloaded (must be a MimeMessage) 87 * @param localMessage The message we'd like to write into the DB 88 * @result true if dirty (changes were made) 89 */ 90 public static boolean updateMessageFields(EmailContent.Message localMessage, Message message, 91 long accountId, long mailboxId) throws MessagingException { 92 93 Address[] from = message.getFrom(); 94 Address[] to = message.getRecipients(Message.RecipientType.TO); 95 Address[] cc = message.getRecipients(Message.RecipientType.CC); 96 Address[] bcc = message.getRecipients(Message.RecipientType.BCC); 97 Address[] replyTo = message.getReplyTo(); 98 String subject = message.getSubject(); 99 Date sentDate = message.getSentDate(); 100 Date internalDate = message.getInternalDate(); 101 102 if (from != null && from.length > 0) { 103 localMessage.mDisplayName = from[0].toFriendly(); 104 } 105 if (sentDate != null) { 106 localMessage.mTimeStamp = sentDate.getTime(); 107 } 108 if (subject != null) { 109 localMessage.mSubject = subject; 110 } 111 localMessage.mFlagRead = message.isSet(Flag.SEEN); 112 113 // Keep the message in the "unloaded" state until it has (at least) a display name. 114 // This prevents early flickering of empty messages in POP download. 115 if (localMessage.mFlagLoaded != EmailContent.Message.FLAG_LOADED_COMPLETE) { 116 if (localMessage.mDisplayName == null || "".equals(localMessage.mDisplayName)) { 117 localMessage.mFlagLoaded = EmailContent.Message.FLAG_LOADED_UNLOADED; 118 } else { 119 localMessage.mFlagLoaded = EmailContent.Message.FLAG_LOADED_PARTIAL; 120 } 121 } 122 localMessage.mFlagFavorite = message.isSet(Flag.FLAGGED); 123// public boolean mFlagAttachment = false; 124// public int mFlags = 0; 125 126 localMessage.mServerId = message.getUid(); 127 if (internalDate != null) { 128 localMessage.mServerTimeStamp = internalDate.getTime(); 129 } 130// public String mClientId; 131 132 // Only replace the local message-id if a new one was found. This is seen in some ISP's 133 // which may deliver messages w/o a message-id header. 134 String messageId = ((MimeMessage)message).getMessageId(); 135 if (messageId != null) { 136 localMessage.mMessageId = messageId; 137 } 138 139// public long mBodyKey; 140 localMessage.mMailboxKey = mailboxId; 141 localMessage.mAccountKey = accountId; 142 143 if (from != null && from.length > 0) { 144 localMessage.mFrom = Address.pack(from); 145 } 146 147 localMessage.mTo = Address.pack(to); 148 localMessage.mCc = Address.pack(cc); 149 localMessage.mBcc = Address.pack(bcc); 150 localMessage.mReplyTo = Address.pack(replyTo); 151 152// public String mText; 153// public String mHtml; 154// public String mTextReply; 155// public String mHtmlReply; 156 157// // Can be used while building messages, but is NOT saved by the Provider 158// transient public ArrayList<Attachment> mAttachments = null; 159 160 return true; 161 } 162 163 /** 164 * Copy body text (plain and/or HTML) from MimeMessage to provider Message 165 */ 166 public static boolean updateBodyFields(EmailContent.Body body, 167 EmailContent.Message localMessage, ArrayList<Part> viewables) 168 throws MessagingException { 169 170 body.mMessageKey = localMessage.mId; 171 172 StringBuffer sbHtml = null; 173 StringBuffer sbText = null; 174 StringBuffer sbHtmlReply = null; 175 StringBuffer sbTextReply = null; 176 StringBuffer sbIntroText = null; 177 178 for (Part viewable : viewables) { 179 String text = MimeUtility.getTextFromPart(viewable); 180 String[] replyTags = viewable.getHeader(MimeHeader.HEADER_ANDROID_BODY_QUOTED_PART); 181 String replyTag = null; 182 if (replyTags != null && replyTags.length > 0) { 183 replyTag = replyTags[0]; 184 } 185 // Deploy text as marked by the various tags 186 boolean isHtml = "text/html".equalsIgnoreCase(viewable.getMimeType()); 187 188 if (replyTag != null) { 189 boolean isQuotedReply = BODY_QUOTED_PART_REPLY.equalsIgnoreCase(replyTag); 190 boolean isQuotedForward = BODY_QUOTED_PART_FORWARD.equalsIgnoreCase(replyTag); 191 boolean isQuotedIntro = BODY_QUOTED_PART_INTRO.equalsIgnoreCase(replyTag); 192 193 if (isQuotedReply || isQuotedForward) { 194 if (isHtml) { 195 sbHtmlReply = appendTextPart(sbHtmlReply, text); 196 } else { 197 sbTextReply = appendTextPart(sbTextReply, text); 198 } 199 // Set message flags as well 200 localMessage.mFlags &= ~EmailContent.Message.FLAG_TYPE_MASK; 201 localMessage.mFlags |= isQuotedReply 202 ? EmailContent.Message.FLAG_TYPE_REPLY 203 : EmailContent.Message.FLAG_TYPE_FORWARD; 204 continue; 205 } 206 if (isQuotedIntro) { 207 sbIntroText = appendTextPart(sbIntroText, text); 208 continue; 209 } 210 } 211 212 // Most of the time, just process regular body parts 213 if (isHtml) { 214 sbHtml = appendTextPart(sbHtml, text); 215 } else { 216 sbText = appendTextPart(sbText, text); 217 } 218 } 219 220 // write the combined data to the body part 221 if (!TextUtils.isEmpty(sbText)) { 222 String text = sbText.toString(); 223 body.mTextContent = text; 224 localMessage.mSnippet = Snippet.fromPlainText(text); 225 } 226 if (!TextUtils.isEmpty(sbHtml)) { 227 String text = sbHtml.toString(); 228 body.mHtmlContent = text; 229 if (localMessage.mSnippet == null) { 230 localMessage.mSnippet = Snippet.fromHtmlText(text); 231 } 232 } 233 if (sbHtmlReply != null && sbHtmlReply.length() != 0) { 234 body.mHtmlReply = sbHtmlReply.toString(); 235 } 236 if (sbTextReply != null && sbTextReply.length() != 0) { 237 body.mTextReply = sbTextReply.toString(); 238 } 239 if (sbIntroText != null && sbIntroText.length() != 0) { 240 body.mIntroText = sbIntroText.toString(); 241 } 242 return true; 243 } 244 245 /** 246 * Helper function to append text to a StringBuffer, creating it if necessary. 247 * Optimization: The majority of the time we are *not* appending - we should have a path 248 * that deals with single strings. 249 */ 250 private static StringBuffer appendTextPart(StringBuffer sb, String newText) { 251 if (newText == null) { 252 return sb; 253 } 254 else if (sb == null) { 255 sb = new StringBuffer(newText); 256 } else { 257 if (sb.length() > 0) { 258 sb.append('\n'); 259 } 260 sb.append(newText); 261 } 262 return sb; 263 } 264 265 /** 266 * Copy attachments from MimeMessage to provider Message. 267 * 268 * @param context a context for file operations 269 * @param localMessage the attachments will be built against this message 270 * @param attachments the attachments to add 271 * @param upgrading if true, we are upgrading a local account - handle attachments differently 272 * @throws IOException 273 */ 274 public static void updateAttachments(Context context, EmailContent.Message localMessage, 275 ArrayList<Part> attachments, boolean upgrading) throws MessagingException, IOException { 276 localMessage.mAttachments = null; 277 for (Part attachmentPart : attachments) { 278 addOneAttachment(context, localMessage, attachmentPart, upgrading); 279 } 280 } 281 282 /** 283 * Add a single attachment part to the message 284 * 285 * This will skip adding attachments if they are already found in the attachments table. 286 * The heuristic for this will fail (false-positive) if two identical attachments are 287 * included in a single POP3 message. 288 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments 289 * position within the list of multipart/mixed elements. This would make every POP3 attachment 290 * unique, and might also simplify the code (since we could just look at the positions, and 291 * ignore the filename, etc.) 292 * 293 * TODO: Take a closer look at encoding and deal with it if necessary. 294 * 295 * @param context a context for file operations 296 * @param localMessage the attachments will be built against this message 297 * @param part a single attachment part from POP or IMAP 298 * @param upgrading true if upgrading a local account - handle attachments differently 299 * @throws IOException 300 */ 301 private static void addOneAttachment(Context context, EmailContent.Message localMessage, 302 Part part, boolean upgrading) throws MessagingException, IOException { 303 304 Attachment localAttachment = new Attachment(); 305 306 // Transfer fields from mime format to provider format 307 String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); 308 String name = MimeUtility.getHeaderParameter(contentType, "name"); 309 if (name == null) { 310 String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); 311 name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); 312 } 313 314 // Select the URI for the new attachments. For attachments downloaded by the legacy 315 // IMAP/POP code, this is not determined yet, so is null (it will be rewritten below, 316 // or later, when the actual attachment file is created.) 317 // 318 // When upgrading older local accounts, the URI represents a local asset (e.g. a photo) 319 // so we need to preserve the URI. 320 // TODO This works for outgoing messages, where the URI does not change. May need 321 // additional logic to handle the case of rewriting URI for received attachments. 322 Uri contentUri = null; 323 String contentUriString = null; 324 if (upgrading) { 325 Body body = part.getBody(); 326 if (body instanceof LocalStore.LocalAttachmentBody) { 327 LocalStore.LocalAttachmentBody localBody = (LocalStore.LocalAttachmentBody) body; 328 contentUri = localBody.getContentUri(); 329 if (contentUri != null) { 330 contentUriString = contentUri.toString(); 331 } 332 } 333 } 334 335 // Find size, if available, via a number of techniques: 336 long size = 0; 337 if (upgrading) { 338 // If upgrading a legacy account, the size must be recaptured from the data source 339 if (contentUri != null) { 340 Cursor metadataCursor = context.getContentResolver().query(contentUri, 341 ATTACHMENT_META_COLUMNS_PROJECTION, null, null, null); 342 if (metadataCursor != null) { 343 try { 344 if (metadataCursor.moveToFirst()) { 345 size = metadataCursor.getInt(ATTACHMENT_META_COLUMNS_SIZE); 346 } 347 } finally { 348 metadataCursor.close(); 349 } 350 } 351 } 352 // TODO: a downloaded legacy attachment - see if the above code works 353 } else { 354 // Incoming attachment: Try to pull size from disposition (if not downloaded yet) 355 String disposition = part.getDisposition(); 356 if (disposition != null) { 357 String s = MimeUtility.getHeaderParameter(disposition, "size"); 358 if (s != null) { 359 size = Long.parseLong(s); 360 } 361 } 362 } 363 364 // Get partId for unloaded IMAP attachments (if any) 365 // This is only provided (and used) when we have structure but not the actual attachment 366 String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA); 367 String partId = partIds != null ? partIds[0] : null; 368 369 localAttachment.mFileName = name; 370 localAttachment.mMimeType = part.getMimeType(); 371 localAttachment.mSize = size; // May be reset below if file handled 372 localAttachment.mContentId = part.getContentId(); 373 localAttachment.mContentUri = contentUriString; 374 localAttachment.mMessageKey = localMessage.mId; 375 localAttachment.mLocation = partId; 376 localAttachment.mEncoding = "B"; // TODO - convert other known encodings 377 378 if (DEBUG_ATTACHMENTS) { 379 Log.d(Email.LOG_TAG, "Add attachment " + localAttachment); 380 } 381 382 // To prevent duplication - do we already have a matching attachment? 383 // The fields we'll check for equality are: 384 // mFileName, mMimeType, mContentId, mMessageKey, mLocation 385 // NOTE: This will false-positive if you attach the exact same file, twice, to a POP3 386 // message. We can live with that - you'll get one of the copies. 387 Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId); 388 Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, 389 null, null, null); 390 boolean attachmentFoundInDb = false; 391 try { 392 while (cursor.moveToNext()) { 393 Attachment dbAttachment = new Attachment().restore(cursor); 394 // We test each of the fields here (instead of in SQL) because they may be 395 // null, or may be strings. 396 if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName)) continue; 397 if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType)) continue; 398 if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId)) continue; 399 if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation)) continue; 400 // We found a match, so use the existing attachment id, and stop looking/looping 401 attachmentFoundInDb = true; 402 localAttachment.mId = dbAttachment.mId; 403 if (DEBUG_ATTACHMENTS) { 404 Log.d(Email.LOG_TAG, "Skipped, found db attachment " + dbAttachment); 405 } 406 break; 407 } 408 } finally { 409 cursor.close(); 410 } 411 412 // Save the attachment (so far) in order to obtain an id 413 if (!attachmentFoundInDb) { 414 localAttachment.save(context); 415 } 416 417 // If an attachment body was actually provided, we need to write the file now 418 if (!upgrading) { 419 saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey); 420 } 421 422 if (localMessage.mAttachments == null) { 423 localMessage.mAttachments = new ArrayList<Attachment>(); 424 } 425 localMessage.mAttachments.add(localAttachment); 426 localMessage.mFlagAttachment = true; 427 } 428 429 /** 430 * Helper for addOneAttachment that compares two strings, deals with nulls, and treats 431 * nulls and empty strings as equal. 432 */ 433 /* package */ static boolean stringNotEqual(String a, String b) { 434 if (a == null && b == null) return false; // fast exit for two null strings 435 if (a == null) a = ""; 436 if (b == null) b = ""; 437 return !a.equals(b); 438 } 439 440 /** 441 * Save the body part of a single attachment, to a file in the attachments directory. 442 */ 443 public static void saveAttachmentBody(Context context, Part part, Attachment localAttachment, 444 long accountId) throws MessagingException, IOException { 445 if (part.getBody() != null) { 446 long attachmentId = localAttachment.mId; 447 448 InputStream in = part.getBody().getInputStream(); 449 450 File saveIn = AttachmentProvider.getAttachmentDirectory(context, accountId); 451 if (!saveIn.exists()) { 452 saveIn.mkdirs(); 453 } 454 File saveAs = AttachmentProvider.getAttachmentFilename(context, accountId, 455 attachmentId); 456 saveAs.createNewFile(); 457 FileOutputStream out = new FileOutputStream(saveAs); 458 long copySize = IOUtils.copy(in, out); 459 in.close(); 460 out.close(); 461 462 // update the attachment with the extra information we now know 463 String contentUriString = AttachmentProvider.getAttachmentUri( 464 accountId, attachmentId).toString(); 465 466 localAttachment.mSize = copySize; 467 localAttachment.mContentUri = contentUriString; 468 469 // update the attachment in the database as well 470 ContentValues cv = new ContentValues(); 471 cv.put(AttachmentColumns.SIZE, copySize); 472 cv.put(AttachmentColumns.CONTENT_URI, contentUriString); 473 Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId); 474 context.getContentResolver().update(uri, cv, null, null); 475 } 476 } 477 478 /** 479 * Read a complete Provider message into a legacy message (for IMAP upload). This 480 * is basically the equivalent of LocalFolder.getMessages() + LocalFolder.fetch(). 481 */ 482 public static Message makeMessage(Context context, EmailContent.Message localMessage) 483 throws MessagingException { 484 MimeMessage message = new MimeMessage(); 485 486 // LocalFolder.getMessages() equivalent: Copy message fields 487 message.setSubject(localMessage.mSubject == null ? "" : localMessage.mSubject); 488 Address[] from = Address.unpack(localMessage.mFrom); 489 if (from.length > 0) { 490 message.setFrom(from[0]); 491 } 492 message.setSentDate(new Date(localMessage.mTimeStamp)); 493 message.setUid(localMessage.mServerId); 494 message.setFlag(Flag.DELETED, 495 localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_DELETED); 496 message.setFlag(Flag.SEEN, localMessage.mFlagRead); 497 message.setFlag(Flag.FLAGGED, localMessage.mFlagFavorite); 498// message.setFlag(Flag.DRAFT, localMessage.mMailboxKey == draftMailboxKey); 499 message.setRecipients(RecipientType.TO, Address.unpack(localMessage.mTo)); 500 message.setRecipients(RecipientType.CC, Address.unpack(localMessage.mCc)); 501 message.setRecipients(RecipientType.BCC, Address.unpack(localMessage.mBcc)); 502 message.setReplyTo(Address.unpack(localMessage.mReplyTo)); 503 message.setInternalDate(new Date(localMessage.mServerTimeStamp)); 504 message.setMessageId(localMessage.mMessageId); 505 506 // LocalFolder.fetch() equivalent: build body parts 507 message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed"); 508 MimeMultipart mp = new MimeMultipart(); 509 mp.setSubType("mixed"); 510 message.setBody(mp); 511 512 try { 513 addTextBodyPart(mp, "text/html", null, 514 EmailContent.Body.restoreBodyHtmlWithMessageId(context, localMessage.mId)); 515 } catch (RuntimeException rte) { 516 Log.d(Email.LOG_TAG, "Exception while reading html body " + rte.toString()); 517 } 518 519 try { 520 addTextBodyPart(mp, "text/plain", null, 521 EmailContent.Body.restoreBodyTextWithMessageId(context, localMessage.mId)); 522 } catch (RuntimeException rte) { 523 Log.d(Email.LOG_TAG, "Exception while reading text body " + rte.toString()); 524 } 525 526 boolean isReply = (localMessage.mFlags & EmailContent.Message.FLAG_TYPE_REPLY) != 0; 527 boolean isForward = (localMessage.mFlags & EmailContent.Message.FLAG_TYPE_FORWARD) != 0; 528 529 // If there is a quoted part (forwarding or reply), add the intro first, and then the 530 // rest of it. If it is opened in some other viewer, it will (hopefully) be displayed in 531 // the same order as we've just set up the blocks: composed text, intro, replied text 532 if (isReply || isForward) { 533 try { 534 addTextBodyPart(mp, "text/plain", BODY_QUOTED_PART_INTRO, 535 EmailContent.Body.restoreIntroTextWithMessageId(context, localMessage.mId)); 536 } catch (RuntimeException rte) { 537 Log.d(Email.LOG_TAG, "Exception while reading text reply " + rte.toString()); 538 } 539 540 String replyTag = isReply ? BODY_QUOTED_PART_REPLY : BODY_QUOTED_PART_FORWARD; 541 try { 542 addTextBodyPart(mp, "text/html", replyTag, 543 EmailContent.Body.restoreReplyHtmlWithMessageId(context, localMessage.mId)); 544 } catch (RuntimeException rte) { 545 Log.d(Email.LOG_TAG, "Exception while reading html reply " + rte.toString()); 546 } 547 548 try { 549 addTextBodyPart(mp, "text/plain", replyTag, 550 EmailContent.Body.restoreReplyTextWithMessageId(context, localMessage.mId)); 551 } catch (RuntimeException rte) { 552 Log.d(Email.LOG_TAG, "Exception while reading text reply " + rte.toString()); 553 } 554 } 555 556 // Attachments 557 // TODO: Make sure we deal with these as structures and don't accidentally upload files 558// Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId); 559// Cursor attachments = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, 560// null, null, null); 561// try { 562// 563// } finally { 564// attachments.close(); 565// } 566 567 return message; 568 } 569 570 /** 571 * Helper method to add a body part for a given type of text, if found 572 * 573 * @param mp The text body part will be added to this multipart 574 * @param contentType The content-type of the text being added 575 * @param quotedPartTag If non-null, HEADER_ANDROID_BODY_QUOTED_PART will be set to this value 576 * @param partText The text to add. If null, nothing happens 577 */ 578 private static void addTextBodyPart(MimeMultipart mp, String contentType, String quotedPartTag, 579 String partText) throws MessagingException { 580 if (partText == null) { 581 return; 582 } 583 TextBody body = new TextBody(partText); 584 MimeBodyPart bp = new MimeBodyPart(body, contentType); 585 if (quotedPartTag != null) { 586 bp.addHeader(MimeHeader.HEADER_ANDROID_BODY_QUOTED_PART, quotedPartTag); 587 } 588 mp.addBodyPart(bp); 589 } 590 591 /** 592 * Conversion from provider account to legacy account 593 * 594 * Used for backup/restore. 595 * 596 * @param context application context 597 * @param fromAccount the provider account to be backed up (including transient hostauth's) 598 * @return a legacy Account object ready to be committed to preferences 599 */ 600 /* package */ static Account makeLegacyAccount(Context context, 601 EmailContent.Account fromAccount) { 602 Account result = new Account(context); 603 604 result.setDescription(fromAccount.getDisplayName()); 605 result.setEmail(fromAccount.getEmailAddress()); 606 // fromAccount.mSyncKey - assume lost if restoring 607 result.setSyncWindow(fromAccount.getSyncLookback()); 608 result.setAutomaticCheckIntervalMinutes(fromAccount.getSyncInterval()); 609 // fromAccount.mHostAuthKeyRecv - id not saved; will be reassigned when restoring 610 // fromAccount.mHostAuthKeySend - id not saved; will be reassigned when restoring 611 612 // Provider Account flags, and how they are mapped. 613 // FLAGS_NOTIFY_NEW_MAIL -> mNotifyNewMail 614 // FLAGS_VIBRATE_ALWAYS -> mVibrate 615 // FLAGS_VIBRATE_WHEN_SILENT -> mVibrateWhenSilent 616 // DELETE_POLICY_NEVER -> mDeletePolicy 617 // DELETE_POLICY_7DAYS 618 // DELETE_POLICY_ON_DELETE 619 result.setNotifyNewMail(0 != 620 (fromAccount.getFlags() & EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL)); 621 result.setVibrate(0 != 622 (fromAccount.getFlags() & EmailContent.Account.FLAGS_VIBRATE_ALWAYS)); 623 result.setVibrateWhenSilent(0 != 624 (fromAccount.getFlags() & EmailContent.Account.FLAGS_VIBRATE_WHEN_SILENT)); 625 result.setDeletePolicy(fromAccount.getDeletePolicy()); 626 627 result.mUuid = fromAccount.getUuid(); 628 result.setName(fromAccount.mSenderName); 629 result.setRingtone(fromAccount.mRingtoneUri); 630 result.mProtocolVersion = fromAccount.mProtocolVersion; 631 // int fromAccount.mNewMessageCount = will be reset on next sync 632 result.mSecurityFlags = fromAccount.mSecurityFlags; 633 result.mSignature = fromAccount.mSignature; 634 635 // Use the existing conversions from HostAuth <-> Uri 636 result.setStoreUri(fromAccount.getStoreUri(context)); 637 result.setSenderUri(fromAccount.getSenderUri(context)); 638 639 return result; 640 } 641 642 /** 643 * Conversion from legacy account to provider account 644 * 645 * Used for backup/restore and for account migration. 646 * 647 * @param context application context 648 * @param fromAccount the legacy account to convert to modern format 649 * @return an Account ready to be committed to provider 650 */ 651 public static EmailContent.Account makeAccount(Context context, Account fromAccount) { 652 653 EmailContent.Account result = new EmailContent.Account(); 654 655 result.setDisplayName(fromAccount.getDescription()); 656 result.setEmailAddress(fromAccount.getEmail()); 657 result.mSyncKey = null; 658 result.setSyncLookback(fromAccount.getSyncWindow()); 659 result.setSyncInterval(fromAccount.getAutomaticCheckIntervalMinutes()); 660 // result.mHostAuthKeyRecv; -- will be set when object is saved 661 // result.mHostAuthKeySend; -- will be set when object is saved 662 int flags = 0; 663 if (fromAccount.isNotifyNewMail()) flags |= EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL; 664 if (fromAccount.isVibrate()) flags |= EmailContent.Account.FLAGS_VIBRATE_ALWAYS; 665 if (fromAccount.isVibrateWhenSilent()) 666 flags |= EmailContent.Account.FLAGS_VIBRATE_WHEN_SILENT; 667 result.setFlags(flags); 668 result.setDeletePolicy(fromAccount.getDeletePolicy()); 669 // result.setDefaultAccount(); -- will be set by caller, if neededf 670 result.mCompatibilityUuid = fromAccount.getUuid(); 671 result.setSenderName(fromAccount.getName()); 672 result.setRingtone(fromAccount.getRingtone()); 673 result.mProtocolVersion = fromAccount.mProtocolVersion; 674 result.mNewMessageCount = 0; 675 result.mSecurityFlags = fromAccount.mSecurityFlags; 676 result.mSecuritySyncKey = null; 677 result.mSignature = fromAccount.mSignature; 678 679 result.setStoreUri(context, fromAccount.getStoreUri()); 680 result.setSenderUri(context, fromAccount.getSenderUri()); 681 682 return result; 683 } 684 685 /** 686 * Conversion from legacy folder to provider mailbox. Used for account migration. 687 * Note: Many mailbox fields are unused in IMAP & POP accounts. 688 * 689 * @param context application context 690 * @param toAccount the provider account that this folder will be associated with 691 * @param fromFolder the legacy folder to convert to modern format 692 * @return an Account ready to be committed to provider 693 */ 694 public static EmailContent.Mailbox makeMailbox(Context context, EmailContent.Account toAccount, 695 Folder fromFolder) throws MessagingException { 696 EmailContent.Mailbox result = new EmailContent.Mailbox(); 697 698 result.mDisplayName = fromFolder.getName(); 699 // result.mServerId 700 // result.mParentServerId 701 result.mAccountKey = toAccount.mId; 702 result.mType = inferMailboxTypeFromName(context, fromFolder.getName()); 703 // result.mDelimiter 704 // result.mSyncKey 705 // result.mSyncLookback 706 // result.mSyncInterval 707 result.mSyncTime = 0; 708 result.mFlagVisible = true; 709 result.mFlags = 0; 710 result.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT; 711 // result.mSyncStatus 712 713 return result; 714 } 715 716 /** 717 * Infer mailbox type from mailbox name. Used by MessagingController (for live folder sync) 718 * and for legacy account upgrades. 719 */ 720 public static synchronized int inferMailboxTypeFromName(Context context, String mailboxName) { 721 if (sServerMailboxNames.size() == 0) { 722 // preload the hashmap, one time only 723 sServerMailboxNames.put( 724 context.getString(R.string.mailbox_name_server_inbox).toLowerCase(), 725 Mailbox.TYPE_INBOX); 726 sServerMailboxNames.put( 727 context.getString(R.string.mailbox_name_server_outbox).toLowerCase(), 728 Mailbox.TYPE_OUTBOX); 729 sServerMailboxNames.put( 730 context.getString(R.string.mailbox_name_server_drafts).toLowerCase(), 731 Mailbox.TYPE_DRAFTS); 732 sServerMailboxNames.put( 733 context.getString(R.string.mailbox_name_server_trash).toLowerCase(), 734 Mailbox.TYPE_TRASH); 735 sServerMailboxNames.put( 736 context.getString(R.string.mailbox_name_server_sent).toLowerCase(), 737 Mailbox.TYPE_SENT); 738 sServerMailboxNames.put( 739 context.getString(R.string.mailbox_name_server_junk).toLowerCase(), 740 Mailbox.TYPE_JUNK); 741 } 742 if (mailboxName == null || mailboxName.length() == 0) { 743 return EmailContent.Mailbox.TYPE_MAIL; 744 } 745 String lowerCaseName = mailboxName.toLowerCase(); 746 Integer type = sServerMailboxNames.get(lowerCaseName); 747 if (type != null) { 748 return type; 749 } 750 return EmailContent.Mailbox.TYPE_MAIL; 751 } 752} 753