Esempio n. 1
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();
}
Esempio n. 2
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());
	}
}
Esempio n. 3
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;
}
Esempio n. 4
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;
    }
}
Esempio n. 5
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);
    }
}
Esempio n. 6
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;
}
Esempio n. 7
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);
    }

}
Esempio n. 8
0
void Pastebin::onLoginFinished() {
    QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender());
    QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << "Login complete:" << statusCode.toInt();

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

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

        if(response.startsWith("Bad API request")) {
            emit loginFailed(response);
        }
        else {
            QNetworkRequest networkRequest = networkReply->request();

            emit loginComplete(response);
        }
    }
    else {
        qWarning() << "Error:" << networkReply->errorString();
        emit loginFailed(QString::null);
    }
}
Esempio n. 9
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);
    }
}
void OVDataRelatedContentYouTubeDataEngine::processReplyXML( QNetworkReply& _rReply, QList<OVDataRelatedContentResult *>& out_rlResults )
{
    // since NetworkAccessManager is NOT thread safe, we should NOT thread this function

    OVDataRelatedContentYouTubeDataEngineXmlStreamReader parser;

    parser.addData( _rReply.readAll() );
    parser.parseContent();

    out_rlResults = parser.getResults();

    foreach( OVDataRelatedContentResult* pResult, out_rlResults )
    {
        // foreach(QString imgUrl, r->thumbnailsLinks())
        // NDAL - just DL the FIRST image !!!
        if( pResult->thumbnailsLinks().size() > 0 )
        {
            QString strFilename = OVDataRelatedContentResult::convertHTTPLinkToFilename( pResult->thumbnailsLinks().at( 0 ) );
            QString strFilePath = strFilename;
            strFilePath.prepend( "/tmp/mnt/diska3/ov/img/youtube/" );

            // avoid re downloading it if it is already available in our temp dir
            if( ! QFile::exists( strFilePath ) )
            {
                QString imgUrl = pResult->thumbnailsLinks().at(0);
                //                                qDebug() << "    Downloading img: " << imgUrl;
                QNetworkReply* tmpReply = m_pManager->get( QNetworkRequest(QUrl( imgUrl ) ) );
                m_expectedImageMap.insert(tmpReply,pResult);
            }
            else
            {
                pResult->setValue( OVDataRelatedContentResult::Thumbnails, strFilename );
            }
        }
    }
}
Esempio n. 11
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 );
    }
}
Esempio n. 12
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);
}
Esempio n. 13
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());
	}
}
Esempio n. 14
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 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);
}
Esempio n. 16
0
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  QNetworkReply *reply = mCapabilitiesReply;
  reply->deleteLater();
  mCapabilitiesReply = 0;

  // handle network errors
  if ( reply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = reply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
  if ( !redirect.isNull() )
  {
    QgsDebugMsg( "redirecting to " + redirect.toUrl().toString() );
    QNetworkRequest request( redirect.toUrl() );
    setAuthorization( request );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

    connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
    return;
  }

  QByteArray buffer = reply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWFSCapabilities::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // hangle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWFSCapabilities::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  QString version = capabilitiesDocument.documentElement().attribute( "version" );
  if ( version != "1.0.0" && version != "1.0" )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "Either the WFS server does not support WFS version 1.0.0 or the WFS url is wrong" );
    emit gotCapabilities();
    return;
  }

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = capabilitiesDocument.elementsByTagNameNS( WFS_NAMESPACE, "FeatureType" );
  for ( unsigned int i = 0; i < featureTypeList.length(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "DefaultSRS" );
    if ( defaultCRSList.length() > 0 )
    {
      featureType.crslist.append( defaultCRSList.at( 0 ).toElement().text() );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "OtherSRS" );
    for ( unsigned int i = 0; i < otherCRSList.length(); ++i )
    {
      featureType.crslist.append( otherCRSList.at( i ).toElement().text() );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "SRS" );
    for ( unsigned int i = 0; i < srsList.length(); ++i )
    {
      featureType.crslist.append( srsList.at( i ).toElement().text() );
    }

    mCaps.featureTypes.append( featureType );
  }

  emit gotCapabilities();
}
void MagnatuneDownloadDialog::DownloadReadyRead() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
  download_file_->write(reply->readAll());
}
Esempio n. 18
0
void EntityServer::startDynamicDomainVerification() {
    qCDebug(entities) << "Starting Dynamic Domain Verification...";

    QString thisDomainID = DependencyManager::get<AddressManager>()->getDomainID().remove(QRegExp("\\{|\\}"));

    EntityTreePointer tree = std::static_pointer_cast<EntityTree>(_tree);
    QHash<QString, EntityItemID> localMap(tree->getEntityCertificateIDMap());

    QHashIterator<QString, EntityItemID> i(localMap);
    qCDebug(entities) << localMap.size() << "entities in _entityCertificateIDMap";
    while (i.hasNext()) {
        i.next();

        EntityItemPointer entity = tree->findEntityByEntityItemID(i.value());

        if (entity) {
            if (!entity->getProperties().verifyStaticCertificateProperties()) {
                qCDebug(entities) << "During Dynamic Domain Verification, a certified entity with ID" << i.value() << "failed"
                    << "static certificate verification.";
                // Delete the entity if it doesn't pass static certificate verification
                tree->deleteEntity(i.value(), true);
            } else {

                QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
                QNetworkRequest networkRequest;
                networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
                networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
                QUrl requestURL = NetworkingConstants::METAVERSE_SERVER_URL();
                requestURL.setPath("/api/v1/commerce/proof_of_purchase_status/location");
                QJsonObject request;
                request["certificate_id"] = i.key();
                networkRequest.setUrl(requestURL);

                QNetworkReply* networkReply = NULL;
                networkReply = networkAccessManager.put(networkRequest, QJsonDocument(request).toJson());

                connect(networkReply, &QNetworkReply::finished, [=]() {
                    QJsonObject jsonObject = QJsonDocument::fromJson(networkReply->readAll()).object();
                    jsonObject = jsonObject["data"].toObject();

                    if (networkReply->error() == QNetworkReply::NoError) {
                        if (jsonObject["domain_id"].toString() != thisDomainID) {
                            qCDebug(entities) << "Entity's cert's domain ID" << jsonObject["domain_id"].toString()
                                << "doesn't match the current Domain ID" << thisDomainID << "; deleting entity" << i.value();
                            tree->deleteEntity(i.value(), true);
                        } else {
                            qCDebug(entities) << "Entity passed dynamic domain verification:" << i.value();
                        }
                    } else {
                        qCDebug(entities) << "Call to" << networkReply->url() << "failed with error" << networkReply->error() << "; deleting entity" << i.value()
                            << "More info:" << jsonObject;
                        tree->deleteEntity(i.value(), true);
                    }

                    networkReply->deleteLater();
                });
            }
        } else {
            qCWarning(entities) << "During DDV, an entity with ID" << i.value() << "was NOT found in the Entity Tree!";
        }
    }

    int nextInterval = qrand() % ((_MAXIMUM_DYNAMIC_DOMAIN_VERIFICATION_TIMER_MS + 1) - _MINIMUM_DYNAMIC_DOMAIN_VERIFICATION_TIMER_MS) + _MINIMUM_DYNAMIC_DOMAIN_VERIFICATION_TIMER_MS;
    qCDebug(entities) << "Restarting Dynamic Domain Verification timer for" << nextInterval / 1000 << "seconds";
    _dynamicDomainVerificationTimer.start(nextInterval);
}
Esempio n. 19
0
void AppModel::handleWeatherNetworkData(QObject *replyObj)
{
    QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj);
    if (!networkReply)
        return;

    if (!networkReply->error()) {
        QString xmlData = QString::fromUtf8(networkReply->readAll());

        foreach (WeatherData *inf, d->forecast)
            delete inf;
        d->forecast.clear();

        QXmlStreamReader xml(xmlData);
        while (!xml.atEnd()) {
            xml.readNext();

            if (xml.name() == "current_conditions") {
                while (!xml.atEnd()) {
                    xml.readNext();
                    if (xml.name() == "current_conditions")
                        break;
                    if (xml.tokenType() == QXmlStreamReader::StartElement) {
                        if (xml.name() == "condition") {
                            d->now.setWeatherDesc(GET_DATA_ATTR);
                        } else if (xml.name() == "icon") {
                            d->now.setWeather(google2name(GET_DATA_ATTR));
                        } else if (xml.name() == "temp_f") {
                            d->now.setTempString(GET_DATA_ATTR + QChar(176));
                        }
                    }
                }
            }

            if (xml.name() == "forecast_conditions") {
                WeatherData *cur = NULL;

                while (!xml.atEnd()) {
                    xml.readNext();

                    if (xml.name() == "forecast_conditions") {
                        if (cur) {
                            d->forecast.append(cur);
                        }
                        break;
                    } else if (xml.tokenType() == QXmlStreamReader::StartElement) {
                        if (!cur)
                            cur = new WeatherData();
                        if (xml.name() == "day_of_week") {
                            cur->setDayOfWeek(GET_DATA_ATTR);
                        } else if (xml.name() == "icon") {
                            cur->setWeather(google2name(GET_DATA_ATTR));
                        } else if (xml.name() == "low") {
                            QString v = cur->tempString();
                            QStringList parts = v.split("/");
                            if (parts.size() >= 1)
                                parts.replace(0, GET_DATA_ATTR + QChar(176));
                            if (parts.size() == 0)
                                parts.append(GET_DATA_ATTR + QChar(176));

                            cur->setTempString(parts.join("/"));
                        } else if (xml.name() == "high") {
                            QString v = cur->tempString();
                            QStringList parts = v.split("/");
                            if (parts.size() == 2)
                                parts.replace(1, GET_DATA_ATTR + QChar(176));
                            if (parts.size() == 0)
                                parts.append("");
                            if (parts.size() == 1)
                                parts.append(GET_DATA_ATTR + QChar(176));

                            cur->setTempString(parts.join("/"));
                        }
                    }
                }
            }
        }

        if (!(d->ready)) {
            d->ready = true;
            emit readyChanged();
        }

        emit weatherChanged();
    }
    networkReply->deleteLater();
}
bool weatherStation::update()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkRequest netRequest(*apiLink);
    QNetworkReply *netReply;

    QTimer timer;
    timer.setSingleShot(true);
    QEventLoop loop;

    netReply = manager->get(netRequest);
    connect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

    timer.start(10000);

    loop.exec();

    QString data;
    QFile weatherTempData("weatherTempData.txt");

    weatherTempData.open(QFile::ReadWrite);

    if(timer.isActive()) {
        timer.stop();
        if(netReply->error() > 0) {
          qDebug() << "network error";
          data = weatherTempData.readAll();
          qDebug() << "read from file";
        }
        else {
          int v = netReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

          if (v >= 200 && v < 300) {  // Success
              data = netReply->readAll();
              weatherTempData.seek(0);
              QTextStream out(&weatherTempData);
              out << data;
              weatherTempData.seek(0);
              //qDebug() << weatherTempData.readAll();
          }
        }
    } else {
       // timeout
       disconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));

       netReply->abort();
       data = weatherTempData.readAll();
       qDebug() << "read from file";
    }
    weatherTempData.close();
    QXmlStreamReader *xmlReader = new QXmlStreamReader(data);
    int weatherRecordCounter = 0;
    //Parse the XML until we reach end of it
    while(!xmlReader->atEnd() && !xmlReader->hasError()) {
            // Read next element
            QXmlStreamReader::TokenType token = xmlReader->readNext();
            //If token is just StartDocument - go to next
            if(token == QXmlStreamReader::StartDocument) {
                    continue;
            }
            //qDebug() << xmlReader->name();


            if(token == QXmlStreamReader::EndElement)
                   if(xmlReader->name() == "time")
                   {
                        weatherRecordCounter++;
                        //qDebug() << "is end element";
                        continue;
                   }

            //
            //If token is StartElement - read it
            if(token == QXmlStreamReader::StartElement) {

                    if(xmlReader->name() == "sun") {
                        QXmlStreamAttributes att = xmlReader->attributes();
                        sunrise = sunrise.fromString(att.value("rise").toString(),"yyyy-MM-ddTHH:mm:ss");
                        sunrise.setTimeSpec(Qt::UTC);
                        sunrise = sunrise.toLocalTime();
                        sunset = sunset.fromString(att.value("set").toString(),"yyyy-MM-ddTHH:mm:ss");
                        sunset.setTimeSpec(Qt::UTC);
                        sunset = sunset.toLocalTime();
                        //qDebug() << sunrise.toString("yyyy-MM-ddTHH:mm:ss");
                        //qDebug() << sunset.toString("yyyy-MM-ddTHH:mm:ss");
                            continue;
                    }

                    if(xmlReader->name() == "time") {


                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecord *record = new weatherRecord();
                            record->day = record->day.fromString(att.value("day").toString(),"yyyy-MM-dd");
                            /*record->from = record->from.fromString(att.value("from").toString(),"yyyy-MM-ddTHH:mm:ss");
                            record->to = record->to.fromString(att.value("to").toString(),"yyyy-MM-ddTHH:mm:ss");
                            qDebug() << record->from.toString("yyyy-MM-ddTHH:mm:ss");
                            qDebug() << record->to.toString("yyyy-MM-ddTHH:mm:ss");*/
                            weatherRecords.append(record);
                            continue;

                    }

                    if(xmlReader->name() == "precipitation")
                    {
                        if(xmlReader->isEndElement())
                        {
                            weatherRecords.at(weatherRecordCounter)->precipitationType = "no";
                            continue;
                        }
                        else
                        {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->precipitationType=att.value("type").toString();
                            weatherRecords.at(weatherRecordCounter)->precipitationValue=att.value("value").toFloat();
                            weatherRecords.at(weatherRecordCounter)->precipitationUnit=att.value("unit").toString();
                            continue;
                        }
                    }

                    if(xmlReader->name() == "windDirection")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->windDirection=att.value("deg").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "windSpeed")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->windSpeed=att.value("mps").toFloat();
                            weatherRecords.at(weatherRecordCounter)->windType=att.value("name").toString();
                            continue;
                    }
                    if(xmlReader->name() == "temperature")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->currentTemp=att.value("day").toFloat();
                            weatherRecords.at(weatherRecordCounter)->minTemp=att.value("min").toFloat();
                            weatherRecords.at(weatherRecordCounter)->maxTemp=att.value("max").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "pressure")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->pressure=att.value("value").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "humidity")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->humidity=att.value("value").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "clouds")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->cloudsPercent=att.value("all").toInt();
                            weatherRecords.at(weatherRecordCounter)->cloudsName=att.value("value").toString();
                            continue;
                    }
                    if(xmlReader->name() == "symbol")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->icon=att.value("var").toString();

                            continue;
                    }

            }
    }
    if(xmlReader->hasError()) return false;
    return true;
}
Esempio n. 21
0
void UrlFactory::TryCorrectGoogleVersions()
{
    static bool versionRetrieved = false;

    if (versionRetrieved)
    {
        return;
    }
    QMutexLocker locker(&mutex);
    if(CorrectGoogleVersions && !IsCorrectGoogleVersions())
    {
        QNetworkReply *reply;
        QNetworkRequest qheader;
        QNetworkAccessManager network;
        QEventLoop q;
        QTimer tT;
        tT.setSingleShot(true);
        connect(&network, SIGNAL(finished(QNetworkReply*)),
                &q, SLOT(quit()));
        connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
        network.setProxy(Proxy);
#ifdef DEBUG_URLFACTORY
        qDebug()<<"Correct GoogleVersion";
#endif //DEBUG_URLFACTORY
        setIsCorrectGoogleVersions(true);
        QString url = "http://maps.google.com";

        qheader.setUrl(QUrl(url));
        qheader.setRawHeader("User-Agent",UserAgent);
        reply=network.get(qheader);
        tT.start(Timeout);
        q.exec();
        if(!tT.isActive())
            return;
        tT.stop();
        if( (reply->error()!=QNetworkReply::NoError))
        {
#ifdef DEBUG_URLFACTORY
            qDebug()<<"Try corrected version withou abort or error:"<<reply->errorString();
#endif //DEBUG_URLFACTORY
            return;
        }
        QString html=QString(reply->readAll());
        QRegExp reg("\"*http://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
        if(reg.indexIn(html)!=-1)
        {
            QStringList gc=reg.capturedTexts();
            VersionGoogleMap = QString("m@%1").arg(gc[1]);
            VersionGoogleMapChina = VersionGoogleMap;

#ifdef DEBUG_URLFACTORY
            qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap;
#endif //DEBUG_URLFACTORY
        }

        reg=QRegExp("\"*http://mt0.google.com/vt/lyrs=h@(\\d*)",Qt::CaseInsensitive);
        if(reg.indexIn(html)!=-1)
        {
            QStringList gc=reg.capturedTexts();
            VersionGoogleLabels = QString("h@%1").arg(gc[1]);
            VersionGoogleLabelsChina = VersionGoogleLabels;
#ifdef DEBUG_URLFACTORY
            qDebug()<<"TryCorrectGoogleVersions, VersionGoogleLabels: "<<VersionGoogleLabels;
#endif //DEBUG_URLFACTORY
        }
        reg=QRegExp("\"*http://khm\\D?\\d.google.com/kh/v=(\\d*)",Qt::CaseInsensitive);
        if(reg.indexIn(html)!=-1)
        {
            QStringList gc=reg.capturedTexts();
            VersionGoogleSatellite = gc[1];
            VersionGoogleSatelliteKorea = VersionGoogleSatellite;
            VersionGoogleSatelliteChina = "s@" + VersionGoogleSatellite;
            qDebug()<<"TryCorrectGoogleVersions, VersionGoogleSatellite: "<<VersionGoogleSatellite;

        }
        reg=QRegExp("\"*http://mt0.google.com/vt/lyrs=t@(\\d*),r@(\\d*)",Qt::CaseInsensitive);
        if(reg.indexIn(html)!=-1)
        {
            QStringList gc=reg.capturedTexts();
            VersionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]);
            VersionGoogleTerrainChina = VersionGoogleTerrain;
#ifdef DEBUG_URLFACTORY
            qDebug()<<"TryCorrectGoogleVersions, VersionGoogleTerrain: "<<VersionGoogleTerrain;
#endif //DEBUG_URLFACTORY
        }
        reply->deleteLater();

    }
