示例#1
0
void
NwReqTracker::onReplyFinished()
{
    replyTimer.stop ();

    bool rv = false, done = false;
    QByteArray response;
    QNetworkReply *origReply = reply;

    do { // Begin cleanup block (not a loop)
        if (aborted) {
            Q_WARN("Reply was aborted");
            break;
        }

        if (QNetworkReply::NoError != origReply->error ()) {
            Q_WARN("Response error: ") << origReply->errorString ();
            break;
        }

        response = origReply->readAll ();
        rv = true;
    } while (0); // End cleanup block (not a loop)

    do { // Begin cleanup block (not a loop)
        done = true;

        if (!rv) {
            break;
        }

        if (!autoRedirect) {
            break;
        }

        QUrl urlMoved = hasMoved (origReply);
        if (urlMoved.isEmpty ()) {
            break;
        }

        QNetworkRequest req(urlMoved);
        req.setRawHeader("User-Agent", uaString);

        NwReqTracker::setCookies (jar, req);
        QNetworkReply *nextReply = nwMgr.get(req);
        if (!nextReply) {
            break;
        }

        disconnectReply ();
        init (nextReply, ctx, emitLog, autoDelete);
        autoRedirect = true;

        done = false;
    } while (0); // End cleanup block (not a loop)

    if (done) {
        if (!autoRedirect && response.contains ("Moved Temporarily")) {
            QString msg = "Auto-redirect not requested, but page content "
                          "probably indicates that this page has been "
                          "temporarily moved. Original request = %1";

            msg = msg.arg (origReply->request().url().toString ());

            QString strResp = response;
            int pos = strResp.indexOf ("a href=", 0, Qt::CaseInsensitive);
            if (-1 != pos) {
                int endpos = strResp.indexOf ("</a>", pos, Qt::CaseInsensitive);
                if (-1 != endpos) {
                    msg += "\nRedirect URL = " + strResp.mid(pos+8, endpos-pos);
                }
            }

            Q_WARN(msg);
        }

        emit sigDone (rv, response, origReply, ctx);
    }

    origReply->deleteLater ();
    if (done && autoDelete) {
        this->deleteLater ();
    }
}//NwReqTracker::onReplyFinished
示例#2
0
bool autobots_toutiao::AuthorByRenren(const QString& name, const QString& password)
{
	//1.检验验证码
	QString vcode, code_sign;
	bool need_code = NeedValidateCode(name, vcode, code_sign);
	QString str_need_code = need_code ? "true" : "";

	QString str_url1 = "https://graph.renren.com/oauth/grant";

	QUrl url1(str_url1);

	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";

	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", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list.push_back(HttpParamItem("Host", "graph.renren.com"));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//Referer	
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	HttpParamList post_data;
	QString t = QString("http://api.snssdk.com/auth/login_success/") + "&client_id=" + m_client_id;
	//post_data.push_back(HttpParamItem("authFeed","true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	//post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "touch"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", vcode));
	post_data.push_back(HttpParamItem("isNeedIcode", str_need_code));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", password));
	post_data.push_back(HttpParamItem("porigin", "80103"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", t));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", m_state_id));
	post_data.push_back(HttpParamItem("username", name));

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

	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)
	{
		reply->deleteLater();
		return false;
	}

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

	int n = statusCodeV.toInt();

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

		QUrl red_url = redirectionTarget.toUrl();

		QString str = red_url.toString();

		int r = ProcessRedirectLoginGet(str);

		if (r == 0)
		{
			res = true;
		}
		else if (r == -2)
		{
			// 验证码错误
			VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
			obj->ReportError("bestsalt", code_sign);
		}
	}
	else
	{
		QString msg = reply->readAll();
		res = false;
	}

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

	return res;
}
示例#3
0
void SubscribeThread::processSubscribeDanmakuResponse()
{

    QNetworkReply *reply = (QNetworkReply *)sender();
    int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
    if(reply->hasRawHeader("Location")){
        QString strLocation = reply->header(QNetworkRequest::LocationHeader).toString();

        this->subscribeDanmaku(strLocation);

    }else if(statusCode == 200){

        QByteArray responseData = reply->readAll();
//        qDebug()<<"response data:"<<responseData;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        if(jsonDoc.isNull() ||!jsonDoc.isArray())
        {//  null or not array format
            goto out;
        }
        QJsonArray jsonArray = jsonDoc.array();
        for(int i = 0; i < jsonArray.count();i++){
            QJsonValue jsonValue = jsonArray[i];
            if(jsonValue.isUndefined()||jsonValue.isNull())
            {
                goto out;
            }
            QString text = jsonValue.toObject().value("text").toString();
            QString position = jsonValue.toObject().value("position").toString();
            QString style = jsonValue.toObject().value("style").toString();


            if(text.size()>128){
                text.resize(128);
            }
            Danmaku_Msg msg;
            msg.msg = text;
            if(style=="blue"){
                msg.color = QColor("#0000FF");
            }else if(style=="white"){
                msg.color = QColor("#FFFFFF");
            }else if(style=="red"){
                msg.color = QColor("#FF0000");
            }else if(style=="yellow"){
                msg.color = QColor("yellow");
            }else if(style=="cyan"){
                msg.color = QColor("cyan");
            }else if(style=="green"){
                msg.color = QColor("#00FF00");
            }else if(style=="purple"){
                msg.color = QColor("#871F78");
            }else{
                msg.color = QColor("black");
            }



            if(position=="top"){
                msg.positon = BULLET_TOP;
            }else if(position == "bottom")
            {
                msg.positon = BULLET_BOTTOM;
            }else
            {
                msg.positon = BULLET_FLY;
            }

            emit this->receivedDamanku(msg);
        }
    }
out:
    qApp->processEvents(QEventLoop::AllEvents);
    if(reply->error() == QNetworkReply::NoError){
        this->pullDanmaku();
    }else
    {
        QTimer::singleShot(2000,this,SLOT(pullDanmaku()));
    }
    reply->deleteLater();
    return;
}
示例#4
0
// 0 正常,-1 未知错误, -2 验证码错误
int autobots_toutiao::ProcessRedirectLoginGetTemp(const QString& str)
{
	WaitforSeconds(2);

	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Host", "api.snssdk.com"));
	header_list.push_back(HttpParamItem("Referer", "http://graph.renren.com/oauth/grant?client_id=394e2173327e4ead8302dc27f4ae8879&redirect_uri=http%3A%2F%2Fapi.snssdk.com%2Fauth%2Flogin_success%2F&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000"));
	//header_list.push_back(HttpParamItem("",""));
	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,zh;q=0.8"));
	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 || _timeout)
	{

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

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	int n = statusCodeV.toInt();

	if ((reply->error() != QNetworkReply::NoError) && n != 500)
	{
		QString t = reply->errorString();
		return -1;
	}

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

		QUrl red_url = redirectionTarget.toUrl();

		QString str2 = red_url.toString();

		res = ProcessRedirectLoginGet2(str2) ? 0 : -1;
	}
	else if (n == 302)
	{
		QString str2 = reply->readAll();
		if (str2.contains(QStringLiteral("验证码错误")))
		{
			res = -2;
		}
	}
	else if (n == 500)
	{
		// 找不到页面
		res = ProcessRedirectLoginGetTemp2(str);
	}

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

	return res;
}
示例#5
0
bool autobots_toutiao::NeedValidateCode(const QString& name, QString& vcode, QString& code_sign)
{
	QString str_url1 = "http://graph.renren.com/icode/check";

	QUrl url1(str_url1);
	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";
	HttpParamList header_list;
	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", "graph.renren.com"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//network.GetManager().setCookieJar(new QNetworkCookieJar(this));

	HttpParamList post_data;
	post_data.push_back(HttpParamItem("authFeed", "true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "page"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", ""));
	post_data.push_back(HttpParamItem("isNeedIcode", ""));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", ""));
	post_data.push_back(HttpParamItem("porigin", "80100"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", "http://api.snssdk.com/auth/login_success/"));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", "renren_sns__0____toutiao____2__0__24"));
	post_data.push_back(HttpParamItem("username", name));

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

	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;
	}

	QString str = reply->readAll();

	reply->deleteLater();

	if (str.toInt() == 0)
	{
		return false;
	}

	// 获取验证码

	QUrl url2("http://icode.renren.com/getcode.do?t=openplatform");
	HttpParamList header_list2;
	header_list2.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//  header_list2.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
	header_list2.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list2.push_back(HttpParamItem("Host", "icode.renren.com"));
	header_list2.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list2.push_back(HttpParamItem("Referer", str_temp));

	QNetworkReply* reply2 = network.GetRequest(url2, header_list2);

	_t.restart();

	_timeout = false;

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

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

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

	n = statusCodeV.toInt();

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

	QByteArray data = reply2->readAll();

	QImage image_ = QImage::fromData(data);//(data.data(),100,40,QImage::Format_RGB32);

	if (m_code_online)
	{
		// 在线验证
		//bool result = image_.save("e:\\1.jpg");
		VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
		int res = obj->GetRecResults(data, "bestsalt", "hh610520;;", "bestsalt", vcode, code_sign);
	}
	else
	{
		// 手动验证
		ValidateDlg dlg(this, image_);
		if (dlg.exec() == QDialog::Accepted)
		{
			vcode = dlg.getCode();
		}
	}

	return true;
}
void QBNetwork::onRequestUsers() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile destFile("app/native/assets/users.json");
				if (!destFile.open(QIODevice::WriteOnly))
					return;
				destFile.write(response.toAscii());
				destFile.close();

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "user") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "id") {
									break;
								}
							}
						}
					}
				}

				successLoad = true;
				emit loadingChanged();
				emit completeLogin();

			}
		} else {
			successLoad = true;
			emit loadingChanged();
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			showError("QBlox Server Error = " + response);
		}
		reply->deleteLater();
	}
}
示例#7
0
void Twitter::onDataReceived()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    QString response;
    bool success = false;
    if (reply)
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            int available = reply->bytesAvailable();
            if (available > 0)
            {
                int bufSize = sizeof(char) * available + sizeof(char);
                QByteArray buffer(bufSize, 0);
                reply->read(buffer.data(), available);
                response = QString(buffer);
                success = true;
            }
        }
        else
        {
            response =  QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
            emit tweetParseComplete(false, "We can't connect to the internet");
        }
        reply->deleteLater();
    }
    if (success )
    {
    	if (response != "[]") {
    		bb::data::JsonDataAccess jda;
    		QVariant jsonva = jda.loadFromBuffer(response);
    		QVariantMap map = jsonva.toMap();
    		QVariantList results = map.value("results").toList();
    		//okay let's get the news items

    		int numTweets = 0;
    		foreach (QVariant v, results) {
    			QVariantMap map = v.toMap();

    			Tweet *tweet = new Tweet();
    			tweet->parse(v);

    			QVariant q = QVariant::fromValue(tweet);

        		_tweetList.append(q); //to go from a QVariant back to a Tweet* item: Tweet *Tweet = q.value<Tweet*>();

    			QVariantList path;
				path.append(_tweetList.indexOf(q));

				emit  itemAdded (path);
				numTweets++;
    		}

        	if (numTweets > 0) {
        		emit tweetParseComplete(true, "Parsed successfully");
        	} else {
        		if (_tweetList.count() == 0) {
        			emit tweetParseComplete(false, "No Tweets yet");
        		}
        	}
    	}
示例#8
0
AutoUpdater::VersionInfo AutoUpdater::getUpdateVersion()
{
    VersionInfo versionInfo;
    versionInfo.timestamp = 0;

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

    if (abortFlag)
        return versionInfo;

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

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "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] != '3')
    {
        qWarning() << "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() << "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;
}
示例#9
0
void ReverseGeoLookupThread::run() {
	if (geo_lookup_data.isEmpty())
		return;

	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	QEventLoop loop;
	QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3");
	QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50");
	QTimer timer;

	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

	Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) {
		struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site;

		// first check the findNearbyPlaces API from geonames - that should give us country, state, city
		request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));

		QNetworkReply *reply = rgl->get(request);
		timer.setSingleShot(true);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();

		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant geoNamesObject = obj.value("geonames").toVariant();
			QVariantList geoNames = geoNamesObject.toList();
			if (geoNames.count() > 0) {
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();
		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant oceanObject = obj.value("ocean").toVariant();
			QVariantMap oceanName = oceanObject.toMap();
			if (oceanName["name"].isValid()) {
				int idx;
				if (ds->taxonomy.category == NULL)
					ds->taxonomy.category = alloc_taxonomy();
				idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN);
				if (idx == -1)
					idx = ds->taxonomy.nr;
				if (idx < TC_NR_CATEGORIES) {
					ds->taxonomy.category[idx].category = TC_OCEAN;
					ds->taxonomy.category[idx].origin = taxonomy::GEOCODED;
					ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString()));
					if (idx == ds->taxonomy.nr)
						ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}

