void LastFmLoginWidget::getToken()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkReply *reply = manager->get(QNetworkRequest(getTokenUrl));
    QEventLoop wait;
    connect(manager,SIGNAL(finished(QNetworkReply*)),&wait,SLOT(quit()));
    connect(manager,SIGNAL(finished(QNetworkReply*)), manager, SLOT(deleteLater()));
    //one take is gonna be 10sec
    QTimer oneTake;
    oneTake.start(10000);
    connect(&oneTake,SIGNAL(timeout()),&wait,SLOT(quit()));
    wait.exec();
    //finally get the reply
    QByteArray byteArrayToken = reply->readAll();
    reply->deleteLater();
    //parse xml response
    QXmlStreamReader xmlReader;
    xmlReader.addData(byteArrayToken);
    while (!(xmlReader.name().toString()=="token"))
        xmlReader.readNext();
    TOKEN = xmlReader.readElementText();
    qDebug()<< TOKEN;
    authUrl = QUrl("http://www.last.fm/api/auth/?api_key=" + API_KEY + "&token=" + TOKEN);
}
Пример #2
0
void QTwitchChat::onSelfLoaded()
{
    QNetworkReply *reply = qobject_cast< QNetworkReply * >( sender() );

    QJsonParseError parseError;
    QJsonDocument jsonDoc;

    jsonDoc = QJsonDocument::fromJson( reply->readAll(), &parseError );

    if( parseError.error == QJsonParseError::NoError )
    {
        if( jsonDoc.isObject() )
        {
            QJsonObject _links = ( jsonDoc.object() )[ "_links" ].toObject() ;

            selfLink_ = _links[ "self" ].toString();
            emotIconsLink_ = _links[ "emoticons" ].toString();
            badgesLink_ = _links[ "badges" ].toString();

            getEmotIcons();
        }
    }
    reply->deleteLater();
}
Пример #3
0
// Download a single file
bool Handler::downloadFile(string file)
{
    QNetworkAccessManager m_WebCtrl;
    QUrl url((gitHub + file).c_str());
    QEventLoop loop;
    QNetworkRequest request(url);
    QNetworkReply* reply = m_WebCtrl.get(request);
    connect(reply,SIGNAL(finished()),&loop, SLOT(quit()));
    loop.exec();
    QString fileName = url.toDisplayString().remove(gitHub.c_str());

    QByteArray m_DownloadedData;
    m_DownloadedData = reply->readAll();
    reply->deleteLater();
    if (m_DownloadedData.startsWith("Not Found")) {
        writeLog((fileName + " not found from source.\n").toStdString());
        return false;
    }
    QFile qfile("./" + fileName);
    qfile.open(QIODevice::WriteOnly);
    qfile.write(m_DownloadedData);
    qfile.close();
    return true;
}
Пример #4
0
bool WizDocumentEditStatusSyncThread::sendEditingMessage(const QString& strUserAlias, const QString& strObjID)
{
    QString strUrl = ::WizFormatString5("%1/add?obj_id=%2&user_id=%3&t=%4&token=%5",
                                        WizKMGetDocumentEditStatusURL(),
                                        strObjID,
                                        strUserAlias,
                                        ::WizIntToStr(WizGetTickCount()),
                                        WizToken::token());

    if (!m_netManager)
    {
        m_netManager = new QNetworkAccessManager();
    }
    QNetworkReply* reply = m_netManager->get(QNetworkRequest(strUrl));

    //qDebug() << "sendEditingMessage called " <<strUrl;
    qDebug() << "[EditStatus]:Send editing status : " << strObjID;

    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    return reply->error() == QNetworkReply::NoError;
}
Пример #5
0
BtsApiNotifier *BtsApi::getFolderHosts(const QString &secret)
{
	QueryList ql;

	ql << QueryPair("secret", secret);

	QUrl apiUrl = getApiUrl(p, "get_folder_hosts", ql);

	QNetworkReply *reply = p->nam->get(QNetworkRequest(apiUrl));
	BtsApiNotifier *notifier = new BtsApiNotifier(this);

	connect(reply, &QNetworkReply::finished, [this, reply, notifier, secret]()
	{
		notifier->deleteLater();

		if(checkForError(reply, notifier))
			return;

		QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());

		if(checkForError(doc, notifier))
			return;

		QJsonObject obj = doc.object();
		QJsonArray arr = obj.value("hosts").toArray();
		QStringList res;

		for(const QJsonValue &val: arr)
			res << val.toString();

		emit getFolderHostsResult(res, secret);
		emit notifier->getFolderHostsResult(res, secret);
	});

	return notifier;
}
void CommandFileList::queryFinished()
{
    Q_D(CommandFileList);
    tryAutoDelete();
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply)
        return;
    reply->deleteLater();

    if (checkInvalidReplyAndRefreshToken(reply))
        return;

    QVariantMap map;
    if (!parseJsonReply(reply, map))
        return;

    d->files.clear();
    Q_FOREACH (const QVariant& item, map.value("items").toList())
    {
        d->files << FileInfo(item.toMap());
    }

    emitSuccess();
}
Пример #7
0
void SpotifyImages::FetchInfo(int id, const Song& metadata) {
  if (metadata.artist().isEmpty()) {
    emit Finished(id);
    return;
  }

  // Fetch artist id.
  QUrl search_url(kSpotifySearchUrl);
  search_url.addQueryItem("q", metadata.artist());
  search_url.addQueryItem("type", "artist");
  search_url.addQueryItem("limit", "1");

  qLog(Debug) << "Fetching artist:" << search_url;

  QNetworkRequest request(search_url);
  QNetworkReply* reply = network_->get(request);
  NewClosure(reply, SIGNAL(finished()), [this, id, reply]() {
    reply->deleteLater();
    QJson::Parser parser;
    QVariantMap result = parser.parse(reply).toMap();
    QVariantMap artists = result["artists"].toMap();
    if (artists.isEmpty()) {
      emit Finished(id);
      return;
    }
    QVariantList items = artists["items"].toList();
    if (items.isEmpty()) {
      emit Finished(id);
      return;
    }
    QVariantMap artist = items.first().toMap();
    QString spotify_uri = artist["uri"].toString();

    FetchImagesForArtist(id, ExtractSpotifyId(spotify_uri));
  });
}
Пример #8
0
void PlaylistTest::testStatic1()
{
    DynamicPlaylist::PlaylistParams p;
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "tallest man on earth" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "bon iver" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "mumford and sons" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Type, Echonest::DynamicPlaylist::ArtistRadioType ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Results, 10 ) );

    QNetworkReply* reply = DynamicPlaylist::staticPlaylist( p );

    qDebug() << reply->url().toString();
    QVERIFY( reply->url().toString() == QLatin1String( "http://developer.echonest.com/api/v4/playlist/static?api_key=JGJCRKWLXLBZIFAZB&format=xml&artist=tallest+man+on+earth&artist=bon+iver&artist=mumford+and+sons&type=artist-radio&results=10" ) );

    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();
    SongList songs = DynamicPlaylist::parseStaticPlaylist( reply );

    QVERIFY( songs.size() == 10 );
    Q_FOREACH( const Song& song, songs )
        QVERIFY( !song.id().isEmpty() );

}
Пример #9
0
void
MusicBrainzPlugin::notInCacheSlot( InfoStringHash criteria, InfoRequestData requestData )
{
    switch ( requestData.type )
    {
        case InfoArtistReleases:
        {
            QString requestString( "http://musicbrainz.org/ws/2/artist" );
            QUrl url( requestString );
            url.addQueryItem( "query", criteria["artist"] );
            QNetworkReply* reply = TomahawkUtils::nam()->get( QNetworkRequest( url ) );
            reply->setProperty( "requestData", QVariant::fromValue< Tomahawk::InfoSystem::InfoRequestData >( requestData ) );

            connect( reply, SIGNAL( finished() ), SLOT( artistSearchSlot() ) );
            break;
        }

        case InfoAlbumSongs:
        {
            QString requestString( "http://musicbrainz.org/ws/2/artist" );
            QUrl url( requestString );
            url.addQueryItem( "query", criteria["artist"] );
            QNetworkReply* reply = TomahawkUtils::nam()->get( QNetworkRequest( url ) );
            reply->setProperty( "requestData", QVariant::fromValue< Tomahawk::InfoSystem::InfoRequestData >( requestData ) );

            connect( reply, SIGNAL( finished() ), SLOT( albumSearchSlot() ) );
            break;
        }

        default:
        {
            Q_ASSERT( false );
            break;
        }
    }
}
Пример #10
0
void OnlineSearchBioRxiv::bibTeXDownloadDone() {
    emit progress(++curStep, numSteps);
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

    if (handleErrors(reply)) {
        /// ensure proper treatment of UTF-8 characters
        const QString bibTeXcode = QString::fromUtf8(reply->readAll().constData());

        if (!bibTeXcode.isEmpty()) {
            FileImporterBibTeX importer;
            File *bibtexFile = importer.fromString(bibTeXcode);

            if (bibtexFile != NULL) {
                for (File::ConstIterator it = bibtexFile->constBegin(); it != bibtexFile->constEnd(); ++it) {
                    QSharedPointer<Entry> entry = (*it).dynamicCast<Entry>();
                    publishEntry(entry);
                }

                delete bibtexFile;
            } else {
                qCWarning(LOG_KBIBTEX_NETWORKING) << "No valid BibTeX file results returned on request on" << reply->url().toDisplayString();
            }
        }
    }

    if (d->resultPageUrls.isEmpty())
        stopSearch(resultNoError);
    else {
        const QUrl firstUrl = *d->resultPageUrls.constBegin();
        d->resultPageUrls.remove(firstUrl);
        QNetworkRequest request(firstUrl);
        QNetworkReply *reply = InternalNetworkAccessManager::self()->get(request);
        InternalNetworkAccessManager::self()->setNetworkReplyTimeout(reply);
        connect(reply, &QNetworkReply::finished, this, &OnlineSearchBioRxiv::resultPageDone);
    }
}
Пример #11
0
void AzubuHandler::handleStreams() {

    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    QByteArray data = reply->readAll();

    // delete the reply
    reply->deleteLater();

    QJsonDocument response(QJsonDocument::fromJson(data.mid(1,data.length()-2)));
    QJsonArray streamsArray = response.array();

    for(int i=0; i<streamsArray.size(); ++i) {

        QJsonObject streamJson = streamsArray[i].toObject();
        AzubuStream stream;

        // populate the stream
        stream.read(streamJson);

        // emit signal
        emit addStream(stream);
    }

}
Пример #12
0
void MusicBrainzProvider::downloadCover(QByteArray ba, QNetworkReply *reply)
{
	QString album = reply->property("album").toString();

	// In case we don't get the picture at the first attempt, try again
	QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
	if (redirectionTarget.isNull()) {

		// The current cover has been downloaded to a temporary location, the lists can be populated
		//QPixmap pixmap;

		// It's possible to have a valid release but without cover yet :(
		//if (pixmap.loadFromData(ba)) {
		//	emit aboutToCreateCover(album, pixmap);
		//}
		emit aboutToCreateCover(album, ba);
	} else {
		QUrl newUrl = reply->url().resolved(redirectionTarget.toUrl());
		QNetworkReply *reply = _manager->get(QNetworkRequest(newUrl));
		reply->setProperty("type", type());
		reply->setProperty("requestType", FO_DownloadCover);
		reply->setProperty("album", album);
	}
}
Пример #13
0
void
UpcomingEventsWidget::loadImage()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>( sender() );
    if( !reply )
        return;

    reply->deleteLater();
    const KUrl &url = reply->request().url();
    if( m_imageUrl != url )
        return;

    if( reply->error() != QNetworkReply::NoError )
        return;

    QPixmap image;
    if( image.loadFromData( reply->readAll() ) )
    {
        image = image.scaled( 116, 116, Qt::KeepAspectRatio, Qt::SmoothTransformation );
        image = The::svgHandler()->addBordersToPixmap( image, 6, QString(), true );
        QPixmapCache::insert( url.url(), image );
        m_image->setPixmap( image );
    }
}
Пример #14
0
void NetworkTaskManager::startDownload( LoadImageTask * task )
{
	IniConfig & ini = config();
	ini.pushSection( "Image_Loading" );
	QString prefix = ini.readString( "HttpUrl" );
	QString user = ini.readString( "HttpUser" );
	QString password = ini.readString( "HttpPassword" );
	ini.popSection();
	
	if( task->mPath[0].isLetter() )
		task->mPath[0] = task->mPath[0].toLower();
	
	QUrl url( prefix + task->mPath.replace(":","").replace("\\","/") );
	LOG_5( "Fetching URL: " + url.toString() );
	QNetworkRequest request(url);
	request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2").arg(user).arg(password).toAscii()).toBase64()); 
	QNetworkReply * reply = mNetworkAccessManager->get(request);
	reply->setReadBufferSize(0);
	connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(slotError(QNetworkReply::NetworkError)) );
