Beispiel #1
0
FileHandler::FileHandler(QString newFileName, QObject * parent):
    QObject(parent),
    fileName(newFileName),
    fileObject(fileName),
    fileStatus(unknown)
{
    if (fileObject.exists())
    {
        setFileStatus(exists);

        fileInfos = new QFileInfo(fileName);
        fileDateCreated = fileInfos->created();
        delete fileInfos;

        if (isOutdated())
        {
            setFileStatus(outdated);
        } else {
            setFileStatus(good);
        }

    } else {
        setFileStatus(missing);
    }
    QUrl fileUrl("http://www.netmark.pl/templates/portal/images/whmcslogo.png");
    m_Downloader = new Downloader(fileUrl, this);
    connect(m_Downloader, SIGNAL(downloaded()), this, SLOT(loadFile()));
    connect(m_Downloader, SIGNAL(logmsg(QString)),this,SLOT(mainlog(QString)));
}
QString ShareFileInfo::fileDisplayName() const
{
    Q_D(const DAbstractFileInfo);
    if (systemPathManager->isSystemPath(fileUrl().toString()))
        return systemPathManager->getSystemPathDisplayNameByPath(fileUrl().toString());
    ShareInfo info = userShareManager->getShareInfoByPath(fileUrl().path());
    QString displayName = info.shareName();
    if (!displayName.isEmpty()) {
        return displayName;
    } else {
        if (d->proxy) {
            return d->proxy->fileDisplayName();
        }
    }
    return QString("");
}
/// Display a file dialog.  If `directory` is an invalid file or directory the browser will start at the current
/// working directory.
/// \param const QString& title title of the window
/// \param const QString& directory directory to start the file browser at
/// \param const QString& nameFilter filter to filter filenames by - see `QFileDialog`
/// \return QScriptValue file path as a string if one was selected, otherwise `QScriptValue::NullValue`
QScriptValue WindowScriptingInterface::showBrowse(const QString& title, const QString& directory, const QString& nameFilter,
                                                  QFileDialog::AcceptMode acceptMode) {
    // On OS X `directory` does not work as expected unless a file is included in the path, so we append a bogus
    // filename if the directory is valid.
    QString path = "";
    QFileInfo fileInfo = QFileInfo(directory);
    qDebug() << "File: " << directory << fileInfo.isFile();
    if (fileInfo.isDir()) {
        fileInfo.setFile(directory, "__HIFI_INVALID_FILE__");
        path = fileInfo.filePath();
    }
    
    QFileDialog fileDialog(Application::getInstance()->getWindow(), title, path, nameFilter);
    fileDialog.setAcceptMode(acceptMode);
    qDebug() << "Opening!";
    QUrl fileUrl(directory);
    if (acceptMode == QFileDialog::AcceptSave) {
        fileDialog.setFileMode(QFileDialog::Directory);
        fileDialog.selectFile(fileUrl.fileName());
    }
    if (fileDialog.exec()) {
        return QScriptValue(fileDialog.selectedFiles().first());
    }
    return QScriptValue::NullValue;
}
// If IAttachementExecute is available, use the CheckPolicy call to find out
// if this download should be prevented due to Security Zone Policy settings.
AVCheckPolicyState
nsDownloadScanner::CheckPolicy(nsIURI *aSource, nsIURI *aTarget)
{
  nsresult rv;

  if (!mAESExists || !aSource || !aTarget)
    return AVPOLICY_DOWNLOAD;

  nsAutoCString source;
  rv = aSource->GetSpec(source);
  if (NS_FAILED(rv))
    return AVPOLICY_DOWNLOAD;

  nsCOMPtr<nsIFileURL> fileUrl(do_QueryInterface(aTarget));
  if (!fileUrl)
    return AVPOLICY_DOWNLOAD;

  nsCOMPtr<nsIFile> theFile;
  nsAutoString aFileName;
  if (NS_FAILED(fileUrl->GetFile(getter_AddRefs(theFile))) ||
      NS_FAILED(theFile->GetLeafName(aFileName)))
    return AVPOLICY_DOWNLOAD;

  // IAttachementExecute prohibits src data: schemes by default but we
  // support them. If this is a data src, skip off doing a policy check.
  // (The file will still be scanned once it lands on the local system.)
  bool isDataScheme(false);
  nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(aSource);
  if (innerURI)
    (void)innerURI->SchemeIs("data", &isDataScheme);
  if (isDataScheme)
    return AVPOLICY_DOWNLOAD;

  nsRefPtr<IAttachmentExecute> ae;
  HRESULT hr;
  hr = CoCreateInstance(CLSID_AttachmentServices, nullptr, CLSCTX_INPROC,
                        IID_IAttachmentExecute, getter_AddRefs(ae));
  if (FAILED(hr))
    return AVPOLICY_DOWNLOAD;

  (void)ae->SetClientGuid(GUID_MozillaVirusScannerPromptGeneric);
  (void)ae->SetSource(NS_ConvertUTF8toUTF16(source).get());
  (void)ae->SetFileName(aFileName.get());

  // Any failure means the file download/exec will be blocked by the system.
  // S_OK or S_FALSE imply it's ok.
  hr = ae->CheckPolicy();

  if (hr == S_OK)
    return AVPOLICY_DOWNLOAD;

  if (hr == S_FALSE)
    return AVPOLICY_PROMPT;

  if (hr == E_INVALIDARG)
    return AVPOLICY_PROMPT;

  return AVPOLICY_BLOCKED;
}
void KPrHtmlExport::writeHtmlFileToTmpDir(const QString &fileName, const QString &htmlBody)
{
    KUrl fileUrl(m_tmpDirPath, fileName);
    QFile file(fileUrl.toLocalFile());
    file.open(QIODevice::WriteOnly);
    QTextStream stream(&file);
    stream << htmlBody;
}
Beispiel #6
0
void ShareProvider::publish(const QString& filePath)
{
    d->m_filePath = filePath;
    KUrl fileUrl(filePath);

    KIO::MimetypeJob *mimetypeJob = KIO::mimetype(fileUrl, KIO::HideProgressInfo);
    connect(mimetypeJob, SIGNAL(finished(KJob*)), this, SLOT(onMimetypeJobFinished(KJob*)));
}
SLC::Provider::Actions SendByEmailProvider::actionsFor(const QVariantHash &content) const
{
    KUrl fileUrl(content.value("URI").toString());

    if (fileUrl.isLocalFile() && !fileUrl.path().endsWith(QLatin1String(".desktop"))) {
        return Share;
    } else {
        return NoAction;
    }
}
Beispiel #8
0
void FileEdit::buttonClicked()
{
    QUrl url = QFileDialog::getOpenFileUrl(window(),
                                           tr("Choose a File"),
                                           fileUrl(),
                                           mFilter);
    if (url.isEmpty())
        return;
    setFileUrl(url);
    emit fileUrlChanged(url);
}
Beispiel #9
0
void DecoderHandler::customEvent(QEvent *event)
{
    if (DecoderHandlerEvent *dhe = dynamic_cast<DecoderHandlerEvent*>(event))
    {
        // Proxy all DecoderHandlerEvents
        return dispatch(*dhe);
    }
    else if (event->type() == MythEvent::MythEventMessage)
    {
        MythEvent *me = (MythEvent *)event;
        QStringList tokens = me->Message().split(" ", QString::SkipEmptyParts);

        if (tokens.isEmpty())
            return;

        if (tokens[0] == "DOWNLOAD_FILE")
        {
            QStringList args = me->ExtraDataList();

            if (tokens[1] == "UPDATE")
            {
            }
            else if (tokens[1] == "FINISHED")
            {
                QString downloadUrl = args[0];
                int fileSize  = args[2].toInt();
                int errorCode = args[4].toInt();
                QString filename = args[1];

                if ((errorCode != 0) || (fileSize == 0))
                {
                    LOG(VB_GENERAL, LOG_ERR, QString("DecoderHandler: failed to download playlist from '%1'")
                        .arg(downloadUrl));
                    QUrl url(downloadUrl);
                    m_state = STOPPED;
                    doOperationStop();
                    doFailed(url, "Could not get playlist");
                }
                else
                {
                    QUrl fileUrl(filename);
                    createPlaylistFromFile(fileUrl);
                }
            }
        }
    }
}
void yandexnarodPlugin::actionStart()
{
	currentJid = sender()->property("jid").toString();
	currentAccount = sender()->property("account").toInt();
	QString filepath = QFileDialog::getOpenFileName(uploadwidget, O_M(MChooseFile),
							psiOptions->getPluginOption(CONST_LAST_FOLDER).toString());

	if (!filepath.isEmpty()) {
		fi = QFileInfo(filepath);
		psiOptions->setPluginOption(CONST_LAST_FOLDER, fi.dir().path());

		uploadwidget = new uploadDialog();
		connect(uploadwidget, SIGNAL(fileUrl(QString)), this, SLOT(onFileURL(QString)));

		uploadwidget->show();
		uploadwidget->start(filepath);
	}
}
Beispiel #11
0
QString XmlValidatorJob::getLocalURLForSchema ( const QString& file, const QString& schema ) {
    if ( file.isEmpty() || schema.isEmpty() )
        return QString();
    KUrl schemaUrl(schema);
    KUrl fileUrl(file);
    if ( schemaUrl.isRelative() ) {
        QString schemaDir = schemaUrl.directory ( KUrl::IgnoreTrailingSlash );
        QString localFile;
        if ( !schemaDir.isEmpty() )
            localFile =  QString ( "%1/%2/%3" ).arg ( fileUrl.directory (), schemaDir, schemaUrl.fileName() );
        else
            localFile = QString ( "%1/%2" ).arg ( fileUrl.directory (), schemaUrl.fileName() );
        if (QFile::exists(localFile))
            return localFile;
    }

    QString url = IDocumentCacheManager::self()->getLocalUrl(schema);
    return url;
}
Beispiel #12
0
    void pasteFileToOtherPartition()
    {
        const QString filePath = homeTmpDir() + "fileFromHome";
        const QString dest = otherTmpDir() + "fileFromHome_copied";
        QFile::remove(dest);
        createTestFile( filePath );

        QMimeData* mimeData = new QMimeData;
        KUrl fileUrl(filePath);
        fileUrl.populateMimeData(mimeData);
        QApplication::clipboard()->setMimeData(mimeData);

        KIO::Job* job = KIO::pasteClipboard(otherTmpDir(), static_cast<QWidget*>(0));
        job->setUiDelegate(0);
        bool ok = KIO::NetAccess::synchronousRun(job, 0);
        QVERIFY( ok );

        QVERIFY( QFile::exists( dest ) );
        QVERIFY( QFile::exists( filePath ) ); // still there
    }
