Esempio n. 1
2
void HttpWindow::startRequest(const QUrl &requestedUrl)
{
    if(isPost())
    {
        url = requestedUrl;
        httpRequestAborted = false;

        QByteArray postData;
        QNetworkRequest request;

        postData.append("username=elvis");
        postData.append("&passwd=hash");
        postData.append("&client=localhost");
        postData.append("&sql=select * from user");

        QByteArray size;
        size.append(postData.size());

        request.setUrl(requestedUrl);
        request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
        request.setRawHeader("Accept","text/html, application/xhtml+xml, */*");
        request.setRawHeader("Referer","http://localhost:8080");
        request.setRawHeader("Accept-Language","en-US,*");
        request.setRawHeader("X-Requested-With","XMLHttpRequest");
        request.setRawHeader("User-Agent","Mozilla/5.0");
        request.setRawHeader("Accept-Encoding","gzip,deflate");
        request.setRawHeader("Host","localhost:8080");

        request.setRawHeader("Content-Length",size);
        request.setRawHeader("Connection","Keep-Alive");
        request.setRawHeader("Cache-Control","no-cache");

        reply = qnam.post(request , postData);

        //connect(reply ,&QNetworkReply::downloadProgress , this , &HttpWindow::slotNetworkReplyProgress);
        //connect(reply, &QNetworkReply::finished , this , &HttpWindow::slotDownFinish);

        connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);
        connect(reply, &QNetworkReply::finished , this , &HttpWindow::httpFinished);
        connect(reply ,&QNetworkReply::downloadProgress , this , &HttpWindow::slotNetworkReplyProgress);

    }
    else
    {
        url = requestedUrl;
        httpRequestAborted = false;

        reply = qnam.get(QNetworkRequest(url));

        connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);

        //ProgressDialog *progressDialog = new ProgressDialog(url, this);
        //progressDialog->setAttribute(Qt::WA_DeleteOnClose);
        //connect(progressDialog, &QProgressDialog::canceled, this, &HttpWindow::cancelDownload);
        //connect(reply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress);

        connect(reply ,&QNetworkReply::downloadProgress , this , &HttpWindow::slotNetworkReplyProgress);

        //connect(reply, &QNetworkReply::finished, progressDialog, &ProgressDialog::hide);
        //connect(reply, &QNetworkReply::finished , this , &HttpWindow::slotDownFinish);

        connect(reply, &QNetworkReply::finished , this , &HttpWindow::httpFinished);

        //progressDialog->show();
        //statusLabel->setText(tr("Downloading %1...").arg(url.toString()));
    }
}
void KisNetworkAccessManager::getUrl(const QUrl &url)
{
    QNetworkRequest req;
    req.setUrl(url);
    get(req);
}
Esempio n. 3
0
void FileMates::checkCaptcha() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

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

    QRegExp re("http://files-dl\\d+\\.com/cgi-bin/[^'\"]+");
    QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).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_rand = response.section("rand\" value=\"", 1, 1).section('"', 0, 0);
            QString codeBlock = response.section("<td align=right>", 1, 1).section("</span></div>", 0, 0);
            QStringList codeList = codeBlock.split("padding-left:", QString::SkipEmptyParts);

            if (!codeList.isEmpty()) {
                codeList.removeFirst();

                QMap<int, QString> codeMap;

                int i = 1;

                while ((!codeList.isEmpty()) && (i < 5)) {
                    QString code = codeList.takeFirst();
                    int key = code.section('p', 0, 0).toInt();
                    QString value = QString::number(code.section(">&#", 1, 1).left(2).toInt() - 48);
                    codeMap[key] = value;
                    i++;
                }

                QList<int> codeKeys = codeMap.keys();
                qSort(codeKeys.begin(), codeKeys.end());

                foreach (int key, codeKeys) {
                    m_code.append(codeMap[key]);
                }
            }

            if ((m_rand.isEmpty()) || (m_code.isEmpty())) {
                QString errorString = response.section("<div class=\"err\">", 1, 1).section('<', 0, 0);

                if (!errorString.isEmpty()) {
                    if (errorString.startsWith("You have to wait")) {
                        int mins = errorString.section(" minutes", 0, 0).section(' ', -1).toInt();
                        int secs = errorString.section(" seconds", 0, 0).section(' ', -1).toInt();
                        this->startWait((mins * 60000) + (secs * 1000));
                        this->connect(this, SIGNAL(waitFinished()), this, SLOT(onWaitFinished()));
                    }
                    else {
                        emit error(UnknownError);
                    }
                }
                else {
                    emit error(UnknownError);
                }
            }
            else {
                this->startWait(30000);
                this->connect(this, SIGNAL(waitFinished()), this, SLOT(submitCaptcha()));
            }
        }