clear_reply:
		reply->deleteLater();
	}
	rgl->deleteLater();
}
示例#10
0
void SwfToHtml5::process()
{
    m_filesLstWgt->clear();
    m_filesLstWgt->addItems(m_pathToFiles);
    m_pBeginConvertBtn->setEnabled(false);
    m_pLoadFileBtn->setEnabled(false);
    m_pLoadFileBtn->setText("Convertation started!");
    if (m_pathToFiles.size() < 1)
        return;

    for (int i = 0; i < m_pathToFiles.size(); ++i) {
        if (QFileInfo(m_pathToFiles.at(i)).isFile()) {
            QFile inputFile(m_pathToFiles.at(i));
            QByteArray bufBa;
            m_nameOfFile = m_pathToFiles.at(i);
            m_nameOfFile = m_nameOfFile.remove(".swf");
            m_nameOfFile += ".html";
            //read swf file
            if (!inputFile.open(QIODevice::ReadOnly)) {
                qDebug()<<"Could not open the input file\n"<<m_pathToFiles.at(i);
                return;
            } else {
                while(!inputFile.atEnd()) {
                    bufBa += inputFile.readLine();
                }
            }
            bufBa = bufBa.toBase64();
            bufBa = bufBa.replace('+', '-');
            bufBa = bufBa.replace('/', '_');

            QUrl apiUrl("https://www.googleapis.com/rpc?key=AIzaSyCC_WIu0oVvLtQGzv4-g7oaWNoc-u8JpEI");
            QByteArray req = "{ \"apiVersion\": \"v1\",\"method\": \"swiffy.convertToHtml\", \"params\": { \"client\": \"Swiffy Flash Extension\", \"input\": \"$\" } }";
            req = req.replace('$', bufBa);

            QNetworkRequest request(apiUrl);

            QEventLoop eventLoop;

            request.setHeader(QNetworkRequest::ContentTypeHeader, "www.googleapis.com");

            QNetworkAccessManager *manager = new QNetworkAccessManager(this);

            connect(manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);

            QNetworkReply *reply = manager->post(request, req);
            eventLoop.exec();

            QString dataFromReply;
            if (reply->error() == QNetworkReply::NoError) {
                dataFromReply = QString::fromUtf8(reply->readAll());
            }
            QByteArray replyBa;
            replyBa.append(dataFromReply);

            QFile replyFile("json.txt");
            replyFile.open(QIODevice::WriteOnly);
            replyFile.write(replyBa);
            replyFile.close();

            QFile jsonFile("json.txt");
            if (jsonFile.open(QIODevice::ReadOnly)) {
                QJsonParseError parseError;
                QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonFile.readAll(), &parseError);
                if (parseError.error == QJsonParseError::NoError) {
                    if(jsonDoc.isObject())
                        parseJSON(jsonDoc.object());
                }
                else
                    qDebug() << "JSON parse error: " << parseError.errorString();
            }
            else
                qDebug() << "json.txt not open";
            reply->deleteLater();
        }
        ++cnt;
    }
    cnt = 0;
    m_pLoadFileBtn->setText("Load files");
    m_pLoadFileBtn->setEnabled(true);
    m_filesLstWgt->addItem("Finished!");
    m_pBeginConvertBtn->setEnabled(true);
}
示例#11
0
void DVRServer::updateCamerasReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply)
        return;

    qDebug() << "DVRServer: Received cameras list reply";

    reply->deleteLater();

    if (reply->error() != QNetworkReply::NoError)
    {
        /* TODO: Handle this well */
        qWarning() << "DVRServer: Error from updating cameras:" << reply->errorString();
        return;
    }

    QByteArray data = reply->readAll();
    QXmlStreamReader xml(data);

    QSet<int> idSet;
    bool hasDevicesElement = false;
    bool wasEmpty = m_visibleCameras.isEmpty();

    while (xml.readNextStartElement())
    {
        if (xml.name() == QLatin1String("devices"))
        {
            hasDevicesElement = true;

            while (xml.readNext() != QXmlStreamReader::Invalid)
            {
                if (xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == QLatin1String("devices"))
                    break;
                else if (xml.tokenType() != QXmlStreamReader::StartElement)
                    continue;

                if (xml.name() == QLatin1String("device"))
                {
                    bool ok = false;
                    QString idv = xml.attributes().value(QLatin1String("id")).toString();
                    if (idv.isNull())
                        continue;
                    int deviceId = (int)idv.toUInt(&ok);
                    if (!ok)
                    {
                        xml.raiseError(QLatin1String("Invalid device ID"));
                        continue;
                    }

                    idSet.insert(deviceId);
                    DVRCamera *camera = getCamera(deviceId);

                    if (camera)
                    {
                        camera->setOnline(true);
                        
                        DVRCameraXMLReader xmlReader;
                        if (!xmlReader.readCamera(camera, xml))
                        {
                            if (!xml.hasError())
                                xml.raiseError(QLatin1String("Device parsing failed"));
                            continue;
                        }
                        else
                        {
                            DVRCameraSettingsWriter settingsWriter;
                            settingsWriter.writeCamera(camera);
                        }
                    }

                    if (!m_visibleCameras.contains(camera))
                    {
                        m_visibleCameras.append(camera);
                        emit cameraAdded(camera);
                    }
                }
            }
            break;
        }
        else
            xml.skipCurrentElement();
    }

    if (!hasDevicesElement)
        xml.raiseError(QLatin1String("Invalid format: no devices element"));

    if (xml.hasError())
    {
        qWarning() << "DVRServer: Error while parsing camera list:" << xml.errorString();
        return;
    }

    for (int i = 0; i < m_visibleCameras.size(); ++i)
    {
        if (!idSet.contains(m_visibleCameras[i]->data().id()))
        {
            DVRCamera *c = m_visibleCameras[i];
            m_visibleCameras.removeAt(i);
            m_camerasMap.remove(c->data().id());
            qDebug("DVRServer: camera %d removed", c->data().id());
            emit cameraRemoved(c);
            --i;

            delete c;
        }
    }

    if (!m_devicesLoaded || (wasEmpty && !m_visibleCameras.isEmpty()))
    {
        m_devicesLoaded = true;
        emit devicesReady();
    }
}
PlaylistItemList SubsonicDynamicPlaylist::GenerateMore(int count) {
  SubsonicService* service = InternetModel::Service<SubsonicService>();
  const int task_id =
      service->app_->task_manager()->StartTask(tr("Fetching Playlist Items"));

  BOOST_SCOPE_EXIT((service)(task_id)) {
    // stop task when we're done
    service->app_->task_manager()->SetTaskFinished(task_id);
  }
  BOOST_SCOPE_EXIT_END

  QUrl url = service->BuildRequestUrl("GetAlbumList");
  QNetworkAccessManager network;

  if (count > kMaxCount) count = kMaxCount;

  url.addQueryItem("type", GetTypeString());
  url.addQueryItem("size", QString::number(count));
  url.addQueryItem("offset", QString::number(offset_));

  PlaylistItemList items;

  QNetworkReply* reply = Send(network, url, service->usesslv3_);
  WaitForSignal(reply, SIGNAL(finished()));

  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    qLog(Warning) << "HTTP error returned from Subsonic:"
                  << reply->errorString() << ", url:" << url.toString();
    return items;  // empty
  }

  QXmlStreamReader reader(reply);
  reader.readNextStartElement();
  if (reader.name() != "subsonic-response") {
    qLog(Warning) << "Not a subsonic-response, aboring playlist fetch";
    return items;
  }

  if (reader.attributes().value("status") != "ok") {
    reader.readNextStartElement();
    int error = reader.attributes().value("code").toString().toInt();
    qLog(Warning) << "An error occured fetching data.  Code: " << error
                  << " Message: "
                  << reader.attributes().value("message").toString();
  }

  reader.readNextStartElement();
  if (reader.name() != "albumList") {
    qLog(Warning) << "albumList tag expected.  Aboring playlist fetch";
    return items;
  }

  while (reader.readNextStartElement()) {
    if (reader.name() != "album") {
      qLog(Warning) << "album tag expected. Aboring playlist fetch";
      return items;
    }

    qLog(Debug) << "Getting album: "
                << reader.attributes().value("album").toString();
    GetAlbum(service, items, reader.attributes().value("id").toString(),
             network, service->usesslv3_);
    reader.skipCurrentElement();
  }
  offset_ += count;
  return items;
}
void SubsonicDynamicPlaylist::GetAlbum(SubsonicService* service,
                                       PlaylistItemList& list, QString id,
                                       QNetworkAccessManager& network,
                                       const bool usesslv3) {
  QUrl url = service->BuildRequestUrl("getAlbum");
  url.addQueryItem("id", id);
  if (service->IsAmpache()) {
    url.addQueryItem("ampache", "1");
  }
  QNetworkReply* reply = Send(network, url, usesslv3);
  WaitForSignal(reply, SIGNAL(finished()));
  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    qLog(Warning) << "HTTP error returned from Subsonic:"
                  << reply->errorString() << ", url:" << url.toString();
    return;
  }

  QXmlStreamReader reader(reply);
  reader.readNextStartElement();

  if (reader.name() != "subsonic-response") {
    qLog(Warning) << "Not a subsonic-response. Aborting playlist fetch.";
    return;
  }

  if (reader.attributes().value("status") != "ok") {
    qLog(Warning) << "Status not okay. Aborting playlist fetch.";
    return;
  }

  // Read album information
  reader.readNextStartElement();
  if (reader.name() != "album") {
    qLog(Warning) << "album tag expected. Aborting playlist fetch.";
    return;
  }

  QString album_artist = reader.attributes().value("artist").toString();

  // Read song information
  while (reader.readNextStartElement()) {
    if (reader.name() != "song") {
      qLog(Warning) << "song tag expected. Aborting playlist fetch.";
      return;
    }

    Song song;
    QString id = reader.attributes().value("id").toString();
    song.set_title(reader.attributes().value("title").toString());
    song.set_album(reader.attributes().value("album").toString());
    song.set_track(reader.attributes().value("track").toString().toInt());
    song.set_disc(reader.attributes().value("discNumber").toString().toInt());
    song.set_artist(reader.attributes().value("artist").toString());
    song.set_albumartist(album_artist);
    song.set_bitrate(reader.attributes().value("bitRate").toString().toInt());
    song.set_year(reader.attributes().value("year").toString().toInt());
    song.set_genre(reader.attributes().value("genre").toString());
    qint64 length = reader.attributes().value("duration").toString().toInt();
    length *= kNsecPerSec;
    song.set_length_nanosec(length);
    QUrl url = QUrl(QString("subsonic://%1").arg(id));
    song.set_url(url);
    song.set_filesize(reader.attributes().value("size").toString().toInt());
    QFileInfo fi(reader.attributes().value("path").toString());
    song.set_basefilename(fi.fileName());
    // We need to set these to satisfy the database constraints
    song.set_directory_id(0);
    song.set_mtime(0);
    song.set_ctime(0);

    if (reader.attributes().hasAttribute("playCount")) {
      song.set_playcount(
          reader.attributes().value("playCount").toString().toInt());
    }

    list << std::shared_ptr<PlaylistItem>(
        new InternetPlaylistItem(service, song));

    reader.skipCurrentElement();
  }
}
void FirmwareDownloader::performUpgrade()
{
    if (!m_updateAvailable) {
        qWarning() << "No update available";
        return;
    }

    if (m_upgradeInProgress) {
        qWarning() << "Upgrade already in progress. Won't start another one";
        return;
    }

    m_upgradeInProgress = true;
    emit upgradingChanged();

    QNetworkRequest request(m_url);
    QNetworkReply *reply = m_nam->get(request);
    connect(reply, &QNetworkReply::finished, [this, reply](){
        reply->deleteLater();

        if (reply->error() != QNetworkReply::NoError) {
            qWarning() << "Erorr fetching firmware" << reply->errorString();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        QByteArray data = reply->readAll();

        QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex();

        if (hash != m_hash) {
            qWarning() << "Downloaded data hash doesn't match hash from target";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        QDir dir("/tmp/" + m_pebble->address().toString().replace(":", "_"));
        if (!dir.exists() && !dir.mkpath(dir.absolutePath())) {
            qWarning() << "Error saving file" << dir.absolutePath();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }
        QString path = "/tmp/" + m_pebble->address().toString().replace(":", "_");
        QFile f(path + "/" + reply->request().url().fileName());
        if (!f.open(QFile::WriteOnly | QFile::Truncate)) {
            qWarning() << "Cannot open tmp file for writing" << f.fileName();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }
        f.write(data);
        f.close();

        if (!ZipHelper::unpackArchive(f.fileName(), path)) {
            qWarning() << "Error unpacking firmware archive";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        Bundle firmware(path);
        if (firmware.file(Bundle::FileTypeFirmware).isEmpty() || firmware.file(Bundle::FileTypeResources).isEmpty()) {
            qWarning() << "Firmware bundle file missing binary or resources";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        qDebug() << "** Starting firmware upgrade **";
        m_bundlePath = path;
        m_connection->systemMessage(WatchConnection::SystemMessageFirmwareStart);

    });
}
//SLOTS
void QBNetwork::onRequestSessionRegister() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile sourceFile("app/native/assets/JDataSession.json");
				if (!sourceFile.open(QIODevice::WriteOnly))
					return;
				sourceFile.write(response.toAscii());

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "session") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "user_id") {
									m_userId = sit.value().toString();
								}
								if (sit.key() == "token") {
									m_token = sit.value().toString();
								}
							}
						}
					}
				}
			}
		} else {
			successLoad = true;
			emit loadingChanged();
			emit unauthorizedChanged();
			emit completeLogin();

			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}

			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "401") {
				showError("Incorrect login or password");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
				showError("Login has already been taken");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "404") {
				showError("The requested resource could not be found");
				return;
			} else {
				//another error
				showError("QBlox Server Error = " + response);
				return;
			}
		}
		reply->deleteLater();
	}
	//successLoad = true;
	//emit loadingChanged();
	//emit unauthorizedChanged();
	//emit completeLogin();

	registrationNewUser();
}
void OnlineDataNodeOSF::nodeInfoReceived() {

	QNetworkReply *reply = (QNetworkReply*)this->sender();

	bool success = false;
	bool finished = false;

	if (reply->error() != QNetworkReply::NoError)
	{
		setError(true, reply->errorString());
		finished = true;
	}
	else
	{
		QByteArray data = reply->readAll();
		QString dataString = (QString) data;

		QJsonParseError error;
		QJsonDocument doc = QJsonDocument::fromJson(dataString.toUtf8(), &error);

		QJsonObject json = doc.object();

		QJsonObject nodeObject;


		if (json.value("data").isArray() && _expectedName != "")
		{
			bool lastItem = _subPath.count() == 1;
			QString searchName =_subPath.first();
			searchName = searchName.right(searchName.length() - searchName.lastIndexOf("/") - 1);

			QJsonArray arrayObject = json.value("data").toArray();

			bool found = searchList(searchName, lastItem ? _kind : OnlineDataNode::Folder, arrayObject, nodeObject);

			if ( ! found)
			{
			   QJsonObject contentLevelLinks = json.value("links").toObject();

				QJsonValue nextContentList = contentLevelLinks.value("next");
				if (nextContentList.isNull() == false)
				{
					processUrl(QUrl(nextContentList.toString()));
					finished = false;
				}
				else if (lastItem)
				{
					finished = true;
					success = true;
					_exists = false;
				}
				else
				{
					finished = true;
					success = false;
				}
			}
			else if (_subPath.count() > 1)
			{
				_subPath.removeFirst();
				QString basePath = "";
				if (_subPath.count() == 1)
				{
					populateNodeData(nodeObject);
					basePath = getBaseUrl(nodeObject);
				}
				else
					basePath = getContentsUrl(nodeObject);
				processUrl(QUrl(basePath));
				finished = false;
			}
			else
			{
				populateNodeData(nodeObject);
				finished = true;
				success = true;
			}
		}
		else if (json.value("data").isObject())
		{
			nodeObject = json.value("data").toObject();
			finished = interpretNode(nodeObject);
			success = true;
		}
		else
		{
			setError(true, "Online node data in unknown form.");
			finished = true;
			success = false;
		}
	}

	reply->deleteLater();

	if (finished)
		endInit(success);
}
void QBNetwork::onRequestSessionWithLogin() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			successShow = true;
			emit unauthorizedChanged();
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "session") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "user_id") {
									m_userId = sit.value().toString();
								} else if (sit.key() == "token") {
									m_token = sit.value().toString();
								}
							}
						}
					}
				}

				if (m_token != NULL && m_userId != NULL) {
					requestLogin();
				}
			}
		} else {
			successShow = false;
			successLoad = true;
			emit unauthorizedChanged();
			emit loadingChanged();
			emit completeLogin();

			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}

			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "401") {
				showError("Incorrect login or password");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
				showError("User is not registered 1");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "404") {
				showError("The requested resource could not be found");
				return;
			} else {
				//another error
				showError("QBlox Server Error = " + response);
				return;
			}
		}
		reply->deleteLater();
	}
