Exemple #1
0
AutoUpdater::UpdateFile AutoUpdater::getUpdateFile(UpdateFileMeta fileMeta,
                                        std::function<void(int,int)> progressCallback)
{
    UpdateFile file;
    file.metadata = fileMeta;

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

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

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

    return file;
}
/**
 * @brief Called when the search result was downloaded
 *        Emits "searchDone" if there are no more pages in the result set
 * @see Cinefacts::parseSearch
 */
void Cinefacts::searchFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(QObject::sender());
    reply->deleteLater();

    if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 302 ||
        reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 301) {
        qDebug() << "Got redirect" << reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
        if (!redirect.startsWith("http"))
            redirect.prepend("http://www.cinefacts.de");
        QUrl url(redirect);
        QNetworkReply *reply = qnam()->get(QNetworkRequest(url));
        new NetworkReplyWatcher(this, reply);
        connect(reply, SIGNAL(finished()), this, SLOT(searchFinished()));
        return;
    }

    QList<ScraperSearchResult> results;
    if (reply->error() == QNetworkReply::NoError) {
        QString msg = QString::fromUtf8(reply->readAll());
        results = parseSearch(msg);
    } else {
        qWarning() << "Network Error" << reply->errorString();
    }
    emit searchDone(results);
}
QJsonDocument sendRequest(const QString &url) {
    // create custom temporary event loop on stack
    QEventLoop eventLoop;
    // "quit()" the event-loop, when the network request "finished()"
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    // the HTTP request
    QUrl qurl = QUrl( url );
    QNetworkRequest req( qurl );
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called
    if (reply->error() == QNetworkReply::NoError) {
        QString strReply = (QString)reply->readAll();
        //qDebug() << "Response:" << strReply;
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        delete reply;
        return jsonResponse;
    }
    else {
        //failure
        qDebug() << "sendRequest failure: " <<reply->errorString();
        delete reply;
    }
    return QJsonDocument();
}
Exemple #4
0
QByteArray AutoUpdater::getUpdateFlist()
{
    QByteArray flist;

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

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

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

    return flist;
}
Exemple #5
0
/**
 * @brief Called when backdrops are loaded
 */