Esempio n. 4
0
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
{
    if (m_ignoreAllWarnings) {
        reply->ignoreSslErrors(errors);
        return;
    }

    if (reply->property("downReply").toBool()) {
        return;
    }

    int errorsIgnored = 0;
    foreach(const QSslError & error, errors) {
        if (m_ignoredCerts.contains(error.certificate())) {
            ++errorsIgnored;
        }
    }

    if (errorsIgnored == errors.count()) {
        return;
    }

    QNetworkRequest request = reply->request();
    QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
    WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
    if (!webPage) {
        return;
    }

    QString title = tr("SSL Certificate Error!");
    QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:");

    QString certs;

    foreach(const QSslError & error, errors) {
        if (m_localCerts.contains(error.certificate())) {
            continue;
        }
        if (error.error() == QSslError::NoError) { //Weird behavior on Windows
            continue;
        }

        QSslCertificate cert = error.certificate();
        certs.append("<ul><li>");
        certs.append(tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization)));
        certs.append("</li><li>");
        certs.append(tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName)));
        certs.append("</li><li>");
        certs.append(tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy"));
        certs.append("</li><li>");
        certs.append(tr("<b>Error: </b>") + error.errorString());
        certs.append("</li></ul>");
    }

    QString text2 = tr("Would you like to make an exception for this certificate?");
    QString message = QString("<b>%1</b><p>%2</p>%3<p>%4</p>").arg(title, text1, certs, text2);

    if (!certs.isEmpty())  {
        if (QMessageBox::critical(webPage->view(), tr("SSL Certificate Error!"), message,
                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) {
            return;
        }

        foreach(const QSslError & error, errors) {
            if (!m_localCerts.contains(error.certificate())) {
                addLocalCertificate(error.certificate());
            }
        }
    }

    reply->ignoreSslErrors(errors);
}
Esempio n. 5
0
void Discogs::handleRelease( QNetworkReply* reply ){

    Album album;
    QNetworkRequest request = reply->request();
    QString key = request.attribute(QNetworkRequest::User).toString();

    if( albums_.contains(key) ){
        album = albums_[key];
        //album.setArtists( QStringList() );
        //album.setSongs( QList<Song>() );
    }


    //cover->setText("");
    QString err;
    QByteArray response(reply->readAll());
    QXmlStreamReader xml(response);

    QList<Artist> Artists;
    QList<QUrl> images;
    QStringList artists,roles;
    QList<Song> songs;
    while (!xml.atEnd()) {
        xml.readNext();
        //qDebug()<<xml.name();

        if( xml.name() == "release" && xml.attributes().hasAttribute("id") ){
            QString id = xml.attributes().value("id").toString();
            album.setRelease(id);
        }

        if(xml.tokenType() == QXmlStreamReader::StartElement){
            if( xml.attributes().hasAttribute("stat") ){
                QString stat = xml.attributes().value("stat").toString();
                if(stat=="fail"){
                    while(xml.readNextStartElement()){
                        if( xml.name() == "error" ){
                            err.append(xml.readElementText()+"\n");
                        }else{
                            xml.skipCurrentElement();
                        }
                    }
                }
            }
            if( xml.attributes().hasAttribute("requests") ){
                //&nSearches = xml.attributes().value("requests").toString().toInt();
                //info->setText(QString::number(nSearches)+" searches performed within the last 24 hours");
            }
            if(xml.name() == "images"){
                xml.readNext();
                while(xml.name()=="image"){
                    if( xml.attributes().hasAttribute("uri") ){
                        images.append( QUrl( xml.attributes().value("uri").toString() ) );
                        //qDebug()<<"found image "<<xml.attributes().value("uri").toString();
                    }
                    xml.readNext();
                }
            }
            if(xml.name() == "artists"){
                while(xml.readNextStartElement()){
                    if(xml.name() == "artist"){
                        while(xml.readNextStartElement()){
                            if(xml.name() == "name"){
                                artists.append( xml.readElementText() );
                            }else{
                                xml.skipCurrentElement();
                            }
                        }
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
            if(xml.name() == "extraartists"){
                while(xml.readNextStartElement()){
                    if(xml.name() == "artist"){
                        //QString name;QString role;
                        Artist a;
                        while(xml.readNextStartElement()){
                            if(xml.name() == "name"){
                                a.setName( xml.readElementText() );
                            }else if(xml.name() == "role"){
                                a.setRole( xml.readElementText() );
                            }else{
                                xml.skipCurrentElement();
                            }
                            Artists.append(a);
                        }
                        //qDebug()<<role+": "+name;
                        //album.roles.append( role+": "+name );
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
            if(xml.name() == "formats"){
                while(xml.readNextStartElement()){
                    if( xml.name()=="format" && xml.attributes().hasAttribute("name") ){
                        QString sep=", ";
                        if(album.format().isEmpty()){
                            sep="";
                        }
                        album.setFormat( album.format() + sep + xml.attributes().value("name").toString() );
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
            if(xml.name() == "title"){
                album.setTitle( xml.readElementText() );
            }
            if(xml.name() == "labels"){
                xml.readNext();
                while(xml.name()=="label"){
                    if( xml.attributes().hasAttribute("name") ){
                        QString sep=", ";
                        if(album.label().isEmpty()){
                            sep="";
                        }
                        album.setLabel( album.label()+sep+xml.attributes().value("name").toString() );
                    }
                    xml.readNext();
                }
            }
            if(xml.name() == "genres"){
                while(xml.readNextStartElement()){
                    if(xml.name() == "genre"){
                        QString sep=", ";
                        if(album.genre().isEmpty()){
                            sep="";
                        }
                        album.setGenre( album.genre() + sep + xml.readElementText() );
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
            if(xml.name() == "styles"){
                while(xml.readNextStartElement()){
                    if(xml.name() == "style"){
                        QString sep=", ";
                        if(album.style().isEmpty()){
                            sep="";
                        }
                        album.setStyle( album.style() + sep + xml.readElementText() );
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
            if(xml.name() == "country"){
                album.setCountry( xml.readElementText() );
            }
            if(xml.name() == "released"){
                album.setYear( xml.readElementText().toInt() );
            }
            if(xml.name() == "notes"){
                album.setNotes( xml.readElementText() );
            }
            if(xml.name() == "tracklist"){
                while(xml.readNextStartElement()){
                    if(xml.name() == "track"){
                        Song s;
                        while(xml.readNextStartElement()){
                            //qDebug()<<xml.name()<<xml.readElementText();
                            if(xml.name() == "position"){
                                s.setTrack( xml.readElementText() );
                            }else if(xml.name() == "title"){
                                s.setTitle( xml.readElementText() );
                            }else if(xml.name() == "duration"){
                                QStringList tmp = xml.readElementText().split(":");
                                int sum=0;
                                for(int j=0;j<tmp.size();j++){
                                    sum = sum + ( tmp[j].toInt()*pow(60,tmp.size()-j-1) );
                                }
                                s.setLength(sum);
                            }else{
                                xml.skipCurrentElement();
                            }
                        }
                        songs.append(s);
                    }else{
                        xml.skipCurrentElement();
                    }
                }
            }
        }
    }

    //fix/compress roles for artists
    //QList<artist> newArtists;
    while( Artists.size()>0 ){
        QString role = Artists[0].role();
        if(role.isEmpty()){
            Artists.removeAt(0);
            continue;
        }
        Artist a;a.setRole(role);a.setName(Artists[0].name());
        //qDebug()<<role;
        for(int j=Artists.size()-1;j>=1;j--){
            if( Artists[j].role()==role ){
                if( !a.name().contains( Artists[j].name() ) ){
                    a.setName(a.name()+"/"+Artists[j].name());
                    //qDebug()<<a.name;
                }
                Artists.removeAt(j);
            }
        }
        Artists.removeAt(0);
        roles.append( a.role()+": "+a.name() );
        //newArtists.append(a);
    }

    //remove html links from notes
    QString notes = album.notes();
    while(1){
        int ind = notes.indexOf("<a href");
        if(ind==-1){
            break;
        }
        int ind2 = notes.indexOf(">",ind);
        notes.remove(ind,ind2-ind+1);
    }
    notes.remove("</a>",Qt::CaseInsensitive);
    album.setNotes(notes);

    if( reply->error() || !err.isEmpty() ){
        if( reply->error() ){
            err = reply->errorString()+":\n"+err;
        }
        QMessageBox::critical(0, "Error",
                              err, QMessageBox::Ok, QMessageBox::Ok);
    }

    album.setArtists(artists);
    album.setRoles(roles);
    album.setImages(images);
    album.setSongs(songs);

    albums_.insert(album.key(),album);
    reply->deleteLater();

    /*
    if(images.size()>0){
        //qDebug()<<"starting image downloading for album "+album.title()<<", images: "<<images;
        QNetworkRequest coverRequest(images[0]);        
        coverRequest.setAttribute(QNetworkRequest::User,album.key());
        QNetworkAccessManager *coverManager = new QNetworkAccessManager;
        connect(coverManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleCover(QNetworkReply*)));
        coverManager->get(coverRequest);
    }else {
        */
        nDownloaded_++;
        qDebug()<<"downloaded album "<<album.title();
        if( downloadImmediately_ && nDownloaded_==albums_.size() ){
            emit albumsDownloaded( albums_ );
        }
        if(!downloadImmediately_){
            emit albumDownloaded( album );
        }
    //}


}
Esempio n. 6
0
	// Makes a UPnP action request (keeps pointers from the external interface)
	int Service::callActionInternal(const QString & actionName, const QMap<QString, QString> * arguments, const QString & prefix)
	{
		qDebug() << "UPnP::Service: calling remote procedure '" << actionName << "'." << endl;

		// Create the data message
		//NOTE: we shouldm use serviceId_ instead of serviceType_, but it seems that my router
		// (and maybe others) are reporting wrong Ids, while they're gonna accepting only the
		// correct ones. This is a decoded reply from my Zyxel:

		//  Service :
		//    servicetype = urn:schemas-upnp-org:service:Layer3Forwarding:1
		//    controlurl = /UD/act?0
		//    eventsuburl = /?0
		//    scpdurl = /L3Fwd.xml
		//    serviceid = urn:upnp-org:serviceId:L3Forwarding1

		// this router wants us to use servicetype in the following requests

		QString soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
		                      "<"
		    + m_szBaseXmlPrefix + ":Envelope xmlns:" + m_szBaseXmlPrefix + "=\"http://schemas.xmlsoap.org/soap/envelope/\""
		                                                                   " "
		    + m_szBaseXmlPrefix + ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
		                          " <"
		    + m_szBaseXmlPrefix + ":Body>\n"
		                          "  <"
		    + prefix + ":" + actionName + " xmlns:" + prefix + "=\"" + m_szServiceType + "\">\n";

		// Do we have any arguments?
		if(arguments != nullptr)
		{
			// Add the arguments
			QMap<QString, QString>::const_iterator it;
			for(it = arguments->begin(); it != arguments->end(); ++it)
			{
				QString argumentName = it.key();
				soapMessage += "<" + argumentName + ">" + it.value() + "</" + argumentName + ">";
			}
		}

		// Add the closing tags
		soapMessage += "  </" + prefix + ":" + actionName + ">\n </" + m_szBaseXmlPrefix + ":Body>\n</" + m_szBaseXmlPrefix + ":Envelope>\n";

		// Get an utf8 encoding string
		QByteArray content = soapMessage.toUtf8().data();

		// Create the HTTP header
		QNetworkRequest request;
		request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml");
		request.setHeader(QNetworkRequest::ContentLengthHeader, content.size());
		request.setRawHeader("SOAPAction", QString("\"%1#%2\"").arg(m_szServiceType, actionName).toUtf8());

		QString port;
		port.setNum(m_iPort);
		request.setRawHeader("HOST", QString("%1:%2").arg(m_szHostname, port).toUtf8());

		QUrl url;
		url.setHost(m_szHostname);
		url.setPort(m_iPort);
		request.setUrl(url);

		// Send the POST request
		m_iPendingRequests++;

		QByteArray dummy;
		QNetworkReply * pReply = KviNetworkAccessManager::getInstance()->post(request, dummy);
		connect(pReply, SIGNAL(finished()), this, SLOT(slotRequestFinished()));

		return 0;
	}
Esempio n. 7
0
bool NewAccountPage::validatePage()
{
    if(hasCreatedAccount)
    {
        return true;
    }
    serverQueryFinished = false;
    serverQueryError = false;
    //Check if passwords match
    if(input_password->text() != input_confirmPassword->text())
    {
        label_message->setText(tr("<font color='red'>Passwords do not match</font>"));
        return false;
    }
    label_message->setText("Creating account...");
    QUrl baseUrl( "https://api.screencloud.net/1.0/users/register.xml" );
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrlQuery query(baseUrl);
#else
    QUrl query(baseUrl);
#endif
    query.addQueryItem("oauth_version", "1.0");
    query.addQueryItem("oauth_signature_method", "PLAINTEXT");
    query.addQueryItem("oauth_consumer_key", CONSUMER_KEY_SCREENCLOUD);
    query.addQueryItem("oauth_signature", CONSUMER_SECRET_SCREENCLOUD);
    query.addQueryItem("oauth_timestamp", QString::number(QDateTime::currentDateTimeUtc().toTime_t()));
    query.addQueryItem("oauth_nonce", NetworkUtils::generateNonce(15));
    // create a request parameters map
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrlQuery bodyParams;
#else
    QUrl bodyParams;
#endif
    bodyParams.addQueryItem("data[User][email]", input_email->text());
    bodyParams.addQueryItem("data[User][password]", input_password->text());
    bodyParams.addQueryItem("data[User][password_confirmation]", input_confirmPassword->text());

    // construct the body string
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QByteArray body = bodyParams.query(QUrl::FullyEncoded).toUtf8();
#else
    QByteArray body = bodyParams.encodedQuery();
#endif

#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrl fullUrl(baseUrl);
    fullUrl.setQuery(query);
#else
    QUrl fullUrl(query);
#endif
    QNetworkRequest request;
    request.setUrl(fullUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    manager->post(request, body);
    while (!serverQueryFinished) {
       qApp->processEvents(QEventLoop::WaitForMoreEvents);
    }
    if(serverQueryError)
    {
        return false;
    }
    hasCreatedAccount = true;
    return true;
}
Esempio n. 8
0
QNetworkRequest ResourceRequest::toNetworkRequest(QObject* originatingFrame) const
{
    QNetworkRequest request;
    request.setUrl(url());
    request.setOriginatingObject(originatingFrame);

    const HTTPHeaderMap &headers = httpHeaderFields();
    for (HTTPHeaderMap::const_iterator it = headers.begin(), end = headers.end();
         it != end; ++it) {
        QByteArray name = QString(it->first).toAscii();
        QByteArray value = QString(it->second).toAscii();
        // QNetworkRequest::setRawHeader() would remove the header if the value is null
        // Make sure to set an empty header instead of null header.
        if (!value.isNull())
            request.setRawHeader(name, value);
        else
            request.setRawHeader(name, "");
    }

    // Make sure we always have an Accept header; some sites require this to
    // serve subresources
    if (!request.hasRawHeader("Accept"))
        request.setRawHeader("Accept", "*/*");

    switch (cachePolicy()) {
    case ReloadIgnoringCacheData:
        request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
        break;
    case ReturnCacheDataElseLoad:
        request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
        break;
    case ReturnCacheDataDontLoad:
        request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
        break;
    case UseProtocolCachePolicy:
        // QNetworkRequest::PreferNetwork
    default:
        break;
    }

    if (!allowCookies() || !thirdPartyCookiePolicyPermitsForFrame(originatingFrame, url(), firstPartyForCookies())) {
        request.setAttribute(QNetworkRequest::CookieSaveControlAttribute, QNetworkRequest::Manual);
        request.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);
    }

    if (!allowCookies())
        request.setAttribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Manual);

    return request;
}
int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    application.setOrganizationName("CutePaste");
    application.setApplicationName("CutePaste Desktop Console Frontend");

    QTextStream standardOutputStream(stdout);
    QFile dataFile;
    QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);
    if (!firstArgument.isEmpty()) {
        dataFile.setFileName(firstArgument);
        dataFile.open(QIODevice::ReadOnly);
    } else {
        dataFile.open(stdin, QIODevice::ReadOnly);
    }

    QByteArray pasteTextByteArray = dataFile.readAll();

    QJsonObject requestJsonObject;
    requestJsonObject.insert(QStringLiteral("data"), QString::fromUtf8(pasteTextByteArray));
    requestJsonObject.insert(QStringLiteral("language"), QStringLiteral("text"));

    QJsonDocument requestJsonDocument(requestJsonObject);

    QString baseUrlString = QStringLiteral("http://pastebin.kde.org");

    QNetworkRequest networkRequest;
    networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    networkRequest.setUrl(QUrl(baseUrlString + "/api/json/create"));

    QNetworkAccessManager networkAccessManager;
    QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));
    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {

        QJsonParseError jsonParseError;
        QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();
        QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);
        if (jsonParseError.error != QJsonParseError::NoError) {
            qDebug() << "The json network reply is not valid json:" << jsonParseError.errorString();
            QCoreApplication::quit();
        }

        if (!replyJsonDocument.isObject()) {
            qDebug() << "The json network reply is not an object";
            QCoreApplication::quit();
        }
        
        QJsonObject replyJsonObject = replyJsonDocument.object();
        QJsonValue resultValue = replyJsonObject.value(QStringLiteral("result"));

        if (!resultValue.isObject()) {
            qDebug() << "The json network reply does not contain an object for the \"result\" key";
            QCoreApplication::quit();
        }

        QJsonValue identifierValue = resultValue.toObject().value(QStringLiteral("id"));

        if (!identifierValue.isString()) {
            qDebug() << "The json network reply does not contain a string for the \"id\" key";
            QCoreApplication::quit();
        }

        endl(standardOutputStream << baseUrlString << '/' << identifierValue.toString());

        QCoreApplication::quit();
    });

    QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {
        if (networkReplyError != QNetworkReply::NoError)
            endl(standardOutputStream << networkReplyScopedPointer->errorString());
    });

    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {
        if (!networkReplySslErrors.isEmpty()) {
            foreach (const QSslError &networkReplySslError, networkReplySslErrors)
                endl(standardOutputStream << networkReplySslError.errorString());
        }
    });
Esempio n. 10
0
bool AWebservice::postChange (const AMessage2SendList& list_messages, const ARating2SendList& list_rating, const AModerate2SendList& list_moderate, ACommitInfo& commit_info)
{
	QString data;
	data += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
	data += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
	data += "  <soap:Body>\r\n";
	data += "    <PostChange xmlns=\"http://rsdn.ru/Janus/\">\r\n";
	data += "      <postRequest>\r\n";
	data += (QString)"        <userName>" + m_rsdn_login    + "</userName>\r\n";
	data += (QString)"        <password>" + m_rsdn_password + "</password>\r\n";

	// сообщения
	if (list_messages.count() > 0)
	{
		data += "        <writedMessages>\r\n";

		for (int i = 0; i < list_messages.count(); i++)
		{
			QString message = list_messages[i].Message;

			QString subject = list_messages[i].Subject;

			subject.replace("&", "&amp;");
			subject.replace("<", "&lt;");
			subject.replace(">", "&gt;");

			data += "          <PostMessageInfo>\r\n";
			data += (QString)"            <localMessageId>" + QString::number(list_messages[i].ID)       + "</localMessageId>\r\n";
			data += (QString)"            <parentId>"       + QString::number(list_messages[i].IDParent) + "</parentId>\r\n";
			data += (QString)"            <forumId>"        + QString::number(list_messages[i].IDForum)  + "</forumId>\r\n";
			data += (QString)"            <subject>"        + subject                                    + "</subject>\r\n";
			data += (QString)"            <message>"        + message                                    + "</message>\r\n";
			data += "          </PostMessageInfo>\r\n";
		}

		data += "        </writedMessages>\r\n";
	}
	else
		data += "        <writedMessages />\r\n";

	// рейтинги
	if (list_rating.count() > 0)
	{
		data += "        <rates>\r\n";

		for (int i = 0; i < list_rating.count(); i++)
		{
			data += "          <PostRatingInfo>\r\n";
			data += (QString)"            <localRatingId>" + QString::number(list_rating[i].ID)        + "</localRatingId>\r\n";
			data += (QString)"            <messageId>"     + QString::number(list_rating[i].IDMessage) + "</messageId>\r\n";
			data += (QString)"            <rate>"          + QString::number(list_rating[i].Rate)      + "</rate>\r\n";
			data += "          </PostRatingInfo>\r\n";
		}

		data += "        </rates>\r\n";
	}
	else
		data += "        <rates />\r\n";

	// модерилки
	if (list_moderate.count() > 0)
	{
		data += "        <moderates>\r\n";

		for (int i = 0; i < list_moderate.count(); i++)
		{
			QString description = list_moderate[i].Description;

			description.replace("&", "&amp;");
			description.replace("<", "&lt;");
			description.replace(">", "&gt;");

			data += "          <PostModerateInfo>\r\n";
			data += (QString)"            <LocalModerateId>"   + QString::number(list_moderate[i].ID)          + "</LocalModerateId>\r\n";
			data += (QString)"            <MessageId>"         + QString::number(list_moderate[i].IDMessage)   + "</MessageId>\r\n";
			data += (QString)"            <ModerateAction>"    + list_moderate[i].Action                       + "</ModerateAction>\r\n";
			data += (QString)"            <ModerateToForumId>" + QString::number(list_moderate[i].IDForum)     + "</ModerateToForumId>\r\n";
			data += (QString)"            <Description>"       + description                                   + "</Description>\r\n";
			data += (QString)"            <AsModerator>"       + QString::number(list_moderate[i].AsModerator) + "</AsModerator>\r\n";
			data += "          </PostModerateInfo>\r\n";
		}

		data += "        </moderates>\r\n";
	}
	else
		data += "        <moderates />\r\n";

	data += "      </postRequest>\r\n";
	data += "    </PostChange>\r\n";
	data += "  </soap:Body>\r\n";
	data += "</soap:Envelope>\r\n";

	QNetworkRequest request;
	prepareRequest(request, m_rsdn_proto, "PostChange", data.toUtf8().size());

	if (makeRequest(request, data) == false)
		return false;

	QString cookie;
	QString result = parsePostChange(m_headers, cookie);

	if (result.length() > 0)
	{
		m_error = result;
		return false;
	}

	data  = "";
	data += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
	data += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
	data += "  <soap:Body>\r\n";
	data += "    <PostChangeCommit xmlns=\"http://rsdn.ru/Janus/\" />\r\n";
	data += "  </soap:Body>\r\n";
	data += "</soap:Envelope>\r\n";

	prepareRequest(request, m_rsdn_proto, "PostChangeCommit", data.toUtf8().size());

	if (cookie.length() > 0)
		request.setRawHeader("Cookie", cookie.toUtf8());

	if (makeRequest(request, data) == false)
		return false;

	result = parsePostChangeCommit(m_body, commit_info);

	if (result.length() > 0)
	{
		m_error = result;
		return false;
	}

	return true;
}
Esempio n. 11
0
/*!
    Returns a new QNetworkReply object to handle the operation \a op
    and request \a req. The device \a outgoingData is always 0 for Get and
    Head requests, but is the value passed to post() and put() in
    those operations (the QByteArray variants will pass a QBuffer
    object).

    The default implementation calls QNetworkCookieJar::cookiesForUrl()
    on the cookie jar set with setCookieJar() to obtain the cookies to
    be sent to the remote server.

    The returned object must be in an open state.
*/
QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op,
                                                    const QNetworkRequest &req,
                                                    QIODevice *outgoingData)
{
    Q_D(QNetworkAccessManager);

    // fast path for GET on file:// URLs
    // Also if the scheme is empty we consider it a file.
    // The QNetworkAccessFileBackend will right now only be used
    // for PUT or qrc://
    if ((op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation)
         && (req.url().scheme() == QLatin1String("file")
             || req.url().scheme().isEmpty())) {
        return new QFileNetworkReply(this, req, op);
    }

#ifndef QT_NO_BEARERMANAGEMENT
    // Return a disabled network reply if network access is disabled.
    // Except if the scheme is empty or file://.
    if (!d->networkAccessible && !(req.url().scheme() == QLatin1String("file") ||
                                      req.url().scheme().isEmpty())) {
        return new QDisabledNetworkReply(this, req, op);
    }

    if (!d->networkSession && (d->initializeSession || !d->networkConfiguration.isEmpty())) {
        QNetworkConfigurationManager manager;
        if (!d->networkConfiguration.isEmpty()) {
            d->createSession(manager.configurationFromIdentifier(d->networkConfiguration));
        } else {
            if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
                d->createSession(manager.defaultConfiguration());
            else
                d->initializeSession = false;
        }
    }

    if (d->networkSession)
        d->networkSession->setSessionProperty(QLatin1String("AutoCloseSessionTimeout"), -1);
#endif

    QNetworkRequest request = req;
    if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() &&
        outgoingData && !outgoingData->isSequential()) {
        // request has no Content-Length
        // but the data that is outgoing is random-access
        request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size());
    }
    if (d->cookieJar) {
        QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url());
        if (!cookies.isEmpty())
            request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies));
    }

    // first step: create the reply
    QUrl url = request.url();
    QNetworkReplyImpl *reply = new QNetworkReplyImpl(this);
#ifndef QT_NO_BEARERMANAGEMENT
    if (req.url().scheme() != QLatin1String("file") && !req.url().scheme().isEmpty()) {
        connect(this, SIGNAL(networkSessionConnected()),
                reply, SLOT(_q_networkSessionConnected()));
    }
#endif
    QNetworkReplyImplPrivate *priv = reply->d_func();
    priv->manager = this;

    // second step: fetch cached credentials
    QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url);
    if (cred) {
        url.setUserName(cred->user);
        url.setPassword(cred->password);
        priv->urlForLastAuthentication = url;
    }

    // third step: find a backend
    priv->backend = d->findBackend(op, request);

#ifndef QT_NO_NETWORKPROXY
    QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url()));
    priv->proxyList = proxyList;
