Exemplo n.º 1
0
void RequestModel::update()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply)
        return;

    int offset;
    for (offset = m_requests.count() - 1; offset >= 0; --offset) {
        if (m_requests[offset].reply == reply)
            break;
    }
    if (offset < 0)
        return;

    // Save reply headers
    foreach (const QByteArray &header, reply->rawHeaderList() ) {
        QPair<QByteArray, QByteArray> pair(header, reply->rawHeader(header));
        m_requests[offset].replyHeaders.append(pair);
    }

    // Save reply info to be displayed
    int status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
    QString reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    m_requests[offset].response = QString(QLatin1String("%1 %2")).arg(status).arg(reason);
    m_requests[offset].length = reply->header(QNetworkRequest::ContentLengthHeader).toInt();
    m_requests[offset].contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString();

    if (status == 302) {
        QUrl target = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl();
        m_requests[offset].info = tr("Redirect: %1").arg(target.toString());
    }
}
Exemplo n.º 2
0
void YandexNarodUploadJob::onPublishFinished()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
	Q_ASSERT(reply);
	reply->deleteLater();

	QUrl url = reply->header(QNetworkRequest::LocationHeader).toUrl();
	if (url.isRelative())
		url = reply->url().resolved(url);

	QString text = tr("File sent: %1 (%n bytes)\nDownload url: %2",
					  "%1 - filename, %2 - url",
					  m_data->size())
				   .arg(fileName(), url.toString());

	Message message(text);
	message.setIncoming(false);
	message.setProperty("service", true);
	if (ChatSession *s = ChatLayer::get(chatUnit(), false))
		s->appendMessage(message);
	message.setProperty("service", false);
	chatUnit()->account()->getUnitForSession(chatUnit())->send(message);

	setState(Finished);
}
Exemplo n.º 3
0
void LocationManager::errorDataReceived(QNetworkReply& errorReply) {
    
    if (errorReply.header(QNetworkRequest::ContentTypeHeader).toString().startsWith("application/json")) {
        // we have some JSON error data we can parse for our error message
        QJsonDocument responseJson = QJsonDocument::fromJson(errorReply.readAll());
        
        QJsonObject dataObject = responseJson.object()["data"].toObject();
        
        qDebug() << dataObject;
        
        QString errorString = "There was a problem creating that location.\n";
        
        // construct the error string from the returned attribute errors
        foreach(const QString& key, dataObject.keys()) {
            errorString += "\n\u2022 " + key + " - ";
            
            QJsonValue keyedErrorValue = dataObject[key];
           
            if (keyedErrorValue.isArray()) {
                foreach(const QJsonValue& attributeErrorValue, keyedErrorValue.toArray()) {
                    errorString += attributeErrorValue.toString() + ", ";
                }
                
                // remove the trailing comma at end of error list
                errorString.remove(errorString.length() - 2, 2);
            } else if (keyedErrorValue.isString()) {
QVariant QNetworkReplyProto::header(QNetworkRequest::KnownHeaders header) const
{
  QNetworkReply *item = qscriptvalue_cast<QNetworkReply*>(thisObject());
  if (item)
    return item->header(header);
  return QVariant();
}
    void onQNetworkReplyReadyRead() {
        DEBUG("onQNetworkReplyReadyRead()");
        bool firstRead = invocationStatus != Invocation::RESPONSE_RECEIVED;
        invocationStatus = Invocation::RESPONSE_RECEIVED;

        QVariant statusCode = qreply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
        if (statusCode.isValid())
        {
            httpStatus = HTTPInvocationDefinition::resolveHttpStatus(statusCode.toInt());
        } else {
            // TODO: what to do, when no code?
            invocationStatus = Invocation::ERROR;
            result << InvocationErrors::INVOCATION_FAILED
                   << Result::reasonFromDesc("Http status code not valid");
            return;
        }

        if (httpStatus != HTTPInvocationDefinition::OK_200) {
            invocationStatus = Invocation::ERROR;
            result << InvocationErrors::INVOCATION_FAILED
                   << Result::reasonFromDesc("Http error response code (not 200)")
                   << Result::Meta("http_code", statusCode.toString());

            // nothing to save to file
            DEBUG("Error no data to save to file");
            return;
        }

        // is target open?
        if (!outputFile.isOpen()) {
            if (!outputFile.open(QIODevice::WriteOnly)) {
                q->abort();
                result << InvocationErrors::INVOCATION_INVALID
                       << Result::reasonFromDesc("Open output file failed")
                       << Result::Meta("file_path", outputFilePath);

                invocationStatus = Invocation::INVALID_INVOCATION;
                emit q->finishedError(q);
                return;
            }
        }

        if (firstRead)
            emit q->downloadStarted(q);

        QVariant contentLength = qreply->header(QNetworkRequest::ContentLengthHeader);
        qint64 bytesTotal = contentLength.isValid() ? contentLength.toInt() : -1;

        int readBytes = 0;
        while ( (readBytes = qreply->read(readBuffer, READ_BUFFER_SIZE) ) > 0) {
            totalReadBytes += readBytes;
            outputFile.write(readBuffer, readBytes);
            onQNetworkReplyDownloadProgress(totalReadBytes, bytesTotal);
        }

    }
void SidebarPrivate::linkClickedFinished()
{
    QNetworkReply * reply = static_cast< QNetworkReply * >(sender());

    QString target = reply->property("__target").toString();
    QVariant redirectsVariant = reply->property("__redirects");
    int redirects = redirectsVariant.isNull() ? 20 : redirectsVariant.toInt();

    // Redirect?
    QUrl redirectedUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (redirectedUrl.isValid())
    {
        if (redirectedUrl.isRelative())
        {
            QUrl oldUrl = reply->url();
            redirectedUrl.setScheme(oldUrl.scheme());
            redirectedUrl.setAuthority(oldUrl.authority());
        }
        if (redirects > 0)
        {
            QNetworkRequest request = reply->request();
            request.setUrl(redirectedUrl);
            QNetworkReply * reply = networkAccessManager()->get(request);
            reply->setProperty("__target", target);
            connect(reply, SIGNAL(finished()), this, SLOT(linkClickedFinished()));
        }
        else
        {
            // TOO MANY REDIRECTS
        }
        reply->deleteLater();
        return;
    }

    // Check headers... if PDF then launch a new window, otherwise give it to the OS
    QString contentType(reply->header(QNetworkRequest::ContentTypeHeader).toString());
    if (contentType.contains("application/pdf")) {
        emit urlRequested(reply->request().url(), "tab");
    } else {
        QUrl href(reply->request().url());
        if (href.isValid()) {
            if (href.scheme() == "http" || href.scheme() == "https") {
                if (target == "sidebar") {
                    webView->setUrl(href);
                    slideLayout->push("web");
                    return;
                }
            }

            QDesktopServices::openUrl(href);
        }
        // FIXME error
    }

    reply->deleteLater();
}
Exemplo n.º 7
0
int Downloader::checkHeader(const QString &url)
{
    qDebug() << "About to check";
    QNetworkReply *reply = d->manager->head(d->createNetworkRequest(QUrl(url)));
    reply->setProperty("is_Header_Check", true);
    qDebug() << "Head check done";
    QEventLoop e;
    connect(reply, SIGNAL(finished()), &e, SLOT(quit()));
    e.exec();
    return reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toTime_t();
}
Exemplo n.º 8
0
void CWizXmlRpcServer::on_replyFinished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply *>(sender());

    if (reply->error()) {
        reply->deleteLater();
        return;
    }

    QString strContentType = reply->header(QNetworkRequest::ContentTypeHeader).toString();
    if (strContentType != "text/xml;charset=UTF-8") {
        processError(errorContentType, 0, "Invalid content type of response");
        reply->deleteLater();
        return;
    }

    m_replyData = reply->readAll();

#ifdef WIZNOTE_DEBUG_XMLRPC
    QString requestFile = QDir::tempPath() + "/WizNote/" + m_strMethodName;
    QString replyFile = QDir::tempPath() + "/WizNote/on_" + m_strMethodName;
    WizSaveUnicodeTextToUtf8File(requestFile, QString(m_requestData));
    WizSaveUnicodeTextToUtf8File(replyFile, QString(m_replyData));
#endif

    QString strXml = QString::fromUtf8(m_replyData.constData());

    CWizXMLDocument doc;
    if (!doc.LoadXML(strXml)) {
        processError(errorXmlFormat, 0, "Invalid xml");
        reply->deleteLater();
        return;
    }

    CWizXmlRpcValue* pRet = NULL;

    if (!WizXmlRpcResultFromXml(doc, &pRet)) {
        processError(errorXmlRpcFormat, 0, "Can not parse xmlrpc");
        reply->deleteLater();
        return;
    }

    Q_ASSERT(pRet);

    if (CWizXmlRpcFaultValue* pFault = dynamic_cast<CWizXmlRpcFaultValue *>(pRet)) {
        processError(errorXmlRpcFault, pFault->GetFaultCode(), pFault->GetFaultString());
        reply->deleteLater();
        delete pRet;
        return;
    }

    processReturn(*pRet);
}
void KVNetworkAccessManager::trackedGETReadyRead()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	bool ok;
	/*qint64 length = */reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(&ok);

	// Don't report progress for replies without a Content-Length
	if(ok)
	{
		trackedGETProgress += reply->bytesAvailable();
		emit trackedProgressChanged(trackedGETProgress, trackedGETTotalSize);
	}
}
Exemplo n.º 10
0
	void Plugin::handleMetadata ()
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
		{
			qWarning () << Q_FUNC_INFO
					<< "sender is not a QNetworkReply:"
					<< sender ();
			return;
		}

		const QString& pasteUrl = reply->header (QNetworkRequest::LocationHeader).toString ();
		QPointer<QObject> entryObj = Reply2Entry_ [reply];
		if (!entryObj)
		{
			QApplication::clipboard ()->setText (pasteUrl, QClipboard::Clipboard);
			QApplication::clipboard ()->setText (pasteUrl, QClipboard::Selection);
			const Entity& e = Util::MakeNotification (tr ("Text pasted"),
					tr ("Your text has been pasted: %1. The URL has "
						"been copied to the clipboard."),
					PInfo_);
			emit gotEntity (e);
			return;
		}

		ICLEntry *entry = qobject_cast<ICLEntry*> (entryObj);
		if (!entry)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to cast"
					<< entryObj
					<< "to ICLEntry";
			return;
		}

		IMessage::MessageType type =
				entry->GetEntryType () == ICLEntry::ETMUC ?
						IMessage::MTMUCMessage :
						IMessage::MTChatMessage;
		QObject *msgObj = entry->CreateMessage (type, QString (), pasteUrl);
		IMessage *msg = qobject_cast<IMessage*> (msgObj);
		if (!msg)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to cast"
					<< msgObj
					<< "to IMessage";
			return;
		}
		msg->Send ();
	}