/*	successLoad = true;
	emit loadingChanged();
	emit completeLogin();*/
}
示例#18
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 mMissingSvg;
    }
  }

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

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

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

    // not found...
    return mMissingSvg;
  }

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

  // 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 ( true )
  {
    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, &QNetworkReply::downloadProgress, this, &QgsSvgCache::downloadProgress );

    //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(), 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 mMissingSvg;
  }

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

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

  return ba;
}
示例#19
0
void FvUpdater::httpUpdateDownloadFinished()
{
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	if(reply==NULL)
	{
		qWarning()<<"The slot httpUpdateDownloadFinished() should only be invoked by S&S.";
		return;
	}

	if(reply->error() == QNetworkReply::NoError)
	{
		int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();

		// no error received?
		if (reply->error() == QNetworkReply::NoError)
		{
			if (reply->isReadable())
			{
#ifdef Q_OS_MAC
                CFURLRef appURLRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
                char path[PATH_MAX];
                if (!CFURLGetFileSystemRepresentation(appURLRef, TRUE, (UInt8 *)path, PATH_MAX)) {
                    // error!
                }

                CFRelease(appURLRef);
                QString filePath = QString(path);
                QString rootDirectory = filePath.left(filePath.lastIndexOf("/"));
#else
                QString rootDirectory = QCoreApplication::applicationDirPath() + "/";
#endif
                
				// Write download into File
				QFileInfo fileInfo=reply->url().path();
				QString fileName = rootDirectory + fileInfo.fileName();
				//qDebug()<<"Writing downloaded file into "<<fileName;
	
				QFile file(fileName);
				file.open(QIODevice::WriteOnly);
				file.write(reply->readAll());
				file.close();

				// Retrieve List of updated files (Placed in an extra scope to avoid QuaZIP handles the archive permanently and thus avoids the deletion.)
				{	
					QuaZip zip(fileName);
					if (!zip.open(QuaZip::mdUnzip)) {
						qWarning("testRead(): zip.open(): %d", zip.getZipError());
						return;
					}
					zip.setFileNameCodec("IBM866");
					QList<QuaZipFileInfo> updateFiles = zip.getFileInfoList();
		
					// Rename all current files with available update.
					for (int i=0;i<updateFiles.size();i++)
					{
						QString sourceFilePath = rootDirectory + "\\" + updateFiles[i].name;
						QDir appDir( QCoreApplication::applicationDirPath() );

						QFileInfo file(	sourceFilePath );
						if(file.exists())
						{
							//qDebug()<<tr("Moving file %1 to %2").arg(sourceFilePath).arg(sourceFilePath+".oldversion");
							appDir.rename( sourceFilePath, sourceFilePath+".oldversion" );
						}
					}
				}

				// Install updated Files
				unzipUpdate(fileName, rootDirectory);

				// Delete update archive
                while(QFile::remove(fileName) )
                {
                };

				// Restart ap to clean up and start usual business
				restartApplication();

			}
			else qDebug()<<"Error: QNetworkReply is not readable!";
		}
		else 
		{
			qDebug()<<"Download errors ocurred! HTTP Error Code:"<<httpstatuscode;
		}

		reply->deleteLater();
    }	// If !reply->error END
}	// httpUpdateDownloadFinished END
void ItemsManagerWorker::OnFirstTabReceived() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(QObject::sender());
    QByteArray bytes = reply->readAll();
    rapidjson::Document doc;
    doc.Parse(bytes.constData());

    int index = 0;
    if (!doc.IsObject()) {
        QLOG_ERROR() << "Can't even fetch first tab. Failed to update items.";
        updating_ = false;
        StatusFinished();
        return;
    }
    if (!doc.HasMember("tabs") || doc["tabs"].Size() == 0) {
        QLOG_WARN() << "There are no tabs, this should not happen, bailing out.";
        updating_ = false;
        StatusFinished();
        return;
    }

    tabs_as_string_ = Util::RapidjsonSerialize(doc["tabs"]);

    QLOG_INFO() << "Received tabs list, there are" << doc["tabs"].Size() << "tabs";

    // Setup tab exclusions
    std::string exclusions = data_manager_.Get("tab_exclusions");
    QList<QRegularExpression> expressions;
    rapidjson::Document exclusionDoc;
    exclusionDoc.Parse(exclusions.c_str());

    if (exclusionDoc.IsArray()) {
        for (auto &excl : exclusionDoc) {
            QRegularExpression expr(excl.GetString());
            if (expr.isValid()) expressions.append(expr);
        }
    }

    tabs_.clear();
    for (auto &tab : doc["tabs"]) {
        std::string label = tab["n"].GetString();
        bool skip = false;
        for (QRegularExpression expr : expressions) {
            QRegularExpressionMatch match = expr.match(QString::fromStdString(label));
            if (match.isValid() && match.hasMatch()) {
                skip = true;
                break;
            }
        }

        if (skip) continue;

        tabs_.push_back(label);
        if (index > 0) {
            ItemLocation location;
            location.set_type(ItemLocationType::STASH);
            location.set_tab_id(index);
            location.set_tab_label(label);
            if (!tab.HasMember("hidden") || !tab["hidden"].GetBool())
                QueueRequest(MakeTabRequest(index), location);
        }
        ++index;
    }

    if (tabs_.size() == 0) {
        QLOG_WARN() << "There are no tabs to be downloaded. Try clearing your tab exclusions list.";
        updating_ = false;
        StatusFinished();
        return;
    }

    ItemLocation first_tab_location;
    first_tab_location.set_type(ItemLocationType::STASH);
    first_tab_location.set_tab_id(0);
    first_tab_location.set_tab_label(tabs_[0]);
    if (!doc["tabs"][0].HasMember("hidden") || !doc["tabs"][0]["hidden"].GetBool())
        ParseItems(&doc["items"], first_tab_location, doc.GetAllocator());

    total_needed_ = queue_.size() + 1;
    total_completed_ = 1;
    FetchItems(kThrottleRequests - 1);

    connect(signal_mapper_, SIGNAL(mapped(int)), this, SLOT(OnTabReceived(int)));
    reply->deleteLater();
}
示例#21
0
// 0 正常,-1 未知错误, -2 验证码错误
int autobots_toutiao::ProcessRedirectLoginGet(const QString& str)
{
	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Host", "api.snssdk.com"));
	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,zh;q=0.8"));
	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)
	{
		if (reply != NULL)
		{
			QString t = reply->errorString();

			int n = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

			t = reply->readAll();
			//reply->deleteLater();
			return ProcessRedirectLoginGetTemp(str);
		}
		else
		{
			return -1;
		}
	}

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

	int n = statusCodeV.toInt();
	int res = -1;
	if (n == 302 || n == 301)
	{
		// 重定向
		QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

		QUrl red_url = redirectionTarget.toUrl();

		QString str2 = red_url.toString();

		if (str2.contains("session_key="))
			return 0;

		res = ProcessRedirectLoginGet2(str2) ? 0 : -1;
	}
	else if (n == 302)
	{
		QString str2 = reply->readAll();
		if (str2.contains(QStringLiteral("验证码错误")))
		{
			res = -2;
		}
	}
	else if (n == 500)
	{
		// 找不到页面
		res = ProcessRedirectLoginGetTemp(str);
	}
	else
	{
		QString t = reply->readAll();
	}

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

	return res;
}
示例#22
0
void
Downloader::getFilesFromIndex(const QString& rootUrl, const QString& relPath, const QStringList& wantedExtensions)
{
	// ASSUMPTION: relPath ends with '/'

	++expectedIndexCount;
	QNetworkRequest indexReq(QUrl(rootUrl + relPath));
	QNetworkReply* indexReply = nam->get(indexReq);
	connect(indexReply, &QNetworkReply::finished, [=]
	{
		++loadedIndexCount;

		QString page = indexReply->readAll();
		indexReply->deleteLater();

		// ASSUMPTION: There's no whitespace around the '='
		QStringList links = page.split("a href=\"");
		links.removeFirst();

		QStringList wantedFiles;
		for (int i = 0; i < links.size(); ++i)
		{
			QString link = links[i].split('"').at(0);
			if (isWanted(link, wantedExtensions))
				wantedFiles << link;
		}

		expectedFileCount += wantedFiles.size();
		for (const QString& filename : wantedFiles)
		{
			QNetworkRequest fileReq(QUrl(rootUrl + relPath + filename));
			auto fileReply = nam->get(fileReq);
			connect(fileReply, &QNetworkReply::finished, [=]
			{
				qDebug() << "\tLoaded" << fileReply->url().toString();

				QByteArray data = fileReply->readAll();
				fileReply->deleteLater();

				QFile fileOut(relPath + filename);
				if (!fileOut.open(QFile::WriteOnly))
				{
					qDebug() << "\tERROR: Unable to open file for writing:" << fileOut.fileName();
					return;
				}

				fileOut.write(data);
				fileOut.close();

				this->recordDownload();
			});

			connect(fileReply, ( void (QNetworkReply::*)(QNetworkReply::NetworkError) )&QNetworkReply::error, [=]
			{
				qDebug() << "\tERROR:" << fileReply->errorString();
			});
		}
	});

	connect(indexReply, ( void (QNetworkReply::*)(QNetworkReply::NetworkError) )&QNetworkReply::error, [=]
	{
		qDebug() << "\tERROR:" << indexReply->errorString();
	});
}
示例#23
0
int autobots_toutiao::ProcessRedirectLoginGetTemp2(const QString& str)
{
	//http://api.snssdk.com/auth/login_success/?code=vM988uwAJr91qLN7Yh4tKCxw4alqNDDz&state=renren_sns__0____toutiao____2__0__24
	int pos1 = str.indexOf("code=");
	int pos2 = str.indexOf("&", pos1);
	QString t = str.mid(pos1, pos2 - pos1);
	QString s_url = "http://toutiao.com/auth/connected/?state=renren_sns__0____toutiao____2__0__24&" + t;

	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Host", "www.toutiao.com"));
	//header_list.push_back(HttpParamItem("Referer","http://graph.renren.com/oauth/grant?client_id=394e2173327e4ead8302dc27f4ae8879&redirect_uri=http%3A%2F%2Fapi.snssdk.com%2Fauth%2Flogin_success%2F&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000"));
	//header_list.push_back(HttpParamItem("",""));
	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,zh;q=0.8"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	QNetworkReply* reply = network.GetRequest(QUrl(s_url), 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 || _timeout)
	{

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

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	int n = statusCodeV.toInt();

	if ((reply->error() != QNetworkReply::NoError) && n != 500)
	{
		QString t2 = reply->errorString();
		return -1;
	}

	int res = -1;

	if (n != 200)
	{
		return -1;
	}

	QByteArray data = reply->readAll();

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


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

	return res;
}
示例#24
0
void DownloadTask::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
	qDebug() << QString(__FUNCTION__) << " bytesReceived:" << bytesReceived << " , bytesTotal:" << bytesTotal;
	QNetworkReply *reply = reinterpret_cast<QNetworkReply*>(sender());
	if (reply->error() != QNetworkReply::NoError)
	{
		qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << reply->error();
		return;
	}
	qint64 bytesWritten = 0;
	if (infoFile_.size() == 0)
	{
		size_ = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong();
		taskFile_.setFileName(taskFileFullName());
		//if inf file doesnt exist, task file has to be truncated.
		if (!taskFile_.open(QFile::ReadWrite | QFile::Truncate))
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << taskFile_.error();
			return;
		}
		if (!taskFile_.resize(size_))
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << taskFile_.error();
			return;
		}
		bytesWritten = infoFile_.write((char*)&size_, sizeof(size_));
		if (bytesWritten != sizeof(size_))
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << infoFile_.error();
			return;
		}
		bytesWritten = infoFile_.write((char*)&progress_, sizeof(progress_));
		if (bytesWritten != sizeof(progress_))
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << infoFile_.error();
			return;
		}
		auto urlBytes = url_.toUtf8();
		bytesWritten = infoFile_.write(urlBytes);
		if (bytesWritten != urlBytes.size())
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << infoFile_.error();
			return;
		}
	}
	if (!taskFile_.isOpen())
	{
		taskFile_.setFileName(taskFileFullName());
		if (!taskFile_.open(QFile::ReadWrite))
		{
			qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << taskFile_.error();
			return;
		}
	}
	if (!taskFile_.seek(progress_))
	{
		qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << taskFile_.error();
		return;
	}
	qint64 size = reply->size();
	bytesWritten = taskFile_.write(reply->readAll());
	if (bytesWritten != size)
	{
		qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << taskFile_.error();
		return;
	}
	progress_ += size;

	if (!infoFile_.seek(sizeof(size_)))
	{
		qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << infoFile_.error();
		return;
	}
	bytesWritten = infoFile_.write((char*)&progress_, sizeof(progress_));
	if (bytesWritten != sizeof(progress_))
	{
		qDebug() << QString(__FUNCTION__) << " " << __LINE__ << " error : " << infoFile_.error();
		return;
	}
	speedTest_.downloadBytes_ += size;
	qint64 currentMsecs = QDateTime::currentMSecsSinceEpoch();
	qint64 timeSpan = currentMsecs - speedTest_.lastMSecsSinceEpoch_;
	qint64 bytesPerSecond = 0;
	if (timeSpan > 50)	//每50ms通知一次UI
	{
		bytesPerSecond = speedTest_.bytesPerSecond(currentMsecs);
		emit downloadProgress(progress_, size_, bytesPerSecond);
		qDebug() << "kbytes per second : " << bytesPerSecond / 1024.0f << " timespan : " << timeSpan;
	}
	if (state_ == Pause || state_ == Cancel)
	{
		reply->deleteLater();
		if (state_ == Cancel)
		{
			infoFile_.remove();
			taskFile_.remove();
		}
	}
}
示例#25
0
bool autobots_toutiao::DoSupport()
{

	for (size_t i = 0; i < m_comment_list.size(); i++)
	{
		QString str_url1 = QString("http://isub.snssdk.com/2/relation/follow/v2/?ab_client=a1%2Cf2%2Cf7%2Ce1&ab_feature=z2&ab_group=z2&ab_version=112577%2C101786%2C112146%2C111547%2C101533%2C109464%2C110341%2C109891%2C112474%2C112070%2C106784%2C97142%2C31646%2C111339%2C101605%2C101558%2C112164%2C94046%2C112403%2C112532%2C105610%2C112343%2C105822%2C112578%2C108978%2C111796%2C108489%2C111897%2C110795%2C98042%2C105475&ac=WIFI&aid=13&app_name=news_article&channel=App%20Store&device_id=3135986566&device_platform=iphone&device_type=iPhone%206&idfa=86E011D2-C2DA-40CB-AB9D-DB1E1F9D668A&idfv=674FB6B1-60E9-4315-88FC-AAC84BEFAB46&iid=7730017535&live_sdk_version=1.6.5&new_reason=0&new_source=25&openudid=0d919477efbefb99dfe7a02a2df34d9127ecc947&os_version=9.3.5&resolution=750%2A1334&ssmix=a&user_id=51817712863&version_code=6.0.1&vid=674FB6B1-60E9-4315-88FC-AAC84BEFAB46")
			.arg(m_comment_list[i]);

		QUrl url1;
		url1.setUrl(str_url1);

		HttpParamList header_list;
		header_list.push_back(HttpParamItem("Accept", "*/*"));
		//header_list.push_back(HttpParamItem("Proxy - Connection", "Keep-Alive"));
		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("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
		header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
		//header_list.push_back(HttpParamItem("X-CSRFToken", m_csrf_token));
		header_list.push_back(HttpParamItem("Host", "isub.snssdk.com"));
		//header_list.push_back(HttpParamItem("Referer", m_url));
		header_list.push_back(HttpParamItem("tt-request-time", GetTimeStr()));
		//header_list.push_back(HttpParamItem("User-Agent", "News/5.8.3 (iPhone; iOS 9.3.5; Scale/2.00)"));
		header_list.push_back(HttpParamItem("User-Agent", "News/6.0.1 (iPhone; iOS 9.3.5; Scale/2.00)"));

		//HttpParamList post_data;
		//post_data.push_back(HttpParamItem("thread_id", m_group_id));

		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)
		{
			QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
			int n = statusCodeV.toInt();
			QString ss = reply->errorString();
			ui.lineEdit_msg->setText(ss);
			reply->deleteLater();
			//return false;
			continue;
		}

		QByteArray rp_data = reply->readAll();

		QVariant content_type = reply->header(QNetworkRequest::ContentTypeHeader);

		QString type = content_type.toString();

		if (type.contains("json"))
		{
			//bool res = GetSupportStatus(rp_data);
			//return res;
			if (rp_data.contains("success"))
			{
				ui.lineEdit_msg->setText(QStringLiteral("操作成功"));
			}
		}
		else
		{
			ui.lineEdit_msg->setText(QStringLiteral("操作失败"));
		}
	}
	return true;
}
示例#26
0
/** \fn MythDownloadManager::downloadFinished(MythDownloadInfo* dlInfo)
 *  \brief Callback to process download finished events.
 *  \param dlInfo  MythDownloadInfo for completed download.
 */