#endif
    if (priv->backend) {
        priv->backend->setParent(reply);
        priv->backend->reply = priv;
    }
    // fourth step: setup the reply
    priv->setup(op, request, outgoingData);

#ifndef QT_NO_OPENSSL
    reply->setSslConfiguration(request.sslConfiguration());
#endif
    return reply;
}
Esempio n. 12
0
QVariant LxHttp::httpRequest(QVariant varMethod,  QVariant varUrl ,  QVariant varPostData)//, QScriptEngine *interpreter
{
	enum LxHttpMethod
	{
		GET,
		POST
	};

	QString url = "";
	QString data ="";

	LxHttpMethod method = GET;

	if (varMethod.isNull() || varUrl.isNull()) 
	{
		return QVariant(0);
	}

		QString arg = varMethod.toString().trimmed().toUpper();
		method = (arg == "POST") ?  POST : GET;

		url = varUrl.toString().trimmed();

	if (0 != url.toLower().indexOf("http://")) 
	{
		return QVariant("URIError: URL is not http://");
	}

	data = varPostData.toString();

	QNetworkReply* reply;
	QNetworkRequest req;
	QNetworkAccessManager* manager = new QNetworkAccessManager();

	if (method == POST) 
	{
		// post 数据编码
		req.setUrl(QUrl(url));
		req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
		reply = manager->post(req, QUrl(data).toEncoded());
	} else
	{
		if (data != "")
		{
			if (url.indexOf("?") != -1)
			{
				if (url.lastIndexOf("&") == url.size() - 1)
				{
					url = url + data;
				}
				else
				{
					url = url + "&" + data;
				}
			}
			else 
			{
				url= url + "?" + data;
			}
		}

		reply = manager->get(QNetworkRequest(QUrl(url)));
	}

	// 开启局部事件循环
	QEventLoop eventLoop;
	connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
	eventLoop.exec();

	QByteArray responseData;
	responseData = reply->readAll();

	QString charset = QString(reply->rawHeader("Content-Type")).toLower();
	QRegExp charsetRegExp("charset=([\\w-]+)\\b");
	int pos = charset.indexOf(charsetRegExp);
	if (pos > 0) 
	{
		if (charsetRegExp.cap().size() < 2) 
		{
			charset = "";
		}
		else 
		{
			charset = charsetRegExp.cap(1);
		}
	} 
	else 
	{
		charset = "";
	}

	QTextStream stream(responseData);
	stream.setCodec(QTextCodec::codecForName(QByteArray("utf-8")));//charset.toLocal8Bit()
	return QVariant(QString(stream.readAll()));
}
Esempio n. 13
0
void HttpAgent::debugResponse(QNetworkReply *reply)
{
	//qDebug() << "HttpAgent::debugResponse()";

	if ( !reply )
	{
		qDebug() << "HTTP Response: null!!";
	}

	qDebug() << __FUNCTION__ << ":reply from cache?="
			 << reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool()
			 << ":" << reply->url();

	QNetworkRequest req = reply->request();
	qDebug() << "HTTP Request: " << req.url();

	wpp::qt::System &system = wpp::qt::System::getInstance();

	if (reply->error() != QNetworkReply::NoError)
	{
		QNetworkReply::NetworkError error = reply->error();
		QString errStr("Unknown");
		switch ( error )
		{
		case QNetworkReply::ConnectionRefusedError:
			errStr = "the remote server refused the connection (the server is not accepting requests)";
		break;
		case QNetworkReply::RemoteHostClosedError:
			errStr = "the remote server closed the connection prematurely, before the entire reply was received and processed";
		break;
		case QNetworkReply::HostNotFoundError:
			errStr = "the remote host name was not found (invalid hostname)";
			system.setHasNetwork(false);
			qDebug() << "system.setHasNetwork(false)";
		break;
		case QNetworkReply::TimeoutError:
			errStr = "the connection to the remote server timed out";
		break;
		case QNetworkReply::OperationCanceledError:
			errStr = "the operation was canceled via calls to abort() or close() before it was finished.";
		break;
		case QNetworkReply::SslHandshakeFailedError:
			errStr = "the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.";
		break;
		case QNetworkReply::TemporaryNetworkFailureError:
			errStr = "the connection was broken due to disconnection from the network, however the system has initiated roaming to another access point. The request should be resubmitted and will be processed as soon as the connection is re-established.";
		break;
		case QNetworkReply::NetworkSessionFailedError:
			errStr = "the connection was broken due to disconnection from the network or failure to start the network.";
		break;
		case QNetworkReply::BackgroundRequestNotAllowedError:
			errStr = "the background request is not currently allowed due to platform policy.";
		break;
		case QNetworkReply::ProxyConnectionRefusedError:
			errStr = "the connection to the proxy server was refused (the proxy server is not accepting requests)";
		break;
		case QNetworkReply::ProxyConnectionClosedError:
			errStr = "the proxy server closed the connection prematurely, before the entire reply was received and processed";
		break;
		case QNetworkReply::ProxyNotFoundError:
			errStr = "the proxy host name was not found (invalid proxy hostname)";
		break;
		case QNetworkReply::ProxyTimeoutError:
			errStr = "the connection to the proxy timed out or the proxy did not reply in time to the request sent";
		break;
		case QNetworkReply::ProxyAuthenticationRequiredError:
			errStr = "the proxy requires authentication in order to honour the request but did not accept any credentials offered (if any)";
		break;
		case QNetworkReply::ContentAccessDenied:
			errStr = "the access to the remote content was denied (similar to HTTP error 401)";
		break;
		case QNetworkReply::ContentOperationNotPermittedError:
			errStr = "the operation requested on the remote content is not permitted";
		break;
		case QNetworkReply::ContentNotFoundError:
			errStr = "the remote content was not found at the server (similar to HTTP error 404)";
		break;
		case QNetworkReply::AuthenticationRequiredError:
			errStr = "the remote server requires authentication to serve the content but the credentials provided were not accepted (if any)";
		break;
		case QNetworkReply::ContentReSendError:
			errStr = "the request needed to be sent again, but this failed for example because the upload data could not be read a second time.";
		break;
		case QNetworkReply::ProtocolUnknownError:
			errStr = "the Network Access API cannot honor the request because the protocol is not known";
		break;
		case QNetworkReply::ProtocolInvalidOperationError:
			errStr = "the requested operation is invalid for this protocol";
		break;
		case QNetworkReply::UnknownNetworkError:
			errStr = "an unknown network-related error was detected";
		break;
		case QNetworkReply::UnknownProxyError:
			errStr = "an unknown proxy-related error was detected";
		break;
		case QNetworkReply::UnknownContentError:
			errStr = "an unknown error related to the remote content was detected";
		break;
		case QNetworkReply::ProtocolFailure:
			errStr = "a breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.)";
		break;
		case QNetworkReply::ContentConflictError:
			errStr = "ContentConflictError";
		break;
		case QNetworkReply::ContentGoneError:
			errStr = "ContentGoneError";
		break;
		case QNetworkReply::InternalServerError:
			errStr = "InternalServerError";
		break;
		case QNetworkReply::OperationNotImplementedError:
			errStr = "OperationNotImplementedError";
		break;
		case QNetworkReply::ServiceUnavailableError:
			errStr = "ServiceUnavailableError";
		break;
		case QNetworkReply::UnknownServerError:
			errStr = "UnknownServerError";
		break;
		case QNetworkReply::NoError:
			//not possible to enter this
		break;
		}

		qDebug() << "[ERR] Http has error(" << reply->error() << "): " << errStr;
	}

//	QByteArray bts = reply->readAll();
	//QString str(bts);

	qDebug() << "HTTP Response: status (" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute ).toString() << "):";

}
Esempio n. 14
0
void BrowserView::onDownloadRequested(const QNetworkRequest & request)
{
    Dialog::DownloadDialog dlg (request.url(),this);
    dlg.exec();
}
Esempio n. 15
0
/**
 * @brief ServerCommunicator::fetchNotes
 */