Esempio n. 22
0
void RequestDataJob::readyRead()
{
    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
    m_buffer.write(reply->readAll());
}
Esempio n. 23
0
QByteArray QgsSvgCache::getImageData( const QString &path ) const
{
  // is it a path to local file?
  QFile svgFile( path );
  if ( svgFile.exists() )
  {
    if ( svgFile.open( QIODevice::ReadOnly ) )
    {
      return svgFile.readAll();
    }
    else
    {
      return QByteArray();
    }
  }

  // maybe it's a url...
  if ( !path.contains( "://" ) ) // otherwise short, relative SVG paths might be considered URLs
  {
    return QByteArray();
  }

  QUrl svgUrl( path );
  if ( !svgUrl.isValid() )
  {
    return QByteArray();
  }

  // check whether it's a url pointing to a local file
  if ( svgUrl.scheme().compare( "file", Qt::CaseInsensitive ) == 0 )
  {
    svgFile.setFileName( svgUrl.toLocalFile() );
    if ( svgFile.exists() )
    {
      if ( svgFile.open( QIODevice::ReadOnly ) )
      {
        return svgFile.readAll();
      }
    }

    // not found...
    return QByteArray();
  }

  // the url points to a remote resource, download it!
  QNetworkReply *reply = 0;

  // The following code blocks until the file is downloaded...
  // TODO: use signals to get reply finished notification, in this moment
  // it's executed while rendering.
  while ( 1 )
  {
    QgsDebugMsg( QString( "get svg: %1" ).arg( svgUrl.toString() ) );
    QNetworkRequest request( svgUrl );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    reply = QgsNetworkAccessManager::instance()->get( request );
    connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( downloadProgress( qint64, qint64 ) ) );

    //emit statusChanged( tr( "Downloading svg." ) );

    // wait until the image download finished
    // TODO: connect to the reply->finished() signal
    while ( !reply->isFinished() )
    {
      QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents, 500 );
    }

    if ( reply->error() != QNetworkReply::NoError )
    {
      QgsMessageLog::logMessage( tr( "SVG request failed [error: %1 - url: %2]" ).arg( reply->errorString() ).arg( reply->url().toString() ), tr( "SVG" ) );

      reply->deleteLater();
      return QByteArray();
    }

    QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( redirect.isNull() )
    {
      // neither network error nor redirection
      // TODO: cache the image
      break;
    }

    // do a new request to the redirect url
    svgUrl = redirect.toUrl();
    reply->deleteLater();
  }

  QVariant status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
  if ( !status.isNull() && status.toInt() >= 400 )
  {
    QVariant phrase = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute );
    QgsMessageLog::logMessage( tr( "SVG request error [status: %1 - reason phrase: %2]" ).arg( status.toInt() ).arg( phrase.toString() ), tr( "SVG" ) );

    reply->deleteLater();
    return QByteArray();
  }

  QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString();
  QgsDebugMsg( "contentType: " + contentType );
  if ( !contentType.startsWith( "image/svg+xml", Qt::CaseInsensitive ) )
  {
    reply->deleteLater();
    return QByteArray();
  }

  // read the image data
  QByteArray ba = reply->readAll();
  reply->deleteLater();

  return ba;
}
Esempio n. 24
0
void BillboardOverlay::replyFinished() {
    // replace our byte array with the downloaded data
    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
    _billboard = reply->readAll();
    _isLoaded = true;
}
Esempio n. 25
0
void DriveController::checkDownload() {
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

    QString response;
    if (reply) {
        if (reply->error() == QNetworkReply::NoError) {
            const int available = reply->bytesAvailable();
            if (available > 0) {
                m_Mutex.lockForWrite();
                int selectedDownload;
                for(int i = 0 ; i < m_Downloads.length() ; ++i) {
                    if(m_Downloads.at(i).first == reply->url().toString()) {
                        selectedDownload = i;
                        break;
                    }
                }

                QFile file(m_Downloads.at(selectedDownload).second);
                file.open(QIODevice::WriteOnly);
                file.write(reply->readAll());
                file.close();

                m_Downloads.removeAt(selectedDownload);

                m_Mutex.unlock();

                bb::system::SystemToast *toast = new bb::system::SystemToast(this);
                toast->setBody(tr("Download completed"));
                toast->setPosition(bb::system::SystemUiPosition::MiddleCenter);
                toast->show();

            }

        } else {
            qDebug() << "reply... " << reply->errorString();

            // remove case of failure...
            m_Mutex.lockForWrite();
            int selectedDownload = 0;
            for(int i = 0 ; i < m_Downloads.length() ; ++i) {
                if(m_Downloads.at(i).first == reply->url().toString()) {
                    selectedDownload = i;
                    break;
                }
            }
            if(m_Downloads.size() > 0)
                m_Downloads.removeAt(selectedDownload);
            m_Mutex.unlock();
        }

        reply->deleteLater();
    }


    // download all the files in the stack
    m_Mutex.lockForWrite();
    if(m_Downloads.size() > 0) {
        authentifiedDownload(m_Downloads.first().first);
    }

    m_Mutex.unlock();
}
Esempio n. 26
0
void UpdateManager::requestReceived()
{
	bool haveNewVersion = false;
	QMessageBox msgbox;
	QString msgTitle = tr("Check for updates.");
	QString msgText = "<h3>" + tr("Subsurface was unable to check for updates.") + "</h3>";

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
	if (reply->error() != QNetworkReply::NoError) {
		//Network Error
		msgText = msgText + "<br/><b>" + tr("The following error occurred:") + "</b><br/>" + reply->errorString()
				+ "<br/><br/><b>" + tr("Please check your internet connection.") + "</b>";
	} else {
		//No network error
		QString responseBody(reply->readAll());
		QString responseLink;
		if (responseBody.contains('"'))
			responseLink = responseBody.split("\"").at(1);

		msgbox.setIcon(QMessageBox::Information);
		if (responseBody == "OK") {
			msgText = tr("You are using the latest version of Subsurface.");
		} else if (responseBody.startsWith("[\"http")) {
			haveNewVersion = true;
			msgText = tr("A new version of Subsurface is available.<br/>Click on:<br/><a href=\"%1\">%1</a><br/> to download it.")
					.arg(responseLink);
		} else if (responseBody.startsWith("Latest version")) {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			haveNewVersion = true;
			msgText = QString("<b>") + tr("A new version of Subsurface is available.") + QString("</b><br/><br/>") +
					tr("Latest version is %1, please check %2 our download page %3 for information in how to update.")
					.arg(responseLink).arg("<a href=\"http://subsurface-divelog.org/download\">").arg("</a>");
		} else {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			if (!responseBody.contains("latest development") &&
			    !responseBody.contains("newer") &&
			    !responseBody.contains("beta", Qt::CaseInsensitive))
				haveNewVersion = true;
			if (responseBody.contains("Newest release version is "))
				responseBody.replace("Newest release version is ", tr("Newest release version is "));
			msgText = tr("The server returned the following information:").append("<br/><br/>").append(responseBody);
			msgbox.setIcon(QMessageBox::Warning);
		}
	}
#ifndef SUBSURFACE_MOBILE
	if (haveNewVersion || !isAutomaticCheck) {
		msgbox.setWindowTitle(msgTitle);
		msgbox.setWindowIcon(QIcon(":/subsurface-icon"));
		msgbox.setText(msgText);
		msgbox.setTextFormat(Qt::RichText);
		msgbox.exec();
	}
	if (isAutomaticCheck) {
		QSettings settings;
		settings.beginGroup("UpdateManager");
		if (!settings.contains("DontCheckForUpdates")) {
			// we allow an opt out of future checks
			QMessageBox response(MainWindow::instance());
			QString message = tr("Subsurface is checking every two weeks if a new version is available. If you don't want Subsurface to continue checking, please click Decline.");
			response.addButton(tr("Decline"), QMessageBox::RejectRole);
			response.addButton(tr("Accept"), QMessageBox::AcceptRole);
			response.setText(message);
			response.setWindowTitle(tr("Automatic check for updates"));
			response.setIcon(QMessageBox::Question);
			response.setWindowModality(Qt::WindowModal);
			int ret = response.exec();
			if (ret == QMessageBox::Accepted)
				settings.setValue("DontCheckForUpdates", "FALSE");
			else
				settings.setValue("DontCheckForUpdates", "TRUE");
		}
	}
#endif
}
Esempio n. 27
0
// Callback from fetchIcon
void
MainWindow::iconDownloaded()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString savePath = reply->request().attribute(QNetworkRequest::User).toString();
    int wasRedirected = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1)).toInt();
    QString username = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+2)).toString();
    QString password = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+3)).toString();

    QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if (!redirect.toUrl().isEmpty() && !wasRedirected)
    {
        qDebug() << "Was redirected to " << redirect.toUrl();
        reply->deleteLater();
        QUrl redir = redirect.toUrl();
        if (!username.isEmpty())
        {
            redir.setUserName(username);
            redir.setPassword(password);
        }
        QNetworkRequest req = QNetworkRequest(redir);
        req.setAttribute(QNetworkRequest::User, QVariant(savePath));
        req.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1), QVariant(1));
        QNetworkReply *rep = pManager->get(req);
        connect(rep, SIGNAL(finished()),
                this, SLOT(iconDownloaded()));
        return;
    }

    qDebug() << "Icon downloaded";
    if (reply->error())
    {
        reply->close();
        qDebug() << "Couldn't get icon";
        fetchHTMLIcon(reply->url().toString(), savePath);
        return;
    }

    QByteArray logoData = reply->readAll();
    // The favicon can be in various formats, so convert it to something
    // we know we can safely display
    QBuffer logoBuffer(&logoData);
    logoBuffer.open(QIODevice::ReadOnly);
    QImageReader reader(&logoBuffer);
    QSize iconSize(16, 16);
    if(reader.canRead())
    {
        while((reader.imageCount() > 1) && (reader.currentImageRect() != QRect(0, 0, 16, 16)))
        {
            if (!reader.jumpToNextImage())
                   break;
        }

        reader.setScaledSize(iconSize);
        const QImage icon = reader.read();
        if (icon.format() == QImage::Format_Invalid)
        {
            fetchHTMLIcon(reply->url().toString(), savePath);
        }
        else
        {
            icon.save(savePath, "PNG");
            QFileInfo info(savePath);
            int tabIndex = compareTabName(info.baseName());
            if (tabIndex != -1)
                ui->trackerTab->setTabIcon(tabIndex, QIcon(QPixmap::fromImage(icon)));
        }
    }
    else
    {
        qDebug() << "Invalid image";
        fetchHTMLIcon(reply->url().toString(), savePath);
    }

    logoBuffer.close();
    reply->close();
}
Esempio n. 28
0
int QgsGml::getFeatures( const QString &uri, QgsWkbTypes::Type *wkbType, QgsRectangle *extent, const QString &userName, const QString &password, const QString &authcfg )
{
  //start with empty extent
  mExtent.setMinimal();

  QNetworkRequest request( uri );
  if ( !authcfg.isEmpty() )
  {
    if ( !QgsApplication::authManager()->updateNetworkRequest( request, authcfg ) )
    {
      QgsMessageLog::logMessage(
        tr( "GML Getfeature network request update failed for authcfg %1" ).arg( authcfg ),
        tr( "Network" ),
        Qgis::Critical
      );
      return 1;
    }
  }
  else if ( !userName.isNull() || !password.isNull() )
  {
    request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( userName, password ).toLatin1().toBase64() );
  }
  QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( request );

  if ( !authcfg.isEmpty() )
  {
    if ( !QgsApplication::authManager()->updateNetworkReply( reply, authcfg ) )
    {
      reply->deleteLater();
      QgsMessageLog::logMessage(
        tr( "GML Getfeature network reply update failed for authcfg %1" ).arg( authcfg ),
        tr( "Network" ),
        Qgis::Critical
      );
      return 1;
    }
  }

  connect( reply, &QNetworkReply::finished, this, &QgsGml::setFinished );
  connect( reply, &QNetworkReply::downloadProgress, this, &QgsGml::handleProgressEvent );

  //find out if there is a QGIS main window. If yes, display a progress dialog
  QProgressDialog *progressDialog = nullptr;
  QWidget *mainWindow = nullptr;
  QWidgetList topLevelWidgets = qApp->topLevelWidgets();
  for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it )
  {
    if ( ( *it )->objectName() == QLatin1String( "QgisApp" ) )
    {
      mainWindow = *it;
      break;
    }
  }
  if ( mainWindow )
  {
    progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow );
    progressDialog->setWindowModality( Qt::ApplicationModal );
    connect( this, &QgsGml::dataReadProgress, progressDialog, &QProgressDialog::setValue );
    connect( this, &QgsGml::totalStepsUpdate, progressDialog, &QProgressDialog::setMaximum );
    connect( progressDialog, &QProgressDialog::canceled, this, &QgsGml::setFinished );
    progressDialog->show();
  }

  int atEnd = 0;
  while ( !atEnd )
  {
    if ( mFinished )
    {
      atEnd = 1;
    }
    QByteArray readData = reply->readAll();
    if ( !readData.isEmpty() )
    {
      QString errorMsg;
      if ( !mParser.processData( readData, atEnd, errorMsg ) )
        QgsMessageLog::logMessage( errorMsg, QObject::tr( "WFS" ) );

    }
    QCoreApplication::processEvents();
  }

  fillMapsFromParser();

  QNetworkReply::NetworkError replyError = reply->error();
  QString replyErrorString = reply->errorString();

  delete reply;
  delete progressDialog;

  if ( replyError )
  {
    QgsMessageLog::logMessage(
      tr( "GML Getfeature network request failed with error: %1" ).arg( replyErrorString ),
      tr( "Network" ),
      Qgis::Critical
    );
    return 1;
  }

  *wkbType = mParser.wkbType();

  if ( *wkbType != QgsWkbTypes::Unknown )
  {
    if ( mExtent.isEmpty() )
    {
      //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features
      calculateExtentFromFeatures();
    }
  }

  if ( extent )
    *extent = mExtent;

  return 0;
}
Esempio n. 29
0
/**
 *  Called after response from twitter
 */
