Exemplo n.º 1
0
void TwitterMicroBlog::slotFetchUserLists(KJob *job)
{
    qCDebug(CHOQOK);
    if (!job) {
        qCWarning(CHOQOK) << "NULL Job returned";
        return;
    }
    QString username = mFetchUsersListMap.take(job);
    Choqok::Account *theAccount = mJobsAccount.take(job);
    if (job->error()) {
        qCDebug(CHOQOK) << "Job Error:" << job->errorString();
        Q_EMIT error(theAccount, Choqok::MicroBlog::CommunicationError,
                     i18n("Fetching %1's lists failed. %2", username, job->errorString()), Critical);
    } else {
        KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *> (job);
        QByteArray buffer = stj->data();
        QList<Twitter::List> list = readUserListsFromJson(theAccount, buffer);
        if (list.isEmpty()) {
            qCDebug(CHOQOK) << buffer;
            QString errorMsg;
            errorMsg = checkForError(buffer);
            if (errorMsg.isEmpty()) {
                KMessageBox::information(choqokMainWindow, i18n("There is no list record for user %1", username));
            } else {
                Q_EMIT error(theAccount, ServerError, errorMsg, Critical);
            }
        } else {
            Q_EMIT userLists(theAccount, username, list);
        }
    }
}
Exemplo n.º 2
0
void JobRemoteTest::putAndGet()
{
    const QString filePath = remoteTmpDir() + "putAndGetFile";
    KUrl u(filePath);
    KIO::TransferJob* job = KIO::put( u, 0600, KIO::Overwrite | KIO::HideProgressInfo );
    QDateTime mtime = QDateTime::currentDateTime().addSecs( -30 ); // 30 seconds ago
    mtime.setTime_t(mtime.toTime_t()); // hack for losing the milliseconds
    job->setModificationTime(mtime);
    job->setUiDelegate( 0 );
    connect( job, SIGNAL( result(KJob*) ),
            this, SLOT( slotResult(KJob*) ) );
    connect( job, SIGNAL(dataReq(KIO::Job*, QByteArray&)),
             this, SLOT(slotDataReq(KIO::Job*, QByteArray&)) );
    m_result = -1;
    m_dataReqCount = 0;
    enterLoop();
    QVERIFY( m_result == 0 ); // no error

    m_result = -1;

    KIO::StoredTransferJob* getJob = KIO::storedGet( u, KIO::NoReload, KIO::HideProgressInfo );
    getJob->setUiDelegate( 0 );
    connect( getJob, SIGNAL( result( KJob* ) ),
            this, SLOT( slotGetResult( KJob* ) ) );
    enterLoop();
    QCOMPARE( m_result, 0 ); // no error
    QCOMPARE( m_data, QByteArray("This is a test for KIO::put()\n") );
    //QCOMPARE( m_data.size(), 11 );
}
Exemplo n.º 3
0
void ArchiveOrg::slotParseResults(KJob* job)
{
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QDomDocument doc;
    doc.setContent(QString::fromUtf8(storedQueryJob->data()));
    QDomNodeList links = doc.elementsByTagName(QStringLiteral("a"));
    QString html = QStringLiteral("<style type=\"text/css\">tr.cellone {background-color: %1;}").arg(qApp->palette().alternateBase().color().name());
    html += QLatin1String("</style><table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">");
    QString link;
    int ct = 0;
    m_thumbsPath.clear();
    for (int i = 0; i < links.count(); ++i) {
        QString href = links.at(i).toElement().attribute(QStringLiteral("href"));
        if (href.endsWith(QLatin1String(".thumbs/"))) {
            // sub folder contains image thumbs, display one.
            m_thumbsPath = m_metaInfo.value(QStringLiteral("url")) + '/' + href;
            KJob* thumbJob = KIO::storedGet( QUrl(m_thumbsPath), KIO::NoReload, KIO::HideProgressInfo );
            thumbJob->setProperty("id", m_metaInfo.value(QStringLiteral("id")));
            connect(thumbJob, &KJob::result, this, &ArchiveOrg::slotParseThumbs);
        }
        else if (!href.contains('/') && !href.endsWith(QLatin1String(".xml"))) {
            link = m_metaInfo.value(QStringLiteral("url")) + '/' + href;
            ct++;
            if (ct %2 == 0) {
                html += QLatin1String("<tr class=\"cellone\">");
            }
            else html += QLatin1String("<tr>");
            html += "<td>" + QUrl(link).fileName() + QStringLiteral("</td><td><a href=\"%1\">%2</a></td><td><a href=\"%3\">%4</a></td></tr>").arg(link).arg(i18n("Preview")).arg(link + "_import").arg(i18n("Import"));
        }
    }
    html += QLatin1String("</table>");
    if (m_metaInfo.value(QStringLiteral("id")) == job->property("id").toString()) emit gotMetaInfo(html);
}
Exemplo n.º 4
0
    void Core::downloadFinished(KJob* job)
    {
        KIO::StoredTransferJob* j = (KIO::StoredTransferJob*)job;
        int err = j->error();
        if (err == KIO::ERR_USER_CANCELED)
            return;

        if (err)
        {
            gui->errorMsg(j);
        }
        else
        {
            // load in the file (target is always local)
            QString group;
            QMap<KUrl, QString>::iterator i = add_to_groups.find(j->url());
            if (i != add_to_groups.end())
            {
                group = i.value();
                add_to_groups.erase(i);
            }

            QString dir = locationHint(group);
            if (dir != QString::null)
                loadFromData(j->data(), dir, group, false, j->url());
        }
    }
Exemplo n.º 5
0
void OpenClipArt::slotShowResults(KJob* job)
{
    if (job->error() != 0 ) return;
    m_listWidget->blockSignals(true);    
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    
    QDomDocument doc;
    doc.setContent(QString::fromLatin1(storedQueryJob->data()));
    QDomNodeList items = doc.documentElement().elementsByTagName("item");
    for (int i = 0; i < items.count(); ++i) {
        QDomElement currentClip = items.at(i).toElement();
        QDomElement title = currentClip.firstChildElement("title");
        QListWidgetItem *item = new QListWidgetItem(title.firstChild().nodeValue(), m_listWidget);
        QDomElement thumb = currentClip.firstChildElement("media:thumbnail");
        item->setData(imageRole, thumb.attribute("url"));
        QDomElement enclosure = currentClip.firstChildElement("enclosure");
        item->setData(downloadRole, enclosure.attribute("url"));
        QDomElement link = currentClip.firstChildElement("link");
        item->setData(infoUrl, link.firstChild().nodeValue());
        QDomElement license = currentClip.firstChildElement("cc:license");
        item->setData(licenseRole, license.firstChild().nodeValue());
        QDomElement desc = currentClip.firstChildElement("description");
        item->setData(descriptionRole, desc.firstChild().nodeValue());
        QDomElement author = currentClip.firstChildElement("dc:creator");
        item->setData(authorRole, author.firstChild().nodeValue());
        item->setData(authorUrl, QString("http://openclipart.org/user-detail/") + author.firstChild().nodeValue());
    }        
    m_listWidget->blockSignals(false);
    m_listWidget->setCurrentRow(0);
    emit searchDone();
}
Exemplo n.º 6
0
void TwitterSearch::requestSearchResults(const SearchInfo &searchInfo,
        const QString &sinceStatusId, uint count, uint page)
{
    Q_UNUSED(page)
    qCDebug(CHOQOK);

    TwitterAccount *account = qobject_cast< TwitterAccount * >(searchInfo.account);
    QUrl url = account->apiUrl();

    QUrlQuery urlQuery;
    QOAuth::ParamMap param;

    const QString query = searchInfo.query;
    if (searchInfo.option == TwitterSearch::FromUser) {
        url.setPath(url.path() + QLatin1String("/statuses/user_timeline.json"));

        urlQuery.addQueryItem(QLatin1String("screen_name"), query);
        param.insert("screen_name", query.toLatin1());
    } else {
        url.setPath(url.path() + QLatin1String("/search/tweets.json"));

        const QByteArray formattedQuery(QUrl::toPercentEncoding(mSearchCode[searchInfo.option] + query));
        urlQuery.addQueryItem(QLatin1String("q"), QString::fromLatin1(formattedQuery));
        param.insert("q", formattedQuery);
    }

    if (!sinceStatusId.isEmpty()) {
        urlQuery.addQueryItem(QLatin1String("since_id"), sinceStatusId);
        param.insert("since_id", sinceStatusId.toLatin1());
    }

    int cntStr;
    if (count && count <= 100) { // Twitter API specifies a max count of 100
        cntStr = count;
    } else {
        cntStr = 100;
    }
    urlQuery.addQueryItem(QLatin1String("count"), QString::number(cntStr));
    param.insert("count", QString::number(cntStr).toLatin1());

    const QUrl tmpUrl(url);
    url.setQuery(urlQuery);

    qCDebug(CHOQOK) << url;
    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    if (!job) {
        qCCritical(CHOQOK) << "Cannot create an http GET request!";
        return;
    }

    TwitterApiMicroBlog *microblog = qobject_cast<TwitterApiMicroBlog *>(account->microblog());

    job->addMetaData(QStringLiteral("customHTTPHeader"),
                     QStringLiteral("Authorization: ") +
                     QLatin1String(microblog->authorizationHeader(account, tmpUrl, QOAuth::GET, param)));

    mSearchJobs[job] = searchInfo;
    connect(job, SIGNAL(result(KJob*)), this, SLOT(searchResultsReturned(KJob*)));
    job->start();
}
Exemplo n.º 7
0
void Posterous::slotUpload(KJob *job)
{
    QUrl localUrl = mUrlMap.take(job);
    if (job->error()) {
        qCritical() << "Job Error:" << job->errorString();
        Q_EMIT uploadingFailed(localUrl, job->errorString());
        return;
    } else {
        KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *>(job);
        //qDebug() << stj->data();
        const QJsonDocument json = QJsonDocument::fromJson(stj->data());
        if (!json.isNull()) {
            const QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("error"))) {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
            } else {
                if (PosterousSettings::oauth()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("url")).toString());
                }
                if (PosterousSettings::basic()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("full_url")).toString());
                }
            }
        } else {
            Q_EMIT uploadingFailed(localUrl, i18n("Malformed response"));
            qWarning() << "Parse error:" << stj->data();
        }
    }
}
Exemplo n.º 8
0
ManPageDocumentation::ManPageDocumentation(const QString& name, const QUrl& url)
    : m_url(url), m_name(name)
{
    KIO::StoredTransferJob* transferJob = KIO::storedGet(m_url, KIO::NoReload, KIO::HideProgressInfo);
    connect( transferJob, &KIO::StoredTransferJob::finished, this, &ManPageDocumentation::finished);
    transferJob->start();
}
Exemplo n.º 9
0
void LaconicaSearch::searchResultsReturned(KJob* job)
{
    kDebug();
    if( job == 0 ) {
        kDebug() << "job is a null pointer";
        emit error( i18n( "Unable to fetch search results." ) );
        return;
    }

    SearchInfo info = mSearchJobs.take(job);

    if( job->error() ) {
        kError() << "Error: " << job->errorString();
        emit error( i18n( "Unable to fetch search results: %1", job->errorString() ) );
        return;
    }
    KIO::StoredTransferJob *jj = qobject_cast<KIO::StoredTransferJob *>( job );
    QList<Choqok::Post*> postsList;
    if(info.option == ReferenceHashtag)
        postsList = parseAtom( jj->data() );
    else
        postsList = parseRss( jj->data() );

    kDebug()<<"Emiting searchResultsReceived()";
    emit searchResultsReceived( info, postsList );
}
Exemplo n.º 10
0
void TwitterMicroBlog::fetchUserLists(TwitterAccount *theAccount, const QString &username)
{
    qCDebug(CHOQOK);
    if (!theAccount) {
        return;
    }
    QUrl url = theAccount->apiUrl();
    url.setPath(url.path() + QStringLiteral("/lists/ownerships.%1").arg(format));
    QUrl url_for_oauth(url);//we need base URL (without params) to make OAuth signature with it!
    QUrlQuery urlQuery;
    urlQuery.addQueryItem(QLatin1String("screen_name"), username);
    url.setQuery(urlQuery);
    QOAuth::ParamMap params;
    params.insert("screen_name", username.toLatin1());

    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo) ;
    if (!job) {
        qCCritical(CHOQOK) << "TwitterMicroBlog::loadUserLists: Cannot create an http GET request!";
        return;
    }

    job->addMetaData(QStringLiteral("customHTTPHeader"),
                     QStringLiteral("Authorization: ") +
                     QLatin1String(authorizationHeader(theAccount, url_for_oauth, QOAuth::GET, params)));
    mFetchUsersListMap[ job ] = username;
    mJobsAccount[ job ] = theAccount;
    connect(job, SIGNAL(result(KJob*)), this, SLOT(slotFetchUserLists(KJob*)));
    job->start();
}
Exemplo n.º 11
0
bool Editor::saveFile(const QUrl &targetUrl)
{
	QUrl url(targetUrl);
	bool result = false;
	if (url.isEmpty() && currentUrl().isEmpty()) {
		result = saveFileAs();
	} else {
		if (url.isEmpty()) url = currentUrl();
		QTemporaryFile tmp;  // only used for network export
		tmp.setAutoRemove(false);
		tmp.open();
		QString filename = url.isLocalFile() ? url.toLocalFile() : tmp.fileName();
	
		QSaveFile *savefile = new QSaveFile(filename);
		if (savefile->open(QIODevice::WriteOnly)) {
			QTextStream outputStream(savefile);
			// store commands in their generic @(...) notation format, to be translatable when reopened
			// this allows sharing of scripts written in different languages
			Tokenizer tokenizer;
			tokenizer.initialize(editor->document()->toPlainText());
			const QStringList localizedLooks(Translator::instance()->allLocalizedLooks());
			QString unstranslated;
			Token* t;
			bool pendingEOL = false;  // to avoid writing a final EOL token
			while ((t = tokenizer.getToken())->type() != Token::EndOfInput) {
				if (pendingEOL) {
					unstranslated.append('\n');
					pendingEOL = false;
				}
				if (localizedLooks.contains(t->look())) {
					QString defaultLook(Translator::instance()->defaultLook(t->look()));
					unstranslated.append(QString("@(%1)").arg(defaultLook));
				} else {
					if (t->type() == Token::EndOfLine) 
						pendingEOL = true;
					else
						unstranslated.append(t->look());
				}
			}
			outputStream << KTURTLE_MAGIC_1_0 << '\n';
			outputStream << unstranslated;
			outputStream.flush();
			savefile->commit();  // check for error here?
		}
		delete savefile;
        if (!url.isLocalFile())
           {
            KIO::StoredTransferJob *job = KIO::storedPut(savefile, url, -1, 0);
                 if(job->exec()){
                    setCurrentUrl(url);
                    editor->document()->setModified(false);
                    // MainWindow will add us to the recent file list
                    emit fileSaved(url);
                    result = true; // fix GUI for saveAs and saveExamples. TODO: check 5 lines above
                }
           }
    }
	return result;
}
Exemplo n.º 12
0
//void ThumbnailPicker::parseGooglePage( QStringList &ImList, const QString &URL )
void ThumbnailPicker::parseGooglePage(const QString &URL )
{
    QUrl googleURL(URL);
    KIO::StoredTransferJob *job = KIO::storedGet(googleURL);
    connect(job, SIGNAL(result(KJob*)), this, SLOT(slotProcessGoogleResult(KJob*)));

    job->start();
}
Exemplo n.º 13
0
void ManPageDocumentation::finished(KJob* j)
{
    KIO::StoredTransferJob* job = qobject_cast<KIO::StoredTransferJob*>(j);
    if(job && job->error()==0) {
        m_description = QString::fromUtf8(job->data());
    } else {
        m_description.clear();
    }
    emit descriptionChanged();
}
Exemplo n.º 14
0
	void HTTPTracker::onScrapeResult(KJob* j)
	{
		if (j->error())
		{
			Out(SYS_TRK | LOG_IMPORTANT) << "Scrape failed : " << j->errorString() << endl;
			return;
		}

		KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
		BDecoder dec(st->data(), false, 0);
		BNode* n = 0;

		try
		{
			n = dec.decode();
		}
		catch (bt::Error & err)
		{
			Out(SYS_TRK | LOG_IMPORTANT) << "Invalid scrape data " << err.toString() << endl;
			return;
		}

		if (n && n->getType() == BNode::DICT)
		{
			BDictNode* d = (BDictNode*)n;
			d = d->getDict(QString("files"));
			if (d)
			{
				d = d->getDict(tds->infoHash().toByteArray());
				if (d)
				{
					try
					{
						seeders = d->getInt("complete");
						leechers = d->getInt("incomplete");
						total_downloaded = d->getInt("downloaded");
						supports_partial_seed_extension = d->getValue("downloaders") != 0;
						Out(SYS_TRK | LOG_DEBUG) << "Scrape : leechers = " << leechers
						<< ", seeders = " << seeders << ", downloaded = " << total_downloaded << endl;
					}
					catch (...)
						{}
					scrapeDone();
					if (status == bt::TRACKER_ERROR)
					{
						status = bt::TRACKER_OK;
						failures = 0;
					}
				}
			}
		}

		delete n;
	}