void MythDownloadManager::downloadFinished(MythDownloadInfo *dlInfo)
{
    QNetworkReply *reply = dlInfo->m_reply;

    if (reply)
    {
        QUrl possibleRedirectUrl =
             reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();

        dlInfo->m_redirectedTo =
             redirectUrl(possibleRedirectUrl, dlInfo->m_redirectedTo);
    }

    if(!dlInfo->m_redirectedTo.isEmpty())
    {
        VERBOSE(VB_FILE+VB_EXTRA, LOC +
                QString("downloadFinished(%1): Redirect: %2 -> %3")
                        .arg((long long)dlInfo)
                        .arg(reply->url().toString())
                        .arg(dlInfo->m_redirectedTo.toString()));

        QNetworkRequest request(dlInfo->m_redirectedTo);
        if (dlInfo->m_preferCache)
            request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                                 QNetworkRequest::PreferCache);
        request.setRawHeader("User-Agent",
                             "MythDownloadManager v" MYTH_BINARY_VERSION);

        if (dlInfo->m_post)
            dlInfo->m_reply = m_manager->post(request, *dlInfo->m_data);
        else
            dlInfo->m_reply = m_manager->get(request);

        m_downloadReplies[dlInfo->m_reply] = dlInfo;

        connect(dlInfo->m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
                SLOT(downloadError(QNetworkReply::NetworkError)));
        connect(dlInfo->m_reply, SIGNAL(downloadProgress(qint64, qint64)),
                this, SLOT(downloadProgress(qint64, qint64))); 

        m_downloadReplies.remove(reply);
        reply->deleteLater();
    }
    else
    {
        VERBOSE(VB_FILE+VB_EXTRA, QString("downloadFinished(%1): COMPLETE: %2")
                .arg((long long)dlInfo).arg(dlInfo->m_url));

        dlInfo->m_redirectedTo.clear();

        int dataSize = -1;

        // If we downloaded via the QNetworkAccessManager
        // AND the caller isn't handling the reply directly
        if (reply && dlInfo->m_processReply)
        {
            bool append = (!dlInfo->m_syncMode && dlInfo->m_caller);
            QByteArray data = reply->readAll();
            dataSize = data.size();

            if (append)
                dlInfo->m_bytesReceived += dataSize;
            else
                dlInfo->m_bytesReceived = dataSize;

            dlInfo->m_bytesTotal = dlInfo->m_bytesReceived;

            if (dlInfo->m_data)
            {
                if (append)
                    dlInfo->m_data->append(data);
                else
                    *dlInfo->m_data = data;
            }
            else if (!dlInfo->m_outFile.isEmpty())
            {
                saveFile(dlInfo->m_outFile, data, append);
            }
        }
        else if (!reply)  // If we downloaded via RemoteFile
        {
            if (dlInfo->m_data)
            {
                (*dlInfo->m_data) = dlInfo->m_privData;
            }
            else if (!dlInfo->m_outFile.isEmpty())
            {
                saveFile(dlInfo->m_outFile, dlInfo->m_privData);
            }
            dlInfo->m_bytesReceived += dataSize;
            dlInfo->m_bytesTotal = dlInfo->m_bytesReceived;
        }
        // else we downloaded via QNetworkAccessManager
        // AND the caller is handling the reply

        m_downloadInfos.remove(dlInfo->m_url);
        if (reply)
            m_downloadReplies.remove(reply);

        dlInfo->m_done = true;

        if (!dlInfo->m_syncMode)
        {
            if (dlInfo->m_caller)
            {
                VERBOSE(VB_FILE+VB_EXTRA, QString("downloadFinished(%1): "
                        "COMPLETE: %2, sending event to caller")
                        .arg((long long)dlInfo).arg(dlInfo->m_url));

                QStringList args;
                args << dlInfo->m_url;
                args << dlInfo->m_outFile;
                args << QString::number(dlInfo->m_bytesTotal);
                args << QString();  // placeholder for error string
                args << QString::number((int)dlInfo->m_errorCode);

                QCoreApplication::postEvent(dlInfo->m_caller,
                    new MythEvent("DOWNLOAD_FILE FINISHED", args));
            }

            delete dlInfo;
        }

        m_queueWaitCond.wakeAll();
    }
}
示例#27
0
bool autobots_toutiao::ProcessRedirectSSL(const QString& str)
{
	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	header_list.push_back(HttpParamItem("Proxy-Connection", "keep-alive"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-cn"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	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)
	{
		QString msg = reply->errorString();
		return false;
	}

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

	int n = statusCodeV.toInt();

	bool res = false;

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

		QUrl red_url = redirectionTarget.toUrl();

		QString str2 = red_url.toString();

		res = ProcessRedirectGet(str2);
	}
	else
	{
		res = false;
	}

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

	return res;
}
示例#28
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 = "https://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("\"*https://mts0.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("\"*https://mts0.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("\"*https://khms0.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("\"*https://mts0.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();
            
        }