Exemplo n.º 11
0
QString DownloadWidget::getRealUrl(QString url)
{
    QString realUrl;
    if(url.contains("plyz"))
    {
        int tryTimes=5;
        //尝试tryTimes次
        QString realUrl_temp = this->url;
        while(tryTimes --)
        {
            QEventLoop loop;
            QNetworkReply *reply = manager->head(QNetworkRequest(realUrl_temp));
            connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
            QVariant varLocation = reply->header(QNetworkRequest::LocationHeader);
            if(!varLocation.isNull())
            {
                realUrl_temp = varLocation.toString();
                //qDebug()<<realUrl_temp;
                continue;
            }
            delete reply;
            break;
        }
        realUrl = realUrl_temp;
        if(realUrl == "")
        {
            myTipWin.show();
            myTipWin.setText("获取下载链接失败。");
            myTipWin.timeToHide(3);
        }

    }else if(url.contains("baidupcs.com"))
    {
        realUrl= url;
    }else
    {
        QNetworkRequest request0;
        request0.setUrl(QString("http://www.mvgather.com/mvgather/api/getRealUrl.php?url=%0").arg(url));//
        QNetworkReply *reply0 = manager->get(request0);
        QEventLoop loop0;
        QObject::connect(reply0, SIGNAL(finished()), &loop0, SLOT(quit()));
        loop0.exec();
        QByteArray data0 = reply0->readAll();
        realUrl = data0;
    }
    //qDebug()<<realUrl;
    return realUrl;

}
Exemplo n.º 12
0
void WebLoadManager::onProgress(qint64 already, qint64 size) {
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	if (!reply) return;

	Replies::iterator j = _replies.find(reply);
	if (j == _replies.cend()) { // handled already
		return;
	}
	webFileLoaderPrivate *loader = j.value();

	WebReplyProcessResult result = WebReplyProcessProgress;
	QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	int32 status = statusCode.isValid() ? statusCode.toInt() : 200;
	if (status != 200 && status != 206 && status != 416) {
		if (status == 301 || status == 302) {
			QString loc = reply->header(QNetworkRequest::LocationHeader).toString();
			if (!loc.isEmpty()) {
				if (loader->oneMoreRedirect()) {
					sendRequest(loader, loc);
					return;
				} else {
					LOG(("Network Error: Too many HTTP redirects in onFinished() for web file loader: %1").arg(loc));
					result = WebReplyProcessError;
				}
			}
		} else {
			LOG(("Network Error: Bad HTTP status received in WebLoadManager::onProgress(): %1").arg(statusCode.toInt()));
			result = WebReplyProcessError;
		}
	} else {
		loader->setProgress(already, size);
		QByteArray r = reply->readAll();
		if (!r.isEmpty()) {
			loader->addData(r);
		}
		if (size == 0) {
			LOG(("Network Error: Zero size received for HTTP download progress in WebLoadManager::onProgress(): %1 / %2").arg(already).arg(size));
			result = WebReplyProcessError;
		}
	}
	if (!handleReplyResult(loader, result)) {
		_replies.erase(j);
		_loaders.remove(loader);
		delete loader;

		reply->abort();
		reply->deleteLater();
	}
}
Exemplo n.º 13
0
	void PasteServiceBase::handleMetadata ()
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
		{
			qWarning () << Q_FUNC_INFO
					<< "sender is not a QNetworkReply:"
					<< sender ();
			return;
		}

		const auto& location = reply->header (QNetworkRequest::LocationHeader).toString ();
		if (!location.isEmpty ())
			FeedURL (location);
	}