void VideoBuster::backdropFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(QObject::sender());
    Movie *movie = reply->property("storage").value<Storage*>()->movie();
    QList<int> infos = reply->property("infosToLoad").value<Storage*>()->infosToLoad();
    reply->deleteLater();
    if (!movie)
        return;

    if (reply->error() == QNetworkReply::NoError ) {
        QString msg = reply->readAll();
        QRegExp rx("href=\"https://gfx.videobuster.de/archive/resized/([^\"]*)\"(.*)([^<]*)<img (.*) src=\"https://gfx.videobuster.de/archive/resized/c110/([^\"]*)\"");
        rx.setMinimal(true);
        int pos = 0;
        while ((pos = rx.indexIn(msg, pos)) != -1) {
            pos += rx.matchedLength();
            if (rx.cap(2).contains("titledtl_cover_pictures")) {
                continue;
            }
            Poster p;
            p.thumbUrl = QUrl(QString("https://gfx.videobuster.de/archive/resized/w700/%1").arg(rx.cap(5)));
            p.originalUrl = QUrl(QString("https://gfx.videobuster.de/archive/resized/%1").arg(rx.cap(1)));
            movie->addBackdrop(p);
        }
    } else {
        qWarning() << "Network Error" << reply->errorString();
    }
    movie->controller()->scraperLoadDone();
}
Exemple #6
0
QScriptValue WebPuppeteerTab::get(const QString &url) {
	QNetworkRequest req(url);
	QNetworkReply *rep = networkAccessManager()->get(req);
	QEventLoop e;

	connect(rep, SIGNAL(finished()), &e, SLOT(quit()));
	e.exec();

	if (rep->error() != QNetworkReply::NoError) {
		qDebug("GET error: %s", qPrintable(rep->errorString()));
		rep->deleteLater();
		return parent->engine().currentContext()->throwError(QScriptContext::UnknownError, rep->errorString());
	}

	return parent->engine().newVariant((rep->readAll()));
}
Exemple #7
0
void Config::onCreateDbReceived()
{
    qDebug("[Config::onCreateDbReceived]");

    // extract code
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    int httpCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    qDebug() << "[Config::onCreateDbReceived] Code is: " << httpCode;

    // 201 -> created
    if (httpCode == 201) {
        CliErrorReporter::printNotification("[INFO] Database '" + m_couchDbStruct.dbName + "' created");

        // notify that the configuration process has terminated
        Q_EMIT ready();
    } else {
        CliErrorReporter::printError(CliErrorReporter::DATABASE
                                    , CliErrorReporter::ERROR
                                    , reply->errorString() + "\n" + reply->readAll());

        reply->deleteLater();
        std::exit(1);
    }

    reply->deleteLater();
}
void NXMAccessManager::retrieveCredentials()
{
  qDebug("retrieving credentials");
  QNetworkRequest request(ToQString(GameInfo::instance().getNexusPage())
                          + QString("/Core/Libs/Flamework/Entities/User?GetCredentials&game_id=%1"
                                    ).arg(GameInfo::instance().getNexusGameID()));
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  request.setRawHeader("User-Agent", userAgent().toUtf8());

  QNetworkReply *reply = get(request);
  QTimer timeout;
  connect(&timeout, &QTimer::timeout, [reply] () {
    reply->deleteLater();
  });
  timeout.start();

  connect(reply, &QNetworkReply::finished, [reply, this] () {
    QJsonDocument jdoc = QJsonDocument::fromJson(reply->readAll());
    QJsonArray credentialsData = jdoc.array();
    emit credentialsReceived(credentialsData.at(2).toString(),
                             s_PremiumAccountStates.find(credentialsData.at(1).toInt())
                                                         != s_PremiumAccountStates.end());
    reply->deleteLater();
  });

  connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
          [=] (QNetworkReply::NetworkError) {
    qDebug("failed to retrieve account credentials: %s", qPrintable(reply->errorString()));
    reply->deleteLater();
  });
}
Exemple #9
0
void LoginDialog::OnLoginPageFinished() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(QObject::sender());
    if (reply->error()) {
        DisplayError("Network error: " + reply->errorString() + "\nTry using another login method.");
        return;
    }

    QByteArray bytes = reply->readAll();
    std::string page(bytes.constData(), bytes.size());
    std::string hash = Util::GetCsrfToken(page, "hash");
    if (hash.empty()) {
        DisplayError("Failed to log in (can't extract form hash from page)");
        return;
    }

    QUrlQuery query;
    query.addQueryItem("login_email", EncodeSpecialCharacters(ui->emailLineEdit->text()));
    query.addQueryItem("login_password", EncodeSpecialCharacters(ui->passwordLineEdit->text()));
    query.addQueryItem("hash", QString(hash.c_str()));
    query.addQueryItem("login", "Login");
    query.addQueryItem("remember_me", "1");

    QUrl url(POE_LOGIN_URL);
    QByteArray data(query.query().toUtf8());
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QNetworkReply *logged_in = login_manager_->post(request, data);
    connect(logged_in, SIGNAL(finished()), this, SLOT(OnLoggedIn()));
}
Exemple #10
0
QPair<bool, QByteArray> blockDownloadExtractData(QNetworkReply & reply) {
    QEventLoop pause;
    QObject::connect(&reply, &QNetworkReply::finished, [&pause]() {
        pause.exit();
    });

    QProgressDialog progress("Network Operation…", "Abort", 0, 100, state->mainWindow);
    progress.setModal(true);
    QObject::connect(&progress, &QProgressDialog::canceled, &reply, &QNetworkReply::abort);
    auto processProgress = [&progress](qint64 bytesReceived, qint64 bytesTotal){
        progress.setRange(0, bytesTotal);
        progress.setValue(bytesReceived);
    };
    QObject::connect(&reply, &QNetworkReply::downloadProgress, processProgress);
    QObject::connect(&reply, &QNetworkReply::uploadProgress, processProgress);
    QTimer::singleShot(400, &progress, &QProgressDialog::show);

    pause.exec();

    if (reply.error() != QNetworkReply::NoError) {
        qDebug() << reply.errorString();
    }
    reply.deleteLater();
    return {reply.error() == QNetworkReply::NoError, reply.readAll()};
}
Exemple #11
0
void IMDB::onLoadFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(QObject::sender());
    reply->deleteLater();
    Movie *movie = reply->property("storage").value<Storage*>()->movie();
    QList<int> infos = reply->property("infosToLoad").value<Storage*>()->infosToLoad();
    if (!movie)
        return;

    if (reply->error() == QNetworkReply::NoError ) {
        QString msg = QString::fromUtf8(reply->readAll());
        parseAndAssignInfos(msg, movie, infos);
        QString posterUrl = parsePosters(msg);
        if (infos.contains(MovieScraperInfos::Poster) && !posterUrl.isEmpty()) {
            QNetworkReply *reply = qnam()->get(QNetworkRequest(posterUrl));
            reply->setProperty("storage", Storage::toVariant(reply, movie));
            reply->setProperty("infosToLoad", Storage::toVariant(reply, infos));
            connect(reply, SIGNAL(finished()), this, SLOT(onPosterLoadFinished()));
        } else {
            movie->controller()->scraperLoadDone(this);
        }
    } else {
        qWarning() << "Network Error (load)" << reply->errorString();
    }
}
    void networkReplyError(QNetworkReply::NetworkError code)
    {
        Q_D(QJsonRpcHttpReply);
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        if (!reply) {
            qJsonRpcDebug() << Q_FUNC_INFO << "invalid reply";
            return;
        }

        reply->deleteLater();
        if (code == QNetworkReply::NoError)
            return;

        QJsonRpcMessage response = QJsonRpcMessage::fromJson(reply->readAll());
        if (response.isValid()) {
            d->response = response;
            Q_EMIT messageReceived(response);
        } else {
            d->response = d->request.createErrorResponse(QJsonRpc::InternalError,
                                           QString("error with http request: %1").arg(reply->error()),
                                           reply->errorString());
        }

        Q_EMIT finished();
    }