void ServerCommunicator::fetchNotes() {
    QNetworkRequest request;
    request.setUrl(QUrl("http://sync.silicanote.eu/silicanote-webapp/services/notes/getnotes"));
    manager->get(request);
}
Esempio n. 16
0
QNetworkReply* QWebDAV::sendWebdavRequest(QUrl url, DAVType type,
                                          QByteArray verb, QIODevice *data,
                                          QString extra, QString extra2)
{
    // Prepare the network request and headers
    QNetworkRequest request;
    QNetworkReply *reply;
    request.setUrl(url);
    request.setRawHeader(QByteArray("Host"),url.host().toUtf8());

    qDebug() << "Sending " << type << "with url: " << url;

    // First, find out what type we want
    if( type == DAVLIST ) {
        // A PROPFIND can include 0, 1 or infinity
        QString depthString = extra;
        request.setRawHeader(QByteArray("Depth"),
                             QByteArray(depthString.toLatin1()));
        request.setAttribute(QNetworkRequest::User, QVariant("list"));
        request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
                                                        ATTDATA)
                             ,QVariant(mRequestNumber));
        request.setRawHeader(QByteArray("Content-Type"),
                             QByteArray("text/xml; charset=\"utf-8\""));
        request.setRawHeader(QByteArray("Content-Length"),QByteArray("99999"));

        reply = sendCustomRequest(request,verb,data);
    } else if ( type == DAVGET ) {
        request.setRawHeader("User-Agent", "QWebDAV 0.1");
        request.setAttribute(QNetworkRequest::User, QVariant("get"));
        reply = QNetworkAccessManager::get(request);
        connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
                 this, SLOT(slotError(QNetworkReply::NetworkError)));
        connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
                 this, SLOT(slotSslErrors(QList<QSslError>)));
    } else if ( type == DAVPUT )  {
        request.setAttribute(QNetworkRequest::User, QVariant("put"));
        if ( mRequestFile.value(mRequestNumber) ) {
            request.setAttribute(QNetworkRequest::Attribute(
                                     QNetworkRequest::User+ATTFILE)
                                 ,QVariant(mRequestNumber));
            request.setAttribute(QNetworkRequest::Attribute(
                                     QNetworkRequest::User+ATTPREFIX)
                                 ,QVariant(extra.toLatin1()));
            if( extra2 != 0 ) {
                // We were given a lock token.
                request.setRawHeader(QByteArray("If"),
                                     QByteArray(extra2.toLatin1()));
            }
        } else {
            request.setAttribute(QNetworkRequest::Attribute(
                                     QNetworkRequest::User+ATTDATA)
                             ,QVariant(mRequestNumber));
        }
        reply = QNetworkAccessManager::put(request,data);
    } else if ( type == DAVMKCOL ) {
        request.setAttribute(QNetworkRequest::User, QVariant("mkcol"));
        reply = sendCustomRequest(request,verb,0);
    } else if ( type == DAVDELETE ) {
        request.setAttribute(QNetworkRequest::User, QVariant("delete"));
        reply = sendCustomRequest(request, verb,0);
    } else if ( type == DAVMOVE ) {
        request.setAttribute(QNetworkRequest::User, QVariant("move"));
        request.setRawHeader(QByteArray("Destination"),
                             QByteArray(extra.toLatin1()));
        request.setRawHeader(QByteArray("Overwrite"),
                             QByteArray("T"));
        if( extra2 != 0 ) {
            // We were given (a) lock token(s).
            request.setRawHeader(QByteArray("If"),
                                 QByteArray(extra2.toLatin1()));
            request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
                                                            ATTLOCKTYPE)
                                 ,QVariant(extra.replace(mHostname,"").toLatin1()));
        }
        reply = sendCustomRequest(request, verb,0);
    } else if ( type == DAVLOCK) {
        request.setAttribute(QNetworkRequest::User,
                             QVariant("lock"));
        // We don't bother setting a timeout, apparently the system defaults
        // to 5 minutes anyway.
        request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
                                                        ATTDATA)
                             ,QVariant(mRequestNumber));
        request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
                                                        ATTLOCKTYPE)
                             ,QVariant(extra));

        reply = sendCustomRequest(request,verb,data);
    } else if ( type == DAVUNLOCK) {
        QString token = "<"+extra+">";
        request.setAttribute(QNetworkRequest::User,
                             QVariant("unlock"));
        request.setRawHeader(QByteArray("Lock-Token"),
                             QByteArray(token.toLatin1()));
        reply = sendCustomRequest(request,verb,0);
    } else {
        syncDebug() << "Error! DAV Request of type " << type << " is not known!";
        reply = 0;
    }

    // Connect the finished() signal!
    connectReplyFinished(reply);
    return reply;
}
Esempio n. 17
0
QNetworkReply *NetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
    WebPage *parentPage = qobject_cast<WebPage *>(parent());

    QNetworkReply *reply = 0;

    QNetworkRequest req = request;
    req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
    req.setRawHeader("Accept-Language", _acceptLanguage);

    KIO::CacheControl cc = KProtocolManager::cacheControl();
    switch (cc)
    {
    case KIO::CC_CacheOnly:      // Fail request if not in cache.
        req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
        break;

    case KIO::CC_Refresh:        // Always validate cached entry with remote site.
        req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork);
        break;

    case KIO::CC_Reload:         // Always fetch from remote site
        req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
        break;

    case KIO::CC_Cache:          // Use cached entry if available.
    case KIO::CC_Verify:         // Validate cached entry with remote site if expired.
    default:
        req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
        break;
    }

    // WARNING
    // There are actually 2 exceptions here handled with QNAM
    // instead of KIO that need fixes upstream before removing. They are:
    // 1) DeleteOperation
    // 2) CustomOperation

    switch (op)
    {
    case QNetworkAccessManager::HeadOperation:
        break;

    case QNetworkAccessManager::GetOperation:
        reply = rApp->adblockManager()->block(req, parentPage);
        break;

    case QNetworkAccessManager::PutOperation:
        break;

    case QNetworkAccessManager::PostOperation:
        break;

        // This particular issue has been solved for KDE Version 4.5.96,
        // so we can safely disable this piece of code
#if !KDE_IS_VERSION( 4, 5, 96)

    case QNetworkAccessManager::DeleteOperation:
        kDebug() << "DELETE OPERATION...";
        reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
        if (!reply)
            kDebug() << "OOOOOOOOOOOOOOOOOOO DELETE REPLY NULL";
        break;

    case QNetworkAccessManager::CustomOperation:
        kDebug() << "CUSTOM OPERATION...";
        reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
        if (!reply)
            kDebug() << "OOOOOOOOOOOOOOOOOOO CUSTOM REPLY NULL";
        break;

#endif
    default:
        kDebug() << "NON EXTANT CASE...";
        break;
    }

    if (!reply)
        reply = AccessManager::createRequest(op, req, outgoingData);

    if (parentPage && parentPage->hasNetworkAnalyzerEnabled())
        emit networkData(op, req, reply);

    return reply;
}
Esempio n. 18
0
QScriptValue Web::download(const QString &urlString, const QScriptValue &options)
{
    mData.clear();

    if(mFileValue.isValid())
    {
        if(Code::File *file = qobject_cast<Code::File*>(mFileValue.toQObject()))
            mFile = file->file();
        else
            mFile = new QFile(mFileValue.toString(), this);

        mCloseFile = false;

        if(!mFile->isOpen())
        {
            if(!mFile->open(QIODevice::WriteOnly))
            {
                throwError("OpenFileError", tr("Unable to open the destination file"));
                return thisObject();
            }

            mCloseFile = true;
        }
    }

    QUrl url(urlString);
    if(url.scheme() == QString())
        url = QUrl("http://" + urlString, QUrl::TolerantMode);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    QUrlQuery urlQuery;
#endif

    QNetworkRequest request;

    QScriptValueIterator it(options);
    Method method = Get;
    QByteArray postData;

    while(it.hasNext())
    {
        it.next();

        if(it.name() == "rawHeaders")
        {
            QScriptValueIterator headerIt(it.value());

            while(headerIt.hasNext())
            {
                headerIt.next();

                request.setRawHeader(headerIt.name().toUtf8(), headerIt.value().toString().toUtf8());
            }
        }
        else if(it.name() == "method")
        {
            method = static_cast<Method>(it.value().toInt32());
        }
        else if(it.name() == "postData")
        {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            QScriptValueIterator postDataIt(it.value());
            QUrlQuery postDataParameters;

            while(postDataIt.hasNext())
            {
                postDataIt.next();

                postDataParameters.addQueryItem(postDataIt.name(), postDataIt.value().toString());
            }

            postData = postDataParameters.toString(QUrl::FullyEncoded).toLatin1();
#else
            QScriptValueIterator postDataIt(it.value());
            QUrl postDataParameters;

            while(postDataIt.hasNext())
            {
                postDataIt.next();

                postDataParameters.addQueryItem(postDataIt.name(), postDataIt.value().toString());
            }

            postData = postDataParameters.encodedQuery();
#endif
        }
        else if(it.name() == "query")
        {
            QScriptValueIterator queryIt(it.value());

            while(queryIt.hasNext())
            {
                queryIt.next();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
                urlQuery.addQueryItem(queryIt.name(), queryIt.value().toString());
#else
                url.addQueryItem(queryIt.name(), queryIt.value().toString());
#endif
            }
        }
        else if(it.name() == "user")
        {
            mUser = it.value().toString();
        }
        else if(it.name() == "password")
        {
            mPassword = it.value().toString();
        }
    }

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    url.setQuery(urlQuery);
#endif

    request.setUrl(url);

    switch(method)
    {
    case Post:
        mNetworkReply = mNetworkAccessManager->post(request, postData);
        break;
    case Get:
    default:
        mNetworkReply = mNetworkAccessManager->get(request);
        break;
    }

    QObject::connect(mNetworkReply, SIGNAL(finished()), this, SLOT(finished()));
    QObject::connect(mNetworkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
    QObject::connect(mNetworkReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error()));
    QObject::connect(mNetworkReply, SIGNAL(readyRead()), this, SLOT(readyRead()));

    mIsDownloading = true;

    return thisObject();
}
Esempio n. 19
0
// Handle downloads {{{
//Download request via KIO
void MiniWeb::download(QNetworkRequest request)
{
	KUrl dest = KFileDialog::getSaveUrl();
	KIO::copy(request.url(), dest);
}
Esempio n. 20
0
    void UrlFactory::TryCorrectGoogleVersions()
    {
        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://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleMap = QString("m@%1").arg(gc[1]);
                VersionGoogleMapChina = VersionGoogleMap;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap;
#endif //DEBUG_URLFACTORY
            }

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

                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleSatellite: "<<VersionGoogleSatellite;

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

        }
