nsresult
sbLocalDatabaseLibraryFactory::SetQueryDatabaseFile
                                 (sbIDatabaseQuery* aQuery,
                                  nsIFile*          aDatabaseFile)
{
  NS_ENSURE_ARG_POINTER(aQuery);
  NS_ENSURE_ARG_POINTER(aDatabaseFile);

  nsresult rv;

  nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Figure out a GUID based on the filename. All our database files use the
  // '.db' extension, so if someone requests another extension then that's just
  // too bad.
  nsCOMPtr<nsIURI> fileURI;
  rv = NS_NewFileURI(getter_AddRefs(fileURI), aDatabaseFile, ioService);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURL> fileURL = do_QueryInterface(fileURI, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString fileBaseName;
  rv = fileURL->GetFileBaseName(fileBaseName);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aQuery->SetDatabaseGUID(NS_ConvertUTF8toUTF16(fileBaseName));
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef DEBUG
  // Warn anyone if they passed in an extension other than '.db'.
  nsCAutoString fileExtension;
  rv = fileURL->GetFileExtension(fileExtension);
  if (NS_SUCCEEDED(rv)) {
    if (!fileExtension.IsEmpty() &&
        !fileExtension.Equals("db", CaseInsensitiveCompare)) {
      NS_WARNING("All database files are forced to use the '.db' extension.");
    }
  }
#endif
  // Set the parent directory as the location for the library database file.
  nsCOMPtr<nsIFile> parentDirectory;
  rv = aDatabaseFile->GetParent(getter_AddRefs(parentDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> parentURI;
  rv = NS_NewFileURI(getter_AddRefs(parentURI), parentDirectory, ioService);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aQuery->SetDatabaseLocation(parentURI);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Пример #2
0
NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias)
{
    if (NS_IsMozAliasSound(aSoundAlias)) {
      NS_WARNING("nsISound::playSystemSound is called with \"_moz_\" events, they are obsolete, use nsISound::playEventSound instead");
      if (aSoundAlias.Equals(NS_SYSSOUND_MAIL_BEEP))
        return Beep();
      return NS_OK;
    }

    nsresult rv;
    nsCOMPtr <nsIURI> fileURI;

    // create a nsILocalFile and then a nsIFileURL from that
    nsCOMPtr <nsILocalFile> soundFile;
    rv = NS_NewLocalFile(aSoundAlias, PR_TRUE, 
                         getter_AddRefs(soundFile));
    NS_ENSURE_SUCCESS(rv,rv);

    rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = Play(fileURL);
    return rv;

}
Пример #3
0
NS_IMETHODIMP nsSound::PlaySystemSound(const char *aSoundAlias)
{
    if (!aSoundAlias)
        return NS_ERROR_FAILURE;

    if (strcmp(aSoundAlias, "_moz_mailbeep") == 0) {
        return Beep();
    }

    nsresult rv;
    nsCOMPtr <nsIURI> fileURI;

    // create a nsILocalFile and then a nsIFileURL from that
    nsCOMPtr <nsILocalFile> soundFile;
    rv = NS_NewNativeLocalFile(nsDependentCString(aSoundAlias), PR_TRUE, 
                               getter_AddRefs(soundFile));
    NS_ENSURE_SUCCESS(rv,rv);

    rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = Play(fileURL);

    return rv;
}
Пример #4
0
nsresult
nsMsgAttachmentHandler::ConvertToZipFile(nsILocalFileMac *aSourceFile)
{
  // append ".zip" to the real file name
  nsCAutoString zippedName;
  nsresult rv = aSourceFile->GetNativeLeafName(zippedName);
  NS_ENSURE_SUCCESS(rv, rv);
  zippedName.AppendLiteral(".zip");

  // create a temporary file that we'll work on
  nsCOMPtr <nsIFile> tmpFile;
  rv = nsMsgCreateTempFile(zippedName.get(), getter_AddRefs(tmpFile));
  NS_ENSURE_SUCCESS(rv, rv);
  mEncodedWorkingFile = do_QueryInterface(tmpFile);

  // point our URL at the zipped temp file
  NS_NewFileURI(getter_AddRefs(mURL), mEncodedWorkingFile);

  // zip it!
  rv = nsSimpleZipper::Zip(aSourceFile, mEncodedWorkingFile);
  NS_ENSURE_SUCCESS(rv, rv);

  // set some metadata for this attachment, that will affect the MIME headers.
  m_type = APPLICATION_ZIP;
  m_realName = zippedName.get();

  return NS_OK;
}
Пример #5
0
nsFileChannel::nsFileChannel(nsIURI *uri) 
{
  // If we have a link file, we should resolve its target right away.
  // This is to protect against a same origin attack where the same link file
  // can point to different resources right after the first resource is loaded.
  nsCOMPtr<nsIFile> file;
  nsCOMPtr <nsIURI> targetURI;
  nsAutoCString fileTarget;
  nsCOMPtr<nsIFile> resolvedFile;
  bool symLink;
  nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(uri);
  if (fileURL && 
      NS_SUCCEEDED(fileURL->GetFile(getter_AddRefs(file))) &&
      NS_SUCCEEDED(file->IsSymlink(&symLink)) && 
      symLink &&
      NS_SUCCEEDED(file->GetNativeTarget(fileTarget)) &&
      NS_SUCCEEDED(NS_NewNativeLocalFile(fileTarget, PR_TRUE, 
                                         getter_AddRefs(resolvedFile))) &&
      NS_SUCCEEDED(NS_NewFileURI(getter_AddRefs(targetURI), 
                   resolvedFile, nullptr))) {
    SetURI(targetURI);
    SetOriginalURI(uri);
    nsLoadFlags loadFlags = 0;
    GetLoadFlags(&loadFlags);
    SetLoadFlags(loadFlags | nsIChannel::LOAD_REPLACE);
  } else {
    SetURI(uri);
  }
}
NS_IMETHODIMP
nsMIMEInfoAndroid::LaunchWithFile(nsIFile *aFile)
{
  nsIURI* uri;
  NS_NewFileURI(&uri, aFile);
  LoadUriInternal(uri);
  return NS_OK;
}
Пример #7
0
NS_IMETHODIMP
nsMIMEInfoAndroid::LaunchWithFile(nsIFile *aFile)
{
  nsCOMPtr<nsIURI> uri;
  NS_NewFileURI(getter_AddRefs(uri), aFile);
  LoadUriInternal(uri);
  return NS_OK;
}
Пример #8
0
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::GetFileURL(nsIURI **aFileURL)
{
  *aFileURL = nsnull;
  nsCOMPtr<nsILocalFile> file;
  nsresult rv = GetFile(getter_AddRefs(file));
  if (!file)
    return rv;

  return NS_NewFileURI(aFileURL, file);
}
Пример #9
0
/* readonly attribute nsIFileURL fileURL; */
NS_IMETHODIMP
nsFilePicker::GetFileURL(nsIFileURL * *aFileURL)
{
    nsCOMPtr<nsILocalFile> file;
    GetFile(getter_AddRefs(file));

    nsCOMPtr<nsIURI> uri;
    NS_NewFileURI(getter_AddRefs(uri), file);
    NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);

    return CallQueryInterface(uri, aFileURL);
}
Пример #10
0
void	
MacGetFileType(nsIFile   *fs, 
               bool         *useDefault, 
               char         **fileType, 
               char         **encoding)
{
	if ((fs == NULL) || (fileType == NULL) || (encoding == NULL))
		return;

  bool exists = false;
  fs->Exists(&exists);
  if (!exists)
    return;

	*useDefault = TRUE;
	*fileType = NULL;
	*encoding = NULL;

  nsCOMPtr<nsILocalFileMac> macFile = do_QueryInterface(fs);
  FSRef fsRef;
  FSCatalogInfo catalogInfo;
  OSErr err = errFileOpen;
  if (NS_SUCCEEDED(macFile->GetFSRef(&fsRef)))
    err = ::FSGetCatalogInfo(&fsRef, kFSCatInfoFinderInfo, &catalogInfo, nullptr, nullptr, nullptr);

  if ( (err != noErr) || (((FileInfo*)(&catalogInfo.finderInfo))->fileType == 'TEXT') )
    *fileType = strdup(APPLICATION_OCTET_STREAM);
  else
  {
    // At this point, we should call the mime service and
    // see what we can find out?
    nsresult      rv;
    nsCOMPtr <nsIURI> tURI;
    if (NS_SUCCEEDED(NS_NewFileURI(getter_AddRefs(tURI), fs)) && tURI)
    {
      nsCOMPtr<nsIMIMEService> mimeFinder (do_GetService(NS_MIMESERVICE_CONTRACTID, &rv));
      if (NS_SUCCEEDED(rv) && mimeFinder) 
      {
        nsCAutoString mimeType;
        rv = mimeFinder->GetTypeFromURI(tURI, mimeType);
        if (NS_SUCCEEDED(rv)) 
        {
          *fileType = ToNewCString(mimeType);
          return;
        }        
      }
    }

    // If we hit here, return something...default to this...
    *fileType = strdup(APPLICATION_OCTET_STREAM);
  }
}
void
nsLayoutStylesheetCache::LoadSheetFile(nsIFile* aFile, nsRefPtr<nsCSSStyleSheet> &aSheet)
{
  bool exists = false;
  aFile->Exists(&exists);

  if (!exists) return;

  nsCOMPtr<nsIURI> uri;
  NS_NewFileURI(getter_AddRefs(uri), aFile);

  LoadSheet(uri, aSheet, false);
}
Пример #12
0
nsresult
LocalStoreImpl::LoadData()
{
    nsresult rv;

    // Look for localstore.rdf in the current profile
    // directory. Bomb if we can't find it.

    nsCOMPtr<nsIFile> aFile;
    rv = NS_GetSpecialDirectory(NS_APP_LOCALSTORE_50_FILE, getter_AddRefs(aFile));
    if (NS_FAILED(rv)) return rv;

    bool fileExistsFlag = false;
    (void)aFile->Exists(&fileExistsFlag);
    if (!fileExistsFlag) {
        // if file doesn't exist, create it
        rv = CreateLocalStore(aFile);
        if (NS_FAILED(rv)) return rv;
    }

    mInner = do_CreateInstance(NS_RDF_DATASOURCE_CONTRACTID_PREFIX "xml-datasource", &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIRDFRemoteDataSource> remote = do_QueryInterface(mInner, &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIURI> aURI;
    rv = NS_NewFileURI(getter_AddRefs(aURI), aFile);
    if (NS_FAILED(rv)) return rv;

    nsCAutoString spec;
    rv = aURI->GetSpec(spec);
    if (NS_FAILED(rv)) return rv;

    rv = remote->Init(spec.get());
    if (NS_FAILED(rv)) return rv;

    // Read the datasource synchronously.
    rv = remote->Refresh(true);
    
    if (NS_FAILED(rv)) {
        // Load failed, delete and recreate a fresh localstore
        aFile->Remove(true);
        rv = CreateLocalStore(aFile);
        if (NS_FAILED(rv)) return rv;
        
        rv = remote->Refresh(true);
    }

    return rv;
}
Пример #13
0
nsMsgAttachedFile * nsEudoraCompose::GetLocalAttachments( void)
{
  /*
  nsIURI      *url = nsnull;
  */

  PRInt32 count = 0;
  if (m_pAttachments)
    count = m_pAttachments->Count();
  if (!count)
    return( nsnull);

  nsMsgAttachedFile *a = (nsMsgAttachedFile *) new nsMsgAttachedFile[count + 1];
  if (!a)
    return( nsnull);
  memset(a, 0, sizeof(nsMsgAttachedFile) * (count + 1));

  nsCString urlStr;
  ImportAttachment * pAttach;

  for (PRInt32 i = 0; i < count; i++) {
    // nsMsgNewURL(&url, "file://C:/boxster.jpg");
    // a[i].orig_url = url;

    // NS_PRECONDITION( PR_FALSE, "Forced Break");

    pAttach = (ImportAttachment *) m_pAttachments->ElementAt( i);
                a[i].tmp_file = do_QueryInterface(pAttach->pAttachment);
    urlStr.Adopt(0);

    nsCOMPtr <nsIURI> uri;
    nsresult rv = NS_NewFileURI(getter_AddRefs(uri), pAttach->pAttachment);
    NS_ENSURE_SUCCESS(rv, nsnull);
    uri->GetSpec(urlStr);
    if (urlStr.IsEmpty()) {
      CleanUpAttach( a, count);
      return( nsnull);
    }
    rv = m_pIOService->NewURI( urlStr, nsnull, nsnull, getter_AddRefs(a[i].orig_url));
    if (NS_FAILED( rv)) {
      CleanUpAttach( a, count);
      return( nsnull);
    }

    a[i].type = strdup( pAttach->mimeType);
    a[i].real_name = strdup( pAttach->description);
    a[i].encoding = strdup( ENCODING_BINARY);
  }

  return( a);
}
Пример #14
0
static already_AddRefed<nsIURI>
FileToURI(const char *aFilename, nsresult *aRv = 0)
{
    nsCOMPtr<nsIFile> lf(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, aRv));
    NS_ENSURE_TRUE(lf, nullptr);
    // XXX Handle relative paths somehow.
    lf->InitWithNativePath(nsDependentCString(aFilename));

    nsIURI *uri = nullptr;
    nsresult rv = NS_NewFileURI(&uri, lf);
    if (aRv)
        *aRv = rv;
    return uri;
}
Пример #15
0
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::GetFileURL(nsIFileURL **aFileURL)
{
    nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
    NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);
    file->InitWithNativePath(mFile);

    nsCOMPtr<nsIURI> uri;
    NS_NewFileURI(getter_AddRefs(uri), file);
    nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(uri));
    NS_ENSURE_TRUE(fileURL, NS_ERROR_FAILURE);

    NS_ADDREF(*aFileURL = fileURL);

    return NS_OK;
}
nsresult
sbLocalDatabaseLibraryFactory::UpdateLibrary(nsIFile* aDatabaseFile)
{
  nsresult rv;
  PRInt32 dbOk;

  nsCOMPtr<sbIDatabaseQuery> query =
    do_CreateInstance(SONGBIRD_DATABASEQUERY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->SetAsyncQuery(PR_FALSE);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SetQueryDatabaseFile(query, aDatabaseFile);
  NS_ENSURE_SUCCESS(rv, rv);

  // Update some library media item properties
  nsCOMPtr<sbISQLUpdateBuilder> update =
    do_CreateInstance(SB_SQLBUILDER_UPDATE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = update->SetTableName(NS_LITERAL_STRING("library_media_item"));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> fileURI;
  rv = NS_NewFileURI(getter_AddRefs(fileURI), aDatabaseFile);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString uriSpec;
  rv = fileURI->GetSpec(uriSpec);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = update->AddAssignmentString(NS_LITERAL_STRING("content_url"),
                                   NS_ConvertUTF8toUTF16(uriSpec));
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoString sql;
  rv = update->ToString(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->AddQuery(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->Execute(&dbOk);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE);

  return NS_OK;
}
void
nsFileDataProtocolHandler::AddFileDataEntry(nsACString& aUri, nsIFile* aFile,
                                            nsIPrincipal* aPrincipal)
{
  if (!gFileDataTable) {
    gFileDataTable = new nsClassHashtable<nsCStringHashKey, FileDataInfo>;
    gFileDataTable->Init();
  }

  FileDataInfo* info = new FileDataInfo;

  NS_NewFileURI(getter_AddRefs(info->mFileUri), aFile);
  info->mPrincipal = aPrincipal;

  gFileDataTable->Put(aUri, info);
}
Пример #18
0
nsresult nsEudoraCompose::GetLocalAttachments(nsIArray **aArray)
{
  /*
  nsIURI      *url = nullptr;
  */
  nsresult rv;
  nsCOMPtr<nsIMutableArray> attachments (do_CreateInstance(NS_ARRAY_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_IF_ADDREF(*aArray = attachments);
  int32_t count = 0;
  if (m_pAttachments)
    count = m_pAttachments->Length();
  if (!count)
    return NS_OK;

  nsCString urlStr;
  ImportAttachment * pAttach;

  for (int32_t i = 0; i < count; i++) {
    nsCOMPtr<nsIMsgAttachedFile> a(do_CreateInstance(NS_MSGATTACHEDFILE_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    // nsMsgNewURL(&url, "file://C:/boxster.jpg");
    // a[i].orig_url = url;

    pAttach = m_pAttachments->ElementAt(i);
    nsCOMPtr<nsIFile> tmpFile = do_QueryInterface(pAttach->pAttachment);
    a->SetTmpFile(tmpFile);
    urlStr.Adopt(0);

    nsCOMPtr <nsIURI> uri;
    nsresult rv = NS_NewFileURI(getter_AddRefs(uri), pAttach->pAttachment);
    NS_ENSURE_SUCCESS(rv, rv);
    uri->GetSpec(urlStr);
    if (urlStr.IsEmpty())
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsIURI> origUrl;
    rv = m_pIOService->NewURI(urlStr, nullptr, nullptr, getter_AddRefs(origUrl));
    NS_ENSURE_SUCCESS(rv, rv);
    a->SetOrigUrl(origUrl);
    a->SetType(nsDependentCString(pAttach->mimeType));
    a->SetRealName(nsDependentCString(pAttach->description));
    a->SetEncoding(NS_LITERAL_CSTRING(ENCODING_BINARY));
    attachments->AppendElement(a, false);
  }
  return NS_OK;
}
nsresult
nsNetscapeProfileMigratorBase::LocateSignonsFile(char** aResult)
{
  nsCOMPtr<nsISimpleEnumerator> entries;
  nsresult rv = mSourceProfile->GetDirectoryEntries(getter_AddRefs(entries));
  if (NS_FAILED(rv)) return rv;

  nsCAutoString fileName;
  do {
    bool hasMore = false;
    rv = entries->HasMoreElements(&hasMore);
    if (NS_FAILED(rv) || !hasMore) break;

    nsCOMPtr<nsISupports> supp;
    rv = entries->GetNext(getter_AddRefs(supp));
    if (NS_FAILED(rv)) break;

    nsCOMPtr<nsIFile> currFile(do_QueryInterface(supp));

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewFileURI(getter_AddRefs(uri), currFile);
    if (NS_FAILED(rv)) break;
    nsCOMPtr<nsIURL> url(do_QueryInterface(uri));

    nsCAutoString extn;
    url->GetFileExtension(extn);

#ifdef MOZILLA_INTERNAL_API
    if (extn.EqualsIgnoreCase("s")) {
      url->GetFileName(fileName);
      break;
    }
#else
    if (extn.Equals("s", CaseInsensitiveCompare)) {
      url->GetFileName(fileName);
      break;
    }
#endif
  }
  while (1);

  *aResult = ToNewCString(fileName);

  return NS_OK;
}
Пример #20
0
NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias)
{//printf("%s\n", __PRETTY_FUNCTION__);

//	const char *str = NS_LossyConvertUTF16toASCII(aSoundAlias).get();
//	printf("PlaySystemSound %s", str);


	if (NS_IsMozAliasSound(aSoundAlias)) {
		NS_WARNING("nsISound::playSystemSound is called with \"_moz_\" events, they are obsolete, use nsISound::playEventSound instead");
		PRUint32 eventId;
		if (aSoundAlias.Equals(NS_SYSSOUND_ALERT_DIALOG))
			eventId = EVENT_ALERT_DIALOG_OPEN;
		else if (aSoundAlias.Equals(NS_SYSSOUND_CONFIRM_DIALOG))
			eventId = EVENT_CONFIRM_DIALOG_OPEN;
		else if (aSoundAlias.Equals(NS_SYSSOUND_MAIL_BEEP))
			eventId = EVENT_NEW_MAIL_RECEIVED;
		else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_EXECUTE))
			eventId = EVENT_MENU_EXECUTE;
		else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_POPUP))
			eventId = EVENT_MENU_POPUP;
		else
			return NS_OK;
		return PlayEventSound(eventId);
	}

	nsresult rv;
	nsCOMPtr <nsIURI> fileURI;

	// create a nsILocalFile and then a nsIFileURL from that
	nsCOMPtr <nsILocalFile> soundFile;
	rv = NS_NewLocalFile(aSoundAlias, PR_TRUE,
			getter_AddRefs(soundFile));
	NS_ENSURE_SUCCESS(rv,rv);

	rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile);
	NS_ENSURE_SUCCESS(rv,rv);

	nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv);
	NS_ENSURE_SUCCESS(rv,rv);

	rv = Play(fileURL);

	return rv;
}
Пример #21
0
NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias)
{
    if (NS_IsMozAliasSound(aSoundAlias)) {
        NS_WARNING("nsISound::playSystemSound is called with \"_moz_\" events, they are obsolete, use nsISound::playEventSound instead");
        uint32_t eventId;
        if (aSoundAlias.Equals(NS_SYSSOUND_ALERT_DIALOG))
            eventId = EVENT_ALERT_DIALOG_OPEN;
        else if (aSoundAlias.Equals(NS_SYSSOUND_CONFIRM_DIALOG))
            eventId = EVENT_CONFIRM_DIALOG_OPEN;
        else if (aSoundAlias.Equals(NS_SYSSOUND_MAIL_BEEP))
            eventId = EVENT_NEW_MAIL_RECEIVED;
        else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_EXECUTE))
            eventId = EVENT_MENU_EXECUTE;
        else if (aSoundAlias.Equals(NS_SYSSOUND_MENU_POPUP))
            eventId = EVENT_MENU_POPUP;
        else
            return NS_OK;
        return PlayEventSound(eventId);
    }

    nsresult rv;
    nsCOMPtr <nsIURI> fileURI;

    // create a nsIFile and then a nsIFileURL from that
    nsCOMPtr <nsIFile> soundFile;
    rv = NS_NewLocalFile(aSoundAlias, true, 
                         getter_AddRefs(soundFile));
    NS_ENSURE_SUCCESS(rv,rv);

    rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = Play(fileURL);

    return rv;
}
nsresult
sbLocalDatabaseLibraryFactory::CreateLibraryFromDatabase(nsIFile* aDatabase,
                                                         sbILibrary** _retval,
                                                         nsIPropertyBag2* aCreationParameters,
                                                         nsString aResourceGUID /* = EmptyString() */)
{
  NS_ENSURE_ARG_POINTER(aDatabase);
  NS_ENSURE_ARG_POINTER(_retval);

  nsresult rv;

  // Get a unique value for this database file.
  nsCOMPtr<nsIHashable> hashable = do_QueryInterface(aDatabase, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // We have to copy the file name escaping logic from when we actually create
  // the database, otherwise we end up re-initizliaing the database over and over.
  nsCOMPtr<nsIIOService> ioService = do_GetIOService(&rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> databaseURI;
  rv = NS_NewFileURI(getter_AddRefs(databaseURI), aDatabase, ioService);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURL> databaseURL = do_QueryInterface(databaseURI, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString utf8GUID;
  rv = databaseURL->GetFileBaseName(utf8GUID);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIFile> databaseParent;
  rv = aDatabase->GetParent(getter_AddRefs(databaseParent));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString fileName;
  rv = databaseURL->GetFileName(fileName);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIFile> escapedFile;
  rv = databaseParent->Clone(getter_AddRefs(escapedFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = escapedFile->Append(NS_ConvertUTF8toUTF16(fileName));
  NS_ENSURE_SUCCESS(rv, rv);

  // On Windows, if the file does not exist, its hashcode is different from when it does.
  // If we ever attempt to get the hash code while it doesn't exist, the
  // nsLocalFile caches the hash code and stays incorrect.
  PRBool exists;
  rv = escapedFile->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  // See if we've already created this library. If we have (and it is still
  // alive) just return it.
  nsCOMPtr<nsIWeakReference> weakRef;
  if (exists && mCreatedLibraries.Get(hashable, getter_AddRefs(weakRef))) {
    nsCOMPtr<sbILibrary> existingLibrary = do_QueryReferent(weakRef, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    if (existingLibrary) {
      existingLibrary.swap(*_retval);
      return NS_OK;
    }

    mCreatedLibraries.Remove(hashable);
  }

  // If the database file does not exist, create and initalize it.  Otherwise,
  // update it.
  if (!exists) {
    rv = InitalizeLibrary(aDatabase, aResourceGUID);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  else {
    rv = UpdateLibrary(aDatabase);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCOMPtr<nsIURI> databaseLocation;
  rv = NS_NewFileURI(getter_AddRefs(databaseLocation), databaseParent,
                     ioService);
  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<sbLocalDatabaseLibrary> library(new sbLocalDatabaseLibrary());
  NS_ENSURE_TRUE(library, NS_ERROR_OUT_OF_MEMORY);

  nsCOMPtr<nsIPropertyBag2> creationParams = aCreationParameters;
  if (!creationParams) {
    nsCOMPtr<nsIWritablePropertyBag2> bag =
      do_CreateInstance(SB_PROPERTYBAG_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = bag->SetPropertyAsInterface(NS_LITERAL_STRING(PROPERTY_KEY_DATABASEFILE),
                                     aDatabase);
    NS_ENSURE_SUCCESS(rv, rv);

    creationParams = do_QueryInterface(bag, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = library->Init(NS_ConvertUTF8toUTF16(utf8GUID), creationParams, this,
                     databaseLocation);
  NS_ENSURE_SUCCESS(rv, rv);

  // Add this library to our table of created libraries.
  weakRef = do_GetWeakReference(NS_ISUPPORTS_CAST(sbILibrary*, library),
                                &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool success = mCreatedLibraries.Put(hashable, weakRef);
  NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);

  NS_ADDREF(*_retval = library);
  return NS_OK;
}
nsresult
sbLocalDatabaseLibraryFactory::InitalizeLibrary(nsIFile* aDatabaseFile,
                                                const nsAString &aResourceGUID)
{
  nsresult rv;
  PRInt32 dbOk;

  nsCOMPtr<nsIFile> parentDirectory;
  rv = aDatabaseFile->GetParent(getter_AddRefs(parentDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool parentExists;
  rv = parentDirectory->Exists(&parentExists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!parentExists) {
    rv = CreateDirectory(parentDirectory);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  PRBool parentIsWritable = IsDirectoryWritable(parentDirectory);
  NS_ENSURE_TRUE(parentIsWritable, NS_ERROR_FILE_ACCESS_DENIED);

  // Now that we know we have appropriate permissions make a new query.
  nsCOMPtr<sbIDatabaseQuery> query =
    do_CreateInstance(SONGBIRD_DATABASEQUERY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->SetAsyncQuery(PR_FALSE);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SetQueryDatabaseFile(query, aDatabaseFile);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> schemaURI;
  rv = NS_NewURI(getter_AddRefs(schemaURI), NS_LITERAL_CSTRING(SCHEMA_URL));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInputStream> input;
  rv = NS_OpenURI(getter_AddRefs(input), schemaURI);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIConverterInputStream> converterStream =
    do_CreateInstance("@mozilla.org/intl/converter-input-stream;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = converterStream->Init(input,
                             "UTF-8",
                             CONVERTER_BUFFER_SIZE,
                             nsIConverterInputStream::
                               DEFAULT_REPLACEMENT_CHARACTER);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIUnicharInputStream> unichar =
    do_QueryInterface(converterStream, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 read;
  nsString response, result;
  rv = unichar->ReadString(PR_UINT32_MAX, result, &read);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ASSERTION(read, "Schema file zero bytes?");
  while (read > 0) {
    response.Append(result);
    rv = unichar->ReadString(PR_UINT32_MAX, result, &read);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = unichar->Close();
  NS_ENSURE_SUCCESS(rv, rv);

  NS_NAMED_LITERAL_STRING(colonNewline, ";\n");
  PRInt32 posStart = 0;
  PRInt32 posEnd = response.Find(colonNewline, posStart);
  while (posEnd >= 0) {
    rv = query->AddQuery(Substring(response, posStart, posEnd - posStart));
    NS_ENSURE_SUCCESS(rv, rv);
    posStart = posEnd + 2;
    posEnd = response.Find(colonNewline, posStart);
  }

  rv = query->Execute(&dbOk);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE);

  nsString guid(aResourceGUID);
  if(guid.IsEmpty()) {
    // Create a resource guid for this database.
    nsCOMPtr<nsIUUIDGenerator> uuidGen =
      do_GetService("@mozilla.org/uuid-generator;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsID id;
    rv = uuidGen->GenerateUUIDInPlace(&id);
    NS_ENSURE_SUCCESS(rv, rv);

    char guidChars[NSID_LENGTH];
    id.ToProvidedString(guidChars);

    guid = NS_ConvertASCIItoUTF16(nsDependentCString(guidChars + 1,
                                                     NSID_LENGTH - 3));
  }

  // Insert the guid into the database.
  nsCOMPtr<sbISQLInsertBuilder> insert =
    do_CreateInstance(SB_SQLBUILDER_INSERT_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->SetIntoTableName(NS_LITERAL_STRING("library_metadata"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("name"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("value"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(NS_LITERAL_STRING("resource-guid"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(guid);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoString sql;
  rv = insert->ToString(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->ResetQuery();
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->AddQuery(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->Execute(&dbOk);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE);

  nsString now;
  sbLocalDatabaseLibrary::GetNowString(now);

  nsCOMPtr<nsIURI> fileURI;
  rv = NS_NewFileURI(getter_AddRefs(fileURI), aDatabaseFile);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString uriSpec;
  rv = fileURI->GetSpec(uriSpec);
  NS_ENSURE_SUCCESS(rv, rv);

  // Add the default library media item properties
  insert = do_CreateInstance(SB_SQLBUILDER_INSERT_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->SetIntoTableName(NS_LITERAL_STRING("library_media_item"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("guid"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(guid);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("created"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(now);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("updated"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(now);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("content_url"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueString(NS_ConvertUTF8toUTF16(uriSpec));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("hidden"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueLong(0);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddColumn(NS_LITERAL_STRING("is_list"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->AddValueLong(0);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = insert->ToString(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->ResetQuery();
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->AddQuery(sql);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = query->Execute(&dbOk);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(dbOk == 0, NS_ERROR_FAILURE);

  return NS_OK;
}
Пример #24
0
nsresult
nsMsgAttachmentHandler::ConvertToAppleEncoding(const nsCString &aFileURI, 
                                               const nsCString &aFilePath, 
                                               nsILocalFileMac *aSourceFile)
{
  // convert the apple file to AppleDouble first, and then patch the
  // address in the url.
  
  //We need to retrieve the file type and creator...

  char fileInfo[32];
  OSType type, creator;

  nsresult rv = aSourceFile->GetFileType(&type);
  if (NS_FAILED(rv))
    return false;
  PR_snprintf(fileInfo, sizeof(fileInfo), "%X", type);
  m_xMacType = fileInfo;

  rv = aSourceFile->GetFileCreator(&creator);
  if (NS_FAILED(rv))
    return false;
  PR_snprintf(fileInfo, sizeof(fileInfo), "%X", creator);
  m_xMacCreator = fileInfo;

  FSRef fsRef;
  aSourceFile->GetFSRef(&fsRef);
  bool sendResourceFork = HasResourceFork(&fsRef);

  // if we have a resource fork, check the filename extension, maybe we don't need the resource fork!
  if (sendResourceFork)
  {
    nsCOMPtr<nsIURL> fileUrl(do_CreateInstance(NS_STANDARDURL_CONTRACTID));
    if (fileUrl)
    {
      rv = fileUrl->SetSpec(aFileURI);
      if (NS_SUCCEEDED(rv))
      {
        nsCAutoString ext;
        rv = fileUrl->GetFileExtension(ext);
        if (NS_SUCCEEDED(rv) && !ext.IsEmpty())
        {
          sendResourceFork =
          PL_strcasecmp(ext.get(), "TXT") &&
          PL_strcasecmp(ext.get(), "JPG") &&
          PL_strcasecmp(ext.get(), "GIF") &&
          PL_strcasecmp(ext.get(), "TIF") &&
          PL_strcasecmp(ext.get(), "HTM") &&
          PL_strcasecmp(ext.get(), "HTML") &&
          PL_strcasecmp(ext.get(), "ART") &&
          PL_strcasecmp(ext.get(), "XUL") &&
          PL_strcasecmp(ext.get(), "XML") &&
          PL_strcasecmp(ext.get(), "CSS") &&
          PL_strcasecmp(ext.get(), "JS");
        }
      }
    }
  }

  // Only use appledouble if we aren't uuencoding.
  if( sendResourceFork )
  {
    char *separator;

    separator = mime_make_separator("ad");
    if (!separator)
      return NS_ERROR_OUT_OF_MEMORY;

    nsCOMPtr <nsIFile> tmpFile;
    nsresult rv = nsMsgCreateTempFile("appledouble", getter_AddRefs(tmpFile));
    if (NS_SUCCEEDED(rv))
      mEncodedWorkingFile = do_QueryInterface(tmpFile);
    if (!mEncodedWorkingFile)
    {
      PR_FREEIF(separator);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    //
    // RICHIE_MAC - ok, here's the deal, we have a file that we need
    // to encode in appledouble encoding for the resource fork and put that
    // into the mEncodedWorkingFile location. Then, we need to patch the new file
    // spec into the array and send this as part of the 2 part appledouble/mime
    // encoded mime part.
    //
    AppleDoubleEncodeObject     *obj = new (AppleDoubleEncodeObject);
    if (obj == NULL)
    {
      mEncodedWorkingFile = nsnull;
      PR_FREEIF(separator);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    rv = MsgGetFileStream(mEncodedWorkingFile, getter_AddRefs(obj->fileStream));
    if (NS_FAILED(rv) || !obj->fileStream)
    {
      PR_FREEIF(separator);
      delete obj;
      return NS_ERROR_OUT_OF_MEMORY;
    }

    PRInt32     bSize = AD_WORKING_BUFF_SIZE;

    char  *working_buff = nsnull;
    while (!working_buff && (bSize >= 512))
    {
      working_buff = (char *)PR_CALLOC(bSize);
      if (!working_buff)
        bSize /= 2;
    }

    if (!working_buff)
    {
      PR_FREEIF(separator);
      delete obj;
      return NS_ERROR_OUT_OF_MEMORY;
    }

    obj->buff = working_buff;
    obj->s_buff = bSize;

    //
    //  Setup all the need information on the apple double encoder.
    //
    ap_encode_init(&(obj->ap_encode_obj), aFilePath.get(), separator);

    PRInt32 count;

    nsresult status = noErr;
    m_size = 0;
    while (status == noErr)
    {
      status = ap_encode_next(&(obj->ap_encode_obj), obj->buff, bSize, &count);
      if (status == noErr || status == errDone)
      {
        //
        // we got the encode data, so call the next stream to write it to the disk.
        //
        PRUint32 bytesWritten;
        obj->fileStream->Write(obj->buff, count, &bytesWritten);
        if (bytesWritten != (PRUint32) count)
          status = NS_MSG_ERROR_WRITING_FILE;
      }
    }

    ap_encode_end(&(obj->ap_encode_obj), (status >= 0)); // if this is true, ok, false abort
    if (obj->fileStream)
      obj->fileStream->Close();

    PR_FREEIF(obj->buff);               /* free the working buff.   */
    PR_FREEIF(obj);

    nsCOMPtr <nsIURI> fileURI;
    NS_NewFileURI(getter_AddRefs(fileURI), mEncodedWorkingFile);

    nsCOMPtr<nsIFileURL> theFileURL = do_QueryInterface(fileURI, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    nsCString newURLSpec;
    NS_ENSURE_SUCCESS(rv, rv);
    fileURI->GetSpec(newURLSpec);

    if (newURLSpec.IsEmpty())
    {
      PR_FREEIF(separator);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    if (NS_FAILED(nsMsgNewURL(getter_AddRefs(mURL), newURLSpec.get())))
    {
      PR_FREEIF(separator);
      return NS_ERROR_OUT_OF_MEMORY;
    }

    // Now after conversion, also patch the types.
    char        tmp[128];
    PR_snprintf(tmp, sizeof(tmp), MULTIPART_APPLEDOUBLE ";\r\n boundary=\"%s\"", separator);
    PR_FREEIF(separator);
    m_type = tmp;
  }
  else
  {
    if ( sendResourceFork )
    {
      // For now, just do the encoding, but in the old world we would ask the
      // user about doing this conversion
      printf("...we could ask the user about this conversion, but for now, nahh..\n");
    }

    bool      useDefault;
    char      *macType, *macEncoding;
    if (m_type.IsEmpty() || m_type.LowerCaseEqualsLiteral(TEXT_PLAIN))
    {
# define TEXT_TYPE  0x54455854  /* the characters 'T' 'E' 'X' 'T' */
# define text_TYPE  0x74657874  /* the characters 't' 'e' 'x' 't' */

      if (type != TEXT_TYPE && type != text_TYPE)
      {
        MacGetFileType(aSourceFile, &useDefault, &macType, &macEncoding);
        m_type = macType;
      }
    }
    // don't bother to set the types if we failed in getting the file info.
  }

  return NS_OK;
}
nsresult nsEudoraEditor::GetEmbeddedObjects(nsIArray ** aNodeList)
{
  NS_ENSURE_ARG_POINTER(aNodeList);

  // Check to see if we were already called
  if (m_EmbeddedObjectList != nullptr)
  {
    *aNodeList = m_EmbeddedObjectList;
    return NS_OK;
  }

  // Create array in m_EmbeddedObjectList
  nsresult rv;
  m_EmbeddedObjectList = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Return m_EmbeddedObjectList in aNodeList and increment ref count - caller
  // assumes that we incremented the ref count.
  NS_IF_ADDREF(*aNodeList = m_EmbeddedObjectList);

  // Create the embedded folder spec
  nsCOMPtr<nsIFile>   embeddedFolderSpec;
  // Create the embedded image spec
  nsCOMPtr<nsIFile>   embeddedImageSpec;

  // Fill in the details for the embedded folder spec - "Embedded" folder
  // inside of the mail folder. We don't bother to check to see if the embedded
  // folder exists, because it seems to me that would only save time in the
  // unexpected case where it doesn't exist. Keep in mind that we will be checking
  // for the existence of any embedded images anyway - if the folder doesn't
  // exist that check will fail.
  rv = m_pMailImportLocation->Clone(getter_AddRefs(embeddedFolderSpec));
  NS_ENSURE_SUCCESS(rv, rv);
  embeddedFolderSpec->AppendNative(NS_LITERAL_CSTRING("Embedded"));

  // Look for the start of the last closing tag so that we only search for
  // valid "Embedded Content" lines. (In practice this is not super important,
  // but there were some proof of concept exploits at one point where "Embedded
  // Content" lines were faked in the body of messages).
  int32_t     startLastClosingTag = m_body.RFind("</");
  if (startLastClosingTag == kNotFound)
    startLastClosingTag = 0;
  bool        foundEmbeddedContentLines = false;

  // Search for various translations of "Embedded Content" - as of this writing only
  // one that I know of, but then again I didn't realize that Eudora translators had
  // ever translated "Attachment Converted" as suggested by other Eudora importing code.
  for (int32_t i = 0; *sEudoraEmbeddedContentLines[i] != '\0'; i++)
  {
    // Search for "Embedded Content: " lines starting after last closing tag (if any)
    int32_t   startEmbeddedContentLine = startLastClosingTag;
    int32_t   lenEmbeddedContentTag = strlen(sEudoraEmbeddedContentLines[i]);

    while ((startEmbeddedContentLine = m_body.Find(sEudoraEmbeddedContentLines[i],
                                                   true,
                                                   startEmbeddedContentLine+1)) != kNotFound)
    {
      // Found this translation of "Embedded Content" - remember that so that we don't
      // bother looking for any other translations.
      foundEmbeddedContentLines = true;

      // Extract the file name from the embedded content line
      int32_t   startFileName = startEmbeddedContentLine + lenEmbeddedContentTag;
      int32_t   endFileName = m_body.Find(":", false, startFileName);

      // Create the file spec for the embedded image
      embeddedFolderSpec->Clone(getter_AddRefs(embeddedImageSpec));
      embeddedImageSpec->Append(Substring(m_body, startFileName, endFileName - startFileName));

      // Verify that the embedded image spec exists and is a file
      bool      isFile = false;
      bool      exists = false;
      if (NS_FAILED(embeddedImageSpec->Exists(&exists)) || NS_FAILED(embeddedImageSpec->IsFile(&isFile)))
        continue;
      if (!exists || !isFile)
        continue;

      // Extract CID hash from the embedded content line
      int32_t     cidHashValue;
      int32_t     startCIDHash = m_body.Find(",", false, endFileName);
      if (startCIDHash != kNotFound)
      {
        startCIDHash++;
        int32_t   endCIDHash = m_body.Find(",", false, startCIDHash);

        if (endCIDHash != kNotFound)
        {
          nsString    cidHash;
          cidHash.Assign(Substring(m_body, startCIDHash, endCIDHash - startCIDHash));

          if (!cidHash.IsEmpty())
          {
            // Convert CID hash string to numeric value
            nsresult aErrorCode;
            cidHashValue = cidHash.ToInteger(&aErrorCode, 16);
          }
        }
      }

      // Get the URL for the embedded image
      nsCString     embeddedImageURL;
      rv = NS_GetURLSpecFromFile(embeddedImageSpec, embeddedImageURL);
      NS_ENSURE_SUCCESS(rv, rv);

      NS_ConvertASCIItoUTF16 srcUrl(embeddedImageURL);
      nsString cid;
      // We're going to remember the original cid in the image element,
      // which the send code will retrieve as the kMozCIDAttrName property.
      GetEmbeddedImageCID(cidHashValue, srcUrl, cid);
      nsCOMPtr<nsIURI> embeddedFileURI;
      NS_NewFileURI(getter_AddRefs(embeddedFileURI), embeddedImageSpec);

      // Create the embedded image node
      nsImportEmbeddedImageData *imageData =
        new nsImportEmbeddedImageData(embeddedFileURI, NS_LossyConvertUTF16toASCII(cid));

      // Append the embedded image node to the list
      m_EmbeddedObjectList->AppendElement(imageData, false);

      int32_t   endEmbeddedContentLine = m_body.Find("\r\n", true, startEmbeddedContentLine+1);
      if (endEmbeddedContentLine != kNotFound)
      {
        // We recognized the "Embedded Content" line correctly and found the associated image.
        // Remove the Eudora specific line about it now.
        m_body.Cut(startEmbeddedContentLine, endEmbeddedContentLine - startEmbeddedContentLine + 2);

        // Backup by one to correct where we start looking for the next line
        startEmbeddedContentLine--;
      }
    }

    // Assume at most one translation for "Embedded Content: " in a given message
    if (foundEmbeddedContentLines)
      break;
  }

  return NS_OK;
}
Пример #26
0
nsresult Stream::Init(Core* aController)
{
  nsresult rv;
  mController = aController;
  NS_ASSERTION(mController, "mController is null");

  // Get prefs
  nsCOMPtr<nsIRegistry> registry;
  rv = mController->GetRegistry(registry);
  NS_ENSURE_SUCCESS(rv, rv);

  nsRegistryKey regkey;
  rv = mController->GetRegistryTree(regkey);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = registry->GetKey(regkey,
                        kRegTreeStream.get(),
                        &regkey);
  NS_ENSURE_SUCCESS(rv, rv);

  mRegkeyStream = regkey;

  nsXPIDLString remoteUrlPref;
  rv = registry->GetString(regkey, kRegKeyURL.get(),
                           getter_Copies(remoteUrlPref));
  NS_ENSURE_SUCCESS(rv, rv);

  mRemoteBaseUrl = NS_ConvertUTF16toUTF8(remoteUrlPref);

  /* For easier mass-personalisation via scripts in corporate setups and
     for easier instructed setup by normal users,
     we allow the username to be separate from the URL. */
  nsXPIDLString usernamePref;
  rv = registry->GetString(regkey, kRegKeyUsername.get(),
                           getter_Copies(usernamePref));
  if (NS_SUCCEEDED(rv) && !usernamePref.IsEmpty() )
    /* failure is non-fatal, because username might be in the URL, and
       even if it isn't, the transfer will pull up a prompt. */
  {
    nsCOMPtr<nsIIOService> ioserv = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv))
    {
      nsCOMPtr<nsIURI> uri;
      rv = NS_NewURI(getter_AddRefs(uri), mRemoteBaseUrl);

      if (NS_SUCCEEDED(rv))
      {
        rv = uri->SetUsername(NS_ConvertUTF16toUTF8(usernamePref));
        if (NS_SUCCEEDED(rv))
        {
          // Yikes. Did I mention that I hate that C/wide string crap?
          nsXPIDLCString spec;
          uri->GetSpec(spec);
          mRemoteBaseUrl = spec;
          mRemoteBaseUrl.ReplaceSubstring(NS_LITERAL_CSTRING("$USERID"),
                                          NS_ConvertUTF16toUTF8(usernamePref));
        }
      }
    }
  }

  // we need a / at the end (base URL), fix up, if user error
  if (mRemoteBaseUrl.Last() != (PRUnichar) '/')
    mRemoteBaseUrl += (PRUnichar) '/';

  nsXPIDLString passwordPref;
  rv = registry->GetString(regkey, kRegKeyPassword.get(),
                           getter_Copies(passwordPref));
  /* failure is non-fatal, because if there's no password, the
     transfer will pull up a prompt. */
  mPassword = passwordPref;

  PRInt32 savepw = 0;
  rv = registry->GetInt(regkey, kRegKeySavePassword.get(),
                        &savepw);
  mSavePassword = savepw == 0 ? PR_FALSE : PR_TRUE;

  nsCOMPtr<nsIFile> profiledir;
  rv = mController->GetProfileDir(getter_AddRefs(profiledir));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIIOService> ioserv = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_NewFileURI(getter_AddRefs(mProfileDir), profiledir);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
nsresult
FileSystemDataSource::Init()
{
    nsresult rv;

    mRDFService = do_GetService("@mozilla.org/rdf/rdf-service;1");
    NS_ENSURE_TRUE(mRDFService, NS_ERROR_FAILURE);

    rv =  mRDFService->GetResource(NS_LITERAL_CSTRING("NC:FilesRoot"),
                                   getter_AddRefs(mNC_FileSystemRoot));
    nsresult tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "child"),
                                            getter_AddRefs(mNC_Child));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "Name"),
                                   getter_AddRefs(mNC_Name));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "URL"),
                                   getter_AddRefs(mNC_URL));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "Icon"),
                                   getter_AddRefs(mNC_Icon));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "Content-Length"),
                                   getter_AddRefs(mNC_Length));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "IsDirectory"),
                                   getter_AddRefs(mNC_IsDirectory));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(WEB_NAMESPACE_URI "LastModifiedDate"),
                                   getter_AddRefs(mWEB_LastMod));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "FileSystemObject"),
                                   getter_AddRefs(mNC_FileSystemObject));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI  "pulse"),
                                   getter_AddRefs(mNC_pulse));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "instanceOf"),
                                   getter_AddRefs(mRDF_InstanceOf));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "type"),
                                   getter_AddRefs(mRDF_type));

    static const char16_t kTrue[] = {'t','r','u','e','\0'};
    static const char16_t kFalse[] = {'f','a','l','s','e','\0'};

    tmp = mRDFService->GetLiteral(kTrue, getter_AddRefs(mLiteralTrue));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    tmp = mRDFService->GetLiteral(kFalse, getter_AddRefs(mLiteralFalse));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

#ifdef USE_NC_EXTENSION
    rv = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "extension"),
                                  getter_AddRefs(mNC_extension));
    NS_ENSURE_SUCCESS(rv, rv);
#endif

#ifdef XP_WIN
    rv =  mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "IEFavorite"),
                                   getter_AddRefs(mNC_IEFavoriteObject));
    tmp = mRDFService->GetResource(NS_LITERAL_CSTRING(NC_NAMESPACE_URI "IEFavoriteFolder"),
                                   getter_AddRefs(mNC_IEFavoriteFolder));
    if (NS_FAILED(tmp)) {
        rv = tmp;
    }
    NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);

    nsCOMPtr<nsIFile> file;
    NS_GetSpecialDirectory(NS_WIN_FAVORITES_DIR, getter_AddRefs(file));
    if (file)
    {
        nsCOMPtr<nsIURI> furi;
        NS_NewFileURI(getter_AddRefs(furi), file);
        NS_ENSURE_TRUE(furi, NS_ERROR_FAILURE);

        file->GetNativePath(ieFavoritesDir);
    }
#endif

    return NS_OK;
}