Ejemplo n.º 1
0
int Updater::checkManifest()
{
    QUrl baseUrl(MANIFEST_URL);
    QNetworkAccessManager manager;
    QNetworkRequest request = getNetworkRequest(baseUrl);
    QNetworkReply *rep = manager.get(request);

    while(rep->error() == QNetworkReply::NoError && !rep->isFinished())
        QCoreApplication::processEvents();

    while(true)
    {
        while(!rep->isFinished())
            QCoreApplication::processEvents();

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

        QVariant redirect = rep->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if(redirect.type() != QVariant::Url)
            break;

        // redirect
        baseUrl = baseUrl.resolved(redirect.toUrl());
        request = getNetworkRequest(baseUrl);
        rep = manager.get(request);
    }

    if(rep->isFinished() && rep->size() != 0)
    {
        QString s;
        QString ver(VERSION);
        while(!rep->atEnd())
        {
            s = rep->readLine();

            QStringList parts = s.split(' ', QString::SkipEmptyParts);
            if(parts.size() < 3 || !ver.contains(parts[0]))
                continue;

            if(REVISION < parts[1].toInt())
                return RES_UPDATE_AVAILABLE;
            else
                return RES_NO_UPDATE;
        }
    }
    return RES_NO_UPDATE;
}
Ejemplo n.º 2
0
AutoUpdater::UpdateFile AutoUpdater::getUpdateFile(UpdateFileMeta fileMeta)
{
    UpdateFile file;
    file.metadata = fileMeta;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(filesURI+fileMeta.id)));
    while (!reply->isFinished())
    {
        if (abortFlag)
            return file;
        qApp->processEvents();
    }

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "AutoUpdater: getUpdateFile: network error: "<<reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return file;
    }

    file.data = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();

    return file;
}
Ejemplo n.º 3
0
void KDSoapPendingCall::Private::parseReply()
{
    if (parsed) {
        return;
    }

    QNetworkReply *reply = this->reply.data();

	if (!reply->isFinished()) {
		qDebug() << "KDSoapPendingCall::parseReply: Reply is not finished. Bytes available" << reply->bytesAvailable() << "Error" << reply->error();
	}
    parsed = true;
    if (reply->error()) {
        replyMessage.setFault(true);
        replyMessage.addArgument(QString::fromLatin1("faultcode"), QString::number(reply->error()));
        replyMessage.addArgument(QString::fromLatin1("faultstring"), reply->errorString());
        if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 500) {
            qDebug() << "Status code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << "Error:" << reply->errorString();
            return;
        }
    }

    const QByteArray data = reply->readAll();
    if (!data.isEmpty()) {
        KDSoapMessageReader reader;
        reader.xmlToMessage(data, &replyMessage, 0, &replyHeaders);
    }
}
Ejemplo n.º 4
0
QByteArray AutoUpdater::getUpdateFlist()
{
    QByteArray flist;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    manager->setProxy(Settings::getInstance().getProxy());
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(flistURI)));
    while (!reply->isFinished())
    {
        if (abortFlag)
            return flist;
        qApp->processEvents();
    }

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "getUpdateFlist: network error: " + reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return flist;
    }

    flist = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();

    return flist;
}
Ejemplo n.º 5
0
//! [3]
void AppModel::positionUpdated(QGeoPositionInfo gpsPos)
{
    d->coord = gpsPos.coordinate();

    if (!(d->useGps))
        return;

    QString latitude, longitude;
    longitude.setNum(d->coord.longitude());
    latitude.setNum(d->coord.latitude());
//! [3]
    QUrl url("http://maps.google.com/maps/geo");
    QUrlQuery query;
    query.addQueryItem("q", latitude + "," + longitude);
    query.addQueryItem("output", "xml");
    url.setQuery(query);

    QNetworkReply *rep = d->nam->get(QNetworkRequest(url));
    // connect up the signal right away
    d->geoReplyMapper->setMapping(rep, rep);
    connect(rep, SIGNAL(finished()),
            d->geoReplyMapper, SLOT(map()));
    // it might have finished though while we were connecting it
    // if so, pass it straight on
    if (rep->isFinished())
        this->handleGeoNetworkData(rep);
}
void ImapMsgPartNetAccessManagerTest::testMessageParts()
{
    QFETCH(QByteArray, bodystructure);
    QFETCH(QByteArray, partId);
    QFETCH(QString, url);
    QFETCH(bool, validity);
    QFETCH(QByteArray, text);

    cServer("* 1 FETCH (UID 1 BODYSTRUCTURE (" + bodystructure + "))\r\n" +
            "* 2 FETCH (UID 2 BODYSTRUCTURE (" + bodystructure + "))\r\n"
            + t.last("OK fetched\r\n"));
    QVERIFY(model->rowCount(msg1) > 0);

    netAccessManager->setModelMessage(msg1);
    QNetworkRequest req;
    req.setUrl(QUrl(url));
    QNetworkReply *res = netAccessManager->get(req);
    if (validity) {
        QVERIFY(qobject_cast<Imap::Network::MsgPartNetworkReply*>(res));
        cClient(t.mk("UID FETCH 1 (BODY.PEEK[") + partId + "])\r\n");
        cServer("* 1 FETCH (UID 1 BODY[" + partId + "] {" + QByteArray::number(text.size()) + "}\r\n" +
                                                                               text + ")\r\n" + t.last("OK fetched\r\n"));
        cEmpty();
        QCOMPARE(text, res->readAll());
    } else {
        QVERIFY(qobject_cast<Imap::Network::ForbiddenReply*>(res));
    }
#if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
    QCOMPARE(res->isFinished(), true);
#endif
    cEmpty();
    QVERIFY(errorSpy->isEmpty());
}
Ejemplo n.º 7
0
void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
{
    WebCoreSynchronousLoader syncLoader;
    RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(request, &syncLoader, true, false));

    ResourceHandleInternal* d = handle->getInternal();
    if (!d->m_user.isEmpty() || !d->m_pass.isEmpty()) {
        // If credentials were specified for this request, add them to the url,
        // so that they will be passed to QNetworkRequest.
        KURL urlWithCredentials(d->m_firstRequest.url());
        urlWithCredentials.setUser(d->m_user);
        urlWithCredentials.setPass(d->m_pass);
        d->m_firstRequest.setURL(urlWithCredentials);
    }
    d->m_context = context;
    d->m_job = new QNetworkReplyHandler(handle.get(), QNetworkReplyHandler::SynchronousLoad);

    QNetworkReply* reply = d->m_job->reply();
    // When using synchronous calls, we are finished when reaching this point.
    if (reply->isFinished()) {
        syncLoader.setReplyFinished(true);
        d->m_job->forwardData();
        d->m_job->finish();
    } else
        syncLoader.waitForCompletion();

    error = syncLoader.resourceError();
    data = syncLoader.data();
    response = syncLoader.resourceResponse();
}
Ejemplo n.º 8
0
void auto_dirvers_fatie::logout()
{
	QString str_url_1 = "http://passport.mydrivers.com/logout.aspx?returnurl=http://www.mydrivers.com";

	QUrl url_1(str_url_1);
	url_1.setUrl(str_url_1);
	HttpParamList header_list1;
	header_list1.push_back(HttpParamItem("Accept", "text/html, application/xhtml+xml, */*"));
	header_list1.push_back(HttpParamItem("Connection", "Keep-Alive"));
	header_list1.push_back(HttpParamItem("Accept-Encoding", "gzip, deflate"));
	header_list1.push_back(HttpParamItem("Accept-Language", "zh-cn"));
	header_list1.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
	header_list1.push_back(HttpParamItem("DNT", "1"));
	//header_list1.push_back(HttpParamItem("Cache-Control", "max-age=0"));
	header_list1.push_back(HttpParamItem("Host", "passport.mydrivers.com")); // mhost
	header_list1.push_back(HttpParamItem("User-Agent", S_UA));

	QNetworkReply* rp = network.GetRequest(url_1, header_list1);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (rp && !rp->isFinished())
	{
		QCoreApplication::processEvents();
		if (_t.elapsed() >= 20000) {
			_timeout = true;
			break;
		}
	}

	rp->deleteLater();
}
/** short A fetching operation gets interrupted by switching to the offline mode */
void ImapMsgPartNetAccessManagerTest::testFetchResultOfflineSingle()
{
    COMMON_METADATA_CHAT_PLAIN_AND_SIGNED

    netAccessManager->setModelMessage(msg1);
    QNetworkRequest req;
    req.setUrl(QUrl(QLatin1String("trojita-imap://msg/0")));
    QNetworkReply *res = netAccessManager->get(req);
    QVERIFY(qobject_cast<Imap::Network::MsgPartNetworkReply*>(res));
    cClient(t.mk("UID FETCH 1 (BODY.PEEK[1])\r\n"));

    QPersistentModelIndex msg1p1 = msgListA.child(0, 0).child(0, 0);
    QVERIFY(msg1p1.isValid());
    QCOMPARE(msg1p1.data(Imap::Mailbox::RoleMessageUid), QVariant(1u));
    QCOMPARE(msg1p1.data(Imap::Mailbox::RoleIsFetched), QVariant(false));
    QCOMPARE(msg1p1.data(Imap::Mailbox::RoleIsUnavailable), QVariant(false));

    networkPolicy->setNetworkOffline();
    cClient(t.mk("LOGOUT\r\n"));
    cServer(t.last("OK logged out\r\n") + "* BYE eh\r\n");
    QCOMPARE(msg1p1.data(Imap::Mailbox::RoleIsFetched), QVariant(false));
    QCOMPARE(msg1p1.data(Imap::Mailbox::RoleIsUnavailable), QVariant(true));

#if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
    QCOMPARE(res->isFinished(), true);
#endif
    QCOMPARE(res->error(), QNetworkReply::TimeoutError);
}
Ejemplo n.º 10
0
void IconData::download()
{
    if(m_isRemoteFile)
    {
        if(!s_localImageCache.contains(m_localUrl))
        {
            snoreDebug( SNORE_DEBUG ) << "Downloading:" << m_url;
            QNetworkAccessManager manager;
            QEventLoop loop;
            QNetworkRequest request(m_url);
            request.setRawHeader("User-Agent", "SnoreNotify");
            QNetworkReply *reply = manager.get(request);
            QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            QTimer::singleShot(1000,&loop, SLOT(quit()));//timeout
            loop.exec();
            if(reply->isFinished())
            {
                m_img = QImage::fromData(reply->readAll(), "PNG");
                m_img.save(m_localUrl,"PNG");
                s_localImageCache.insert(m_localUrl);
                snoreDebug( SNORE_DEBUG ) << m_localUrl << "added to cache";
            }
        }
        else
        {
            m_img = QImage(m_localUrl);
        }
    }
}
Ejemplo n.º 11
0
void KDSoapPendingCall::Private::parseReply()
{
    if (parsed)
        return;
    parsed = true;
    const bool doDebug = qgetenv("KDSOAP_DEBUG").toInt();
    QNetworkReply* reply = this->reply.data();
#if QT_VERSION >= 0x040600
    if (!reply->isFinished()) {
        qWarning("KDSoap: Parsing reply before it finished!");
    }
#endif
    if (reply->error()) {
        replyMessage.setFault(true);
        replyMessage.addArgument(QString::fromLatin1("faultcode"), QString::number(reply->error()));
        replyMessage.addArgument(QString::fromLatin1("faultstring"), reply->errorString());
        if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 500) {
            if (doDebug) {
                //qDebug() << reply->readAll();
                qDebug() << reply->errorString();
            }
            return;
        }
        // HTTP 500 is used to return faults, so parse the fault, below
    }
    const QByteArray data = reply->readAll();
    if (doDebug)
        qDebug() << data;

    if (!data.isEmpty()) {
        KDSoapMessageReader reader;
        reader.xmlToMessage(data, &replyMessage, 0, &replyHeaders);
    }
}
Ejemplo n.º 12
0
void RigTests::initTestCase() {
//#define FROM_FILE "/Users/howardstearns/howardHiFi/Zack.fbx"
#ifdef FROM_FILE
    QFile file(FROM_FILE);
    QCOMPARE(file.open(QIODevice::ReadOnly), true);
    FBXGeometry geometry = readFBX(file.readAll(), QVariantHash());
#else
    QUrl fbxUrl("https://s3.amazonaws.com/hifi-public/models/skeletons/Zack/Zack.fbx");
    QNetworkReply* reply = OBJReader().request(fbxUrl, false);  // Just a convenience hack for synchronoud http request
    auto fbxHttpCode = !reply->isFinished() ? -1 : reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QCOMPARE(fbxHttpCode, 200);
    FBXGeometry geometry = readFBX(reply->readAll(), QVariantHash());
#endif
 
    QVector<JointState> jointStates;
    for (int i = 0; i < geometry.joints.size(); ++i) {
        JointState state(geometry.joints[i]);
        jointStates.append(state);
    }

    _rig = std::make_shared<AvatarRig>();
    _rig->initJointStates(jointStates, glm::mat4(), 0, 41, 40, 39, 17, 16, 15); // FIXME? get by name? do we really want to exclude the shoulder blades?
    std::cout << "Rig is ready " << geometry.joints.count() << " joints " << std::endl;
    reportAll(_rig);
   }