Esempio n. 21
0
RadioCL* PlaylistCL::Parse(QUrl pURL){

    RadioCL* newRadio=NULL;

    if (pURL.isLocalFile()){
        QString tFileName=pURL.path().mid(1,pURL.path().length()-1);
        QStringList tFileNameParts=tFileName.split(".");

        QFile drFile(tFileName);
        if (!drFile.open(QIODevice::ReadOnly)){
            qDebug()<<"Unable to open"<<drFile.fileName();
        }
        else{
            drFile.close();
            if ( tFileNameParts.last()=="pls" || tFileNameParts.last()=="m3u"){
                 qDebug()<<"Dropped content is acceptable";
                 if (tFileNameParts.last()=="pls"){
                    newRadio=ParsePls(tFileName);
                    newRadio->SetPlaylist(pURL.url());
                 }
                 if (tFileNameParts.last()=="m3u"){
                    newRadio=ParseM3U(tFileName);
                    newRadio->SetPlaylist(pURL.url());
                 }
            }
            else{
                 qDebug()<<"Parse works with pls and m3u only";
            }
        }
    }
    else{
        // remote url
        qDebug()<<"Getting playlist from "<<pURL.url();
        QNetworkAccessManager *manager = new QNetworkAccessManager(this);

        if (Proxy!=""){
            manager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy,Proxy,ProxyPort.toInt(),ProxyUser,ProxyPass));
        }


        QNetworkRequest req;
        req.setUrl(pURL);
        QNetworkReply *tRemotePlaylist=manager->get(req);


        QEventLoop loop;
        connect(manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
        QApplication::setOverrideCursor(Qt::WaitCursor);
        loop.exec();
        QApplication::restoreOverrideCursor();

        qDebug()<<"Got replay:"<<tRemotePlaylist->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if (tRemotePlaylist->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==0)
                return(NULL);

        QString tPlaylist=QString(tRemotePlaylist->readAll());
        qDebug()<<"Got playlist as:"<<tPlaylist;
        if (tPlaylist=="")
            return(NULL);
        //qDebug()<<"Headers are:"<<tRemotePlaylist->rawHeaderList();
        //qDebug()<<"Content-Disposition:"<<tRemotePlaylist->rawHeader("Content-Disposition");

        QFile tTempFile(GetTempFilePath());
        if (!tTempFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            qDebug()<<"Unable to open"<<tTempFile.fileName();
        }
        int tFileNamePos=tPlaylist.indexOf("filename=",0,Qt::CaseInsensitive);
        int tFileNameEndPos=tPlaylist.indexOf("\n",tFileNamePos,Qt::CaseInsensitive);
        int tFileBeginningPos=tPlaylist.indexOf("\n\n",tFileNameEndPos);

        QString tFileBody;
        if (tFileNamePos!=-1){
            if (tFileNameEndPos!=-1 && tFileBeginningPos!=-1){
                QString tPlaylistName=tPlaylist.mid(tFileNamePos+9,tFileNameEndPos-9-tFileNamePos);
                qDebug()<<"Playlist filename="<<tPlaylistName;
                tFileBody=tPlaylist.right(tPlaylist.length()-tFileBeginningPos-2);
            }
            else{
                qDebug()<<"Error in playlist";
            }
        }
        else{
            tFileBody=tPlaylist;
        }
        qDebug()<<"FileBody:"<<tFileBody;
        tTempFile.write(tFileBody.toLocal8Bit(),tFileBody.length());
        tTempFile.close();

        if (tFileBody.indexOf("[playlist]",Qt::CaseInsensitive)!=-1){
            newRadio=ParsePls(tTempFile.fileName());
        }
        else{
            newRadio=ParseM3U(tTempFile.fileName());
        }
        newRadio->SetPlaylist(pURL.url());
    }

    return(newRadio);
}
Esempio n. 22
0
std::shared_ptr<QNetworkReply> OsmAnd::Network::Downloader::download( const QUrl& url_, const DownloadSettings& settings_ /*= DownloadSettings()*/ )
{
    QWaitCondition resultWaitCondition;
    QMutex resultMutex;
    std::shared_ptr<QNetworkReply> result;
    const auto url = url_;
    const auto settings = settings_;

    resultMutex.lock();
    Concurrent::pools->network->start(new Concurrent::Task([url, settings, &result, &resultMutex, &resultWaitCondition](Concurrent::Task* task, QEventLoop& eventLoop)
        {
            QNetworkAccessManager networkAccessManager;

            // Create request
            QNetworkRequest request;
            request.setUrl(url);
            request.setRawHeader("User-Agent", settings.userAgent.toLocal8Bit());

            // Process until final reply is ready
            auto reply = networkAccessManager.get(request);
            for(;;)
            {
                // Wait for reply to be ready
                QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
                eventLoop.exec();

                // If settings specify that redirects must be followed, do that
                if(settings.autoFollowRedirects)
                {
                    auto redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
                    if(!redirectUrl.isEmpty())
                    {
                        // Delete current reply
                        reply->deleteLater();

                        // Create new request, and wait for reply to arrive
                        QNetworkRequest newRequest;
                        newRequest.setUrl(redirectUrl);
                        request.setRawHeader("User-Agent", settings.userAgent.toLocal8Bit());
                        reply = networkAccessManager.get(newRequest);
                        continue;
                    }
                }

                // Since reply is ready, exit loop
                break;
            }

            // Propagate final reply
            reply->setParent(nullptr);
            {
                QMutexLocker scopedLocker(&resultMutex);
                result.reset(reply);
                resultWaitCondition.wakeAll();
            }

            return;
        }));

    // Wait for condition
    resultWaitCondition.wait(&resultMutex);
    resultMutex.unlock();

    return result;
}
void
TrainingstagebuchUploader::requestUpload()
{
    assert(sessionId.length() > 0 );

    parent->progressLabel->setText(tr("preparing Trainingstagebuch.org data ..."));

    QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType );

    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"upload_submit\""));
    textPart.setBody("hrm");
    body->append( textPart );


    QString fname = context->athlete->home->temp().absoluteFilePath(".ttbupload.pwx" );
    QFile *uploadFile = new QFile( fname );
    uploadFile->setParent(body);

    PwxFileReader reader;
    reader.writeRideFile(context, ride->ride(), *uploadFile );
    parent->progressBar->setValue(parent->progressBar->value()+20/parent->shareSiteCount);

    int limit = proMember
        ? 8 * 1024 * 1024
        : 4 * 1024 * 1024;
    if( uploadFile->size() >= limit ){
        parent->errorLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes")
            .arg(uploadFile->size())
            .arg(limit) );

        eventLoop.quit();
        return;
    }

    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader,
    QVariant("application/octet-stream"));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"file\"; filename=\"gc-upload-ttb.pwx\""));
    uploadFile->open(QIODevice::ReadOnly);
    filePart.setBodyDevice(uploadFile);
    body->append( filePart );


    parent->progressLabel->setText(tr("sending to Trainingstagebuch.org ..."));

    currentRequest = reqUpload;