#ifndef QT_NO_OPENSSL
	connect( reply, SIGNAL(sslErrors(const QList<QSslError> &)), SLOT(slotSslErrors(const QList<QSslError> &)) );
#endif
	mReplyDict[reply] = task;
}
Пример #15
0
extern "C" void reverseGeoLookup(degrees_t latitude, degrees_t longitude, uint32_t uuid)
{
	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	request.setUrl(QString("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3")
		       .arg(uiLanguage(NULL)).arg(latitude.udeg / 1000000.0).arg(longitude.udeg / 1000000.0));
	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	QNetworkReply *reply = rgl->get(request);
	QEventLoop loop;
	QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
	loop.exec();
	QJsonParseError errorObject;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &errorObject);
	if (errorObject.error != QJsonParseError::NoError) {
		qDebug() << errorObject.errorString();
	} else {
		QJsonObject obj = jsonDoc.object();
		QJsonObject address = obj.value("address").toObject();
		qDebug() << "found country:" << address.value("country").toString();
		struct dive_site *ds = get_dive_site_by_uuid(uuid);
		ds->notes = add_to_string(ds->notes, "countrytag: %s", address.value("country").toString().toUtf8().data());
	}
}
Пример #16
0
void Pastebin::onSubmitPasteFinished() {
    QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender());
    QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << "Paste complete:" << statusCode.toInt();

    if(networkReply->error() == QNetworkReply::NoError) {
        const QString response = networkReply->readAll();

        qDebug() << "Response:" << response;

        if(response.startsWith("Bad API request")) {
            qWarning() << "Error with paste";
            emit pasteFailed(response);
        }
        else {
            qDebug() << "Paste successful";
            emit pasteComplete(response);
        }
    }
    else {
        qWarning() << "Error with paste:" << networkReply->errorString();
        emit pasteFailed(QString::null);
    }
}
Пример #17
0
void IMDB::onSearchIdFinished()
{
    QNetworkReply* reply = static_cast<QNetworkReply *>(QObject::sender());
    QList<ScraperSearchResult> results;
    if (reply->error() == QNetworkReply::NoError) {
        QString msg = QString::fromUtf8(reply->readAll());
        ScraperSearchResult result;

        QRegExp rx;
        rx.setMinimal(true);
        rx.setPattern("<h1 class=\"header\"> <span class=\"itemprop\" itemprop=\"name\">(.*)</span>");
        if (rx.indexIn(msg) != -1)
            result.name = rx.cap(1);

        rx.setPattern("<h1 class=\"header\"> <span class=\"itemprop\" itemprop=\"name\">.*<span class=\"nobr\">\\(<a href=\"[^\"]*\" >([0-9]*)</a>\\)</span>");
        if (rx.indexIn(msg) != -1) {
            result.released = QDate::fromString(rx.cap( 1 ), "yyyy");
        } else {
            rx.setPattern("<h1 class=\"header\"> <span class=\"itemprop\" itemprop=\"name\">.*</span>.*<span class=\"nobr\">\\(([0-9]*)\\)</span>");
            if (rx.indexIn(msg) != -1)
                result.released = QDate::fromString(rx.cap(1), "yyyy");
        }

        rx.setPattern("<link rel=\"canonical\" href=\"http://www.imdb.com/title/(.*)/\" />");
        if (rx.indexIn(msg) != -1)
            result.id = rx.cap(1);

        if ((!result.id.isEmpty()) && (!result.name.isEmpty()))
            results.append(result);
    } else {
        qWarning() << "Network Error" << reply->errorString();
    }

    reply->deleteLater();
    emit searchDone(results);
}
Пример #18
0
void ExtenderSOAPAPI::setWLANNoSecurity()
{
    //    NewRadio="";
    //    NewSSID="";
    //    NewChannel="";
    //    NewWirelessMode="";
    QString AXML = "";
    AXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    AXML.append("<SOAP-ENV:Envelope ");
    AXML.append("xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    AXML.append("xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" ");
    AXML.append("xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">");
    AXML.append("<SOAP-ENV:Body>");
    AXML.append("<SetWLANNoSecurity>");
    AXML.append("<NewRadio xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">2.4G</NewRadio>");
    AXML.append("<NewSSID xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">Wireless001_EXT</NewSSID>");
    AXML.append("<NewChannel xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">Auto</NewChannel>");
    AXML.append("<NewWirelessMode xsi:type=\"xsd:string\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">Auto</NewWirelessMode>");
    AXML.append("</SetWLANNoSecurity>");
    AXML.append("</SOAP-ENV:Body>");
    AXML.append("</SOAP-ENV:Envelope>");

    qDebug()<< "------+++++++++"<<AXML;
    QString SOAPAction = "urn:NETGEAR-ROUTER:service:WLANConfiguration:1#SetWLANNoSecurity";
    QString data = AXML;

    QNetworkRequest networkReq;
    networkReq.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml;charset=utf-8"));
    networkReq.setRawHeader("SOAPAction", SOAPAction.toUtf8());
    networkReq.setUrl(QUrl("http://192.168.1.250:80/soap/server_sa/"));

    QNetworkReply *r = manager->post(networkReq, data.toUtf8());
    QTextCodec * codec = QTextCodec::codecForName("utf8");
    QString all = codec->toUnicode(r->readAll());
    qDebug() << "-------" << all;
}
Пример #19
0
void HttpDownloadWorker::slotReplyFinished()
{
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	Q_ASSERT(reply);

	if(!m_error.hasError())
	{
		m_tryTimes = TRY_TIMES;
		int bytes = write2File(reply->readAll());
		m_filePiece.DoneBytes += bytes;
		emit pieceProgressChanged(m_filePiece.ID, m_filePiece.DoneBytes);
// 		QString info = QString("piece id: %0 ,total: %1, left: %2").arg(QString::number(m_filePiece.ID)).arg(QString::number(m_filePiece.DoneBytes)).arg(QString::number(leftBytes()));
// 	    qDebug()<<info;
		if(leftBytes() != 0) 
		{
			downloadSmallPiece();
		}
		else
		{
			emit pieceFinished(m_filePiece.ID);
			emit finished();
		}
	}
	else 
	{
		//Retry
		if((--m_tryTimes) > 0)
		{
			reply->deleteLater();
			downloadSmallPiece();
			return;
		}
		//ÏÂÔØ´íÎó£¬Ìá½»´íÎóÐźÅ;
		emitError(error());
	}
}
Пример #20
0
/**
  * React to servers responce after route has been sent.
  */
void HttpClient::ackOfRoute()
{
    qDebug() << "_ackOfRoute";

    if(myMainw->routeSaveDialog->routeDialog)
        myMainw->routeSaveDialog->routeDialog->setLabelInfoToUser("");

    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

    QNetworkReply::NetworkError errorcode;
    errorcode = reply->error();
    if(errorcode != 0) {
        qDebug() <<  "errorcode:" << errorcode << reply->errorString();
        if(myMainw->routeSaveDialog->routeDialog)
            QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending ",reply->errorString());
        if(myMainw->routeSaveDialog->routeDialog)
            myMainw->routeSaveDialog->routeDialog->setSendServerButtonEnabled();
    }
    else {
        qDebug() << "errorcode:" << errorcode << reply->errorString();
        if(myMainw->routeSaveDialog->routeDialog)
            QMessageBox::about(myMainw->routeSaveDialog->routeDialog, "Server reply to route sending", "Route received " + reply->readAll());
    }
}
Пример #21
0
void RequestModel::handleCurrentChanged (const QModelIndex& newItem)
{
	RequestHeadersModel_->clear ();
	ReplyHeadersModel_->clear ();

	if (!newItem.isValid ())
		return;

	QNetworkReply *reply = item (itemFromIndex (newItem)->row (), 0)->
		data ().value<QNetworkReply*> ();
	if (reply)
	{
		QNetworkRequest r = reply->request ();
		FeedHeaders (&r, RequestHeadersModel_);
		FeedHeaders (reply, ReplyHeadersModel_);
	}
	else
	{
		FeedHeaders (item (itemFromIndex (newItem)->row (), 1)->
				data ().toMap (), RequestHeadersModel_);
		FeedHeaders (item (itemFromIndex (newItem)->row (), 2)->
				data ().toMap (), ReplyHeadersModel_);
	}
}
Пример #22
0
/**
  * React to servers responce after request for categories has been sent.
  */
void HttpClient::ackOfCategories()
{
    qDebug() << "_ackOfCategories";

    if(myMainw->topResultDialog)
        myMainw->topResultDialog->setLabelInfoToUser("");

    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    myXmlreader->xmlReadCategories(reply);

    QNetworkReply::NetworkError errorcode;
    errorcode = reply->error();
    if(errorcode != 0) {
        qDebug() <<  "errorcode:" << errorcode << reply->errorString();
        //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories",reply->errorString());
        if(myMainw->topResultDialog)
            myMainw->topResultDialog->setLabelInfoToUser("You're not logged! Please register or log in.");
    }
    else {
        //QMessageBox::about(myMainw->topResultDialog, "Server reply to requesting categories ", "OK");
        if(myMainw->topResultDialog)
            myMainw->topResultDialog->setLabelInfoToUser("");
    }
}
Пример #23
0
QStringList history() {
    QList<FormField> formData = {
        textField("k", settings.apiKey.toUtf8())
    };

    QHttpMultiPart *form = createForm(formData);
    QNetworkReply *reply = apiCall("/api/hist", form);

    if (!reply)
        return QStringList();

    QString replyText = QString::fromUtf8(reply->readAll());
    QStringList lines = replyText.split('\n', QString::SkipEmptyParts);

    if (lines.isEmpty())
        return QStringList();
    else if (lines.at(0).trimmed() != "0")
        return QStringList();
    else
        lines.removeFirst();

    for (int i = 0; i < lines.count(); ++i) {
        QStringList lineParts = lines.at(i).split(',');

        if (lineParts.length() < 4)
            continue;

        int id = lineParts[0].toInt();
        QDateTime time = QDateTime::fromString(lineParts[1], "yyyy-MM-dd HH:mm:ss");
        QString url = lineParts[2];
        QString fn = lineParts[3];
        recent << PuushedEntry{id, time, url, fn};
    }

    return QStringList();
}
Пример #24
0
requestStruct HTTPdownloader::doGet(QString url) {
	int tries = 0;
	requestStruct strct;
	do {
		qDebug() << "get" << url;
		QNetworkRequest req;
		req.setUrl(QUrl(url));
		//req.setRawHeader("User-Agent", "bsToGetLinklist/1.0 (Nokia; Qt)"); //was a test because bs.to wasnt returning valid results
		QNetworkReply *reply = this->get(static_cast<const QNetworkRequest>(req));
		QEventLoop loop;
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		loop.exec();

		strct.httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
		strct.data = reply->readAll();
		strct.url = url;
		qDebug() << "getDone" << strct.httpStatusCode << strct.data.size() << url << tries;
		reply->deleteLater();
		if (strct.httpStatusCode == 200)
			return strct;
		++tries;
	} while (tries < 4);
	return strct;
}
Пример #25
0
BtsApiNotifier *BtsApi::setPreferences(const QVariantHash &prefs)
{
	QueryList ql;

	for(auto it = prefs.constBegin(); it != prefs.constEnd(); ++it)
		ql << QueryPair(it.key(), it.value().toString());

	QUrl apiUrl = getApiUrl(p, "set_prefs", ql);

	QNetworkReply *reply = p->nam->get(QNetworkRequest(apiUrl));
	BtsApiNotifier *notifier = new BtsApiNotifier(this);

	connect(reply, &QNetworkReply::finished, [this, reply, notifier]()
	{
		notifier->deleteLater();

		if(checkForError(reply, notifier))
			return;

		QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());

		if(checkForError(doc, notifier))
			return;

		QJsonObject obj = doc.object();
		QVariantHash res;

		for(auto it = obj.constBegin(); it != obj.constEnd(); ++it)
			res[it.key()] = it.value().toVariant();

		emit setPreferencesResult(res);
		emit notifier->setPreferencesResult(res);
	});

	return notifier;
}
Пример #26
0
void MainWindow::on_pushButton_7_clicked() //dnsZT
{

    ui->textEdit->clear();
    QEventLoop loop;

    QNetworkRequest req( QUrl( QString("http://api.hackertarget.com/zonetransfer/?q="+ui->lineEdit_8->text())));

    QNetworkAccessManager manager;
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkReply *resposta = manager.get(req);
    loop.exec();

    if (resposta->error() == QNetworkReply::NoError) {
        //qDebug() << "leitura" <<resposta->readAll();
        ui->textEdit->setPlainText(resposta->readAll());
        delete resposta;
    }
    else {
        QMessageBox::critical(this,"Erro",resposta->errorString());
        delete resposta;
    }
}
Пример #27
0
QtJson::JsonObject Rest::post(QString action, QtJson::JsonObject content) {
    url.setUrl(srvAddress + "/" + action);
    request.setUrl(url);

    QByteArray jsonString = QtJson::serialize(content);
    QByteArray postDataSize = QByteArray::number(jsonString.size());

    request.setRawHeader("Content-Type", "application/json");
    request.setRawHeader("Content-Length", postDataSize);
    QNetworkReply* currentReply = networkManager.post(request,jsonString);
    QEventLoop loop;
    QObject::connect(currentReply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    QString data = (QString)currentReply->readAll();
    bool ok;
    QtJson::JsonObject result = QtJson::parse(data,ok).toMap();
    if(!ok) {
        return result;
    } else  {
        return result;
    }

}
Пример #28
0
void ItemsManagerWorker::OnCharacterListReceived() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(QObject::sender());
    QByteArray bytes = reply->readAll();
    rapidjson::Document doc;
    doc.Parse(bytes.constData());

    if (doc.HasParseError() || !doc.IsArray()) {
        QLOG_ERROR() << "Received invalid reply instead of character list. The reply was"
            << bytes.constData();
        if (doc.HasParseError()) {
            QLOG_ERROR() << "The error was" << rapidjson::GetParseError_En(doc.GetParseError());
        }
        updating_ = false;
        return;
    }

    QLOG_INFO() << "Received character list, there are" << doc.Size() << "characters";
    for (auto &character : doc) {
        if (!character.HasMember("league") || !character.HasMember("name") || !character["league"].IsString() || !character["name"].IsString()) {
            QLOG_ERROR() << "Malformed character entry, the reply is most likely invalid" << bytes.constData();
            continue;
        }
        if (character["league"].GetString() == league_) {
            std::string name = character["name"].GetString();
            ItemLocation location;
            location.set_type(ItemLocationType::CHARACTER);
            location.set_character(name);
            QueueRequest(MakeCharacterRequest(name), location);
        }
    }

    // now get first tab and tab list
    QNetworkReply *first_tab = network_manager_.get(MakeTabRequest(0, true));
    connect(first_tab, SIGNAL(finished()), this, SLOT(OnFirstTabReceived()));
    reply->deleteLater();
}
Пример #29
0
/**
 *  Gets access tokens for user entered pin number
 *  @param pin entered pin number
 */
void OAuthTwitter::requestAccessToken(const QString& pin)
{
    Q_ASSERT(m_netManager != 0);

    QUrl url(TWITTER_ACCESS_TOKEN_URL);
    url.addEncodedQueryItem("oauth_verifier", pin.toAscii()); 

    QByteArray oauthHeader = generateAuthorizationHeader(url, OAuth::POST);

    QEventLoop q;
    QTimer t;
    t.setSingleShot(true);

    connect(&t, SIGNAL(timeout()), &q, SLOT(quit()));

    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QNetworkReply *reply = m_netManager->post(req, QByteArray());
    connect(reply, SIGNAL(finished()), &q, SLOT(quit()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error()));

    t.start(5000);
    q.exec();

    if(t.isActive()){
        QByteArray response = reply->readAll();
        parseTokens(response);
        reply->deleteLater();

        emit authorizePinFinished();
    } else {
        qDebug() << "Timeout";
    }
}
    void _replyFinished()
    {
        Q_Q( NetworkAccessManagerProxy );
        QNetworkReply *reply = static_cast<QNetworkReply*>( q->sender() );

        KUrl url = reply->request().url();
        QList<CallBackData*> callbacks = urlMap.values( url );
        urlMap.remove( url );
        QByteArray data = reply->readAll();
        data.detach(); // detach so the bytes are not deleted before methods are invoked
        foreach( const CallBackData *cb, callbacks )
        {
            // There may have been a redirect.
            KUrl redirectUrl = q->getRedirectUrl( reply );

            // Check if there's no redirect.
            if( redirectUrl.isEmpty() )
            {
                QByteArray sig = QMetaObject::normalizedSignature( cb->method );
                sig.remove( 0, 1 ); // remove first char, which is the member code (see qobjectdefs.h)
                                    // and let Qt's meta object system handle the rest.
                if( cb->receiver )
                {
                    bool success( false );
                    const QMetaObject *mo = cb->receiver.data()->metaObject();
                    int methodIndex = mo->indexOfSlot( sig );
                    if( methodIndex != -1 )
                    {
                        Error err = { reply->error(), reply->errorString() };
                        QMetaMethod method = mo->method( methodIndex );
                        success = method.invoke( cb->receiver.data(),
                                                cb->type,
                                                Q_ARG( KUrl, reply->request().url() ),
                                                Q_ARG( QByteArray, data ),
                                                Q_ARG( NetworkAccessManagerProxy::Error, err ) );
                    }

                    if( !success )
                    {
                        debug() << QString( "Failed to invoke method %1 of %2" )
                            .arg( QString(sig) ).arg( mo->className() );
                    }
                }
            }
            else
            {
                debug() << "the server is redirecting the request to: " << redirectUrl;

                // Let's try to fetch the data again, but this time from the new url.
                QNetworkReply *newReply = q->getData( redirectUrl, cb->receiver.data(), cb->method, cb->type );

                emit q->requestRedirected( url, redirectUrl );
                emit q->requestRedirected( reply, newReply );
            }
        }