Exemplo n.º 14
0
//用阻塞的方式获取下载文件的长度
qint64 TcDownloadList::GetFileSize(QUrl url)
{
    QNetworkAccessManager manager;
    //qDebug() << "Getting the file size...";
    QEventLoop loop;
    //发出请求,获取目标地址的头部信息
    QNetworkReply *reply = manager.head(QNetworkRequest(url));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()), Qt::DirectConnection);
    loop.exec();
    QVariant var = reply->header(QNetworkRequest::ContentLengthHeader);
    reply->deleteLater();
    qint64 size = var.toLongLong();
    //qDebug() << "The file size is: " << size;
    return size;
}
Exemplo n.º 15
0
void Uploadtous::onWebPageDownloaded() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

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

    QRegExp re("http://storage\\d+.(uploadto.us|ultramegabit.com)/[^'\"]+");
    QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();

    if (redirect.isEmpty()) {
        redirect = reply->header(QNetworkRequest::LocationHeader).toString();
    }

    if (re.indexIn(redirect) == 0) {
        QNetworkRequest request;
        request.setUrl(QUrl(re.cap()));
        emit downloadRequestReady(request);
    }
    else if (!redirect.isEmpty()) {
        this->getDownloadRequest(QUrl(redirect));
    }
    else {
        QString response(reply->readAll());

        if (re.indexIn(response) >= 0) {
            QNetworkRequest request;
            request.setUrl(QUrl(re.cap()));
            emit downloadRequestReady(request);
        }
        else {
            m_captchaKey = response.section("www.google.com/recaptcha/api/challenge?k=", 1, 1).section('"', 0, 0);
            m_fileId = response.section("encode\" value=\"", 1, 1).section('"', 0, 0);
            m_token = response.section("csrf_token\" value=\"", 1, 1).section('"', 0, 0);

            if ((m_captchaKey.isEmpty()) || (m_fileId.isEmpty()) || (m_token.isEmpty())) {
                emit error(UnknownError);
            }
            else {
                this->startWait(30000);
                this->connect(this, SIGNAL(waitFinished()), this, SLOT(downloadCaptcha()));
            }
        }
    }

    reply->deleteLater();
}
void KVNetworkAccessManager::trackedGETMetaDataChanged()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());

	// For replies with enough headers to fire metaDataChanged() multiple times:
	// Make sure not to append the length more than once
	if(!reply->property("lengthAlreadyAdded").toBool())
	{
		// Only add the total size if it's present and valid
		bool ok;
		qint64 length = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(&ok);
		if(ok)
		{
			trackedGETTotalSize += length;
			reply->setProperty("lengthAlreadyAdded", true);
		}
	}
}
Exemplo n.º 17
0
void Channel::nrf()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    QVariant v = reply->header(QNetworkRequest::SetCookieHeader);
    QList<QNetworkCookie> c = qvariant_cast<QList<QNetworkCookie> >(v);
    //Eventually update cookies, may set S
    bool cookieUpdated = false;
    foreach(QNetworkCookie cookie, c) {
        qDebug() << cookie.name();
        for (int i=0; i<session_cookies.size(); i++) {
            if (session_cookies[i].name() == cookie.name()) {
                session_cookies[i].setValue(cookie.value());
                emit cookieUpdateNeeded(cookie);
                qDebug() << "Updated cookie " << cookie.name();
                cookieUpdated = true;
            }
        }
    }
