コード例 #1
0
NS_IMETHODIMP
nsMsgMaildirStore::GetNewMsgOutputStream(nsIMsgFolder *aFolder,
                                         nsIMsgDBHdr **aNewMsgHdr,
                                         bool *aReusable,
                                         nsIOutputStream **aResult)
{
  NS_ENSURE_ARG_POINTER(aFolder);
  NS_ENSURE_ARG_POINTER(aNewMsgHdr);
  NS_ENSURE_ARG_POINTER(aReusable);
  NS_ENSURE_ARG_POINTER(aResult);

  *aReusable = false; // message per file

  nsCOMPtr<nsIMsgDatabase> db;
  aFolder->GetMsgDatabase(getter_AddRefs(db));
  if (!db)
    NS_ERROR("no db");

  nsresult rv;

  if (!*aNewMsgHdr)
  {
    rv = db->CreateNewHdr(nsMsgKey_None, aNewMsgHdr);
    NS_ENSURE_SUCCESS(rv, rv);

  }
  (*aNewMsgHdr)->SetMessageOffset(0);
  // path to the message download folder
  nsCOMPtr<nsIFile> newFile;
  rv = aFolder->GetFilePath(getter_AddRefs(newFile));
  NS_ENSURE_SUCCESS(rv, rv);
  newFile->Append(NS_LITERAL_STRING("tmp"));

  // let's check if the folder exists
  bool exists;
  newFile->Exists(&exists);
  if (!exists) {
    PR_LOG(MailDirLog, PR_LOG_ALWAYS,
           ("GetNewMsgOutputStream - tmp subfolder does not exist!!\n"));
    rv = newFile->Create(nsIFile::DIRECTORY_TYPE, 0755);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // generate new file name
  nsAutoCString newName;
  newName.AppendInt(static_cast<int64_t>(PR_Now()));
  newFile->AppendNative(newName);
  // CreateUnique, in case we get more than one message per millisecond :-)
  newFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600);
  newFile->GetNativeLeafName(newName);
  // save the file name in the message header - otherwise no way to retrieve it
  (*aNewMsgHdr)->SetStringProperty("storeToken", newName.get());
  return MsgNewBufferedFileOutputStream(aResult, newFile,
                                        PR_WRONLY | PR_CREATE_FILE, 00600);
}
コード例 #2
0
nsresult
nsFolderCompactState::Init(nsIMsgFolder *folder, const char *baseMsgUri, nsIMsgDatabase *db,
                           nsIFile *path, nsIMsgWindow *aMsgWindow)
{
  nsresult rv;

  m_folder = folder;
  m_baseMessageUri = baseMsgUri;
  m_file = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  m_file->InitWithFile(path);
  // need to make sure the temp file goes in the same real directory
  // as the original file, so resolve sym links.
  m_file->SetFollowLinks(true);

  m_file->SetNativeLeafName(NS_LITERAL_CSTRING("nstmp"));
  rv = m_file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600);   //make sure we are not crunching existing nstmp file
  NS_ENSURE_SUCCESS(rv, rv);

  m_window = aMsgWindow;
  m_keyArray = new nsMsgKeyArray;
  m_size = 0;
  m_totalMsgSize = 0;
  rv = InitDB(db);
  if (NS_FAILED(rv))
  {
    CleanupTempFilesAfterError();
    return rv;
  }

  m_curIndex = 0;

  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(m_fileStream), m_file, -1, 00600);
  if (NS_FAILED(rv)) 
    m_folder->ThrowAlertMsg("compactFolderWriteFailed", m_window);
  else
    rv = GetMessageServiceFromURI(nsDependentCString(baseMsgUri),
                                getter_AddRefs(m_messageService));
  if (NS_FAILED(rv))
  {
    m_status = rv;
  }
  return rv;
}
コード例 #3
0
nsresult nsMsgSaveAsListener::SetupMsgWriteStream(nsIFile *aFile, bool addDummyEnvelope)
{
  // If the file already exists, delete it, but do this before
  // getting the outputstream.
  // Due to bug 328027, the nsSaveMsgListener created in
  // nsMessenger::SaveAs now opens the stream on the nsIFile
  // object, thus creating an empty file. Actual save operations for
  // IMAP and NNTP use this nsMsgSaveAsListener here, though, so we
  // have to close the stream before deleting the file, else data
  // would still be written happily into a now non-existing file.
  // (Windows doesn't care, btw, just unixoids do...)
  aFile->Remove(false);

  nsCOMPtr <nsILocalFile> localFile = do_QueryInterface(aFile);
  nsresult rv = MsgNewBufferedFileOutputStream(getter_AddRefs(m_outputStream),
                                               localFile, -1, 00600);
  NS_ENSURE_SUCCESS(rv, rv);

  if (m_outputStream && addDummyEnvelope)
  {
    nsCAutoString result;
    PRUint32 writeCount;

    time_t now = time((time_t*) 0);
    char *ct = ctime(&now);
    // Remove the ending new-line character.
    ct[24] = '\0';
    result = "From - ";
    result += ct;
    result += MSG_LINEBREAK;
    m_outputStream->Write(result.get(), result.Length(), &writeCount);

    result = "X-Mozilla-Status: 0001";
    result += MSG_LINEBREAK;
    result += "X-Mozilla-Status2: 00000000";
    result += MSG_LINEBREAK;
    m_outputStream->Write(result.get(), result.Length(), &writeCount);
  }

  return rv;
}
コード例 #4
0
ファイル: nsMsgFilterList.cpp プロジェクト: dualsky/FossaMail
NS_IMETHODIMP
nsMsgFilterList::GetLogStream(nsIOutputStream **aLogStream)
{
  NS_ENSURE_ARG_POINTER(aLogStream);

  nsresult rv;

  if (!m_logStream) {
    nsCOMPtr <nsIFile> logFile;
    rv = GetLogFile(getter_AddRefs(logFile));
    NS_ENSURE_SUCCESS(rv,rv);

    // append to the end of the log file
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(m_logStream),
                                        logFile,
                                        PR_CREATE_FILE | PR_WRONLY | PR_APPEND,
                                        0600);
    NS_ENSURE_SUCCESS(rv,rv);

    if (!m_logStream)
      return NS_ERROR_FAILURE;

    int64_t fileSize;
    rv = logFile->GetFileSize(&fileSize);
    NS_ENSURE_SUCCESS(rv, rv);

    // write the header at the start
    if (fileSize == 0)
    {
      uint32_t writeCount;

      rv = m_logStream->Write(LOG_HEADER, LOG_HEADER_LEN, &writeCount);
      NS_ENSURE_SUCCESS(rv, rv);
      NS_ASSERTION(writeCount == LOG_HEADER_LEN, "failed to write out log header");
    }
  }

  NS_ADDREF(*aLogStream = m_logStream);
  return NS_OK;
}
コード例 #5
0
ファイル: nsSpamSettings.cpp プロジェクト: vanto/comm-central
NS_IMETHODIMP
nsSpamSettings::GetLogStream(nsIOutputStream **aLogStream)
{
  NS_ENSURE_ARG_POINTER(aLogStream);

  nsresult rv;

  if (!mLogStream) {
    nsCOMPtr <nsILocalFile> logFile = do_QueryInterface(mLogFile, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    // append to the end of the log file
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mLogStream),
                                        logFile,
                                        PR_CREATE_FILE | PR_WRONLY | PR_APPEND,
                                        0600);
    NS_ENSURE_SUCCESS(rv, rv);

    PRInt64 fileSize;
    rv = logFile->GetFileSize(&fileSize);
    NS_ENSURE_SUCCESS(rv, rv);

    PRUint32 fileLen;
    LL_L2UI(fileLen, fileSize);
    // write the header at the start
    if (fileLen == 0)
    {
      PRUint32 writeCount;

      rv = mLogStream->Write(LOG_HEADER, LOG_HEADER_LEN, &writeCount);
      NS_ENSURE_SUCCESS(rv, rv);
      NS_ASSERTION(writeCount == LOG_HEADER_LEN, "failed to write out log header");
    }
  }

  NS_ADDREF(*aLogStream = mLogStream);
  return NS_OK;
}
コード例 #6
0
ファイル: MapiMessage.cpp プロジェクト: Type-of-Tool/ExMail
bool CMapiMessage::CopyMsgAttachToFile(LPATTACH lpAttach, /*out*/ nsIFile **tmp_file)
{
  bool bResult = true;
  LPMESSAGE  lpMsg;
  HRESULT hr = lpAttach->OpenProperty(PR_ATTACH_DATA_OBJ, &IID_IMessage, 0, 0,
                                      reinterpret_cast<LPUNKNOWN *>(&lpMsg));
  NS_ENSURE_SUCCESS(hr, false);

  if (!GetTmpFile(tmp_file))
    return false;

  nsCOMPtr<nsIOutputStream> destOutputStream;
  nsresult rv = MsgNewBufferedFileOutputStream(getter_AddRefs(destOutputStream), *tmp_file, -1, 0600);
  if (NS_SUCCEEDED(rv))
    rv = nsOutlookMail::ImportMessage(lpMsg, destOutputStream, nsIMsgSend::nsMsgSaveAsDraft);

  if (NS_FAILED(rv)) {
    (*tmp_file)->Remove(false);
    (*tmp_file)->Release();
    *tmp_file = 0;
  }

  return NS_SUCCEEDED(rv);
}
コード例 #7
0
int
MimePartBufferWrite (MimePartBufferData *data,
           const char *buf, PRInt32 size)
{
  NS_ASSERTION(data && buf && size > 0, "MimePartBufferWrite: Bad param");
  if (!data || !buf || size <= 0)
    return -1;

  /* If we don't yet have a buffer (either memory or file) try and make a
    memory buffer.
    */
  if (!data->part_buffer &&
      !data->file_buffer)
  {
    int target_size = TARGET_MEMORY_BUFFER_SIZE;
    while (target_size > 0)
    {
      data->part_buffer = (char *) PR_MALLOC(target_size);
      if (data->part_buffer) break;          /* got it! */
      target_size -= TARGET_MEMORY_BUFFER_QUANTUM;  /* decrease it and try
        again */
    }

    if (data->part_buffer)
      data->part_buffer_size = target_size;
    else
      data->part_buffer_size = 0;

    data->part_buffer_fp = 0;
  }

  /* Ok, if at this point we still don't have either kind of buffer, try and
    make a file buffer. */
  if (!data->part_buffer && !data->file_buffer)
  {
    nsCOMPtr <nsIFile> tmpFile;
    nsresult rv = nsMsgCreateTempFile("nsma", getter_AddRefs(tmpFile));
    NS_ENSURE_SUCCESS(rv, MIME_UNABLE_TO_OPEN_TMP_FILE);
    data->file_buffer = do_QueryInterface(tmpFile);

    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(data->output_file_stream), data->file_buffer, PR_WRONLY | PR_CREATE_FILE, 00600);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  NS_ASSERTION(data->part_buffer || data->output_file_stream, "no part_buffer or file_stream");

  /* If this buf will fit in the memory buffer, put it there.
    */
  if (data->part_buffer &&
      data->part_buffer_fp + size < data->part_buffer_size)
  {
    memcpy(data->part_buffer + data->part_buffer_fp,
           buf, size);
    data->part_buffer_fp += size;
  }

  /* Otherwise it won't fit; write it to the file instead. */
  else
  {
    /* If the file isn't open yet, open it, and dump the memory buffer
    to it. */
    if (!data->output_file_stream)
    {
      nsresult rv;
      if (!data->file_buffer)
      {
        nsCOMPtr <nsIFile> tmpFile;
        rv = nsMsgCreateTempFile("nsma", getter_AddRefs(tmpFile));
        NS_ENSURE_SUCCESS(rv, MIME_UNABLE_TO_OPEN_TMP_FILE);
        data->file_buffer = do_QueryInterface(tmpFile);

      }

      rv = MsgNewBufferedFileOutputStream(getter_AddRefs(data->output_file_stream), data->file_buffer, PR_WRONLY | PR_CREATE_FILE, 00600);
      NS_ENSURE_SUCCESS(rv, MIME_UNABLE_TO_OPEN_TMP_FILE);

      if (data->part_buffer && data->part_buffer_fp)
      {
        PRUint32 bytesWritten;
        nsresult rv = data->output_file_stream->Write(data->part_buffer,
                                                 data->part_buffer_fp, &bytesWritten);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      PR_FREEIF(data->part_buffer);
      data->part_buffer_fp = 0;
      data->part_buffer_size = 0;
    }

    /* Dump this buf to the file. */
    PRUint32 bytesWritten;
    nsresult rv = data->output_file_stream->Write (buf, size, &bytesWritten);
    if (NS_FAILED(rv) || (PRInt32) bytesWritten < size)
      return MIME_OUT_OF_MEMORY;
  }

  return 0;
}
コード例 #8
0
NS_IMETHODIMP nsAppleMailImportMail::ImportMailbox(nsIImportMailboxDescriptor *aMailbox, nsIFile *aDestination, 
                                                   PRUnichar **aErrorLog, PRUnichar **aSuccessLog, bool *aFatalError)
{
  nsAutoString errorLog, successLog;

  // reset progress
  mProgress = 0;

  nsAutoString mailboxName;
  aMailbox->GetDisplayName(getter_Copies(mailboxName));

  nsCOMPtr<nsILocalFile> mboxFolder;
  nsresult rv = aMailbox->GetFile(getter_AddRefs(mboxFolder));
  if (NS_FAILED(rv) || !mboxFolder) {
    ReportStatus(APPLEMAILIMPORT_MAILBOX_CONVERTERROR, mailboxName, errorLog);
    SetLogs(successLog, errorLog, aSuccessLog, aErrorLog);
    return NS_ERROR_FAILURE;
  }

  // if we're an account mailbox, nothing do. if we're a real mbox
  // then we've got some messages to import!
  PRUint32 mailboxIdentifier;
  aMailbox->GetIdentifier(&mailboxIdentifier);

  if (mailboxIdentifier != kAccountMailboxID) {
    // move to the .mbox's Messages folder
    nsCOMPtr<nsIFile> messagesFolder;
    mboxFolder->Clone(getter_AddRefs(messagesFolder));
    rv = messagesFolder->Append(NS_LITERAL_STRING("Messages"));
    if (NS_FAILED(rv)) {
      // even if there are no messages, it might still be a valid mailbox, or even
      // a parent for other mailboxes.
      //
      // just indicate that we're done, using the same number that we used to estimate
      // number of messages earlier.
      PRUint32 finalSize;
      aMailbox->GetSize(&finalSize);
      mProgress = finalSize;

      // report that we successfully imported this mailbox
      ReportStatus(APPLEMAILIMPORT_MAILBOX_SUCCESS, mailboxName, successLog);
      SetLogs(successLog, errorLog, aSuccessLog, aErrorLog);
      return NS_OK;
    }

    // let's import the messages!
    nsCOMPtr<nsISimpleEnumerator> directoryEnumerator;
    rv = messagesFolder->GetDirectoryEntries(getter_AddRefs(directoryEnumerator));
    if (NS_FAILED(rv)) {
      ReportStatus(APPLEMAILIMPORT_MAILBOX_CONVERTERROR, mailboxName, errorLog);
      SetLogs(successLog, errorLog, aSuccessLog, aErrorLog);
      return NS_ERROR_FAILURE;
    }

    // prepare an outstream to the destination file
    nsCOMPtr<nsIOutputStream> outStream;
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outStream), aDestination);
    if (!outStream || NS_FAILED(rv)) {
      ReportStatus(APPLEMAILIMPORT_MAILBOX_CONVERTERROR, mailboxName, errorLog);
      SetLogs(successLog, errorLog, aSuccessLog, aErrorLog);
      return NS_ERROR_FAILURE;
    }

    bool hasMore = false;
    while (NS_SUCCEEDED(directoryEnumerator->HasMoreElements(&hasMore)) && hasMore) {
      // get the next file entry
      nsCOMPtr<nsILocalFile> currentEntry;
      {
        nsCOMPtr<nsISupports> rawSupports;
        directoryEnumerator->GetNext(getter_AddRefs(rawSupports));
        if (!rawSupports)
          continue;
        currentEntry = do_QueryInterface(rawSupports);
        if (!currentEntry)
          continue;
      }

      // make sure it's an .emlx file
      bool isFile = false;
      currentEntry->IsFile(&isFile);
      if (!isFile)
        continue;

      nsAutoString leafName;
      currentEntry->GetLeafName(leafName);
      if (!StringEndsWith(leafName, NS_LITERAL_STRING(".emlx")))
        continue;

      // add the data to the mbox stream
      if (NS_SUCCEEDED(nsEmlxHelperUtils::AddEmlxMessageToStream(currentEntry, outStream)))
        mProgress++;
    }
  }

  // just indicate that we're done, using the same number that we used to estimate
  // number of messages earlier.
  PRUint32 finalSize;
  aMailbox->GetSize(&finalSize);
  mProgress = finalSize;

  // report that we successfully imported this mailbox
  ReportStatus(APPLEMAILIMPORT_MAILBOX_SUCCESS, mailboxName, successLog);
  SetLogs(successLog, errorLog, aSuccessLog, aErrorLog);

  return NS_OK;
}
コード例 #9
0
nsresult
nsAbManager::ExportDirectoryToLDIF(nsIAbDirectory *aDirectory, nsILocalFile *aLocalFile)
{
  nsCOMPtr <nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr <nsIAbCard> card;

  nsresult rv;

  nsCOMPtr <nsIOutputStream> outputStream;
  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream),
                                      aLocalFile,
                                      PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE,
                                      0664);

  // the desired file may be read only
  if (NS_FAILED(rv))
    return rv;

  // Get the default attribute map for ldap. We use the default attribute
  // map rather than one for a specific server because if people want an
  // ldif export using a servers specific schema, then they can use ldapsearch
  nsCOMPtr<nsIAbLDAPAttributeMapService> mapSrv =
    do_GetService("@mozilla.org/addressbook/ldap-attribute-map-service;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIAbLDAPAttributeMap> attrMap;
  rv = mapSrv->GetMapForPrefBranch(NS_LITERAL_CSTRING("ldap_2.servers.default.attrmap"),
                                   getter_AddRefs(attrMap));
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 i;
  PRUint32 writeCount;
  PRUint32 length;

  rv = aDirectory->GetChildCards(getter_AddRefs(cardsEnumerator));
  if (NS_SUCCEEDED(rv) && cardsEnumerator) {
    nsCOMPtr<nsISupports> item;
    bool more;
    while (NS_SUCCEEDED(cardsEnumerator->HasMoreElements(&more)) && more) {
      rv = cardsEnumerator->GetNext(getter_AddRefs(item));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr <nsIAbCard> card = do_QueryInterface(item, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        bool isMailList;
        rv = card->GetIsMailList(&isMailList);
        NS_ENSURE_SUCCESS(rv,rv);

        if (isMailList) {
          nsCString mailListCStr;

          rv = AppendLDIFForMailList(card, attrMap, mailListCStr);
          NS_ENSURE_SUCCESS(rv,rv);

          length = mailListCStr.Length();
          rv = outputStream->Write(mailListCStr.get(), length, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (length != writeCount)
            return NS_ERROR_FAILURE;
        }
        else {
          nsString value;
          nsCString valueCStr;

          rv = AppendBasicLDIFForCard(card, attrMap, valueCStr);
          NS_ENSURE_SUCCESS(rv,rv);

          length = valueCStr.Length();
          rv = outputStream->Write(valueCStr.get(), length, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (length != writeCount)
            return NS_ERROR_FAILURE;

          valueCStr.Truncate();

          nsCAutoString ldapAttribute;

          for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
            if (NS_SUCCEEDED(attrMap->GetFirstAttribute(nsDependentCString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName),
                                                        ldapAttribute)) &&
                !ldapAttribute.IsEmpty()) {

              rv = card->GetPropertyAsAString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, value);
              if (NS_FAILED(rv))
                value.Truncate();

              if (!PL_strcmp(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, kPreferMailFormatProperty)) {
                if (value.EqualsLiteral("html"))
                  value.AssignLiteral("true");
                else if (value.EqualsLiteral("plaintext"))
                  value.AssignLiteral("false");
                else
                  value.Truncate(); // unknown.
              }

              if (!value.IsEmpty()) {
                rv = AppendProperty(ldapAttribute.get(), value.get(), valueCStr);
                NS_ENSURE_SUCCESS(rv,rv);

                valueCStr += MSG_LINEBREAK;
              }
              else
                valueCStr.Truncate();

              length = valueCStr.Length();
              if (length) {
                rv = outputStream->Write(valueCStr.get(), length, &writeCount);
                NS_ENSURE_SUCCESS(rv,rv);
                if (length != writeCount)
                  return NS_ERROR_FAILURE;
              }
              valueCStr.Truncate();
            }
            else {
              // something we don't support yet
              // ldif doesn't export multiple addresses
            }
          }

          // write out the linebreak that separates the cards
          rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (MSG_LINEBREAK_LEN != writeCount)
            return NS_ERROR_FAILURE;
        }
      }
    }
  }

  rv = outputStream->Flush();
  NS_ENSURE_SUCCESS(rv,rv);

  rv = outputStream->Close();
  NS_ENSURE_SUCCESS(rv,rv);
  return NS_OK;
}
コード例 #10
0
nsresult
nsAbManager::ExportDirectoryToDelimitedText(nsIAbDirectory *aDirectory, const char *aDelim, PRUint32 aDelimLen, nsILocalFile *aLocalFile)
{
  nsCOMPtr <nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr <nsIAbCard> card;

  nsresult rv;

  nsCOMPtr <nsIOutputStream> outputStream;
  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream),
                                      aLocalFile,
                                      PR_CREATE_FILE | PR_WRONLY | PR_TRUNCATE,
                                      0664);

  // the desired file may be read only
  if (NS_FAILED(rv))
    return rv;

  PRUint32 i;
  PRUint32 writeCount;
  PRUint32 length;

  nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIStringBundle> bundle;
  rv = bundleService->CreateBundle("chrome://messenger/locale/importMsgs.properties", getter_AddRefs(bundle));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString revisedName;
  nsString columnName;

  for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
    if (EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID != 0) {

      // We don't need to truncate the string here as getter_Copies will
      // do that for us.
      if (NS_FAILED(bundle->GetStringFromID(EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID, getter_Copies(columnName))))
        columnName.AppendInt(EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID);

      rv = nsMsgI18NConvertFromUnicode(nsMsgI18NFileSystemCharset(),
                                       columnName, revisedName);
      NS_ENSURE_SUCCESS(rv,rv);

      rv = outputStream->Write(revisedName.get(),
                               revisedName.Length(),
                               &writeCount);
      NS_ENSURE_SUCCESS(rv,rv);

      if (revisedName.Length() != writeCount)
        return NS_ERROR_FAILURE;

      if (i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE) - 1) {
        rv = outputStream->Write(aDelim, aDelimLen, &writeCount);
        NS_ENSURE_SUCCESS(rv,rv);

        if (aDelimLen != writeCount)
          return NS_ERROR_FAILURE;
      }
    }
  }
  rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
  NS_ENSURE_SUCCESS(rv,rv);
  if (MSG_LINEBREAK_LEN != writeCount)
    return NS_ERROR_FAILURE;

  rv = aDirectory->GetChildCards(getter_AddRefs(cardsEnumerator));
  if (NS_SUCCEEDED(rv) && cardsEnumerator) {
    nsCOMPtr<nsISupports> item;
    bool more;
    while (NS_SUCCEEDED(cardsEnumerator->HasMoreElements(&more)) && more) {
      rv = cardsEnumerator->GetNext(getter_AddRefs(item));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr <nsIAbCard> card = do_QueryInterface(item, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        bool isMailList;
        rv = card->GetIsMailList(&isMailList);
        NS_ENSURE_SUCCESS(rv,rv);


        if (isMailList) {
          // .tab, .txt and .csv aren't able to export mailing lists
          // use LDIF for that.
        }
        else {
          nsString value;
          nsCString valueCStr;

          for (i = 0; i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE); i++) {
            if (EXPORT_ATTRIBUTES_TABLE[i].plainTextStringID != 0) {
              rv = card->GetPropertyAsAString(EXPORT_ATTRIBUTES_TABLE[i].abPropertyName, value);
              if (NS_FAILED(rv))
                value.Truncate();

              // If a string contains at least one comma, tab or double quote then
              // we need to quote the entire string. Also if double quote is part
              // of the string we need to quote the double quote(s) as well.
              nsAutoString newValue(value);
              bool needsQuotes = false;
              if(newValue.FindChar('"') != -1)
              {
                needsQuotes = PR_TRUE;
                
                PRInt32 match = 0;
                PRUint32 offset = 0;
                nsString oldSubstr = NS_LITERAL_STRING("\"");
                nsString newSubstr = NS_LITERAL_STRING("\"\""); 
                while (offset < newValue.Length()) {
                    match = newValue.Find(oldSubstr, offset);
                    if (match == -1)
                        break;

                    newValue.Replace(offset + match, oldSubstr.Length(), newSubstr);
                    offset += (match + newSubstr.Length());
                }
              }
              if (!needsQuotes && (newValue.FindChar(',') != -1 || newValue.FindChar('\x09') != -1))
                needsQuotes = PR_TRUE;

              // Make sure we quote if containing CR/LF.
              if (newValue.FindChar('\r') != -1 ||
                  newValue.FindChar('\n') != -1)
                  needsQuotes = PR_TRUE;

              if (needsQuotes)
              {
                newValue.Insert(NS_LITERAL_STRING("\""), 0);
                newValue.AppendLiteral("\"");
              }

              rv = nsMsgI18NConvertFromUnicode(nsMsgI18NFileSystemCharset(),
                                               newValue, valueCStr);
              NS_ENSURE_SUCCESS(rv,rv);

              if (NS_FAILED(rv)) {
                NS_ERROR("failed to convert string to system charset.  use LDIF");
                valueCStr = "?";
              }

              length = valueCStr.Length();
              if (length) {
                rv = outputStream->Write(valueCStr.get(), length, &writeCount);
                NS_ENSURE_SUCCESS(rv,rv);
                if (length != writeCount)
                  return NS_ERROR_FAILURE;
              }
              valueCStr = "";
            }
            else {
              // something we don't support for the current export
              // for example, .tab doesn't export preferred html format
              continue; // go to next field
            }

            if (i < NS_ARRAY_LENGTH(EXPORT_ATTRIBUTES_TABLE) - 1) {
              rv = outputStream->Write(aDelim, aDelimLen, &writeCount);
              NS_ENSURE_SUCCESS(rv,rv);
              if (aDelimLen != writeCount)
                return NS_ERROR_FAILURE;
            }
          }

          // write out the linebreak that separates the cards
          rv = outputStream->Write(MSG_LINEBREAK, MSG_LINEBREAK_LEN, &writeCount);
          NS_ENSURE_SUCCESS(rv,rv);
          if (MSG_LINEBREAK_LEN != writeCount)
            return NS_ERROR_FAILURE;
        }
      }
    }
  }

  rv = outputStream->Flush();
  NS_ENSURE_SUCCESS(rv,rv);

  rv = outputStream->Close();
  NS_ENSURE_SUCCESS(rv,rv);
  return NS_OK;
}
コード例 #11
0
ファイル: mimemrel.cpp プロジェクト: Type-of-Tool/ExMail
static int
MimeMultipartRelated_parse_child_line (MimeObject *obj,
                     const char *line, int32_t length,
                     bool first_line_p)
{
  MimeContainer *cont = (MimeContainer *) obj;
  MimeMultipartRelated *relobj = (MimeMultipartRelated *) obj;
  int status;
  MimeObject *kid;

  if (obj->options && !obj->options->write_html_p
#ifdef MIME_DRAFTS
    && !obj->options->decompose_file_p
#endif /* MIME_DRAFTS */
    )
    {
    /* Oh, just go do the normal thing... */
    return ((MimeMultipartClass*)&MIME_SUPERCLASS)->
      parse_child_line(obj, line, length, first_line_p);
    }

  /* Throw it away if this isn't the head object.  (Someday, maybe we'll
     cache it instead.) */
  PR_ASSERT(cont->nchildren > 0);
  if (cont->nchildren <= 0)
    return -1;
  kid = cont->children[cont->nchildren-1];
  PR_ASSERT(kid);
  if (!kid) return -1;
  if (kid != relobj->headobj) return 0;

  /* Buffer this up (###tw much code duplication from mimemalt.c) */
  /* If we don't yet have a buffer (either memory or file) try and make a
     memory buffer. */
  if (!relobj->head_buffer && !relobj->file_buffer) {
    int target_size = 1024 * 50;       /* try for 50k */
    while (target_size > 0) {
      relobj->head_buffer = (char *) PR_MALLOC(target_size);
      if (relobj->head_buffer) break;  /* got it! */
      target_size -= (1024 * 5);     /* decrease it and try again */
    }

    if (relobj->head_buffer) {
      relobj->head_buffer_size = target_size;
    } else {
      relobj->head_buffer_size = 0;
    }

    relobj->head_buffer_fp = 0;
  }

  nsresult rv;
  /* Ok, if at this point we still don't have either kind of buffer, try and
     make a file buffer. */
  if (!relobj->head_buffer && !relobj->file_buffer)
  {
    nsCOMPtr <nsIFile> file;
    rv = nsMsgCreateTempFile("nsma", getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);
    relobj->file_buffer = do_QueryInterface(file);

    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(relobj->output_file_stream), relobj->file_buffer, PR_WRONLY | PR_CREATE_FILE, 00600);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  PR_ASSERT(relobj->head_buffer || relobj->output_file_stream);


  /* If this line will fit in the memory buffer, put it there.
   */
  if (relobj->head_buffer &&
      relobj->head_buffer_fp + length < relobj->head_buffer_size) {
    memcpy(relobj->head_buffer + relobj->head_buffer_fp, line, length);
    relobj->head_buffer_fp += length;
  } else {
    /* Otherwise it won't fit; write it to the file instead. */

    /* If the file isn't open yet, open it, and dump the memory buffer
       to it. */
    if (!relobj->output_file_stream)
    {
      if (!relobj->file_buffer)
      {
        nsCOMPtr <nsIFile> file;
        rv = nsMsgCreateTempFile("nsma", getter_AddRefs(file));
        NS_ENSURE_SUCCESS(rv, rv);
        relobj->file_buffer = do_QueryInterface(file);
      }

      nsresult rv = MsgNewBufferedFileOutputStream(getter_AddRefs(relobj->output_file_stream), relobj->file_buffer, PR_WRONLY | PR_CREATE_FILE, 00600);
      NS_ENSURE_SUCCESS(rv, rv);

      if (relobj->head_buffer && relobj->head_buffer_fp)
      {
        uint32_t bytesWritten;
        status = relobj->output_file_stream->Write(relobj->head_buffer,
                                                   relobj->head_buffer_fp,
                                                   &bytesWritten);
        if (bytesWritten < relobj->head_buffer_fp)
          return MIME_UNABLE_TO_OPEN_TMP_FILE;
      }

      PR_FREEIF(relobj->head_buffer);
      relobj->head_buffer_fp = 0;
      relobj->head_buffer_size = 0;
    }

    /* Dump this line to the file. */
    uint32_t bytesWritten;
    rv = relobj->output_file_stream->Write(line, length, &bytesWritten);
    if ((int32_t) bytesWritten < length || NS_FAILED(rv))
      return MIME_UNABLE_TO_OPEN_TMP_FILE;
  }

  return 0;
}
コード例 #12
0
nsresult nsOutlookMail::ImportMailbox( PRUint32 *pDoneSoFar, bool *pAbort, PRInt32 index, const PRUnichar *pName, nsIFile *pDest, PRInt32 *pMsgCount)
{
    if ((index < 0) || (index >= m_folderList.GetSize())) {
        IMPORT_LOG0( "*** Bad mailbox identifier, unable to import\n");
        *pAbort = PR_TRUE;
        return( NS_ERROR_FAILURE);
    }

    PRInt32    dummyMsgCount = 0;
    if (pMsgCount)
        *pMsgCount = 0;
    else
        pMsgCount = &dummyMsgCount;

    CMapiFolder *pFolder = m_folderList.GetItem( index);
    OpenMessageStore( pFolder);
    if (!m_lpMdb) {
        IMPORT_LOG1( "*** Unable to obtain mapi message store for mailbox: %S\n", pName);
        return( NS_ERROR_FAILURE);
    }

    if (pFolder->IsStore())
        return( NS_OK);

    nsresult  rv;

    // now what?
    CMapiFolderContents    contents( m_lpMdb, pFolder->GetCBEntryID(), pFolder->GetEntryID());

    BOOL    done = FALSE;
    ULONG    cbEid;
    LPENTRYID  lpEid;
    ULONG    oType;
    LPMESSAGE  lpMsg = nsnull;
    ULONG    totalCount;
    PRFloat64  doneCalc;

    nsCOMPtr<nsIOutputStream> destOutputStream;
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(destOutputStream), pDest, -1, 0600);
    NS_ENSURE_SUCCESS(rv, rv);

    while (!done) {
        if (!contents.GetNext( &cbEid, &lpEid, &oType, &done)) {
            IMPORT_LOG1( "*** Error iterating mailbox: %S\n", pName);
            return( NS_ERROR_FAILURE);
        }

        totalCount = contents.GetCount();
        doneCalc = *pMsgCount;
        doneCalc /= totalCount;
        doneCalc *= 1000;
        if (pDoneSoFar) {
            *pDoneSoFar = (PRUint32) doneCalc;
            if (*pDoneSoFar > 1000)
                *pDoneSoFar = 1000;
        }

        if (!done && (oType == MAPI_MESSAGE)) {
            if (!m_mapi.OpenMdbEntry( m_lpMdb, cbEid, lpEid, (LPUNKNOWN *) &lpMsg)) {
                IMPORT_LOG1( "*** Error opening messages in mailbox: %S\n", pName);
                return( NS_ERROR_FAILURE);
            }

            // See if it's a drafts folder. Outlook doesn't allow drafts
            // folder to be configured so it's ok to hard code it here.
            nsAutoString folderName(pName);
            nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow;
            mode = nsIMsgSend::nsMsgSaveAsDraft;
            if ( folderName.LowerCaseEqualsLiteral("drafts") )
                mode = nsIMsgSend::nsMsgSaveAsDraft;

            rv = ImportMessage(lpMsg, destOutputStream, mode);
            if (NS_SUCCEEDED( rv)) // No errors & really imported
                (*pMsgCount)++;
            else {
                IMPORT_LOG1( "*** Error reading message from mailbox: %S\n", pName);
            }
        }
    }

    return( NS_OK);
}
コード例 #13
0
void
nsImapOfflineSync::ProcessAppendMsgOperation(nsIMsgOfflineImapOperation *currentOp, PRInt32 opType)
{
  nsCOMPtr <nsIMsgDBHdr> mailHdr;
  nsMsgKey msgKey;
  currentOp->GetMessageKey(&msgKey);
  nsresult rv = m_currentDB->GetMsgHdrForKey(msgKey, getter_AddRefs(mailHdr)); 
  if (NS_SUCCEEDED(rv) && mailHdr)
  {
    nsMsgKey messageOffset;
    PRUint32 messageSize;
    mailHdr->GetMessageOffset(&messageOffset);
    mailHdr->GetOfflineMessageSize(&messageSize);
    nsCOMPtr<nsIFile> tmpFile;

    if (NS_FAILED(GetSpecialDirectoryWithFileName(NS_OS_TEMP_DIR,
                                                  "nscpmsg.txt",
                                                  getter_AddRefs(tmpFile))))
      return;

    if (NS_FAILED(tmpFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600)))
      return;

    nsCOMPtr <nsIOutputStream> outputStream;
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(outputStream), tmpFile, PR_WRONLY | PR_CREATE_FILE, 00600);
    if (NS_SUCCEEDED(rv) && outputStream)
    {
      nsCString moveDestination;
      currentOp->GetDestinationFolderURI(getter_Copies(moveDestination));
      nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv));
      nsCOMPtr<nsIRDFResource> res;
      if (NS_FAILED(rv)) return ; // ### return error code.
      rv = rdf->GetResource(moveDestination, getter_AddRefs(res));
      if (NS_SUCCEEDED(rv))
      {
        nsCOMPtr<nsIMsgFolder> destFolder(do_QueryInterface(res, &rv));
        if (NS_SUCCEEDED(rv) && destFolder)
        {
          nsCOMPtr <nsIInputStream> offlineStoreInputStream;
          rv = destFolder->GetOfflineStoreInputStream(getter_AddRefs(offlineStoreInputStream));
          if (NS_SUCCEEDED(rv) && offlineStoreInputStream)
          {
            nsCOMPtr<nsISeekableStream> seekStream = do_QueryInterface(offlineStoreInputStream);
            NS_ASSERTION(seekStream, "non seekable stream - can't read from offline msg");
            if (seekStream)
            {
              rv = seekStream->Seek(PR_SEEK_SET, messageOffset);
              if (NS_SUCCEEDED(rv))
              {
                // now, copy the dest folder offline store msg to the temp file
                PRInt32 inputBufferSize = 10240;
                char *inputBuffer = nsnull;
                
                while (!inputBuffer && (inputBufferSize >= 512))
                {
                  inputBuffer = (char *) PR_Malloc(inputBufferSize);
                  if (!inputBuffer)
                    inputBufferSize /= 2;
                }
                PRInt32 bytesLeft;
                PRUint32 bytesRead, bytesWritten;
                bytesLeft = messageSize;
                rv = NS_OK;
                while (bytesLeft > 0 && NS_SUCCEEDED(rv))
                {
                  PRInt32 bytesToRead = PR_MIN(inputBufferSize, bytesLeft);
                  rv = offlineStoreInputStream->Read(inputBuffer, bytesToRead, &bytesRead);
                  if (NS_SUCCEEDED(rv) && bytesRead > 0)
                  {
                    rv = outputStream->Write(inputBuffer, bytesRead, &bytesWritten);
                    NS_ASSERTION(bytesWritten == bytesRead, "wrote out correct number of bytes");
                  }
                  else
                    break;
                  bytesLeft -= bytesRead;
                }
                outputStream->Flush();
                outputStream->Close();
                if (NS_SUCCEEDED(rv))
                {
                  m_curTempFile = do_QueryInterface(tmpFile);
                  nsCOMPtr<nsIMsgCopyService> copyService = do_GetService(NS_MSGCOPYSERVICE_CONTRACTID);
                  if (copyService)
                    rv = copyService->CopyFileMessage(tmpFile, destFolder,
                    /* nsIMsgDBHdr* msgToReplace */ nsnull,
                    PR_TRUE /* isDraftOrTemplate */,
                    0, // new msg flags - are there interesting flags here?
                    EmptyCString(), /* are there keywords we should get? */
                      this,
                      m_window);
                }
                else
                  tmpFile->Remove(PR_FALSE);
              }
              currentOp->SetPlayingBack(PR_TRUE);
              m_currentOpsToClear.AppendObject(currentOp);
              m_currentDB->DeleteHeader(mailHdr, nsnull, PR_TRUE, PR_TRUE);
            }
          }
          // want to close in failure case too
          outputStream->Close();
        }
      }
    }
  }
}
コード例 #14
0
ファイル: nsMsgSendLater.cpp プロジェクト: dualsky/FossaMail
nsresult
nsMsgSendLater::DeliverQueuedLine(char *line, int32_t length)
{
  int32_t flength = length;
  
  m_bytesRead += length;
  
// convert existing newline to CRLF 
// Don't need this because the calling routine is taking care of it.
//  if (length > 0 && (line[length-1] == '\r' || 
//     (line[length-1] == '\n' && (length < 2 || line[length-2] != '\r'))))
//  {
//    line[length-1] = '\r';
//    line[length++] = '\n';
//  }
//
  //
  // We are going to check if we are looking at a "From - " line. If so, 
  // then just eat it and return NS_OK
  //
  if (!PL_strncasecmp(line, "From - ", 7))
    return NS_OK;

  if (m_inhead)
  {
    if (m_headersPosition == 0)
    {
      // This line is the first line in a header block.
      // Remember its position.
      m_headersPosition = m_position;
      
      // Also, since we're now processing the headers, clear out the
      // slots which we will parse data into, so that the values that
      // were used the last time around do not persist.
      
      // We must do that here, and not in the previous clause of this
      // `else' (the "I've just seen a `From ' line clause") because
      // that clause happens before delivery of the previous message is
      // complete, whereas this clause happens after the previous msg
      // has been delivered.  If we did this up there, then only the
      // last message in the folder would ever be able to be both
      // mailed and posted (or fcc'ed.)
      PR_FREEIF(m_to);
      PR_FREEIF(m_bcc);
      PR_FREEIF(m_newsgroups);
      PR_FREEIF(m_newshost);
      PR_FREEIF(m_fcc);
      PR_FREEIF(mIdentityKey);
    }
    
    if (line[0] == '\r' || line[0] == '\n' || line[0] == 0)
    {
      // End of headers.  Now parse them; open the temp file;
      // and write the appropriate subset of the headers out. 
      m_inhead = false;

      nsresult rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mOutFile), mTempFile, -1, 00600);
      if (NS_FAILED(rv))
        return NS_MSG_ERROR_WRITING_FILE;

      nsresult status = BuildHeaders();
      if (NS_FAILED(status))
        return status;

      uint32_t n;
      rv = mOutFile->Write(m_headers, m_headersFP, &n);
      if (NS_FAILED(rv) || n != (uint32_t)m_headersFP)
        return NS_MSG_ERROR_WRITING_FILE;
    }
    else
    {
      // Otherwise, this line belongs to a header.  So append it to the
      // header data.
      
      if (!PL_strncasecmp (line, HEADER_X_MOZILLA_STATUS, PL_strlen(HEADER_X_MOZILLA_STATUS)))
        // Notice the position of the flags.
        m_flagsPosition = m_position;
      else if (m_headersFP == 0)
        m_flagsPosition = 0;
      
      nsresult status = do_grow_headers (length + m_headersFP + 10);
      if (NS_FAILED(status)) 
        return status;
      
      memcpy(m_headers + m_headersFP, line, length);
      m_headersFP += length;
    }
  }
  else
  {
    // This is a body line.  Write it to the file.
    PR_ASSERT(mOutFile);
    if (mOutFile)
    {
      uint32_t wrote;
      nsresult rv = mOutFile->Write(line, length, &wrote);
      if (NS_FAILED(rv) || wrote < (uint32_t) length) 
        return NS_MSG_ERROR_WRITING_FILE;
    }
  }
  
  m_position += flength;
  return NS_OK;
}
コード例 #15
0
nsresult
nsMsgAttachmentHandler::SnarfMsgAttachment(nsMsgCompFields *compFields)
{
  nsresult rv = NS_ERROR_INVALID_ARG;
  nsCOMPtr <nsIMsgMessageService> messageService;

  if (m_uri.Find("-message:", CaseInsensitiveCompare) != -1)
  {
    nsCOMPtr <nsIFile> tmpFile;
    rv = nsMsgCreateTempFile("nsmail.tmp", getter_AddRefs(tmpFile));
    NS_ENSURE_SUCCESS(rv, rv);
    mTmpFile = do_QueryInterface(tmpFile);
    mDeleteFile = true;
    mCompFields = compFields;
    m_type = MESSAGE_RFC822;
    m_overrideType = MESSAGE_RFC822;
    if (!mTmpFile)
    {
      rv = NS_ERROR_FAILURE;
      goto done;
    }

    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mOutFile), mTmpFile, -1, 00600);
    if (NS_FAILED(rv) || !mOutFile)
    {
      if (m_mime_delivery_state)
      {
        nsCOMPtr<nsIMsgSendReport> sendReport;
        m_mime_delivery_state->GetSendReport(getter_AddRefs(sendReport));
        if (sendReport)
        {
          nsAutoString error_msg;
          nsMsgBuildMessageWithTmpFile(mTmpFile, error_msg);
          sendReport->SetMessage(nsIMsgSendReport::process_Current, error_msg.get(), false);
        }
      }
      rv =  NS_MSG_UNABLE_TO_OPEN_TMP_FILE;
      goto done;
    }

    nsCOMPtr<nsIURLFetcher> fetcher = do_CreateInstance(NS_URLFETCHER_CONTRACTID, &rv);
    if (NS_FAILED(rv) || !fetcher)
    {
      if (NS_SUCCEEDED(rv))
        rv =  NS_ERROR_UNEXPECTED;
      goto done;
    }

    rv = fetcher->Initialize(mTmpFile, mOutFile, FetcherURLDoneCallback, this);
    rv = GetMessageServiceFromURI(m_uri, getter_AddRefs(messageService));
    if (NS_SUCCEEDED(rv) && messageService)
    {
      nsCAutoString uri(m_uri);
      uri += (uri.FindChar('?') == kNotFound) ? '?' : '&';
      uri.Append("fetchCompleteMessage=true");
      nsCOMPtr<nsIStreamListener> strListener;
      fetcher->QueryInterface(NS_GET_IID(nsIStreamListener), getter_AddRefs(strListener));

      // initialize a new stream converter, that uses the strListener as its input
      // obtain the input stream listener from the new converter,
      // and pass the converter's input stream listener to DisplayMessage

      m_mime_parser = do_CreateInstance(NS_MAILNEWS_MIME_STREAM_CONVERTER_CONTRACTID, &rv);
      if (NS_FAILED(rv))
        goto done;

      // Set us as the output stream for HTML data from libmime...
      nsCOMPtr<nsIMimeStreamConverter> mimeConverter = do_QueryInterface(m_mime_parser);
      if (mimeConverter)
      {
        mimeConverter->SetMimeOutputType(nsMimeOutput::nsMimeMessageDecrypt);
        mimeConverter->SetForwardInline(false);
        mimeConverter->SetIdentity(nsnull);
        mimeConverter->SetOriginalMsgURI(nsnull);
      }

      nsCOMPtr<nsIStreamListener> convertedListener = do_QueryInterface(m_mime_parser, &rv);
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIURI> aURL;
      rv = messageService->GetUrlForUri(uri.get(), getter_AddRefs(aURL), nsnull);
      if (aURL)
        aURL->SetSpec(nsDependentCString(uri.get()));

      rv = NS_NewInputStreamChannel(getter_AddRefs(m_converter_channel), aURL, nsnull);
      if (NS_FAILED(rv))
        goto done;

      rv = m_mime_parser->AsyncConvertData(
		    "message/rfc822",
		    "message/rfc822",
		    strListener, m_converter_channel);
      if (NS_FAILED(rv))
        goto done;

      rv = messageService->DisplayMessage(uri.get(), convertedListener, nsnull, nsnull, nsnull, nsnull);
    }
  }