void QTweetNetBase::reply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

    // prep m_response for finished() signal
    if (reply) {
    	m_response = reply->readAll();
    } else {
        m_response.clear();
    }

    // ALWAYS emit a finished signal no matter what happens
	emit finished(m_response);


	// now analyze the response
    if (reply) {

    	QString rateLimit(reply->rawHeader("X-Rate-Limit-Limit"));
    	QString rateRemaining(reply->rawHeader("X-Rate-Limit-Remaining"));
    	QString limitRest(reply->rawHeader("X-Rate-Limit-Reset"));

    	uint timeToReset = limitRest.toLongLong()- QDateTime::currentDateTime().toTime_t();

    	QString contentType(reply->rawHeader("content-type"));
    	bool contentTypeHasJson = contentType.contains("application/json", Qt::CaseInsensitive);

        if (reply->error() == QNetworkReply::NoError) {
        	if (isJsonParsingEnabled() && contentTypeHasJson) {
        		parseJson(m_response);
        	}
        } else {
            //dump error
            qDebug() << "Network error: " << reply->error();
            qDebug() << "Error string: " << reply->errorString();
            qDebug() << "Error response: " << m_response;

            //HTTP status code
            int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

            //prep error
            QTweetNetError* err = 0;

            if (!contentTypeHasJson) {
            	err = new QTweetHttpError(httpStatus, m_response);
            } else {
				//try to json parse the error response
				QJson::Parser parser;
				bool ok;
				QVariant json = parser.parse(m_response, &ok);
				QVariantMap errMsgMap = json.toMap();
				QMap<int, QString> twitterErrors;

				if (ok) {
					// here are a few sample responses we've seen:
					//{"request":"\/1\/users\/search.json?q=&per_page=20&page=1","error":"Client must provide a 'q' parameter with a value."}
					//{"error":"You must enter a query."}
					//{"errors":[{"message": "...", "code": 34}]}
					QList<QVariant> errors = errMsgMap["errors"].toList();
					QList<QVariant>::iterator it = errors.begin();

					while (it != errors.end()) {
						QVariantMap error = (*it).toMap();
						int errorCode = error["code"].toInt();
						QString errorMessage = error["message"].toString();

						twitterErrors[errorCode] = errorMessage;

						it++;
					}

					if (twitterErrors.size() > 0) {
						err = new QTweetServiceErrors(httpStatus, m_response, json, twitterErrors);
					} else {
						qDebug() << "Parsing json ok but twitter errors not found";
						err = new QTweetRawServiceError(httpStatus, m_response, json);
					}
				}
				else {
					qDebug() << "Unable to parse json in response";
					err = new QTweetHttpError(httpStatus, m_response);
				}
            }

            //finally emit the error signal
            if (err) {
            	emit error(*err);
            	err->deleteLater();
            } else {
            	Q_ASSERT(false);
            }
		}
        reply->deleteLater();
    }
}
Esempio n. 30
0
void AppDownloader::appJsonFetched()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(sender());
    reply->deleteLater();

    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "Error fetching App Json" << reply->errorString();
        return;
    }

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error);
    if (error.error != QJsonParseError::NoError) {
        qWarning() << "Error parsing App Json" << error.errorString();
        return;
    }

    QVariantMap map = jsonDoc.toVariant().toMap();
    if (!map.contains("data") || map.value("data").toList().length() == 0) {
        qWarning() << "Unexpected json content:" << jsonDoc.toJson();
        return;
    }
    QVariantMap appMap = map.value("data").toList().first().toMap();
    QString pbwFileUrl = appMap.value("latest_release").toMap().value("pbw_file").toString();
    if (pbwFileUrl.isEmpty()) {
        qWarning() << "pbw file url empty." << jsonDoc.toJson();
        return;
    }

    QString appid = appMap.value("id").toString();
    QUuid quuid = appMap.value("uuid").toUuid();
    QDir dir;
    Pebble *p = (Pebble *)parent();
    if(p->installedAppIds().contains(quuid)) {
        AppInfo ai = p->appInfo(quuid);
        QString exId = ai.storeId();
        if(appid != exId && !dir.exists(m_storagePath+appid) && dir.exists(m_storagePath+exId)) {
            dir.rename(m_storagePath+exId,m_storagePath+appid);
        } else if(appid != exId) {
            qWarning() << "App exists but dir is out of sync:" << exId << "<!>" << appid;
        }
    } else {
        dir.mkpath(m_storagePath + appid);
    }

    QString iconFile = appMap.value("list_image").toMap().value("144x144").toString();
    QNetworkRequest request(iconFile);
    QNetworkReply *imageReply = m_nam->get(request);
    qDebug() << "fetching image" << iconFile;
    connect(imageReply, &QNetworkReply::finished, [this, imageReply, appid]() {
        imageReply->deleteLater();
        QString targetFile = m_storagePath + appid + "/list_image.png";
        qDebug() << "saving image to" << targetFile;
        QFile f(targetFile);
        if (f.open(QFile::WriteOnly)) {
            f.write(imageReply->readAll());
            f.close();
        }
    });
    appid += ("/v" + appMap.value("latest_release").toMap().value("version").toString() + ".pbw");
    fetchPackage(pbwFileUrl, appid);
}