#if QT_VERSION > 0x050000
    QUrlQuery urlquery;
#else
    QUrl urlquery( TTB_URL + "/file/upload" );
#endif
    urlquery.addQueryItem( "view", "xml" );
    urlquery.addQueryItem( "sso", sessionId );


#if QT_VERSION > 0x050000
    QUrl url (TTB_URL + "/file/upload");
    url.setQuery(urlquery.query());
    QNetworkRequest request = QNetworkRequest(url);
#else
    QNetworkRequest request = QNetworkRequest(urlquery);
#endif

    request.setRawHeader( "Accept-Encoding", "identity" );
    request.setRawHeader( "Accept", "application/xml" );
    request.setRawHeader( "Accept-Charset", "utf-8" );

    QNetworkReply *reply = networkMgr.post( request, body );
    body->setParent( reply );
}
Esempio n. 24
0
/** \brief Downloads a QNetworkRequest via the QNetworkAccessManager
 *  \param dlInfo   MythDownloadInfo information for download
 */
void MythDownloadManager::downloadQNetworkRequest(MythDownloadInfo *dlInfo)
{
    if (!dlInfo)
        return;

    static const char dateFormat[] = "ddd, dd MMM yyyy hh:mm:ss 'GMT'";
    QUrl qurl(dlInfo->m_url);
    QNetworkRequest request;

    if (dlInfo->m_request)
    {
        request = *dlInfo->m_request;
        delete dlInfo->m_request;
        dlInfo->m_request = NULL;
    }
    else
        request.setUrl(qurl);

    if (!dlInfo->m_reload)
    {
        // Prefer the in-cache item if one exists and it is less than 5 minutes
        // old and it will not expire in the next 10 seconds
        QDateTime now = MythDate::current();

        // Handle redirects, we want the metadata of the file headers
        QString redirectLoc;
        int limit = 0;
        while (!(redirectLoc = getHeader(qurl, "Location")).isNull())
        {
            if (limit == CACHE_REDIRECTION_LIMIT)
            {
                LOG(VB_GENERAL, LOG_WARNING, QString("Cache Redirection limit "
                                                     "reached for %1")
                                                    .arg(qurl.toString()));
                return;
            }
            qurl.setUrl(redirectLoc);
            limit++;
        }

        LOG(VB_NETWORK, LOG_DEBUG, QString("Checking cache for %1")
                                                    .arg(qurl.toString()));

        m_infoLock->lock();
        QNetworkCacheMetaData urlData = m_manager->cache()->metaData(qurl);
        m_infoLock->unlock();
        if ((urlData.isValid()) &&
            ((!urlData.expirationDate().isValid()) ||
             (QDateTime(urlData.expirationDate().toUTC()).secsTo(now) < 10)))
        {
            QString dateString = getHeader(urlData, "Date");

            if (!dateString.isNull())
            {
                QDateTime loadDate =
                    MythDate::fromString(dateString, dateFormat);
                loadDate.setTimeSpec(Qt::UTC);
                if (loadDate.secsTo(now) <= 720)
                {
                    dlInfo->m_preferCache = true;
                    LOG(VB_NETWORK, LOG_DEBUG, QString("Preferring cache for %1")
                                                    .arg(qurl.toString()));
                }
            }
        }
    }

    if (dlInfo->m_preferCache)
        request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                             QNetworkRequest::PreferCache);

    request.setRawHeader("User-Agent",
                         "MythTV v" MYTH_BINARY_VERSION " MythDownloadManager");

    if (dlInfo->m_headers)
    {
        QHash<QByteArray, QByteArray>::const_iterator it =
            dlInfo->m_headers->constBegin();
        for ( ; it != dlInfo->m_headers->constEnd(); ++it )
        {
            if (!it.key().isEmpty() && !it.value().isEmpty())
            {
                request.setRawHeader(it.key(), it.value());
            }
        }
    }

    switch (dlInfo->m_requestType)
    {
        case kRequestPost :
            dlInfo->m_reply = m_manager->post(request, *dlInfo->m_data);
            break;
        case kRequestHead :
            dlInfo->m_reply = m_manager->head(request);
            break;
        case kRequestGet :
        default:
            dlInfo->m_reply = m_manager->get(request);
            break;
    }

    m_downloadReplies[dlInfo->m_reply] = dlInfo;

    if (dlInfo->m_authCallback)
    {
        connect(m_manager, SIGNAL(authenticationRequired(QNetworkReply *,
                                                         QAuthenticator *)),
                this, SLOT(authCallback(QNetworkReply *, QAuthenticator *)));
    }