示例#29
0
	// The QHttp object retrieved data.
	void Service::slotRequestFinished()
	{
		QNetworkReply * reply = qobject_cast<QNetworkReply *>(sender());

		qDebug() << "UPnP::Service: received HTTP response for request " << endl;

		if(!reply)
		{
			qWarning() << "UPnP::Service - HTTP Request failed: " << reply->errorString() << endl;
			m_iPendingRequests--;
			emit queryFinished(true);
			return;
		}

		if(reply->error() != QNetworkReply::NoError)
		{
			qWarning() << "UPnP::Service - HTTP Request failed: " << reply->errorString() << endl;
			m_iPendingRequests--;
			emit queryFinished(true);
			reply->deleteLater();
			return;
		}

		// Get the XML content
		QByteArray response = reply->readAll();
		QDomDocument xml;

		qDebug() << "Response:\n"
		         << response << "\n---\n";

		// Parse the XML
		QString errorMessage;
		bool error = !xml.setContent(response, false, &errorMessage);

		if(!error)
		{
			QString baseNamespace = xml.documentElement().tagName();

			if(baseNamespace.length() > 0)
			{
				int cutAt = baseNamespace.indexOf(':');
				if(cutAt > -1)
				{
					baseNamespace.truncate(cutAt);
					qDebug() << "Device is using " << baseNamespace << " as XML namespace" << endl;
					m_szBaseXmlPrefix = baseNamespace;
				}
			}

			// Determine how to process the data
			if(xml.namedItem(m_szBaseXmlPrefix + ":Envelope").isNull())
			{
				qDebug() << "UPnP::Service: plain XML detected, calling gotInformationResponse()." << endl;
				// No SOAP envelope found, this is a normal response to callService()
				gotInformationResponse(xml.lastChild());
			}
			else
			{
				qDebug() << xml.toString() << endl;
				// Got a SOAP message response to callAction()
				QDomNode resultNode = XmlFunctions::getNode(xml, "/" + m_szBaseXmlPrefix + ":Envelope/" + m_szBaseXmlPrefix + ":Body").firstChild();

				error = (resultNode.nodeName() == m_szBaseXmlPrefix + ":Fault");

				if(!error)
				{
					if(resultNode.nodeName().startsWith("m:") || resultNode.nodeName().startsWith("u:"))
					{
						qDebug() << "UPnP::Service: SOAP envelope detected, calling gotActionResponse()." << endl;
						// Action success, return SOAP body
						QMap<QString, QString> resultValues;

						// Parse all parameters
						// It's possible to pass the entire QDomNode object to the gotActionResponse()
						// function, but this is somewhat nicer, and reduces code boat in the subclasses
						QDomNodeList children = resultNode.childNodes();
						for(int i = 0; i < children.count(); i++)
						{
							QString key = children.item(i).nodeName();
							resultValues[key] = children.item(i).toElement().text();
						}

						// Call the gotActionResponse()
						gotActionResponse(resultNode.nodeName().mid(2), resultValues);
					}
				}
				else
				{
					qDebug() << "UPnP::Service: SOAP error detected, calling gotActionResponse()." << endl;

					// Action failed
					gotActionErrorResponse(resultNode);
				}
			}
		}
		else
		{
			qWarning() << "UPnP::Service - XML parsing failed: " << errorMessage << endl;
		}

		// Only emit when bytes>0
		m_iPendingRequests--;
		emit queryFinished(error);
	}