done:
  if (NS_FAILED(rv))
  {
      if (mOutFile)
      {
        mOutFile->Close();
        mOutFile = nsnull;
      }

      if (mTmpFile)
      {
        mTmpFile->Remove(false);
        mTmpFile = nsnull;
      }
  }

  return rv;
}
コード例 #16
0
nsresult
nsMsgAttachmentHandler::SnarfAttachment(nsMsgCompFields *compFields)
{
  NS_ASSERTION (! m_done, "Already done");

  if (!mURL)
    return SnarfMsgAttachment(compFields);

  mCompFields = compFields;

  // First, get as file spec and create the stream for the
  // temp file where we will save this data
  nsCOMPtr <nsIFile> tmpFile;
  nsresult rv = nsMsgCreateTempFile("nsmail.tmp", getter_AddRefs(tmpFile));
  NS_ENSURE_SUCCESS(rv, rv);
  mTmpFile = do_QueryInterface(tmpFile);
  mDeleteFile = true;

  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mOutFile), mTmpFile, -1, 00600);
  if (NS_FAILED(rv) || !mOutFile)
  {
    if (m_mime_delivery_state)
    {
      nsCOMPtr<nsIMsgSendReport> sendReport;
      m_mime_delivery_state->GetSendReport(getter_AddRefs(sendReport));
      if (sendReport)
      {
        nsAutoString error_msg;
        nsMsgBuildMessageWithTmpFile(mTmpFile, error_msg);
        sendReport->SetMessage(nsIMsgSendReport::process_Current, error_msg.get(), false);
      }
    }
    mTmpFile->Remove(false);
    mTmpFile = nsnull;
    return NS_MSG_UNABLE_TO_OPEN_TMP_FILE;
  }

  nsCString sourceURISpec;
  mURL->GetSpec(sourceURISpec);