Exemple #13
0
void Session::Request::onLoginPage() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    if (reply->error()) {
        emit loginResult(0x01, "A network error occured: " + reply->errorString());
    }
    else {
        QNetworkRequest request = reply->request();
        // Extract CSF
        const QString hash = getCSRFToken(reply->readAll());
        const QString username = getAttribute(&request, LoginUsername).toString();
        const QString password = getAttribute(&request, LoginPassword).toString();

        QUrlQuery query;
        query.addQueryItem("login_email", username);
        query.addQueryItem("login_password", password);
        query.addQueryItem("hash", hash);
        query.addQueryItem("login", "Login");
        QByteArray data(query.query().toUtf8());

        request = createRequest(LoginUrl());
        setAttribute(&request, LoginUsername, username);
        setAttribute(&request, LoginPassword, password);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

        QNetworkReply *r = _manager->post(request, data);

        connect(r, &QNetworkReply::finished, this, &Session::Request::Request::onLoginPageResult);
    }
    reply->deleteLater();
}
Exemple #14
0
/**
 * @brief Called when the episode infos are downloaded
 * @see TheTvDb::parseAndAssignSingleEpisodeInfos
 */
void TheTvDb::onEpisodeLoadFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(QObject::sender());
    QList<int> infos = reply->property("infosToLoad").value<Storage*>()->infosToLoad();
    reply->deleteLater();
    TvShowEpisode *episode = reply->property("storage").value<Storage*>()->episode();
    if (!episode)
        return;

    if (reply->error() == QNetworkReply::NoError ) {
        QString msg = QString::fromUtf8(reply->readAll());
        QDomDocument domDoc;
        domDoc.setContent(msg);
        for (int i=0, n=domDoc.elementsByTagName("Episode").count() ; i<n ; ++i) {
            QDomElement elem = domDoc.elementsByTagName("Episode").at(i).toElement();
            if (!elem.elementsByTagName("SeasonNumber").isEmpty() && !elem.elementsByTagName("EpisodeNumber").isEmpty()) {
                int seasonNumber = elem.elementsByTagName("SeasonNumber").at(0).toElement().text().toInt();
                int episodeNumber = elem.elementsByTagName("EpisodeNumber").at(0).toElement().text().toInt();
                if (episode->season() == seasonNumber && episode->episode() == episodeNumber) {
                    episode->clear(episode->infosToLoad());
                    parseAndAssignSingleEpisodeInfos(elem, episode, infos);
                }
            }
        }
    } else {
        qWarning() << "Network Error" << reply->errorString();
    }
    episode->scraperLoadDone();
}
void KDSoapPendingCall::Private::parseReply()
{
    if (parsed) {
        return;
    }

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

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

    const QByteArray data = reply->readAll();
    if (!data.isEmpty()) {
        KDSoapMessageReader reader;
        reader.xmlToMessage(data, &replyMessage, 0, &replyHeaders);
    }
}
Exemple #16
0
//===========!!!!!!!!!!!!!!!!============================
void Var::loadJson(QString url, Var* params, QString method)
{
    QNetworkAccessManager* m_pQnaManager;
    m_pQnaManager = new QNetworkAccessManager();

    QString sep = "?";
    if(url.contains("?")) sep="&";
    url+=sep+params->toParamString();

    qDebug()<<url;

    QNetworkReply *r = m_pQnaManager->get(QNetworkRequest(QUrl(url)));
    QEventLoop eLoop;
    QObject::connect(m_pQnaManager, SIGNAL(finished(QNetworkReply*)), &eLoop, SLOT(quit()));
    eLoop.exec();
    if(r->error() != QNetworkReply::NoError)
    {
        qDebug() << " [!]ERROR: " << r->errorString();
    }
    else
    {
        importFromJsonString(r->readAll());
        print();
    }
    delete m_pQnaManager;
}
Exemple #17
0
/**
 * @brief Called when the tv show actors are downloaded
 * Starts download of banners
 * @see TheTvDb::parseAndAssignActors
 * @see TheTvDb::onBannersFinished
 */