Ejemplo n.º 13
0
AutoUpdater::UpdateFile AutoUpdater::getUpdateFile(UpdateFileMeta fileMeta,
                                        std::function<void(int,int)> progressCallback)
{
    UpdateFile file;
    file.metadata = fileMeta;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    manager->setProxy(Settings::getInstance().getProxy());
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(filesURI+fileMeta.id)));
    QObject::connect(reply, &QNetworkReply::downloadProgress, progressCallback);
    while (!reply->isFinished())
    {
        if (abortFlag)
            return file;
        qApp->processEvents();
    }

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "getUpdateFile: network error: " + reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return file;
    }

    file.data = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();

    return file;
}
Ejemplo n.º 14
0
PyObject *PythonQtDecorator::retrieve(QNetworkAccessManager *self, QString url)
{
    //qDebug("QNAM %p retrieve %s", self, qPrintable(url));
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Connection", "keep-alive");

    QNetworkReply *reply = syncGet(self, request);

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning("Network Error: %s", qPrintable(reply->errorString()));

        QByteArray reason = reply->errorString().toUtf8();
        char *creason = (char*)malloc(reason.size() + 1);
        strcpy(creason, reason.constData());
        PyErr_SetString(PyExc_IOError, creason);

        reply->deleteLater();
        return NULL;
    }
    // Reply