Beispiel #13
0
/*--- Prepare download, then issue the FTP commands ---*/
void Downloader::DownloadFile(QString dir, QString file)
{
    qDebug() << "Downloader::DownloadFile " + dir + file;

    // Data
    QUrl fileUrl(*baseUrl);
    QNetworkRequest r;
    QDir tempDir(".");

    // Setup
    downloadedSize = 0;
    lastDownloadedSize = 0;
    currentFtpDir = dir;
    currentFtpFile = file;
    currentFile = new QFile(currentFtpDir + currentFtpFile);
    fileUrl.setPath(FTP_UPDATE_ROOT + currentFtpDir + currentFtpFile);
    r.setUrl(fileUrl);

    // Local file preparation
    if (currentFtpDir.length() > 0)
    {
        tempDir.mkpath(currentFtpDir);
    }
    if (currentFtpFile.length() > 0 && currentFile->exists())
    {
        currentFile->remove();
    }
    currentFile->open(QIODevice::WriteOnly);

    // Download command
    bDownloading = true;
    reply = ftp->get(r);
    reply->setReadBufferSize(FTP_PART_SIZE);
    connect(reply, SIGNAL(readyRead()), this, SLOT(FilePart()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(FileError(QNetworkReply::NetworkError)));

    // Timers
    timeoutTimer->setSingleShot(true);
    timeoutTimer->start(FTP_TIMEOUT);
}
Beispiel #14
0
void Image::loadImage(bool inMemory, bool force)
{
	if (m_loadingImage)
		return;

	if (m_loadedImage && !force)
	{
		emit finishedImage(QNetworkReply::NoError, "");
		return;
	}

	if (m_fileSize > MAX_LOAD_FILESIZE && inMemory)
	{
		emit finishedImage(static_cast<QNetworkReply::NetworkError>(500), "");
		return;
	}

	if (m_loadImage != nullptr)
		m_loadImage->deleteLater();

	if (force)
		setUrl(fileUrl().toString());

	m_loadImage = m_parentSite->get(m_parentSite->fixUrl(m_url), m_parent, "image", this);
	m_loadImage->setParent(this);
	m_loadingImage = true;
	m_loadedImage = false;
	m_data.clear();

	if (inMemory)
	{
		connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageInMemory);
		connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageInMemory);
	}
	else
	{
		connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageBasic);
		connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageBasic);
	}
}
Beispiel #15
0
std::vector<MapElementI*> DesuraJSSettings::getThemes()
{
	std::vector<ThemeStubI*> m_vThemes;
	GetGCThemeManager()->getThemeStubList(m_vThemes);

	std::vector<MapElementI*> ret;

	for (size_t x=0; x<m_vThemes.size(); x++)
	{
		UTIL::FS::Path file(UTIL::OS::getDataPath(L"themes"), L"", false);
		UTIL::FS::Path themePath = UTIL::FS::PathWithFile(m_vThemes[x]->getPreview());
		
		file += themePath;
		file += themePath.getFile();

		if (!UTIL::FS::isValidFile(file))
			continue;

		gcString fileUrl("desura://themeimage/{0}", m_vThemes[x]->getPreview());
		fileUrl = UTIL::STRING::sanitizeFilePath(fileUrl, '/');

		std::map<gcString, gcString> map;

		map["name"] = m_vThemes[x]->getName();
		map["displayName"] = m_vThemes[x]->getPrintName();
		map["image"] = fileUrl;
		map["tooltip"] = m_vThemes[x]->getPrintName();
		map["author"] = m_vThemes[x]->getAuthor();
		map["version"] = m_vThemes[x]->getVersion();
	
		ret.push_back(new MapElement<std::map<gcString, gcString>>(map));
	}

	safe_delete(m_vThemes);
	return ret;
}
QVector<MenuAction> ShareFileInfo::menuActionList(DAbstractFileInfo::MenuType type) const
{
    QVector<MenuAction> actionKeys;

    if(type == SpaceArea) {
        actionKeys << MenuAction::DisplayAs
                   << MenuAction::SortBy;
    } else if (type == SingleFile){
        if(isDir()){
            bool useRemoveBookmarkAction = false;
            DUrl schemeAlteredUrl = fileUrl();
            schemeAlteredUrl.setScheme(FILE_SCHEME);
            // FIXME: reimplement BookMark::exist() 's behavior and use it for check bookmark existance.
            //        after doing this, don't forget to remove the "bookmarkmanager.h" header file include.
            // if (DFileService::instance()->createFileInfo(nullptr, DUrl::fromBookMarkFile(fileUrl(), QString()))) {
            if (Singleton<BookMarkManager>::instance()->checkExist(DUrl::fromBookMarkFile(schemeAlteredUrl, QString()))) {
                useRemoveBookmarkAction = true;
            }
            actionKeys << MenuAction::Open
                       << MenuAction::OpenInNewWindow
                       << MenuAction::OpenInNewTab
                       << MenuAction::Separator
                       << (useRemoveBookmarkAction ? MenuAction::BookmarkRemove : MenuAction::AddToBookMark)
                       << MenuAction::UnShare;
        }
        actionKeys << MenuAction::Separator
                   << MenuAction::Property;

    }else if (type == MultiFiles){
        actionKeys << MenuAction::Open
                   << MenuAction::Separator
                   << MenuAction::Property;
    }

    return actionKeys;
}
QList<ServerNodeInstance>  NodeInstanceServer::createInstances(const QVector<InstanceContainer> &containerVector)
{
    Q_ASSERT(declarativeView() || quickView());
    QList<ServerNodeInstance> instanceList;
    foreach (const InstanceContainer &instanceContainer, containerVector) {
        ServerNodeInstance instance;
        if (instanceContainer.nodeSourceType() == InstanceContainer::ComponentSource) {
            instance = ServerNodeInstance::create(this, instanceContainer, ServerNodeInstance::WrapAsComponent);
        } else {
            instance = ServerNodeInstance::create(this, instanceContainer, ServerNodeInstance::DoNotWrapAsComponent);
        }
        insertInstanceRelationship(instance);
        instanceList.append(instance);
        instance.internalObject()->installEventFilter(childrenChangeEventFilter());
        if (instanceContainer.instanceId() == 0) {
            m_rootNodeInstance = instance;
            if (quickView())
                quickView()->setContent(fileUrl(), m_importComponent, m_rootNodeInstance.rootQuickItem());
            resizeCanvasSizeToRootItemSize();
        }

        foreach (QQmlContext* context, allSubContextsForObject(instance.internalObject()))
            setupDummysForContext(context);
    }
Beispiel #18
0
void FileEdit::textEdited()
{
    emit fileUrlChanged(fileUrl());
}
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;
}
Beispiel #20
0
KUrl DatabaseUrl::fileUrl() const
{
    KUrl fileUrl(albumRoot());
    fileUrl.addPath(path());
    return fileUrl;
}