void TheTvDb::onActorsFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(QObject::sender());
    reply->deleteLater();
    TvShow *show = reply->property("storage").value<Storage*>()->show();
    TvShowUpdateType updateType = static_cast<TvShowUpdateType>(reply->property("updateType").toInt());
    QList<int> infos = reply->property("infosToLoad").value<Storage*>()->infosToLoad();
    if (!show)
        return;

    if (reply->error() == QNetworkReply::NoError ) {
        QString msg = QString::fromUtf8(reply->readAll());
        if (show->infosToLoad().contains(TvShowScraperInfos::Actors) &&
                (updateType == UpdateShow || updateType == UpdateShowAndAllEpisodes || updateType == UpdateShowAndNewEpisodes))
            parseAndAssignActors(msg, show);
    } else {
        qWarning() << "Network Error" << reply->errorString();
    }
    QString mirror = m_xmlMirrors.at(qrand()%m_xmlMirrors.count());
    QUrl url(QString("%1/api/%2/series/%3/banners.xml").arg(mirror).arg(m_apiKey).arg(show->tvdbId()));
    reply = qnam()->get(QNetworkRequest(url));
    reply->setProperty("storage", Storage::toVariant(reply, show));
    reply->setProperty("updateType", updateType);
    reply->setProperty("infosToLoad", Storage::toVariant(reply, infos));
    connect(reply, SIGNAL(finished()), this, SLOT(onBannersFinished()));
}
void LoadSetsPage::actDownloadFinishedSetsFile()
{
    progressLabel->hide();
    progressBar->hide();

    // check for a reply
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
    QNetworkReply::NetworkError errorCode = reply->error();
    if (errorCode != QNetworkReply::NoError) {
        QMessageBox::critical(this, tr("Error"), tr("Network error: %1.").arg(reply->errorString()));

        wizard()->enableButtons();
        setEnabled(true);

        reply->deleteLater();
        return;
    }

    // save allsets.json url, but only if the user customized it and download was successfull
    if(urlLineEdit->text() != QString(ALLSETS_URL))
        wizard()->settings->setValue("allsetsurl", urlLineEdit->text());
    else
        wizard()->settings->remove("allsetsurl");

    readSetsFromByteArray(reply->readAll());
    reply->deleteLater();
}
void NetworkDialog::start()
{
    QNetworkRequest req(url);
    QNetworkReply *reply;

    if (mode == Get)
        reply = netMan.get(req);
    else if (mode == Put)
        reply = netMan.put(req, buffer);

    auto updateProgress = [=](qint64 bytesTransfered, qint64 bytesTotal) {
        ui->progressBar->setMinimum(0);
        ui->progressBar->setMaximum(bytesTotal);
        ui->progressBar->setValue(bytesTransfered);
    };

    connect(reply, &QNetworkReply::downloadProgress, updateProgress);

    connect(reply, &QNetworkReply::uploadProgress, updateProgress);

    connect(reply, (netErrSig)&QNetworkReply::error, [=](QNetworkReply::NetworkError) {
        QMessageBox::critical(this, tr("IO Error"), reply->errorString());
    });

    connect(reply, &QNetworkReply::finished, [=]() {
        if (mode == Get)
            buffer = reply->readAll();
        done(reply->error() ? QDialog::Rejected : QDialog::Accepted);
    });

}
void ClipperNetwork::shortenLink(QString link)
{
    QNetworkRequest request;
    request.setUrl(QUrl(LINK_SHORTEN_URL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QVariantMap args;
    args["longUrl"] = link;

    QNetworkReply* networkRequest = network->post(request, JSON::serialize(QVariant(args), 4));
    connect(networkRequest, &QNetworkReply::finished, [networkRequest, this]() {
        if (networkRequest->error() == QNetworkReply::NoError)
        {
            QVariantMap replyMap = JSON::parse(networkRequest->readAll()).toMap();
            QString link = replyMap["id"].toString();
            if (!link.isEmpty())
                emit linkReady(link);
            else
            {
                qDebug() << replyMap;
                emit failure(UNKNOWN_ERROR);
            }
        }
        else
            emit failure(networkRequest->errorString());

        networkRequest->deleteLater();
    });
}
void PAAlternativeLauncher::manifestReadyRead()
{
	QNetworkReply *reply = dynamic_cast<QNetworkReply *>(sender());
	if(reply)
	{
		if(reply->error() == QNetworkReply::NoError)
		{
			qint64 bytes_available = reply->bytesAvailable();
			QByteArray input = reply->read(bytes_available);
			Q_ASSERT(input.size() == bytes_available);
			mZstream.next_in = (Bytef *)input.constData();
			mZstream.avail_in = bytes_available;

			uInt old_avail_out = mZstream.avail_out;
			int res = inflate(&mZstream, Z_SYNC_FLUSH);
			if(res != Z_OK && res != Z_STREAM_END)
			{
				reply->abort();
				info.warning("ZLib", mZstream.msg, false);
				return;
			}

			mManifestJson.write((const char *)mBuffer, old_avail_out - mZstream.avail_out);
			mZstream.avail_out = mBufferSize;
			mZstream.next_out = mBuffer;
			Q_ASSERT(mZstream.avail_in == 0);
		}
		else
		{
			reply->abort();
			info.critical(tr("Manifest"), tr("Error while getting manifest (1).\n%1").arg(reply->errorString()));
		}
	}
}
void OwncloudSetupWizard::slotAuthError()
{
    QString errorMsg;

    PropfindJob* job = qobject_cast<PropfindJob*>(sender());
    if (!job) {
        qWarning() << "Can't check for authed redirects. This slot should be invoked from PropfindJob!";
        return;
    }
    QNetworkReply* reply = job->reply();

    // If there were redirects on the *authed* requests, also store
    // the updated server URL, similar to redirects on status.php.
    QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redirectUrl.isEmpty()) {
        qDebug() << "authed request was redirected to" << redirectUrl.toString();

        // strip the expected path
        QString path = redirectUrl.path();
        static QString expectedPath = "/" + _ocWizard->account()->davPath();
        if (path.endsWith(expectedPath)) {
            path.chop(expectedPath.size());
            redirectUrl.setPath(path);

            qDebug() << "setting account url to" << redirectUrl.toString();
            _ocWizard->account()->setUrl(redirectUrl);
            testOwnCloudConnect();
            return;
        }
        errorMsg = tr("The authenticated request to the server was redirected to "
                      "'%1'. The URL is bad, the server is misconfigured.")
                   .arg(redirectUrl.toString());

    // A 404 is actually a success: we were authorized to know that the folder does
    // not exist. It will be created later...
    } else if (reply->error() == QNetworkReply::ContentNotFoundError) {
        _ocWizard->successfulStep();
        return;

    // Provide messages for other errors, such as invalid credentials.
    } else if (reply->error() != QNetworkReply::NoError) {
        if (!_ocWizard->account()->credentials()->stillValid(reply)) {
            errorMsg = tr("Access forbidden by server. To verify that you have proper access, "
                          "<a href=\"%1\">click here</a> to access the service with your browser.")
                       .arg(_ocWizard->account()->url().toString());
        } else {
            errorMsg = errorMessage(reply->errorString(), reply->readAll());
        }

    // Something else went wrong, maybe the response was 200 but with invalid data.
    } else {
        errorMsg = tr("There was an invalid response to an authenticated webdav request");
    }

    _ocWizard->show();
    if (_ocWizard->currentId() == WizardCommon::Page_ShibbolethCreds) {
        _ocWizard->back();
    }
    _ocWizard->displayError(errorMsg, _ocWizard->currentId() == WizardCommon::Page_ServerSetup && checkDowngradeAdvised(reply));
}
void ClipperNetwork::shareText(QString &text)
{
    std::shared_ptr<QNetworkRequest> request(new QNetworkRequest(QUrl(HASTEBIN_PUBLISH_URL)));

    QByteArray data;

    request->setRawHeader("Host", "hastebin.com");
    request->setRawHeader("Content-Type", "text/plain");
    data.append(text);

    QNetworkReply *networkRequest = network->post(*request, data);

    connect(networkRequest, &QNetworkReply::finished, [networkRequest, this]() {
        if (networkRequest->error() == QNetworkReply::NoError)
        {
            QVariantMap replyMap = JSON::parse(networkRequest->readAll()).toMap();
            QString link = replyMap["key"].toString();
            if (!link.isEmpty())
                emit linkReady(HASTEBIN_BASE_URL+link);
            else
            {
                qDebug() << replyMap;
                emit failure(UNKNOWN_ERROR);
            }
        }
        else
            emit failure(networkRequest->errorString());

        networkRequest->deleteLater();
    });
}
/**
 * Response: create GameMode
 */
void RatingsProcessor::responseCreateGameMode() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

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

				requestGameModes();
			}
		} else {
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("ResponseCreateGameMode. Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
			}
		}
		reply->deleteLater();
	}
}
/**
 * Response: score average
 */