示例#30
0
文件: fileboom.cpp 项目: marxoft/qdl
void FileBoom::onWebPageDownloaded() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

    if (!reply) {
        emit error(NetworkError);
        return;
    }

    QRegExp re("(http://fboom.me|)/file/url.html\\?file=[^'\"]+");
    QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();

    if (re.indexIn(redirect) == 0) {
        QUrl url(re.cap());

        if (url.host().isEmpty()) {
            url.setScheme("http");
            url.setHost("fboom.me");
        }

        emit downloadRequestReady(QNetworkRequest(url));
    }
    else if (!redirect.isEmpty()) {
        QUrl url(redirect);

        if (url.host().isEmpty()) {
            url.setScheme("http");
            url.setHost("fboom.me");
        }

        this->getDownloadRequest(url);
    }
    else {
        m_url = reply->request().url();

        QString response(reply->readAll());

        if (re.indexIn(response) >= 0) {
            QUrl url(re.cap());

            if (url.host().isEmpty()) {
                url.setScheme("http");
                url.setHost("fboom.me");
            }

            emit downloadRequestReady(QNetworkRequest(url));
        }
        else {
            m_fileId = response.section("data-slow-id=\"", 1, 1).section('"', 0, 0);

            if (m_fileId.isEmpty()) {
                if (response.contains("system is unable to find")) {
                    emit error(NotFound);
                }
                else {
                    emit error(UnknownError);
                }
            }
            else {
                this->getWaitTime();
            }
        }
    }

    reply->deleteLater();
}