#ifdef XP_MACOSX
  if (!m_bogus_attachment && StringBeginsWith(sourceURISpec, NS_LITERAL_CSTRING("file://")))
  {
    // Unescape the path (i.e. un-URLify it) before making a FSSpec
    nsCAutoString filePath;
    filePath.Adopt(nsMsgGetLocalFileFromURL(sourceURISpec.get()));
    nsCAutoString unescapedFilePath;
    MsgUnescapeString(filePath, 0, unescapedFilePath);

    nsCOMPtr<nsILocalFile> sourceFile;
    NS_NewNativeLocalFile(unescapedFilePath, true, getter_AddRefs(sourceFile));
    if (!sourceFile)
      return NS_ERROR_FAILURE;
      
    // check if it is a bundle. if it is, we'll zip it. 
    // if not, we'll apple encode it (applesingle or appledouble)
    nsCOMPtr<nsILocalFileMac> macFile(do_QueryInterface(sourceFile));
    bool isPackage;
    macFile->IsPackage(&isPackage);
    if (isPackage)
      rv = ConvertToZipFile(macFile);
    else
      rv = ConvertToAppleEncoding(sourceURISpec, unescapedFilePath, macFile);
    
    NS_ENSURE_SUCCESS(rv, rv);
  }
#endif /* XP_MACOSX */

  //
  // Ok, here we are, we need to fire the URL off and get the data
  // in the temp file
  //
  // Create a fetcher for the URL attachment...
  
  nsCOMPtr<nsIURLFetcher> fetcher = do_CreateInstance(NS_URLFETCHER_CONTRACTID, &rv);
  if (NS_FAILED(rv) || !fetcher)
  {
    if (NS_SUCCEEDED(rv))
      return NS_ERROR_UNEXPECTED;
    else
      return rv;
  }

  return fetcher->FireURLRequest(mURL, mTmpFile, mOutFile, FetcherURLDoneCallback, this);
}
コード例 #17
0
nsresult nsMailboxProtocol::LoadUrl(nsIURI * aURL, nsISupports * aConsumer)
{
  nsresult rv = NS_OK;
  // if we were already initialized with a consumer, use it...
  nsCOMPtr<nsIStreamListener> consumer = do_QueryInterface(aConsumer);
  if (consumer)
    m_channelListener = consumer;
  
  if (aURL)
  {
    m_runningUrl = do_QueryInterface(aURL);
    if (m_runningUrl)
    {
      // find out from the url what action we are supposed to perform...
      rv = m_runningUrl->GetMailboxAction(&m_mailboxAction);
      
      bool convertData = false;

      // need to check if we're fetching an rfc822 part in order to
      // quote a message.
      if (m_mailboxAction == nsIMailboxUrl::ActionFetchMessage)
      {
        nsCOMPtr<nsIMsgMailNewsUrl> msgUrl = do_QueryInterface(m_runningUrl, &rv);
        NS_ENSURE_SUCCESS(rv,rv);

        nsAutoCString queryStr;
        rv = msgUrl->GetQuery(queryStr);
        NS_ENSURE_SUCCESS(rv,rv);

        // check if this is a filter plugin requesting the message.
        // in that case, set up a text converter
        convertData = (queryStr.Find("header=filter") != -1 ||
                       queryStr.Find("header=attach") != -1);
      }
      else if (m_mailboxAction == nsIMailboxUrl::ActionFetchPart)
      {
        // when fetching a part, we need to insert a converter into the listener chain order to
        // force just the part out of the message. Our channel listener is the consumer we'll
        // pass in to AsyncConvertData.
        convertData = true;
        consumer = m_channelListener;
      }
      if (convertData)
      {
          nsCOMPtr<nsIStreamConverterService> streamConverter = do_GetService("@mozilla.org/streamConverters;1", &rv);
          NS_ENSURE_SUCCESS(rv, rv);
          nsCOMPtr <nsIStreamListener> conversionListener;
          nsCOMPtr<nsIChannel> channel;
          QueryInterface(NS_GET_IID(nsIChannel), getter_AddRefs(channel));

          rv = streamConverter->AsyncConvertData("message/rfc822",
                                                 "*/*",
                                                 consumer, channel, getter_AddRefs(m_channelListener));
      }
      
      if (NS_SUCCEEDED(rv))
      {
        switch (m_mailboxAction)
        {
        case nsIMailboxUrl::ActionParseMailbox:
          // extract the mailbox parser..
          rv = m_runningUrl->GetMailboxParser(getter_AddRefs(m_mailboxParser));
          m_nextState = MAILBOX_READ_FOLDER;
          break;
        case nsIMailboxUrl::ActionSaveMessageToDisk:
          // ohhh, display message already writes a msg to disk (as part of a hack)
          // so we can piggy back off of that!! We just need to change m_tempMessageFile
          // to be the name of our save message to disk file. Since save message to disk
          // urls are run without a docshell to display the msg into, we won't be trying
          // to display the message after we write it to disk...
          {
            nsCOMPtr<nsIMsgMessageUrl> messageUrl = do_QueryInterface(m_runningUrl, &rv);
            if (NS_SUCCEEDED(rv))
            {
              messageUrl->GetMessageFile(getter_AddRefs(m_tempMessageFile));
              rv = MsgNewBufferedFileOutputStream(getter_AddRefs(m_msgFileOutputStream), m_tempMessageFile, -1, 00600);
              NS_ENSURE_SUCCESS(rv, rv);

              bool addDummyEnvelope = false;
              messageUrl->GetAddDummyEnvelope(&addDummyEnvelope);
              if (addDummyEnvelope)
                SetFlag(MAILBOX_MSG_PARSE_FIRST_LINE);
              else
                ClearFlag(MAILBOX_MSG_PARSE_FIRST_LINE);
            }
          }
          m_nextState = MAILBOX_READ_MESSAGE;
          break;
        case nsIMailboxUrl::ActionCopyMessage:
        case nsIMailboxUrl::ActionMoveMessage:
        case nsIMailboxUrl::ActionFetchMessage:
          ClearFlag(MAILBOX_MSG_PARSE_FIRST_LINE);
          m_nextState = MAILBOX_READ_MESSAGE;
          break;
        case nsIMailboxUrl::ActionFetchPart:
            m_nextState = MAILBOX_READ_MESSAGE;
            break;
        default:
          break;
        }
      }
      
      rv = nsMsgProtocol::LoadUrl(aURL, m_channelListener);
      
    } // if we received an MAILBOX url...
  } // if we received a url!
  
  return rv;
}