void RatingsProcessor::responseScoreAverage() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

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

				bb::data::JsonDataAccess jda;
				QVariant vlist = jda.loadFromBuffer(response);

				QVariantMap list = vlist.toMap();

				float temp = list["value"].toFloat();

				m_ratValue = temp;

			}
		} else {
			m_ratValue = 0;
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			//another error
			showError("ResponseScoreAverage. QBlox Server Error = " + response);
			return;
		}
		reply->deleteLater();
	}

	emit ratValueChanged();

	emit imageChanged();

	m_label.clear();
	emit labelChanged();

	emit idRatChanged();

	m_loading = false;
	emit loadingChanged();

	m_urlImage = m_imageUrl;
	emit urlImageChanged();

	m_showing = true;
	emit showingChanged();

	emit ratValueChanged();

	return;
}
Exemple #26
0
void Downloader::downloadError(QNetworkReply::NetworkError code)
{
    Q_UNUSED(code)
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    reply->deleteLater();
    emit error("Download error: " + reply->errorString());
}
void QRestClient::asyncJsonCall(
        QByteArray method,
        QByteArray uri,
        QJsonDocument body,
        jsonPayloadFn successCb,
        jsonPayloadFn errCb)
{
    QNetworkReply *rep = call(method, uri, body.toJson(), Json);
    connect(rep, &QNetworkReply::finished,
            this, [this, successCb, errCb](){

                QNetworkReply *rep = dynamic_cast<QNetworkReply*>(sender());
                if(!rep) return;

                QJsonDocument body = QJsonDocument::fromJson(QString(rep->readAll()).toUtf8());
#ifdef QRESTCLIENT_DEBUG
                qDebug() << __PRETTY_FUNCTION__ << body.toJson();
#endif
                if(rep->error() == QNetworkReply::NoError && successCb){
                    successCb(body);
                }else if(errCb){
                    errCb(buildJsonError(rep->errorString(), body.toJson()));
                }
                rep->deleteLater();
    });
}
//! [1]
void TwitterRequest::onTimelineReply()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

    QString response;
    bool success = false;
    if (reply) {
        if (reply->error() == QNetworkReply::NoError) {
            const int available = reply->bytesAvailable();
            if (available > 0) {
                const QByteArray buffer = reply->readAll();
                response = QString::fromUtf8(buffer);
                success = true;
            }
        } else {
            response =  tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
        }

        reply->deleteLater();
    }

    if (response.trimmed().isEmpty()) {
        response = tr("Twitter request failed. Check internet connection");
    }

    emit complete(response, success);
}
void UpdateChecker::gotReplyFromUserRequest() {
	qDebug("UpdateChecker::gotReplyFromUserRequest");

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			QRegExp rx_version("^latest_version=(.*)");
			QString version;
			while (reply->canReadLine()) {
				QByteArray line = reply->readLine().trimmed();
				if (rx_version.indexIn(line) != -1) {
					version = rx_version.cap(1);
					break;
				}
			}
			if (!version.isEmpty()) {
				if ((formattedVersion(version) > formattedVersion(Version::with_revision()))) {
					qDebug("UpdateChecker::gotReplyFromUserRequest: new version found: %s", version.toUtf8().constData());
					emit newVersionFound(version);
				} else {
					emit noNewVersionFound(version);
				}
			} else {
				emit errorOcurred(1, tr("Failed to get the latest version number") );
			}
		} else {
			int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			qDebug("UpdateChecker::gotReplyFromUserRequest: status: %d", status);
			emit errorOcurred((int)reply->error(), reply->errorString());
		}
		reply->deleteLater();
	}
}
Exemple #30
-1
void Uploader::imgurToken()
{
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

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

  QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object();

  QSettings* s = ScreenshotManager::instance()->settings();
  s->setValue("upload/imgur/access_token"    , imgurResponse["access_token"].toString());
  s->setValue("upload/imgur/refresh_token"   , imgurResponse["refresh_token"].toString());
  s->setValue("upload/imgur/account_username", imgurResponse["account_username"].toString());
  s->setValue("upload/imgur/expires_in"      , imgurResponse["expires_in"].toString());

  for (int i = 0; i < mUploaders.size(); ++i) {
    if (mUploaders[i]->options().value("type") == "imgur") {
      mUploaders[i]->options().remove("access_token");
      mUploaders[i]->options().remove("refresh_token");

      mUploaders[i]->options().insert("access_token" , imgurResponse["access_token"].toString());
      mUploaders[i]->options().insert("refresh_token", imgurResponse["refresh_token"].toString());

      mUploaders[i]->retry();
    }
  }

  emit imgurAuthRefreshed();
}