Esempio n. 25
0
void DownloadManager::download(const QNetworkRequest &request, bool requestFileName)
{
    if (request.url().isEmpty())
        return;
    handleUnsupportedContent(m_manager->get(request), requestFileName);
}
Esempio n. 26
0
bool WizXmlRpcServerBase::xmlRpcCall(const QString& strMethodName, WizXmlRpcResult& result, WizXmlRpcValue* pParam1, WizXmlRpcValue* pParam2 /*= NULL*/, WizXmlRpcValue* pParam3 /*= NULL*/, WizXmlRpcValue* pParam4 /*= NULL*/)
{
    WizXmlRpcRequest data(strMethodName);
    data.addParam(pParam1);
    if (pParam2)
    {
        data.addParam(pParam2);
    }
    if (pParam3)
    {
        data.addParam(pParam3);
    }
    if (pParam4)
    {
        data.addParam(pParam4);
    }
    //
    QUrl url(m_strUrl + "?methodName=" + strMethodName);

    QNetworkRequest request;
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml"));
    request.setHeader(QNetworkRequest::UserAgentHeader, QVariant(QString("WizQT_") + WIZ_CLIENT_VERSION));

    int nCounter = 0;
    while (true)
    {
        QNetworkReply* reply = m_network->post(request, data.toData());
        WizXmlRpcEventLoop loop(reply);
//        qDebug() << "[Sync]Start a xml rpc event loop";
        loop.exec();
//        qDebug() << "[Sync]Xml rpc event loop finished";
        //
        if (loop.error() && nCounter == 0)
        {
            nCounter ++;
            continue;
        }
        //
        if (loop.error())
        {
            m_nLastErrorCode = loop.error();
            m_strLastErrorMessage = loop.errorString();
            return false;
        }
        //
        QString strXml = QString::fromUtf8(loop.result().constData());
        //
        WizXMLDocument doc;
        if (!doc.loadXML(strXml)) {
            m_nLastErrorCode = -1;
            m_strLastErrorMessage = "Invalid xml";
            return false;
        }

        WizXmlRpcValue* pRet = NULL;

        if (!WizXmlRpcResultFromXml(doc, &pRet)) {
            m_nLastErrorCode = -1;
            m_strLastErrorMessage = "Can not parse xmlrpc";
            return false;
        }

        Q_ASSERT(pRet);

        if (WizXmlRpcFaultValue* pFault = dynamic_cast<WizXmlRpcFaultValue *>(pRet)) {
            m_nLastErrorCode = pFault->getFaultCode();
            m_strLastErrorMessage = pFault->getFaultString();
            TOLOG2("XmlRpcCall failed : %1, %2", QString::number(m_nLastErrorCode), m_strLastErrorMessage);
            return false;
        }
        //
        result.setResult(strMethodName, pRet);
        break;
    }
    //
    return true;
}
Esempio n. 27
0
void Profiler::replyFinished(QNetworkReply *reply)
{
//    counter++;
    if(done)
        return;

    // determining the status code of the reply

    /*QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );

    if ( statusCode.isValid() )
    {
        int status = statusCode.toInt();
        if ( status != 200 )
       {
           QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
           qDebug() << "=====================>>> " << status << "reason: " << reason;
       }
    }*/

    // determining the status code of the reply
    /*currentReqEnds = QTime::currentTime().msecsSinceStartOfDay();

    if(prevReqEnds != 0)
    {
        out << currentReqEnds - prevReqEnds << "\t";
        out.flush();
    }

    prevReqEnds = currentReqEnds;*/

    QNetworkRequest req = reply->request();
    QUrl current_url = req.url();

    if(!current_url.isEmpty())
    {
        if(!urlSet.contains(current_url))
        {
#ifdef COUNTSTATISTICS
            // image/js/css counter
            QVariant cVar = reply->header(QNetworkRequest::ContentTypeHeader);
            checkType(cVar);
#endif
            out << current_url.toEncoded().constData() << "\n";
            out.flush();
        }
        else
            qDebug() << "******* redundant url **********";

        urlSet.insert(current_url);

        qDebug() << diskCache->cacheSize() ;
        qDebug() << current_url.toString() ;
    }
    else
        qDebug() << "------------------- empty url ---------------------";

    reply->deleteLater();
//    if(counter == 5)
//    {
//        out.flush();
//        listFile.close();
//        QApplication::exit(0);
//    }
}
Esempio n. 28
0
void
RideWithGpsUploader::requestUploadRideWithGPS()
{
    parent->progressLabel->setText(tr("Upload ride..."));
    parent->progressBar->setValue(parent->progressBar->value()+10/parent->shareSiteCount);

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    int prevSecs = 0;
    long diffSecs = 0;

    int year = ride->fileName.left(4).toInt();
    int month = ride->fileName.mid(5,2).toInt();
    int day = ride->fileName.mid(8,2).toInt();
    int hour = ride->fileName.mid(11,2).toInt();
    int minute = ride->fileName.mid(14,2).toInt();;
    int second = ride->fileName.mid(17,2).toInt();;

    QDate rideDate = QDate(year, month, day);
    QTime rideTime = QTime(hour, minute, second);
    QDateTime rideDateTime = QDateTime(rideDate, rideTime);

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadRideWithGPSFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
    QString out, data;

    QVector<RideFilePoint*> vectorPoints = ride->ride()->dataPoints();
    int totalSize = vectorPoints.size();

    int size = 0;

    QString username = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSUSER).toString();
    QString password = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSPASS).toString();

    // application/json
    out += "{\"apikey\": \"p24n3a9e\", ";
    out += "\"email\": \""+username+"\", ";
    out += "\"password\": \""+password+"\", ";
    out += "\"track_points\": \"";

    data += "\[";
    foreach (const RideFilePoint *point, ride->ride()->dataPoints())
    {
        size++;

        if (point->secs == 0.0)
            continue;

        diffSecs = point->secs - prevSecs;
        prevSecs = point->secs;
        rideDateTime = rideDateTime.addSecs(diffSecs);

        data += "{\"x\": ";
        data += QString("%1").arg(point->lon,0,'f',GPS_COORD_TO_STRING);
        data += ", \"y\": ";
        data += QString("%1").arg(point->lat,0,'f',GPS_COORD_TO_STRING);
        data += ", \"t\": ";
        data += QString("%1").arg(rideDateTime.toTime_t());

        if (parent->altitudeChk->isChecked()) {
            data += ", \"e\": ";
            data += QString("%1").arg(point->alt);
        }
        if (parent->powerChk->isChecked()) {
            data += ", \"p\": ";
            data += QString("%1").arg(point->watts);
        }
        if (parent->cadenceChk->isChecked()) {
            data += ", \"c\": ";
            data += QString("%1").arg(point->cad);
        }
        if (parent->heartrateChk->isChecked()) {
            data += ", \"h\": ";
            data += QString("%1").arg(point->hr);
        }

        data += "}";

        if(size < totalSize)
           data += ",";
    }
    data += "]";
    out += data.replace("\"","\\\"");
    out += "\"}";

    QUrl url = QUrl("http://ridewithgps.com/trips.json");
    QNetworkRequest request = QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    parent->progressBar->setValue(parent->progressBar->value()+30/parent->shareSiteCount);
    parent->progressLabel->setText(tr("Upload ride... Sending to RideWithGPS"));

    networkMgr.post( request, out.toLatin1());
    eventLoop.exec();
}
Esempio n. 29
0
void Synchro::GetJSON()
{
	try {
		if (oldparse.getJSON().empty() != true)
		{
			char acsjson[1024];
			strcpy(acsjson, this->folder);
			strcat(acsjson, ".acsilserver");
			QFile txt(acsjson);

			txt.open(QIODevice::ReadWrite | QIODevice::Text);
			txt.write(myparse.getJSON().c_str());
			txt.close();

			oldparse.parse(myparse.getJSON());
		}
		else
		{
			char acsjson[1024];
			strcpy(acsjson, this->folder);
			strcat(acsjson, ".acsilserver");
			QFile txt(acsjson);
			if (txt.exists() == true)
			{

				std::string	line;
				std::ifstream myfile(acsjson);
				std::getline(myfile, line);
				while (line.find("-0001-11-30T00:00:00+0009") != std::string::npos)
					replace(line, "-0001-11-30T00:00:00+0009", "2014-10-18T14:24:39+0200");
				oldparse.parse(line);
			}
		}


		char toto[1024];
		strcpy(toto, this->URL);
		strcat(toto, "app_dev.php/service/1/op/listAll");
		m_network = new QNetworkAccessManager();
		QNetworkRequest request;
		QString header = "";

		request.setRawHeader("Authorization", "Bearer " + QByteArray(this->xtoken));
		request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
		request.setRawHeader("Accept", "application/json");
		request.setRawHeader("Accept-encoding", "identity");

		request.setUrl(QUrl(toto));
		QNetworkReply *reply = m_network->post(request, QByteArray(header.toUtf8()));

		QEventLoop loop;
		connect(m_network, SIGNAL(finished(QNetworkReply *)), &loop,
			SLOT(quit()));
		loop.exec();

		QString aQString = QString::fromUtf8(reply->readAll().data());
		std::string json = aQString.toStdString();
		while (json.find("-0001-11-30T00:00:00+0009") != std::string::npos)
			replace(json, "-0001-11-30T00:00:00+0009", "2014-10-18T14:24:39+0200");
		disconnect(m_network);
		myparse.parse(json);
	}
	catch (const std::exception & e) {
		printf(e.what());
	}
}
Esempio n. 30
-1
bool HototWebPage::acceptNavigationRequest(QWebFrame * frame, const QNetworkRequest & request, NavigationType type)
{
    Q_UNUSED(frame);
    Q_UNUSED(type);
    return handleUri(request.url().toString());
}