#if 0
    qDebug("Reply: %s %i", qPrintable(reply->url().toString()), reply->isFinished());
    foreach(QNetworkReply::RawHeaderPair header, reply->rawHeaderPairs())
        qDebug("HDR: %s: %s", qPrintable(header.first), qPrintable(header.second));
#endif
    QByteArray barr = reply->readAll();
    reply->deleteLater();
    return toBytes(&barr);
}
Ejemplo n.º 15
0
Archivo: toxme.cpp Proyecto: 1KoT1/qTox
QByteArray Toxme::makeJsonRequest(QString url, QString json, QNetworkReply::NetworkError &error)
{
    if (error)
        return QByteArray();

    QNetworkAccessManager netman;
    netman.setProxy(Settings::getInstance().getProxy());
    QNetworkRequest request{url};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply* reply = netman.post(request,json.toUtf8());

    while (!reply->isFinished())
    {
        QThread::msleep(1);
        qApp->processEvents();
    }

    error = reply->error();
    if (error)
    {
        qWarning() << "makeJsonRequest: A network error occured:" << reply->errorString();
        return QByteArray();
    }

    return reply->readAll();
}
Ejemplo n.º 16
0
/*!
  \brief Fetches game achievement completion values.

  This method fetches the game completion values for the game app ID \p appID.

  \param appID The app ID we want the achievement completion values for.
  \return A \c QHash map with achievements and completion values.
*/
QHash< QString, float >
Steam::fetchAchievementCompletion( int appID )
{
  if( appID <= 0 )
    return( QHash< QString, float >() );

  QUrl url( QL( "http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v2/" ) );
  url.addQueryItem( QL( "gameid" ), QString::number( appID ) );
  QNetworkRequest request( url );

  QNetworkReply *reply = d->network->get( request );
  while( ! reply->isFinished() )
    qApp->processEvents();

  QByteArray data = reply->readAll();
  reply->deleteLater();
  reply = NULL;

  if( data.isEmpty() )
    return( QHash< QString, float >() );

  JSONStreamReader json;
  JSONObject *root = json.read( data );
  if( ! root || json.hasError() )
  {
    delete root;
    root = NULL;

    SteamPrivate::jsonError( json );
    return( QHash< QString, float >() );
  }

  JSONList *achievements = NULL;
  JSONObject *achievementpercentages = root->valueObject( QL( "achievementpercentages" ) );
  if( achievementpercentages )
    achievements = achievementpercentages->valueList( QL( "achievements" ) );

  QHash< QString, float > completion;
  for( int i = 0; achievements && i < achievements->count(); i++ )
  {
    JSONValue *val = achievements->at( i );
    JSONObject *achievement = NULL;
    if( val->type() == JSONValue::T_Object )
      achievement = dynamic_cast< JSONObject * >( val );

    if( achievement )
    {
      QString name  = achievement->valueScalar( QL( "name" ) )->sValue();
      float percent = achievement->valueScalar( QL( "percent" ) )->dValue();

      completion.insert( name, percent );
    }
  }

  delete root;
  root = NULL;

  return completion;
}
Ejemplo n.º 17
0
bool autobots_toutiao::RequestForRenren()
{
	QString str_url1 = QString("http://isub.snssdk.com/2/auth/login/v2/?platform=renren_sns&version_code=5.8.3&uid_type=14&app_name=news_article&vid=%1&device_id=%2&channel=App Store&resolution=750*1334&aid=13&ab_version=83098,79288,87751,87331,85045,86854,86884,87032,86738,31650,87244,82679,87835,87830,87494,87036,87629&ab_feature=z2&ab_group=z2&openudid=0d919477efbefb99dfe7a02a2df34d9127ecc947&live_sdk_version=1.3.0&idfv=%3&ac=WIFI&os_version=9.3.5&ssmix=a&device_platform=iphone&iid=6088961915&ab_client=a1,f2,f7,e1&device_type=%4&idfa=86E011D2-C2DA-40CB-AB9D-DB1E1F9D668A")
		.arg(m_devices_list[m_device_order]._uuid).arg(m_devices_list[m_device_order]._did).arg(m_devices_list[m_device_order]._uuid).arg(m_devices_list[m_device_order]._device_type);

	QUrl url1(str_url1);

	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	header_list.push_back(HttpParamItem("Accept-Encoding", "gzip, deflate"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list.push_back(HttpParamItem("Host", "isub.snssdk.com"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	QNetworkReply* reply = network.GetRequest(url1, header_list);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (reply && !reply->isFinished())
	{
		QCoreApplication::processEvents();

		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

	if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
	{
		return false;
	}

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

	int n = statusCodeV.toInt();

	if (n == 302 || n == 301)
	{
		// 重定向
		QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

		QUrl red_url = redirectionTarget.toUrl();

		QString str = red_url.toString();

		return ProcessRedirectSSL(str);
	}
	else
	{
		return false;
	}

}
Ejemplo n.º 18
0
bool autobots_toutiao::RequestForRenren()
{
  QString str_url1 = "http://toutiao.com/auth/connect/?type=toutiao&platform=renren_sns";

  QUrl url1(str_url1);

  HttpParamList header_list;
  //header_list.push_back(HttpParamItem("(Request-Line)",	"GET /auth/connect/?type=toutiao&platform=renren_sns HTTP/1.1"));
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
//  header_list.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-CN"));
  header_list.push_back(HttpParamItem("Host", "toutiao.com"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  QNetworkReply* reply = network.GetRequest(url1, header_list);

  QTime _t;
  _t.start();

  bool _timeout = false;

  while(reply && !reply->isFinished())
  {
    QCoreApplication::processEvents();

    if (_t.elapsed() >= TIMEOUT) {
      _timeout = true;
      break;
    }
  }

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
    return false;
  }

  QVariant statusCodeV =  reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);  

  int n = statusCodeV.toInt();

  if (n == 302 || n == 301)
  {
    // 重定向
    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    QUrl red_url = redirectionTarget.toUrl();

    QString str = red_url.toString();

    return ProcessRedirectSSL(str);
  }
  else
  {
    return false;
  }

}
Ejemplo n.º 19
0
QString WorkThread::GetToken()
{
    QNetworkRequest req;

    QString str_url1 = m_token_url;

    req.setUrl(QUrl(str_url1));

    QString origin = "http://" + m_host;

    req.setRawHeader("Cache-Control", "no-cache");
    req.setRawHeader("Accept", "*/*");
    req.setRawHeader("Connection", "Keep-Alive");
    //req.setRawHeader("Accept-Encoding", "gzip, deflate");
    req.setRawHeader("Accept-Language", "zh-CN");
    req.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    req.setRawHeader("Content-Length", "0");
    req.setRawHeader("X-Requested-With", "XMLHttpRequest");
    req.setRawHeader("Host", m_host.toUtf8().data());
    req.setRawHeader("Origin", origin.toUtf8().data());
    req.setRawHeader("Referer", m_referer.toUtf8().data());
    req.setRawHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

    /*req.setAttribute()*/
    QByteArray request_params;
    //request_params.append("undefined");
    QNetworkReply* reply = m_manager.post(req, request_params);

	QTime t;
	t.start();
	while (!reply->isFinished())
	{
		QCoreApplication::processEvents();
		if (t.elapsed() >= 10 * 1000) {
			break;
		}
	}

    QString msg;
    if (reply->error() != QNetworkReply::NoError)
    {
        msg = reply->errorString();
    }

    QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    int n = statusCodeV.toInt();

    QByteArray data = reply->readAll();

    QString ret = ParseToken(data);

    reply->deleteLater();

    return ret;
}
Ejemplo n.º 20
0
bool autobots_toutiao::ProcessRedirectSSL(const QString& str)
{
  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
  //header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-cn"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  if (!str.contains("https://",Qt::CaseInsensitive))
  {
    return false;
  }

  QNetworkReply* reply = network.GetRequest_ssl(QUrl(str), header_list);

  QTime _t;
  _t.start();

  bool _timeout = false;

  while(reply && !reply->isFinished())
  {
    QCoreApplication::processEvents();

    if (_t.elapsed() >= TIMEOUT) {
      _timeout = true;
      break;
    }
  }

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
    return false;
  }

  QVariant statusCodeV =  reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);  

  int n = statusCodeV.toInt();

  if (n == 302 || n == 301)
  {
    // 重定向
    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    QUrl red_url = redirectionTarget.toUrl();

    QString str = red_url.toString();

    return ProcessRedirectGet(str);
  }
  else
  {
    return false;
  }
}
Ejemplo n.º 21
0
AutoUpdater::VersionInfo AutoUpdater::getUpdateVersion()
{
    VersionInfo versionInfo;
    versionInfo.timestamp = 0;

    // Updates only for supported platforms
    if (platform.isEmpty())
        return versionInfo;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(checkURI)));
    while (!reply->isFinished())
        qApp->processEvents();

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "AutoUpdater: getUpdateVersion: network error: "<<reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return versionInfo;
    }

    QByteArray data = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();
    if (data.size() < (int)(1+crypto_sign_BYTES))
        return versionInfo;

    // Check updater protocol version
    if ((int)data[0] != '2')
    {
        qWarning() << "AutoUpdater: getUpdateVersion: Bad version "<<(uint8_t)data[0];
        return versionInfo;
    }

    // Check the signature
    QByteArray sigData = data.mid(1, crypto_sign_BYTES);
    unsigned char* sig = (unsigned char*)sigData.data();
    QByteArray msgData = data.mid(1+crypto_sign_BYTES);
    unsigned char* msg = (unsigned char*)msgData.data();

    if (crypto_sign_verify_detached(sig, msg, msgData.size(), key) != 0)
    {
        qCritical() << "AutoUpdater: getUpdateVersion: RECEIVED FORGED VERSION FILE FROM "<<updateServer;
        return versionInfo;
    }

    int sepPos = msgData.indexOf('!');
    versionInfo.timestamp = QString(msgData.left(sepPos)).toInt();
    versionInfo.versionString = msgData.mid(sepPos+1);

    qDebug() << "timestamp:"<<versionInfo.timestamp << ", str:"<<versionInfo.versionString;

    return versionInfo;
}
Ejemplo n.º 22
0
void UpdateChecker::checkForUpdates()
{
    if (!settings->checkUpdates())
        return;
    qWarning() << "Requesting current version info for branch: " << channel;
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl("http://openkj.org/downloads/" + OS + "-" + channel + "-curversion.txt")));
    while (!reply->isFinished())
        QApplication::processEvents();
    qWarning() << "Request completed";
}
Ejemplo n.º 23
0
void SpotifyBlobDownloader::ReplyFinished() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
  if (reply->error() != QNetworkReply::NoError) {
    // Handle network errors
    ShowError(reply->errorString());
    return;
  }

  // Is everything finished?
  foreach (QNetworkReply* reply, replies_) {
    if (!reply->isFinished()) {
      return;
    }
  }

  // Read files into memory first.
  QMap<QString, QByteArray> file_data;
  QStringList signature_filenames;

  foreach (QNetworkReply* reply, replies_) {
    const QString filename = reply->url().path().section('/', -1, -1);

    if (filename.endsWith(kSignatureSuffix)) {
      signature_filenames << filename;
    }

    file_data[filename] = reply->readAll();
  }