Exemplo n.º 15
0
void Resource::authenticate(const QString &name, const QString &password)
{
    QUrl url = baseUrl;
    url = url.adjusted(QUrl::StripTrailingSlash);
    url.setPath(url.path() + '/' + "/authorizations");
    QByteArray data = "{ \"scopes\": [\"repo\"], \"note\": \"KDevelop Github Provider\" }";
    KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo);
    job->addMetaData("customHTTPHeader", "Authorization: Basic " + QString (name + ':' + password).toUtf8().toBase64());
    connect(job, &KIO::StoredTransferJob::result, this, &Resource::slotAuthenticate);
    job->start();
}
Exemplo n.º 16
0
void ArchiveOrg::slotShowResults(KJob* job)
{
    if (job->error() != 0 ) return;
    m_listWidget->blockSignals(true);
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(storedQueryJob->data(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        // There was an error parsing data
        KMessageBox::sorry(m_listWidget, jsonError.errorString(), i18n("Error Loading Data"));
    }
    QVariant data = doc.toVariant();
    
    QVariant sounds;
    if (data.canConvert(QVariant::Map)) {
        QMap <QString, QVariant> map = data.toMap();
        QMap<QString, QVariant>::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            if (i.key() == QLatin1String("response")) {
                sounds = i.value();
                if (sounds.canConvert(QVariant::Map)) {
                    QMap <QString, QVariant> soundsList = sounds.toMap();
                    if (soundsList.contains(QStringLiteral("numFound"))) emit searchInfo(i18np("Found %1 result", "Found %1 results", soundsList.value("numFound").toInt()));
                    QList <QVariant> resultsList;
                    if (soundsList.contains(QStringLiteral("docs"))) {
                        resultsList = soundsList.value(QStringLiteral("docs")).toList();
                    }
                    
                    for (int j = 0; j < resultsList.count(); ++j) {
                        if (resultsList.at(j).canConvert(QVariant::Map)) {
                            QMap <QString, QVariant> soundmap = resultsList.at(j).toMap();
                            if (soundmap.contains(QStringLiteral("title"))) {
                                QListWidgetItem *item = new   QListWidgetItem(soundmap.value(QStringLiteral("title")).toString(), m_listWidget);
                                item->setData(descriptionRole, soundmap.value(QStringLiteral("description")).toString());
                                item->setData(idRole, soundmap.value(QStringLiteral("identifier")).toString());
                                QString author = soundmap.value(QStringLiteral("creator")).toString();
                                item->setData(authorRole, author);
                                if (author.startsWith(QLatin1String("http"))) item->setData(authorUrl, author);
                                item->setData(infoUrl, "http://archive.org/details/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(downloadRole, "http://archive.org/download/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(licenseRole, soundmap.value(QStringLiteral("licenseurl")).toString());                        
                            }
                        }
                    }
                }
            }
            ++i;
        }
    }
    m_listWidget->blockSignals(false);
    m_listWidget->setCurrentRow(0);
    emit searchDone();
}
Exemplo n.º 17
0
void HTTPTracker::onScrapeResult(KIO::Job* j)
{
    if (j->error())
    {
        Out(SYS_TRK|LOG_IMPORTANT) << "Scrape failed : " << j->errorString() << endl;
        return;
    }

    KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
    BDecoder dec(st->data(),false,0);
    BNode* n = 0;

    try
    {
        n = dec.decode();
    }
    catch (bt::Error & err)
    {
        Out(SYS_TRK|LOG_IMPORTANT) << "Invalid scrape data " << err.toString() << endl;
        return;
    }

    if (n && n->getType() == BNode::DICT)
    {
        BDictNode* d = (BDictNode*)n;
        d = d->getDict("files");
        if (d)
        {
            d = d->getDict(tor->getInfoHash().toByteArray());
            if (d)
            {
                BValueNode* vn = d->getValue("complete");
                if (vn && vn->data().getType() == Value::INT)
                {
                    seeders = vn->data().toInt();
                }


                vn = d->getValue("incomplete");
                if (vn && vn->data().getType() == Value::INT)
                {
                    leechers = vn->data().toInt();
                }

                Out(SYS_TRK|LOG_DEBUG) << "Scrape : leechers = " << leechers
                                       << ", seeders = " << seeders << endl;
            }
        }
    }

    delete n;
}
Exemplo n.º 18
0
void ThumbnailPicker::slotProcessGoogleResult(KJob *result)
{
    //Preload ImageList with the URLs in the object's ImageList:
    QStringList ImageList( Object->ImageList() );

    if (result->error())
    {
        result->uiDelegate()->showErrorMessage();
        result->kill();
        return;
    }

    QString PageHTML(static_cast<KIO::StoredTransferJob*>(result)->data());

    int index = PageHTML.indexOf( "src=\"http:", 0 );
    while ( index >= 0 )
    {
        index += 5; //move to end of "src=\"http:" marker

        //Image URL is everything from index to next occurrence of "\""
        ImageList.append( PageHTML.mid( index, PageHTML.indexOf( "\"", index ) - index ) );

        index = PageHTML.indexOf( "src=\"http:", index );
    }

    //Total Number of images to be loaded:
    int nImages = ImageList.count();
    if ( nImages )
    {
        ui->SearchProgress->setMinimum( 0 );
        ui->SearchProgress->setMaximum( nImages-1 );
        ui->SearchLabel->setText( i18n( "Loading images..." ) );
    }
    else
    {
            close();
            return;
   }

    //Add images from the ImageList
    for ( int i=0; i<ImageList.size(); ++i ) {
        QString s( ImageList[i] );
        QUrl u( ImageList[i] );

        if ( u.isValid() ) {
            KIO::StoredTransferJob *j = KIO::storedGet( u, KIO::NoReload, KIO::HideProgressInfo );
            j->setUiDelegate(0);
            connect( j, SIGNAL( result(KJob*) ), SLOT( slotJobResult(KJob*) ) );
        }
    }
}
void LoadWaiter::setImageData(KJob *job)
{
    if (m_vectorShape) {
        KIO::StoredTransferJob *transferJob = qobject_cast<KIO::StoredTransferJob*>(job);
        Q_ASSERT(transferJob);

        const QByteArray contents = transferJob->data();
        const VectorShape::VectorType vectorType = VectorShape::vectorType(contents);

        m_vectorShape->setCompressedContents(qCompress(contents), vectorType);
    }

    deleteLater();
}
Exemplo n.º 20
0
void KexiUserFeedbackAgent::sendDataFinished(KFakeJob* job)
{
    if (job->error()) {
        //! @todo error...
        return;
    }
    KIO::StoredTransferJob* sendJob = qobject_cast<KIO::StoredTransferJob*>(job);
    QByteArray result = sendJob->data();
    result.chop(1); // remove \n
    kDebug() << result;
    if (result == "ok") {
        d->sentDataInThisSession = d->areas;
    }
}
Exemplo n.º 21
0
void JobRemoteTest::openFileReading()
{

    const QString filePath = remoteTmpDir() + "openFileReading";
    KUrl u(filePath);

    const QByteArray putData("test1test2test3test4test5");

    KIO::StoredTransferJob * putJob = KIO::storedPut( putData,
            u,
            0600, KIO::Overwrite | KIO::HideProgressInfo
        );

    QDateTime mtime = QDateTime::currentDateTime().addSecs( -30 ); // 30 seconds ago
    mtime.setTime_t(mtime.toTime_t()); // hack for losing the milliseconds
    putJob->setModificationTime(mtime);
    putJob->setUiDelegate( 0 );
    connect( putJob, SIGNAL( result(KJob*) ),
            this, SLOT( slotResult(KJob*) ) );
    m_result = -1;
    enterLoop();
    QVERIFY( m_result == 0 ); // no error


    m_rwCount = 4;
    m_data = QByteArray();

    fileJob = KIO::open(u, QIODevice::ReadOnly);

    fileJob->setUiDelegate( 0 );
    connect( fileJob, SIGNAL( result(KJob*) ),
            this, SLOT( slotResult(KJob*) ) );
    connect( fileJob, SIGNAL(data(KIO::Job*, const QByteArray&)),
             this, SLOT(slotFileJob2Data(KIO::Job*, const QByteArray&)) );
    connect( fileJob, SIGNAL(open(KIO::Job*)),
             this, SLOT(slotFileJob2Open(KIO::Job*)) );
    connect( fileJob, SIGNAL(written(KIO::Job *, KIO::filesize_t)),
             this, SLOT(slotFileJob2Written (KIO::Job *, KIO::filesize_t)) );
    connect( fileJob, SIGNAL(position (KIO::Job *, KIO::filesize_t)),
             this, SLOT(slotFileJob2Position (KIO::Job *, KIO::filesize_t)) );
    connect( fileJob, SIGNAL(close(KIO::Job*)),
             this, SLOT(slotFileJob2Close(KIO::Job*)) );
    m_result = -1;

    enterLoop();
    QVERIFY( m_result == 0 ); // no error
    kDebug() << "resulting m_data: " << QString(m_data);
    QCOMPARE( m_data, QByteArray("test5test4test3test2test1"));

}
Exemplo n.º 22
0
void HTTPTracker::doAnnounce(const KURL & u)
{
    Out(SYS_TRK|LOG_NOTICE) << "Doing tracker request to url : " << u.prettyURL() << endl;
    KIO::MetaData md;
    setupMetaData(md);
    KIO::StoredTransferJob* j = KIO::storedGet(u,false,false);
    // set the meta data
    j->setMetaData(md);
    KIO::Scheduler::scheduleJob(j);

    connect(j,SIGNAL(result(KIO::Job* )),this,SLOT(onAnnounceResult( KIO::Job* )));

    active_job = j;
    requestPending();
}
Exemplo n.º 23
0
void LaconicaSearch::requestSearchResults(const SearchInfo &searchInfo,
                                          const ChoqokId& sinceStatusId,
                                          uint count, uint page)
{
    kDebug();
    KUrl url = buildUrl( searchInfo, sinceStatusId, count, page );
    kDebug()<<url;
    KIO::StoredTransferJob *job = KIO::storedGet( url, KIO::Reload, KIO::HideProgressInfo );
    if( !job ) {
        kError() << "Cannot create an http GET request!";
        return;
    }
    mSearchJobs[job] = searchInfo;
    connect( job, SIGNAL( result( KJob* ) ), this, SLOT( searchResultsReturned( KJob* ) ) );
    job->start();
}
Exemplo n.º 24
0
void ArchiveOrg::slotParseThumbs(KJob* job)
{
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QDomDocument doc;
    doc.setContent(QString::fromUtf8(storedQueryJob->data()));
    QDomNodeList links = doc.elementsByTagName(QStringLiteral("a"));
    if (links.isEmpty()) return;
    for (int i = 0; i < links.count(); ++i) {
        QString href = links.at(i).toElement().attribute(QStringLiteral("href"));
        if (!href.contains('/') && i >= links.count() / 2) {
            QString thumbUrl = m_thumbsPath + href;
            if (m_metaInfo.value(QStringLiteral("id")) == job->property("id").toString())
                emit gotThumb(thumbUrl);
            break;
        }
    }
}
Exemplo n.º 25
0
void ThumbnailPicker::slotSetFromURL() {
    //Attempt to load the specified URL
    QUrl u = ui->ImageURLBox->url();

    if ( u.isValid() ) {
        if ( u.isLocalFile() ) {
            QFile localFile( u.toLocalFile() );

            //Add image to list
            //If image is taller than desktop, rescale it.
            QImage im( localFile.fileName() );

            if ( im.isNull() ) {
                KMessageBox::sorry( 0,
                                    i18n("Failed to load image at %1", localFile.fileName() ),
                                    i18n("Failed to load image") );
                return;
            }

            uint w = im.width();
            uint h = im.height();
            uint pad = 0;/* FIXME later 4*marginHint() + 2*ui->SearchLabel->height() + actionButton( Ok )->height() + 25; */
            uint hDesk = QApplication::desktop()->availableGeometry().height() - pad;

            if ( h > hDesk )
                im = im.scaled( w*hDesk/h, hDesk, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );

            //Add Image to top of list and 50x50 thumbnail image and URL to top of listbox
            PixList.insert( 0, new QPixmap( QPixmap::fromImage( im ) ) );
            ui->ImageList->insertItem( 0, new QListWidgetItem ( QIcon(shrinkImage( PixList.last(), 50 )), u.url() ));

            //Select the new image
            ui->ImageList->setCurrentRow( 0 );
            slotSetFromList(0);

        } else {
            KIO::StoredTransferJob *j = KIO::storedGet( u, KIO::NoReload, KIO::HideProgressInfo );
            j->setUiDelegate(0);
            connect( j, SIGNAL( result(KJob*) ), SLOT( slotJobResult(KJob*) ) );
        }
    }
}
Exemplo n.º 26
0
bool Editor::openFile(const QUrl &_url)
{
	QUrl url = _url;
	if (maybeSave()) {
		if (url.isEmpty()) {
            url = QFileDialog::getOpenFileUrl(this, 
                                              i18n("Open"), 
                                              QUrl(), 
                                              QString("%1 (*.turtle);;%2 (*)").arg(i18n("Turtle code files")).arg(i18n("All files"))
                    );
		}
		if (!url.isEmpty()) {
			KIO::StoredTransferJob *job = KIO::storedGet(url);
			if (job->exec()) {
				QByteArray data = job->data();
				QBuffer buffer(&data);
				if (!buffer.open(QIODevice::ReadOnly | QIODevice::Text)) {
					return false; // can't happen
				}
				QTextStream in(&buffer);
				// check for our magic identifier
				QString s;
				s = in.readLine();
				if (s != KTURTLE_MAGIC_1_0) {
					KMessageBox::error(this, i18n("The file you try to open is not a valid KTurtle script, or is incompatible with this version of KTurtle.\nCannot open %1", url.toDisplayString(QUrl::PreferLocalFile)));
					return false;
				}
				QString localizedScript = Translator::instance()->localizeScript(in.readAll());
				setContent(localizedScript);
				setCurrentUrl(url);
				editor->document()->setModified(false);
				emit fileOpened(url);
				return true;
			} else {
				KMessageBox::error(this, job->errorString());
				return false;
			}
		}
	}
//	statusbar "Nothing opened"
	return false;
}
Exemplo n.º 27
0
        void UPnPRouter::downloadFinished(KJob* j)
        {
            if (j->error())
            {
                error = i18n("Failed to download %1: %2",location.url(),j->errorString());
                qDebug() << error << endl;
                return;
            }

            KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
            // load in the file (target is always local)
            UPnPDescriptionParser desc_parse;
            bool ret = desc_parse.parse(st->data(),this);
            if (!ret)
            {
                error = i18n("Error parsing router description.");
            }

            emit xmlFileDownloaded(this,ret);
        }
Exemplo n.º 28
0
void Bit_ly_Config::slotValidate()
{
    ui.validate_button->setEnabled(false);
    ui.validate_button->setText(i18n("Checking..."));
    QString login = QLatin1String("choqok");
    QString apiKey = QLatin1String("R_bdd1ae8b6191dd36e13fc77ca1d4f27f");
    QUrl reqUrl(QLatin1String("http://api.bit.ly/v3/validate"));
    QUrlQuery reqQuery;

    reqQuery.addQueryItem(QLatin1String("x_login"), ui.kcfg_login->text());
    reqQuery.addQueryItem(QLatin1String("x_apiKey"), ui.kcfg_api_key->text());

    if (Bit_ly_Settings::domain() == QLatin1String("j.mp")) {   //bit.ly is default domain
        reqQuery.addQueryItem(QLatin1String("domain"), QLatin1String("j.mp"));
    }

    reqQuery.addQueryItem(QLatin1String("login"), QLatin1String(login.toUtf8()));
    reqQuery.addQueryItem(QLatin1String("apiKey"), QLatin1String(apiKey.toUtf8()));
    reqQuery.addQueryItem(QLatin1String("format"), QLatin1String("txt"));
    reqUrl.setQuery(reqQuery);

    KIO::StoredTransferJob *job = KIO::storedGet(reqUrl, KIO::Reload, KIO::HideProgressInfo);
    job->exec();

    if (!job->error()) {
        QString output(QLatin1String(job->data()));
        if (output.startsWith(QLatin1Char('0')))
            KMessageBox::error(this, i18nc("The your_api_key part of the URL is a fixed part of the URL "
                                           "and should probably not be changed in localization.",
                                           "Provided data is invalid. Try another login or API key.\n"
                                           "You can find it on http://bit.ly/a/your_api_key"));
        if (output.startsWith(QLatin1Char('1'))) {
            KMessageBox::information(this, i18n("You entered valid information."));
        }
    } else {
        Choqok::NotifyManager::error(job->errorString(), i18n("bit.ly Config Error"));
    }

    ui.validate_button->setEnabled(true);
    ui.validate_button->setText(i18n("Validate"));
}
Exemplo n.º 29
0
    void UPnPRouter::downloadFinished(KJob* j)
    {
        if(j->error())
        {
            d->error = i18n("Failed to download %1: %2", d->location.toDisplayString(), j->errorString());
            Out(SYS_PNP | LOG_IMPORTANT) << d->error << endl;
            return;
        }

        KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
        // load in the file (target is always local)
        UPnPDescriptionParser desc_parse;
        bool ret = desc_parse.parse(st->data(), this);
        if(!ret)
        {
            d->error = i18n("Error parsing router description.");
        }

        xmlFileDownloaded(this, ret);
        d->getExternalIP();
    }
Exemplo n.º 30
0
QString Posterous::getAuthToken(const QUrl &localUrl)
{
    QUrl url(QLatin1String("http://posterous.com/api/2/auth/token"));
    QString login = PosterousSettings::login();
    QString pass = Choqok::PasswordManager::self()->readPassword(QStringLiteral("posterous_%1").arg(PosterousSettings::login()));
    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    job->addMetaData(QLatin1String("customHTTPHeader"),
                     QLatin1String("Authorization: Basic ") + QLatin1String(QStringLiteral("%1:%2").arg(login).arg(pass).toUtf8().toBase64()));
    job->exec();
    if (!job->error()) {
        const QByteArray data = job->data();
        const QJsonDocument json = QJsonDocument::fromJson(data);
        if (!json.isNull()) {
            QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("api_token"))) {
                QString tkn = map.value(QLatin1String("api_token")).toString();
                return tkn;
            } else {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
                qWarning() << "Parse error:" << data;
            }
        }
    } else {
        qCritical() << "Job error:" << job->errorString();
    }

    return QString();
}