void KVNetworkAccessManager::trackedGETFinished()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	bool ok;
	qint64 length = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(&ok);

	if(ok)
	{
		trackedGETProgress -= length;
		if(trackedGETProgress < 0)
			trackedGETProgress = 0;

		trackedGETTotalSize -= length;
		if(trackedGETTotalSize < 0)
			trackedGETTotalSize = 0;

		emit trackedProgressChanged(trackedGETProgress, trackedGETTotalSize);
	}
}
Exemplo n.º 19
0
void WizXmlRpcServer::on_replyFinished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply *>(sender());

    if (reply->error()) {
        reply->deleteLater();
        return;
    }

    QString strContentType = reply->header(QNetworkRequest::ContentTypeHeader).toString();
    if (strContentType != "text/xml;charset=UTF-8") {
        processError(errorContentType, 0, "Invalid content type of response");
        reply->deleteLater();
        return;
    }

    QString strXml = QString::fromUtf8(reply->readAll().constData());

    WizXMLDocument doc;
    if (!doc.loadXML(strXml)) {
        processError(errorXmlFormat, 0, "Invalid xml");
        reply->deleteLater();
        return;
    }

    WizXmlRpcValue* pRet = NULL;

    if (!WizXmlRpcResultFromXml(doc, &pRet)) {
        processError(errorXmlRpcFormat, 0, "Can not parse xmlrpc");
        reply->deleteLater();
        return;
    }

    Q_ASSERT(pRet);

    if (WizXmlRpcFaultValue* pFault = dynamic_cast<WizXmlRpcFaultValue *>(pRet)) {
        processError(errorXmlRpcFault, pFault->getFaultCode(), pFault->getFaultString());
    }

    processReturn(*pRet);

    reply->deleteLater();
}
Exemplo n.º 20
0
void Updater::headersReceived()
{
    QNetworkReply * reply = qobject_cast<QNetworkReply *>( sender() );

    Q_ASSERT( 0 != reply );

    qDebug() << " Headers received " << reply->url() << "\nStatus: " << reply->error();

    if( GettingHeaders == m_state )
    {
        if( QNetworkReply::NoError == reply->error() )
        {
            QDateTime lastModified = reply->header( QNetworkRequest::LastModifiedHeader ).toDateTime();

            if( AdvertisementsList::instance()->at( m_currentAdIndex ).lastModified() == lastModified )
            {
                // ad didn't changed. Go to next one if any
                requestNext();
            }
            else
            {
                m_pkg = new Package( m_currentAdIndex );
                m_pkg->setLastModified( lastModified );

                requestFile();
            }
        }
        else
        {
            qDebug() << "Error occured during headers request" << reply->errorString();
            // try to get next one
            requestNext();
        }
    }
    else
    {
        // this should not happen
        Q_ASSERT( false );
    }

    // schedule delete of replay. We don't need it anymore
    reply->deleteLater();
}
Exemplo n.º 21
0
void Uploadtous::onCaptchaSubmitted() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

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

    QRegExp re("http://storage\\d+.(uploadto.us|ultramegabit.com)/[^'\"]+");
    QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();

    if (redirect.isEmpty()) {
        redirect = reply->header(QNetworkRequest::LocationHeader).toString();
    }
    
    if (re.indexIn(redirect) == 0) {
        QNetworkRequest request;
        request.setUrl(QUrl(re.cap()));
        emit downloadRequestReady(request);
    }
    else if (redirect.contains("delay")) {
        this->startWait(600000);
        this->connect(this, SIGNAL(waitFinished()), this, SLOT(onWaitFinished()));
    }
    else {
        QString response(reply->readAll());

        if (re.indexIn(response) >= 0) {
            QNetworkRequest request;
            request.setUrl(QUrl(re.cap()));
            emit downloadRequestReady(request);
        }
        else if (response.contains("check_recaptcha")) {
            emit error(CaptchaError);
        }
        else {
            emit error(UnknownError);
        }
    }

    reply->deleteLater();
}
Exemplo n.º 22
0
QByteArray MarketSession::executeRawHttpsQuery(const QByteArray &request)
{
    QByteArray data;
    QUrl url("https://android.clients.google.com/market/api/ApiRequest");
    QNetworkAccessManager manager;
    QNetworkRequest req;
    req.setUrl(url);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    req.setRawHeader("Cookie",QString("ANDROIDSECURE=%1").arg(authSubToken).toUtf8());
    req.setRawHeader("User-Agent", "Android-Market/2 (sapphire PLAT-RC33); gzip");
    req.setRawHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    QString requestData=QString("version=%1&request=%2")
            .arg(PROTOCOL_VERSION).arg(QString(request.toBase64()));
    QNetworkReply* http = manager.post(req,requestData.toUtf8());
    QEventLoop eventLoop;
    connect(http,SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec();
    data=gzipDecompress(http->read(http->header(QNetworkRequest::ContentLengthHeader).toUInt()));
    delete http;
    return data;
}
Exemplo n.º 23
0
	void YoutubePlayer::handleFormatCheckFinished ()
	{
		Ui_.Quality_->setEnabled (true);
		QNetworkReply *rep = qobject_cast<QNetworkReply*> (sender ());
		if (!rep)
		{
			qWarning () << Q_FUNC_INFO
				<< "sender is not a QNetworkReply*"
				<< sender ();
			return;
		}
		rep->deleteLater ();

		QString fmt = rep->property ("fmt").toString ();

		int code = rep->attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt ();
		if (code == 404)
		{
			QMessageBox::critical (this,
					"LeechCraft",
					tr ("This format is unavailable, please select another one."));
			return;
		}
		// 3xx codes => redirection
		else if (code / 100 == 3)
		{
			QUrl url = rep->header (QNetworkRequest::LocationHeader).value<QUrl> ();
			ReqAndContinueFormatCheck (url)->setProperty ("fmt", fmt);
			return;
		}
		XmlSettingsManager::Instance ()->
			setProperty ("YoutubePreviousQuality", fmt);

		QUrl url = OriginalURL_;
		url.addQueryItem ("fmt", fmt);
		SetVideoUrl (url);
	}
Exemplo n.º 24
0
bool autobots_toutiao::DoPostFatie(const QString& content)
{
  QString str_url1 = "http://live.bilibili.com/msg/send";

  QUrl url1;
  url1.setUrl(str_url1);

  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Accept",	"application/json, text/javascript, */*; q=0.01"));
  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("Host", "live.bilibili.com"));
  header_list.push_back(HttpParamItem("Origin", "http://toutiao.com"));
  header_list.push_back(HttpParamItem("Referer", "http://static.hdslb.com/live-static/swf/LivePlayerEx_1.swf?2016062801"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  HttpParamList post_data;
  post_data.push_back(HttpParamItem("color", "16777215"));
  post_data.push_back(HttpParamItem("fontsize", "25"));
  post_data.push_back(HttpParamItem("mode", "1"));
  post_data.push_back(HttpParamItem("msg", content));
  post_data.push_back(HttpParamItem("roomid", "5313"));

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

  QByteArray rp_data = reply->readAll();

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

  QString type = content_type.toString();

  if (type.contains("json"))
  {
    bool res = GetFatieStatus(rp_data); 
     if (!res)
     {
       QString msg = rp_data;
       ui.lineEdit_msg->setText(msg);
     }

     return res;    
  }
  else 
  {
      return false;
  } 
  
}
Exemplo n.º 25
0
QByteArray QgsSvgCache::getImageData( const QString &path ) const
{
  // is it a path to local file?
  QFile svgFile( path );
  if ( svgFile.exists() )
  {
    if ( svgFile.open( QIODevice::ReadOnly ) )
    {
      return svgFile.readAll();
    }
    else
    {
      return QByteArray();
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return ba;
}
Exemplo n.º 26
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;
}
Exemplo n.º 27
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;
}
Exemplo n.º 28
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();
		}
	}
}