#ifdef HAVE_QCA
  // Load the public key
  QCA::ConvertResult conversion_result;
  QCA::PublicKey key = QCA::PublicKey::fromPEMFile(":/clementine-spotify-public.pem",
                                                   &conversion_result);
  if (QCA::ConvertGood != conversion_result) {
    ShowError("Failed to load Spotify public key");
    return;
  }

  // Verify signatures
  foreach (const QString& signature_filename, signature_filenames) {
    QString actual_filename = signature_filename;
    actual_filename.remove(kSignatureSuffix);

    qLog(Debug) << "Verifying" << actual_filename << "against" << signature_filename;

    if (!key.verifyMessage(file_data[actual_filename],
                           file_data[signature_filename],
                           QCA::EMSA3_SHA1)) {
      ShowError("Invalid signature: " + actual_filename);
      return;
    }
  }
Ejemplo n.º 24
0
  std::pair<QNetworkReply::NetworkError, QString> NetworkProxyDialog::testProxyConnection(const QNetworkProxy &t_proxy, QWidget *t_parent)
  {
    QProgressDialog dlg("Verifying Proxy Connection", "Cancel",0, 1000, t_parent);
    dlg.setWindowModality(Qt::WindowModal);
    dlg.setValue(0);
    dlg.setMinimumDuration(1000);

    QNetworkAccessManager nam;
    nam.setProxy(t_proxy);
    QNetworkReply *head = nam.head(QNetworkRequest(QUrl("https://bcl.nrel.gov/")));

    if (!head) return std::make_pair(QNetworkReply::UnknownNetworkError, QString("Unknown error creating connection to proxy."));

    boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
    while ( !head->isFinished()
            && (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds() < 10000
            && !dlg.wasCanceled())
    {
      int time = (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds();
      dlg.setValue(time);
      if (time >= 950 && dlg.maximum() < 10000)
      {
        dlg.setMaximum(10000);
      }
    }
    dlg.reset();
    Application::instance().processEvents();

    head->deleteLater();

    if (!head->isFinished()) 
    {
      head->abort();
      return std::make_pair(QNetworkReply::TimeoutError, QString("Timed out while attempting to verify proxy connection"));
    }

    LOG(Debug, " errorString from proxy test " << toString(head->errorString()) << " " << head->error());

    return std::make_pair(head->error(), head->errorString());
  }
Ejemplo n.º 25
0
void autobots_toutiao::GetIDList(bool& has_more, int offset)
{
	//http://www.toutiao.com/api/comment/list/?group_id=6333409505736392961&item_id=6333409505912553985&offset=5&count=10
	QString str_url = QString("http://www.toutiao.com/api/comment/list/?group_id=%1&item_id=%2&offset=%3&count=500").arg(
		m_group_id, m_item_id, QString::number(offset));

	QNetworkAccessManager manager;
	QNetworkRequest req;
	req.setUrl(str_url);
	req.setRawHeader("Cache-Control", "no-cache");
	req.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	req.setRawHeader("Connection", "Keep-Alive");
	req.setRawHeader("Referer", m_url.toUtf8().data());
	req.setRawHeader("Accept-Language", "zh-CN");
	req.setRawHeader("Host", "www.toutiao.com");
	req.setRawHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");

	QNetworkReply* reply = manager.get(req);

	while (!reply->isFinished())
	{
		QCoreApplication::processEvents();
	}

	QString msg;
	if (reply->error() != QNetworkReply::NoError)
	{
		msg = reply->errorString();
		ui.lineEdit_msg->setText(msg);
		reply->deleteLater();
		return;
	}

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

	int n = statusCodeV.toInt();

	if (n != 200)
	{
		ui.lineEdit_msg->setText(QStringLiteral("获取动态ID失败"));
		reply->deleteLater();
		return;
	}

	QByteArray rp_data = reply->readAll();

	bool res = ExactComments(rp_data, has_more);

	reply->deleteLater();

	//return res;
}
Ejemplo n.º 26
0
bool autobots_toutiao::ProcessRedirectLoginGet2(const QString& str)
{
  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
  header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-cn"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  QNetworkReply* reply = network->GetRequest(QUrl(str), header_list);

  QTime _t;
  _t.start();

  bool _timeout = false;

  while(reply && !reply->isFinished())
  {
    QCoreApplication::processEvents();

    if (_t.elapsed() >= TIMEOUT) {
      _timeout = true;
      break;
    }
  }

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
    return false;
  }

  QVariant statusCodeV =  reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);  

  int n = statusCodeV.toInt();

  if (n != 200)
  {
    return false;
  }

  QByteArray data = reply->readAll();

  reply->deleteLater();

  QString temp_s = data;
  if (temp_s.contains("window.opener.user.connected") 
    || temp_s.contains("window.parent.user.connected") )
  {
    return true;
  }

  return false;
}
Ejemplo n.º 27
0
int auto_smzdm::smzdm_run()
{
  QNetworkCookieJar* cookie = new QNetworkCookieJar(this);

  network.GetManager().setCookieJar(cookie);

  GetContent();

  foreach(QString str, m_comment_list)
  {

    QString jq = QString("jQuery") + "11100" + GetNumberString(16) +"_" + GetTimeStr();

    QString str_url1 = QString(
      "http://zhiyou.smzdm.com/user/comment/ajax_rating?callback=%1&comment_id=%2&rating=1&_=%3").arg(jq,str,GetTimeStr());

    QUrl url1(str_url1);

    HttpParamList header_list;
    header_list.push_back(HttpParamItem("Referer", m_news_url));
    header_list.push_back(HttpParamItem("Accept", "application/javascript, */*;q=0.8"));
    header_list.push_back(HttpParamItem("Cache-Control","no-cache"));
    header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
    //header_list.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
    header_list.push_back(HttpParamItem("Accept-Language","zh-CN"));
    header_list.push_back(HttpParamItem("Host", m_host));
    header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

    QNetworkReply* reply = network.GetRequest(url1, header_list);

#ifdef _DEBUG

       QTime _t;
       _t.start();
   
       bool _timeout = false;
  
       while (reply && !reply->isFinished())
       {
         QCoreApplication::processEvents();
         if (_t.elapsed() >= 10*1000) {
           _timeout = true;
           break;
         }
       }

      QString rt = reply->readAll();
#endif //_DEBUG
      reply->deleteLater();
// 
   }
Ejemplo n.º 28
0
bool autobots_toutiao::ProcessRedirectGet(const QString& str)
{
  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
  header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-cn"));
  header_list.push_back(HttpParamItem("Referer", "https://sso.toutiao.com/login/"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  QNetworkReply* reply = network->GetRequest_ssl(QUrl(str), header_list);

  QTime _t;
  _t.start();

  bool _timeout = false;

  while(reply && !reply->isFinished())
  {
    QCoreApplication::processEvents();

    if (_t.elapsed() >= TIMEOUT) {
      _timeout = true;
      break;
    }
  }

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
    return false;
  }

  QVariant statusCodeV =  reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);  

  int n = statusCodeV.toInt();

//   if (n != 200)
//   {
//     return false;
//   }

  QByteArray data = reply->readAll();

  //bool res = GetPostId(data);

  if (reply != NULL)
  {
    reply->deleteLater();
  }

  return true;
}
Ejemplo n.º 29
0
bool autobots_toutiao::ProcessRedirectGet(const QString& str)
{
	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//  header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-cn"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	QNetworkReply* reply = network.GetRequest(QUrl(str), header_list);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (reply && !reply->isFinished())
	{
		QCoreApplication::processEvents();

		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

	if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
	{
		return false;
	}

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

	int n = statusCodeV.toInt();

	if (n != 200)
	{
		return false;
	}

	QByteArray data = reply->readAll();

	if (reply != NULL)
	{
		reply->deleteLater();
	}

	return GetPostId(data);

}
Ejemplo n.º 30
0
int QueryThread::queryWord(QString mainWord, QString assistWord, QNetworkRequest &request, QString currentIp)
{
    qDebug() << this->cookieJar->getCookies();
    QString hostName = "m.baidu.com";
    qDebug() << "thread: " << id << " query: " << mainWord << " " << assistWord;
    QEventLoop loop;
    int resultCode = 0;
    QString url = this->buildUrl(mainWord, assistWord);
    request.setUrl(url);
    this->setRequestHeader(request, hostName, lastUrl);
    lastUrl = url;
    QNetworkReply* reply = networkManager->get(request);
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    QObject::connect(timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    timer->start(3000);
    loop.exec();
//    reply->waitForReadyRead(3000);
//    this->sleep(3);
    if (reply->isFinished())
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            QString value = reply->readAll();
            qDebug() << value.left(100);
            qDebug() << "===get request value in thread:"  << id << " ==";
            QString currentEngine = "手机百度";
            QString currentUrl = "http://m.baidu.com";
            QPair<QString, QString> currentKeyWord(mainWord, assistWord);
            QString currentLinkName = "get link";
            QString currentLinkUrl = url;
            UpdateInfo updateInfo(currentEngine,
                                  currentUrl,
                                  currentKeyWord,
                                  currentLinkName,
                                  currentLinkUrl,
                                  currentIp);
            emit updateClickInfo(updateInfo);
            this->updateCookie();
        }
        else
        {
            resultCode = 1;
        }
    } else {
        if (this->networkManager->networkAccessible() != QNetworkAccessManager::Accessible) resultCode = 2;
    }
    reply->deleteLater();
    return resultCode;
}