/**
   * Parse a message from the server stream.
   *
   * @return the parsed Message
   * @throws IOException
   */
  private EmailContent.Message addParser(final int endingTag)
      throws IOException, CommandStatusException {
    EmailContent.Message msg = new EmailContent.Message();
    msg.mAccountKey = mAccount.mId;
    msg.mMailboxKey = mMailbox.mId;
    msg.mFlagLoaded = EmailContent.Message.FLAG_LOADED_COMPLETE;
    // Default to 1 (success) in case we don't get this tag
    int status = 1;

    while (nextTag(endingTag) != END) {
      switch (tag) {
        case Tags.SYNC_SERVER_ID:
          msg.mServerId = getValue();
          LogUtils.d(TAG, "ServerId: %s", msg.mServerId);
          break;
        case Tags.SYNC_STATUS:
          status = getValueInt();
          break;
        case Tags.SYNC_APPLICATION_DATA:
          addData(msg, tag);
          break;
        default:
          skipTag();
      }
    }
    // For sync, status 1 = success
    if (status != 1) {
      throw new CommandStatusException(status, msg.mServerId);
    }
    return msg;
  }
예제 #2
0
  @Override
  public void loadAttachment(
      final IEmailServiceCallback cb, final long attachmentId, final boolean background)
      throws RemoteException {
    /// M: We Can't load attachment in low storage state @{
    if (StorageLowState.checkIfStorageLow(mContext)) {
      LogUtils.e(Logging.LOG_TAG, "Can't load attachment due to low storage");
      cb.loadAttachmentStatus(0, attachmentId, EmailServiceStatus.SUCCESS, 0);
      return;
    }
    /// @}
    Folder remoteFolder = null;
    try {
      // 1. Check if the attachment is already here and return early in that case
      Attachment attachment = Attachment.restoreAttachmentWithId(mContext, attachmentId);
      if (attachment == null) {
        cb.loadAttachmentStatus(0, attachmentId, EmailServiceStatus.ATTACHMENT_NOT_FOUND, 0);
        return;
      }
      final long messageId = attachment.mMessageKey;

      final EmailContent.Message message =
          EmailContent.Message.restoreMessageWithId(mContext, attachment.mMessageKey);
      if (message == null) {
        cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.MESSAGE_NOT_FOUND, 0);
        return;
      }

      // If the message is loaded, just report that we're finished
      if (Utility.attachmentExists(mContext, attachment)
          && attachment.mUiState == UIProvider.AttachmentState.SAVED) {
        cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.SUCCESS, 0);
        return;
      }

      // Say we're starting...
      cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.IN_PROGRESS, 0);

      // 2. Open the remote folder.
      final Account account = Account.restoreAccountWithId(mContext, message.mAccountKey);
      Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);

      if (mailbox.mType == Mailbox.TYPE_OUTBOX
          /// M: View an attachment which comes from refMessage need sourceKey to identify
          || mailbox.mType == Mailbox.TYPE_DRAFTS) {
        long sourceId =
            Utility.getFirstRowLong(
                mContext,
                Body.CONTENT_URI,
                new String[] {BodyColumns.SOURCE_MESSAGE_KEY},
                BodyColumns.MESSAGE_KEY + "=?",
                new String[] {Long.toString(messageId)},
                null,
                0,
                -1L);
        if (sourceId != -1) {
          EmailContent.Message sourceMsg =
              EmailContent.Message.restoreMessageWithId(mContext, sourceId);
          if (sourceMsg != null) {
            mailbox = Mailbox.restoreMailboxWithId(mContext, sourceMsg.mMailboxKey);
            message.mServerId = sourceMsg.mServerId;
          }
        }
      } else if (mailbox.mType == Mailbox.TYPE_SEARCH && message.mMainMailboxKey != 0) {
        mailbox = Mailbox.restoreMailboxWithId(mContext, message.mMainMailboxKey);
      }

      if (account == null || mailbox == null) {
        // If the account/mailbox are gone, just report success; the UI handles this
        cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.SUCCESS, 0);
        return;
      }
      TrafficStats.setThreadStatsTag(TrafficFlags.getAttachmentFlags(mContext, account));

      final Store remoteStore = Store.getInstance(account, mContext);
      remoteFolder = remoteStore.getFolder(mailbox.mServerId);
      remoteFolder.open(OpenMode.READ_WRITE);

      // 3. Generate a shell message in which to retrieve the attachment,
      // and a shell BodyPart for the attachment.  Then glue them together.
      final Message storeMessage = remoteFolder.createMessage(message.mServerId);
      final MimeBodyPart storePart = new MimeBodyPart();
      storePart.setSize((int) attachment.mSize);
      storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, attachment.mLocation);
      storePart.setHeader(
          MimeHeader.HEADER_CONTENT_TYPE,
          String.format("%s;\n name=\"%s\"", attachment.mMimeType, attachment.mFileName));

      // TODO is this always true for attachments?  I think we dropped the
      // true encoding along the way
      /// M: set encoding type according to data base record.
      String encoding = attachment.mEncoding;
      if (TextUtils.isEmpty(encoding)) {
        encoding = "base64";
      }
      storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding);

      final MimeMultipart multipart = new MimeMultipart();
      multipart.setSubType("mixed");
      multipart.addBodyPart(storePart);

      storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
      storeMessage.setBody(multipart);

      // 4. Now ask for the attachment to be fetched
      final FetchProfile fp = new FetchProfile();
      fp.add(storePart);
      remoteFolder.fetch(
          new Message[] {storeMessage},
          fp,
          new MessageRetrievalListenerBridge(messageId, attachmentId, cb));

      // If we failed to load the attachment, throw an Exception here, so that
      // AttachmentDownloadService knows that we failed
      if (storePart.getBody() == null) {
        throw new MessagingException("Attachment not loaded.");
      }

      // Save the attachment to wherever it's going
      AttachmentUtilities.saveAttachment(
          mContext, storePart.getBody().getInputStream(), attachment);

      // 6. Report success
      cb.loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.SUCCESS, 0);

    } catch (MessagingException me) {
      LogUtils.i(Logging.LOG_TAG, me, "Error loading attachment");

      final ContentValues cv = new ContentValues(1);
      cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
      final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId);
      mContext.getContentResolver().update(uri, cv, null, null);

      cb.loadAttachmentStatus(0, attachmentId, EmailServiceStatus.CONNECTION_ERROR, 0);
    } finally {
      if (remoteFolder != null) {
        remoteFolder.close(false);
      }
    }
  }
  /**
   * Copy field-by-field from a "store" message to a "provider" message
   *
   * @param message The message we've just downloaded (must be a MimeMessage)
   * @param localMessage The message we'd like to write into the DB
   * @return true if dirty (changes were made)
   */
  public static boolean updateMessageFields(
      final EmailContent.Message localMessage,
      final Message message,
      final long accountId,
      final long mailboxId)
      throws MessagingException {

    final Address[] from = message.getFrom();
    final Address[] to = message.getRecipients(Message.RecipientType.TO);
    final Address[] cc = message.getRecipients(Message.RecipientType.CC);
    final Address[] bcc = message.getRecipients(Message.RecipientType.BCC);
    final Address[] replyTo = message.getReplyTo();
    final String subject = message.getSubject();
    final Date sentDate = message.getSentDate();
    final Date internalDate = message.getInternalDate();

    if (from != null && from.length > 0) {
      localMessage.mDisplayName = from[0].toFriendly();
    }
    if (sentDate != null) {
      localMessage.mTimeStamp = sentDate.getTime();
    } else if (internalDate != null) {
      LogUtils.w(Logging.LOG_TAG, "No sentDate, falling back to internalDate");
      localMessage.mTimeStamp = internalDate.getTime();
    }
    if (subject != null) {
      localMessage.mSubject = subject;
    }
    localMessage.mFlagRead = message.isSet(Flag.SEEN);
    if (message.isSet(Flag.ANSWERED)) {
      localMessage.mFlags |= EmailContent.Message.FLAG_REPLIED_TO;
    }

    // Keep the message in the "unloaded" state until it has (at least) a display name.
    // This prevents early flickering of empty messages in POP download.
    if (localMessage.mFlagLoaded != EmailContent.Message.FLAG_LOADED_COMPLETE) {
      if (localMessage.mDisplayName == null || "".equals(localMessage.mDisplayName)) {
        localMessage.mFlagLoaded = EmailContent.Message.FLAG_LOADED_UNLOADED;
      } else {
        localMessage.mFlagLoaded = EmailContent.Message.FLAG_LOADED_PARTIAL;
      }
    }
    localMessage.mFlagFavorite = message.isSet(Flag.FLAGGED);
    //        public boolean mFlagAttachment = false;
    //        public int mFlags = 0;

    localMessage.mServerId = message.getUid();
    if (internalDate != null) {
      localMessage.mServerTimeStamp = internalDate.getTime();
    }
    //        public String mClientId;

    // Only replace the local message-id if a new one was found.  This is seen in some ISP's
    // which may deliver messages w/o a message-id header.
    final String messageId = message.getMessageId();
    if (messageId != null) {
      localMessage.mMessageId = messageId;
    }

    //        public long mBodyKey;
    localMessage.mMailboxKey = mailboxId;
    localMessage.mAccountKey = accountId;

    if (from != null && from.length > 0) {
      localMessage.mFrom = Address.toString(from);
    }

    localMessage.mTo = Address.toString(to);
    localMessage.mCc = Address.toString(cc);
    localMessage.mBcc = Address.toString(bcc);
    localMessage.mReplyTo = Address.toString(replyTo);

    //        public String mText;
    //        public String mHtml;
    //        public String mTextReply;
    //        public String mHtmlReply;

    //        // Can be used while building messages, but is NOT saved by the Provider
    //        transient public ArrayList<Attachment> mAttachments = null;

    return true;
  }