Beispiel #1
0
// Shutdown the application server
bool shutdownServer(QUrl url)
{
    QNetworkAccessManager manager;
    QEventLoop loop;
    QNetworkReply *reply;
    QVariant redirectUrl;

    url.setPath("/misc/shutdown");

    do
    {
        reply = manager.get(QNetworkRequest(url));

        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        url = redirectUrl.toUrl();

        if (!redirectUrl.isNull())
            delete reply;

    } while (!redirectUrl.isNull());

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

    QString response = reply->readAll();

    if (response != "SHUTDOWN")
    {
        qDebug() << "Failed to connect, server response: " << response;
        return false;
    }

    return true;
}
Beispiel #2
0
void Uploadtous::checkUrlIsValid() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

    if (!reply) {
        emit urlChecked(false);
        return;
    }

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

    if ((!redirect.isEmpty()) && (re.indexIn(redirect) == -1)) {
        this->checkUrl(QUrl(redirect));
    }
    else {
        QString response(reply->readAll());
        QString fileName = response.section("<title>uploadto.us -", 1, 1).section('<', 0, 0).trimmed();        
        emit urlChecked(true, reply->request().url(), this->serviceName(), fileName);
    }

    reply->deleteLater();
}
Beispiel #3
0
void FileDefend::checkUrlIsValid() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

    if (!reply) {
        emit urlChecked(false);
        return;
    }

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

    if ((!redirect.isEmpty()) && (re.indexIn(redirect) == -1)) {
        this->checkUrl(QUrl(redirect));
    }
    else {
        QString response(reply->readAll());
        QString fileName = response.section("fname\" value=\"", 1, 1).section('"', 0, 0);

        if (fileName.isEmpty()) {
            emit urlChecked(false);
        }
        else {
            QString urlString = reply->request().url().toString();

            if (!urlString.endsWith(fileName)) {
                if (!urlString.endsWith('/')) {
                    urlString.append('/');
                }

                urlString.append(fileName);
            }

            QUrl url(urlString);
            emit urlChecked(true, url, this->serviceName(), fileName);
        }
    }

    reply->deleteLater();
}
void SolveMediaRecaptchaPlugin::onCaptchaDownloaded() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

    if (!reply) {
        emit error(tr("Network error"));
        return;
    }

    switch (reply->error()) {
    case QNetworkReply::NoError:
        break;
    case QNetworkReply::OperationCanceledError:
        reply->deleteLater();
        return;
    default:
        emit error(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
        reply->deleteLater();
        return;
    }

    const QVariantMap map = QtJson::Json::parse(QString::fromUtf8(reply->readAll())).toMap();
    reply->deleteLater();

    if (map.contains("ACChallengeResult")) {
        const QVariantMap result = map.value("ACChallengeResult").toMap();

        if (result.contains("chid")) {
            const QString challenge = result.value("chid").toString();

            if (!challenge.isEmpty()) {
                downloadCaptchaImage(challenge);
                return;
            }
        }
    }

    emit error(tr("No captcha challenge found"));
}
Beispiel #5
0
void Session::Request::onLoginPageResult() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (status != 302) {
        emit loginResult(0x01, "Failed to log in (invalid password or expired session ID).");
    }
    else {
        QList<QNetworkCookie> cookies = reply->manager()->cookieJar()->cookiesForUrl(MainUrl());
        for (auto &cookie : cookies) {
            if (QString(cookie.name()) == SessionIdCookie()) {
                _sessionId = cookie.value();
                emit loginResult(0x00, "Logged in!");
                break;
            }
        }

        QNetworkRequest request = createRequest(AccountUrl());
        QNetworkReply *r = _manager->get(request);

        connect(r, &QNetworkReply::finished, this, &Session::Request::Request::onAccountPageResult);
    }
    reply->deleteLater();
}
Beispiel #6
0
/**
 * @brief 通过HTTP GET发送URL,因为QNetWorkAccessManager默认不CACHE,所以不必设置
 **/
QByteArray WebUtils::getByUrl(const QUrl &url)
{
  QNetworkReply *reply = qnam.get(QNetworkRequest(url));
  QEventLoop loop;
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

  // WARNING: taobao only have once redirect url
  if (reply->error()) {
    qDebug() << reply->errorString();
    return "";
  } else if (!redirectionTarget.isNull()) {
    QUrl newUrl = url.resolved(redirectionTarget.toUrl());
    reply->deleteLater();
    return getByUrl(newUrl);
  }

  QByteArray returnStr = reply->readAll();
  reply->deleteLater();
  return returnStr;
}
void SolveMediaRecaptchaPlugin::onCaptchaImageDownloaded() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

    if (!reply) {
        emit error(tr("Network error"));
        return;
    }

    switch (reply->error()) {
    case QNetworkReply::NoError:
        break;
    case QNetworkReply::OperationCanceledError:
        reply->deleteLater();
        return;
    default:
        emit error(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
        reply->deleteLater();
        return;
    }

    emit captcha(CaptchaType::Image, QByteArray(m_challenge.toUtf8() + "\n" + reply->readAll().toBase64()));
    reply->deleteLater();
}
Beispiel #8
0
void DepositFiles::checkUrlIsValid() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

    if (!reply) {
        emit urlChecked(false);
        return;
    }

    QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
    QRegExp re("http(s|)://fileshare\\d+.(depositfiles.com|dfiles.\\w+)/[^'\"]+");

    if ((!redirect.isEmpty()) && (re.indexIn(redirect) == -1)) {
        this->checkUrl(QUrl(redirect));
    }
    else {
        QString response(reply->readAll());

        if (response.contains("file does not exist")) {
            emit urlChecked(false);
        }
        else {
            QScriptEngine engine;
            QString script = response.section("eval( ", 1, 1).section(");", 0, 0);
            QString fileNameElement = engine.evaluate(script).toString();

            if (fileNameElement.isEmpty()) {
                emit urlChecked(false);
            }
            else {
                QString fileName = fileNameElement.section("title=\"", 1, 1).section('"', 0, 0);
                emit urlChecked(true, reply->request().url(), this->serviceName(), fileName);
            }
        }
    }

    reply->deleteLater();
}
void AvatarDownloader::on_queryUserAvatar_finished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply *>(sender());
    reply->deleteLater();

    if (reply->error()) {
        qDebug() << "[AvatarHost]Error occured: " << reply->errorString();
        fetchUserAvatarEnd(false);
        return;
    }

    // cause we use "default", redirection may occur
    QVariant possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    m_urlRedirectedTo = redirectUrl(possibleRedirectUrl.toUrl(), m_urlRedirectedTo);

    if(!m_urlRedirectedTo.isEmpty()) {
        qDebug() << "[AvatarHost]fetching redirected, url: "
                 << m_urlRedirectedTo.toString();

        QNetworkReply* replyNext = m_net->get(QNetworkRequest(m_urlRedirectedTo));
        connect(replyNext, SIGNAL(finished()), SLOT(on_queryUserAvatar_finished()));
    } else {
        // finally arrive destination...

        // read and save avatar
        QByteArray bReply = reply->readAll();

        if (!save(m_strCurrentUser, bReply)) {
            qDebug() << "[AvatarHost]failed: unable to save user avatar, guid: " << m_strCurrentUser;
            fetchUserAvatarEnd(false);
            return;
        }

        qDebug() << "[AvatarHost]fetching finished, guid: " << m_strCurrentUser;
        fetchUserAvatarEnd(true);
    }
}
Beispiel #10
0
	void YoutubePlayer::handleFormatCheckFinished ()
	{
		Ui_.Quality_->setEnabled (true);
		QNetworkReply *rep = qobject_cast<QNetworkReply*> (sender ());
		if (!rep)
		{
			qWarning () << Q_FUNC_INFO
				<< "sender is not a QNetworkReply*"
				<< sender ();
			return;
		}
		rep->deleteLater ();

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

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

		QUrl url = OriginalURL_;
		url.addQueryItem ("fmt", fmt);
		SetVideoUrl (url);
	}
Beispiel #11
0
void Cramit::onWebPageDownloaded() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

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

    QRegExp re("http://cramit.in/file_download/[^'\"]+");
    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 if (response.contains("File Not Found")) {
            emit error(NotFound);
        }
        else {
            this->getWaitTime();
        }
    }

    reply->deleteLater();
}
Beispiel #12
0
void Pastebin::onLoginFinished() {
    QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender());
    QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << "Login complete:" << statusCode.toInt();

    if(networkReply->error() == QNetworkReply::NoError) {
        QString response = networkReply->readAll();

        qDebug() << "Response:" << response;

        if(response.startsWith("Bad API request")) {
            emit loginFailed(response);
        }
        else {
            QNetworkRequest networkRequest = networkReply->request();

            emit loginComplete(response);
        }
    }
    else {
        qWarning() << "Error:" << networkReply->errorString();
        emit loginFailed(QString::null);
    }
}
Beispiel #13
0
void SearchController::checkReply() {
	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);
				QRegExp loading("Votre recherche est en cours, merci de bien vouloir patienter");
				if(loading.indexIn(response, 0) != -1)
					waitMore(response);
				else
					parse(response);
			}
		} else {
			response = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
			qDebug() << response;
		}

		reply->deleteLater();
	}
}
Beispiel #14
0
void Pastebin::onSubmitPasteFinished() {
    QNetworkReply *networkReply = qobject_cast<QNetworkReply *>(sender());
    QVariant statusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << "Paste complete:" << statusCode.toInt();

    if(networkReply->error() == QNetworkReply::NoError) {
        const QString response = networkReply->readAll();

        qDebug() << "Response:" << response;

        if(response.startsWith("Bad API request")) {
            qWarning() << "Error with paste";
            emit pasteFailed(response);
        }
        else {
            qDebug() << "Paste successful";
            emit pasteComplete(response);
        }
    }
    else {
        qWarning() << "Error with paste:" << networkReply->errorString();
        emit pasteFailed(QString::null);
    }
}
requestStruct HTTPdownloader::doGet(QString url) {
	int tries = 0;
	requestStruct strct;
	do {
		qDebug() << "get" << url;
		QNetworkRequest req;
		req.setUrl(QUrl(url));
		//req.setRawHeader("User-Agent", "bsToGetLinklist/1.0 (Nokia; Qt)"); //was a test because bs.to wasnt returning valid results
		QNetworkReply *reply = this->get(static_cast<const QNetworkRequest>(req));
		QEventLoop loop;
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		loop.exec();

		strct.httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
		strct.data = reply->readAll();
		strct.url = url;
		qDebug() << "getDone" << strct.httpStatusCode << strct.data.size() << url << tries;
		reply->deleteLater();
		if (strct.httpStatusCode == 200)
			return strct;
		++tries;
	} while (tries < 4);
	return strct;
}
void UpdateChecker::gotReply() {
	qDebug("UpdateChecker::gotReply");

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

	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			//read data from reply
			QRegExp rx_version("^version=(.*)");
			QString version;
			while (reply->canReadLine()) {
				QByteArray line = reply->readLine().trimmed();
				//qDebug("line: %s", line.constData());
				if (rx_version.indexIn(line) != -1) {
					version = rx_version.cap(1);
					//qDebug("version: %s", version.toUtf8().constData());
					break;
				}
			} 
			if (!version.isEmpty()) {
				d->last_checked = QDate::currentDate();
				//qDebug("last known: %s version: %s", d->last_known_version.toUtf8().constData(), version.toUtf8().constData());
				//qDebug("version_with_revision: %s", Version::with_revision().toUtf8().constData());
				if ((d->last_known_version != version) && (formattedVersion(version) > formattedVersion(Version::with_revision()))) {
					qDebug("UpdateChecker::gotReply: new version found: %s", version.toUtf8().constData());
					emit newVersionFound(version);
				}
			}
		} else {
			//get http status code
			int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			qDebug("UpdateChecker::gotReply: status: %d", status);
		}
		reply->deleteLater();
	}
}
// Callback from fetchIcon
void
MainWindow::iconDownloaded()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString savePath = reply->request().attribute(QNetworkRequest::User).toString();
    int wasRedirected = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1)).toInt();
    QString username = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+2)).toString();
    QString password = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+3)).toString();

    QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if (!redirect.toUrl().isEmpty() && !wasRedirected)
    {
        qDebug() << "Was redirected to " << redirect.toUrl();
        reply->deleteLater();
        QUrl redir = redirect.toUrl();
        if (!username.isEmpty())
        {
            redir.setUserName(username);
            redir.setPassword(password);
        }
        QNetworkRequest req = QNetworkRequest(redir);
        req.setAttribute(QNetworkRequest::User, QVariant(savePath));
        req.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1), QVariant(1));
        QNetworkReply *rep = pManager->get(req);
        connect(rep, SIGNAL(finished()),
                this, SLOT(iconDownloaded()));
        return;
    }

    qDebug() << "Icon downloaded";
    if (reply->error())
    {
        reply->close();
        qDebug() << "Couldn't get icon";
        fetchHTMLIcon(reply->url().toString(), savePath);
        return;
    }

    QByteArray logoData = reply->readAll();
    // The favicon can be in various formats, so convert it to something
    // we know we can safely display
    QBuffer logoBuffer(&logoData);
    logoBuffer.open(QIODevice::ReadOnly);
    QImageReader reader(&logoBuffer);
    QSize iconSize(16, 16);
    if(reader.canRead())
    {
        while((reader.imageCount() > 1) && (reader.currentImageRect() != QRect(0, 0, 16, 16)))
        {
            if (!reader.jumpToNextImage())
                   break;
        }

        reader.setScaledSize(iconSize);
        const QImage icon = reader.read();
        if (icon.format() == QImage::Format_Invalid)
        {
            fetchHTMLIcon(reply->url().toString(), savePath);
        }
        else
        {
            icon.save(savePath, "PNG");
            QFileInfo info(savePath);
            int tabIndex = compareTabName(info.baseName());
            if (tabIndex != -1)
                ui->trackerTab->setTabIcon(tabIndex, QIcon(QPixmap::fromImage(icon)));
        }
    }
    else
    {
        qDebug() << "Invalid image";
        fetchHTMLIcon(reply->url().toString(), savePath);
    }

    logoBuffer.close();
    reply->close();
}
Beispiel #18
0
void FileDefend::checkCaptcha() {
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());

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

    QRegExp re("http://\\w+.filedefend.com:\\d+/d/[^'\"]+");
    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("Enter code below", 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(45000);
                this->connect(this, SIGNAL(waitFinished()), this, SLOT(submitCaptcha()));
            }
        }
void UltimateLyricsProvider::LyricsFetched() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
  if (!reply) {
    url_hop_ = false;
    return;
  }

  int id = requests_.take(reply);
  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    url_hop_ = false;
    emit Finished(id);
    return;
  }

  // Handle redirects
  QVariant redirect_target = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
  if (redirect_target.isValid()) {
    if (redirect_count_ >= kRedirectLimit) {
      url_hop_ = false;
      emit Finished(id);
      return;
    }

    QUrl target = redirect_target.toUrl();
    if (target.scheme().isEmpty() || target.host().isEmpty()) {
      QString path = target.path();
      target = reply->url();
      target.setPath(path);
    }

    redirect_count_ ++;
    QNetworkReply* reply = network_->get(QNetworkRequest(target));
    requests_[reply] = id;
    connect(reply, SIGNAL(finished()), SLOT(LyricsFetched()));
    return;
  }

  const QTextCodec* codec = QTextCodec::codecForName(charset_.toAscii().constData());
  const QString original_content = codec->toUnicode(reply->readAll());
  QString lyrics;

  // Check for invalid indicators
  foreach (const QString& indicator, invalid_indicators_) {
    if (original_content.contains(indicator)) {
      qLog(Debug) << "Found invalid indicator" << indicator;
      url_hop_ = false;
      emit Finished(id);
      return;
    }
  }

  if (!url_hop_) {
    // Apply extract rules
    foreach (const Rule& rule, extract_rules_) {
      // Modify the rule for this request's metadata
      Rule rule_copy(rule);
      for (Rule::iterator it = rule_copy.begin() ; it != rule_copy.end() ; ++it) {
        ReplaceFields(metadata_, &it->first);
      }

      QString content = original_content;
      if (ApplyExtractRule(rule_copy, &content)) {
        url_hop_ = true;
        QUrl url(content);
        qLog(Debug) << "Next url hop: " << url;
        QNetworkReply* reply = network_->get(QNetworkRequest(url));
        requests_[reply] = id;
        connect(reply, SIGNAL(finished()), SLOT(LyricsFetched()));
        return;
      }

      // Apply exclude rules
      foreach (const Rule& rule, exclude_rules_) {
        ApplyExcludeRule(rule, &lyrics);
      }
Beispiel #20
0
bool autobots_toutiao::DoPostFatie(const QString& content)
{
  //NeedValidate();
  QString token = GetToken();

  if (token.isEmpty())
  {
	  token = GetToken();
  }

  //http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/BQLRJGAA00014SEH/comments?ibc=newspc
  QString str_url = QString("http://%1/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/%2/comments?ibc=newspc").arg(m_host,m_news_id);

  QUrl url1;
  url1.setUrl(str_url);

  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Accept",	"*/*"));
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
  header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-cn"));
  header_list.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
  header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
  header_list.push_back(HttpParamItem("X-Requested-With", "XMLHttpRequest"));
  header_list.push_back(HttpParamItem("Host", m_host));
  header_list.push_back(HttpParamItem("Referer", m_url));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  HttpParamList post_data;
  post_data.push_back(HttpParamItem("board", m_chanel));
  post_data.push_back(HttpParamItem("content", content));
  post_data.push_back(HttpParamItem("parentId", ""));
  post_data.push_back(HttpParamItem("ntoken", token));

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
	  QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	  QString msg = reply->errorString();
    return false;
  }
  
  QVariant statusCodeV =  reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);  

  int n = statusCodeV.toInt();

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

  QByteArray rp_data = reply->readAll();
  QString t = rp_data;
  return GetFatieStatus(rp_data); 
 
}
Beispiel #21
0
void MainWindow::onRetroArchUpdateDownloadFinished()
{
   QNetworkReply *reply = m_updateReply.data();
   QNetworkReply::NetworkError error;
   int code;

   m_updateProgressDialog->cancel();

   /* At least on Linux, the progress dialog will refuse to hide itself and will stay on screen in a corrupted way if we happen to show an error message in this function. processEvents() will sometimes fix it, other times not... seems random. */
   qApp->processEvents();

   if (!reply)
      return;

   error = reply->error();
   code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

   if (m_updateFile.isOpen())
      m_updateFile.close();

   if (code != 200)
   {
      emit showErrorMessageDeferred(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_NETWORK_ERROR)) + ": HTTP Code " + QString::number(code));
      RARCH_ERR("[Qt]: RetroArch update failed with HTTP status code: %d\n", code);
      reply->disconnect();
      reply->abort();
      reply->deleteLater();
      return;
   }

   if (error == QNetworkReply::NoError)
   {
      int index = m_updateFile.fileName().lastIndexOf(PARTIAL_EXTENSION);
      QString newFileName = m_updateFile.fileName().left(index);
      QFile newFile(newFileName);

      /* rename() requires the old file to be deleted first if it exists */
      if (newFile.exists() && !newFile.remove())
         RARCH_ERR("[Qt]: RetroArch update finished, but old file could not be deleted.\n");
      else
      {
         if (m_updateFile.rename(newFileName))
         {
            RARCH_LOG("[Qt]: RetroArch update finished downloading successfully.\n");
            emit extractArchiveDeferred(newFileName);
         }
         else
         {
            RARCH_ERR("[Qt]: RetroArch update finished, but temp file could not be renamed.\n");
            emit showErrorMessageDeferred(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_COULD_NOT_RENAME_FILE));
         }
      }
   }
   else
   {
      QByteArray errorArray = reply->errorString().toUtf8();
      const char *errorData = errorArray.constData();

      RARCH_ERR("[Qt]: RetroArch update ended prematurely: %s\n", errorData);
      emit showErrorMessageDeferred(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_NETWORK_ERROR)) + ": Code " + QString::number(code) + ": " + errorData);
   }

   reply->disconnect();
   reply->close();
   reply->deleteLater();
}
void WeatherWorker::onWeatherObserveReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    bool redirection = false;

    if(reply->error() != QNetworkReply::NoError || statusCode != 200) {//200 is normal status
        //qDebug() << "weather request error:" << reply->error() << ", statusCode=" << statusCode;
        if (statusCode == 301 || statusCode == 302) {//redirect
            QVariant redirectionUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
            //qDebug() << "redirectionUrl=" << redirectionUrl.toString();
            redirection = AccessDedirectUrl(redirectionUrl.toString(), WeatherType::Type_Observe);//AccessDedirectUrl(reply->rawHeader("Location"));
            reply->close();
            reply->deleteLater();
        }
        if (!redirection) {
            emit responseFailure(statusCode);
        }
        return;
    }

    QByteArray ba = reply->readAll();
    //QString reply_content = QString::fromUtf8(ba);
    reply->close();
    reply->deleteLater();
    //qDebug() << "weather observe size: " << ba.size();

    QJsonParseError err;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &err);
    if (err.error != QJsonParseError::NoError) {// Json type error
        qDebug() << "Json type error";
        emit responseFailure(0);
        return;
    }
    if (jsonDocument.isNull() || jsonDocument.isEmpty()) {
        qDebug() << "Json null or empty!";
        emit responseFailure(0);
        return;
    }

    QJsonObject jsonObject = jsonDocument.object();
    //qDebug() << "jsonObject" << jsonObject;

    QJsonObject mainObj = jsonObject.value("KylinWeather").toObject();
    QJsonObject airObj = mainObj.value("air").toObject();
    QJsonObject weatherObj = mainObj.value("weather").toObject();
    //qDebug() << "airObj" << airObj;

    m_preferences->air.id = weatherObj.value("id").toString();
    m_preferences->air.aqi = airObj.value("aqi").toString();
    m_preferences->air.qlty = airObj.value("qlty").toString();
    m_preferences->air.main = airObj.value("main").toString();
    m_preferences->air.pm25 = airObj.value("pm25").toString();
    m_preferences->air.pm10 = airObj.value("pm10").toString();
    m_preferences->air.no2 = airObj.value("no2").toString();
    m_preferences->air.so2 = airObj.value("so2").toString();
    m_preferences->air.co = airObj.value("co").toString();
    m_preferences->air.o3 = airObj.value("o3").toString();

    m_preferences->weather.id = weatherObj.value("id").toString();
    m_preferences->weather.city = weatherObj.value("location").toString();
    m_preferences->weather.updatetime = weatherObj.value("update_loc").toString();
    m_preferences->weather.air = QString("%1(%2)").arg(airObj.value("aqi").toString()).arg(airObj.value("qlty").toString());
    m_preferences->weather.cloud = weatherObj.value("cloud").toString();
    m_preferences->weather.cond_code = weatherObj.value("cond_code").toString();
    m_preferences->weather.cond_txt = weatherObj.value("cond_txt").toString();
    m_preferences->weather.fl = weatherObj.value("fl").toString();
    m_preferences->weather.hum = weatherObj.value("hum").toString();
    m_preferences->weather.pcpn = weatherObj.value("pcpn").toString();
    m_preferences->weather.pres = weatherObj.value("pres").toString();
    m_preferences->weather.tmp = weatherObj.value("tmp").toString();
    m_preferences->weather.vis = weatherObj.value("vis").toString();
    m_preferences->weather.wind_deg = weatherObj.value("wind_deg").toString();
    m_preferences->weather.wind_dir = weatherObj.value("wind_dir").toString();
    m_preferences->weather.wind_sc = weatherObj.value("wind_sc").toString();
    m_preferences->weather.wind_spd = weatherObj.value("wind_spd").toString();

    /*ObserveWeather observeData;
    observeData.id = weatherObj.value("id").toString();
    observeData.city = weatherObj.value("location").toString();
    observeData.updatetime = weatherObj.value("update_loc").toString();
    observeData.air = QString("%1(%2)").arg(airObj.value("aqi").toString()).arg(airObj.value("qlty").toString());
    observeData.cloud = weatherObj.value("cloud").toString();
    observeData.cond_code = weatherObj.value("cond_code").toString();
    observeData.cond_txt = weatherObj.value("cond_txt").toString();
    observeData.fl = weatherObj.value("fl").toString();
    observeData.hum = weatherObj.value("hum").toString();
    observeData.pcpn = weatherObj.value("pcpn").toString();
    observeData.pres = weatherObj.value("pres").toString();
    observeData.tmp = weatherObj.value("tmp").toString();
    observeData.vis = weatherObj.value("vis").toString();
    observeData.wind_deg = weatherObj.value("wind_deg").toString();
    observeData.wind_dir = weatherObj.value("wind_dir").toString();
    observeData.wind_sc = weatherObj.value("wind_sc").toString();
    observeData.wind_spd = weatherObj.value("wind_spd").toString();*/

    emit this->observeDataRefreshed(m_preferences->weather);
}
Beispiel #23
0
// 0 正常,-1 未知错误, -2 验证码错误
int autobots_toutiao::ProcessRedirectLoginGet(const QString& str)
{
  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
  header_list.push_back(HttpParamItem("Host","api.snssdk.com"));
  header_list.push_back(HttpParamItem("Connection","keep-alive"));
  header_list.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-CN,zh;q=0.8"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"));

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

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

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
    if(reply != NULL)
    {
      QString t = reply->errorString();

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

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

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

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

    QUrl red_url = redirectionTarget.toUrl();

    QString str = red_url.toString();

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

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

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

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

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

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

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

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

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

    QUrl red_url = redirectionTarget.toUrl();

    QString str = red_url.toString();

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

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

  return res;
}
Beispiel #25
0
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  QNetworkReply *reply = mCapabilitiesReply;
  reply->deleteLater();
  mCapabilitiesReply = 0;

  // handle network errors
  if ( reply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = reply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
  if ( !redirect.isNull() )
  {
    QgsDebugMsg( "redirecting to " + redirect.toUrl().toString() );
    QNetworkRequest request( redirect.toUrl() );
    setAuthorization( request );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

    connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
    return;
  }

  QByteArray buffer = reply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWFSCapabilities::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // hangle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWFSCapabilities::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  QString version = capabilitiesDocument.documentElement().attribute( "version" );
  if ( version != "1.0.0" && version != "1.0" )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "Either the WFS server does not support WFS version 1.0.0 or the WFS url is wrong" );
    emit gotCapabilities();
    return;
  }

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = capabilitiesDocument.elementsByTagNameNS( WFS_NAMESPACE, "FeatureType" );
  for ( unsigned int i = 0; i < featureTypeList.length(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "DefaultSRS" );
    if ( defaultCRSList.length() > 0 )
    {
      featureType.crslist.append( defaultCRSList.at( 0 ).toElement().text() );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "OtherSRS" );
    for ( unsigned int i = 0; i < otherCRSList.length(); ++i )
    {
      featureType.crslist.append( otherCRSList.at( i ).toElement().text() );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "SRS" );
    for ( unsigned int i = 0; i < srsList.length(); ++i )
    {
      featureType.crslist.append( srsList.at( i ).toElement().text() );
    }

    mCaps.featureTypes.append( featureType );
  }

  emit gotCapabilities();
}
Beispiel #26
0
QByteArray QgsSvgCache::getImageData( const QString &path ) const
{
  // is it a path to local file?
  QFile svgFile( path );
  if ( svgFile.exists() )
  {
    if ( svgFile.open( QIODevice::ReadOnly ) )
    {
      return svgFile.readAll();
    }
    else
    {
      return QByteArray();
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return ba;
}
bool weatherStation::update()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkRequest netRequest(*apiLink);
    QNetworkReply *netReply;

    QTimer timer;
    timer.setSingleShot(true);
    QEventLoop loop;

    netReply = manager->get(netRequest);
    connect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

    timer.start(10000);

    loop.exec();

    QString data;
    QFile weatherTempData("weatherTempData.txt");

    weatherTempData.open(QFile::ReadWrite);

    if(timer.isActive()) {
        timer.stop();
        if(netReply->error() > 0) {
          qDebug() << "network error";
          data = weatherTempData.readAll();
          qDebug() << "read from file";
        }
        else {
          int v = netReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

          if (v >= 200 && v < 300) {  // Success
              data = netReply->readAll();
              weatherTempData.seek(0);
              QTextStream out(&weatherTempData);
              out << data;
              weatherTempData.seek(0);
              //qDebug() << weatherTempData.readAll();
          }
        }
    } else {
       // timeout
       disconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));

       netReply->abort();
       data = weatherTempData.readAll();
       qDebug() << "read from file";
    }
    weatherTempData.close();
    QXmlStreamReader *xmlReader = new QXmlStreamReader(data);
    int weatherRecordCounter = 0;
    //Parse the XML until we reach end of it
    while(!xmlReader->atEnd() && !xmlReader->hasError()) {
            // Read next element
            QXmlStreamReader::TokenType token = xmlReader->readNext();
            //If token is just StartDocument - go to next
            if(token == QXmlStreamReader::StartDocument) {
                    continue;
            }
            //qDebug() << xmlReader->name();


            if(token == QXmlStreamReader::EndElement)
                   if(xmlReader->name() == "time")
                   {
                        weatherRecordCounter++;
                        //qDebug() << "is end element";
                        continue;
                   }

            //
            //If token is StartElement - read it
            if(token == QXmlStreamReader::StartElement) {

                    if(xmlReader->name() == "sun") {
                        QXmlStreamAttributes att = xmlReader->attributes();
                        sunrise = sunrise.fromString(att.value("rise").toString(),"yyyy-MM-ddTHH:mm:ss");
                        sunrise.setTimeSpec(Qt::UTC);
                        sunrise = sunrise.toLocalTime();
                        sunset = sunset.fromString(att.value("set").toString(),"yyyy-MM-ddTHH:mm:ss");
                        sunset.setTimeSpec(Qt::UTC);
                        sunset = sunset.toLocalTime();
                        //qDebug() << sunrise.toString("yyyy-MM-ddTHH:mm:ss");
                        //qDebug() << sunset.toString("yyyy-MM-ddTHH:mm:ss");
                            continue;
                    }

                    if(xmlReader->name() == "time") {


                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecord *record = new weatherRecord();
                            record->day = record->day.fromString(att.value("day").toString(),"yyyy-MM-dd");
                            /*record->from = record->from.fromString(att.value("from").toString(),"yyyy-MM-ddTHH:mm:ss");
                            record->to = record->to.fromString(att.value("to").toString(),"yyyy-MM-ddTHH:mm:ss");
                            qDebug() << record->from.toString("yyyy-MM-ddTHH:mm:ss");
                            qDebug() << record->to.toString("yyyy-MM-ddTHH:mm:ss");*/
                            weatherRecords.append(record);
                            continue;

                    }

                    if(xmlReader->name() == "precipitation")
                    {
                        if(xmlReader->isEndElement())
                        {
                            weatherRecords.at(weatherRecordCounter)->precipitationType = "no";
                            continue;
                        }
                        else
                        {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->precipitationType=att.value("type").toString();
                            weatherRecords.at(weatherRecordCounter)->precipitationValue=att.value("value").toFloat();
                            weatherRecords.at(weatherRecordCounter)->precipitationUnit=att.value("unit").toString();
                            continue;
                        }
                    }

                    if(xmlReader->name() == "windDirection")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->windDirection=att.value("deg").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "windSpeed")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->windSpeed=att.value("mps").toFloat();
                            weatherRecords.at(weatherRecordCounter)->windType=att.value("name").toString();
                            continue;
                    }
                    if(xmlReader->name() == "temperature")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->currentTemp=att.value("day").toFloat();
                            weatherRecords.at(weatherRecordCounter)->minTemp=att.value("min").toFloat();
                            weatherRecords.at(weatherRecordCounter)->maxTemp=att.value("max").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "pressure")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->pressure=att.value("value").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "humidity")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->humidity=att.value("value").toFloat();
                            continue;
                    }
                    if(xmlReader->name() == "clouds")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->cloudsPercent=att.value("all").toInt();
                            weatherRecords.at(weatherRecordCounter)->cloudsName=att.value("value").toString();
                            continue;
                    }
                    if(xmlReader->name() == "symbol")
                    {
                            QXmlStreamAttributes att = xmlReader->attributes();
                            weatherRecords.at(weatherRecordCounter)->icon=att.value("var").toString();

                            continue;
                    }

            }
    }
    if(xmlReader->hasError()) return false;
    return true;
}
void WeatherWorker::onWeatherForecastReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    bool redirection = false;

    if(reply->error() != QNetworkReply::NoError || statusCode != 200) {//200 is normal status
        //qDebug() << "weather forecast request error:" << reply->error() << ", statusCode=" << statusCode;
        if (statusCode == 301 || statusCode == 302) {//redirect
            QVariant redirectionUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
            //qDebug() << "redirectionUrl=" << redirectionUrl.toString();
            redirection = AccessDedirectUrl(redirectionUrl.toString(), WeatherType::Type_Forecast);//AccessDedirectUrl(reply->rawHeader("Location"));
            reply->close();
            reply->deleteLater();
        }
        if (!redirection) {
            emit responseFailure(statusCode);
        }
        return;
    }

    QByteArray ba = reply->readAll();
    //QString reply_content = QString::fromUtf8(ba);
    reply->close();
    reply->deleteLater();
    //qDebug() << "weather forecast size: " << ba.size();

    QJsonParseError err;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &err);
    if (err.error != QJsonParseError::NoError) {// Json type error
        qDebug() << "Json type error";
        emit responseFailure(0);
        return;
    }
    if (jsonDocument.isNull() || jsonDocument.isEmpty()) {
        qDebug() << "Json null or empty!";
        emit responseFailure(0);
        return;
    }

    QJsonObject jsonObject = jsonDocument.object();
    //qDebug() << "jsonObject" << jsonObject;

    QJsonObject mainObj = jsonObject.value("KylinWeather").toObject();
    QJsonObject forecastObj = mainObj.value("forecast").toObject();
    QJsonObject lifestyleObj = mainObj.value("lifestyle").toObject();

    m_preferences->forecast0.forcast_date = forecastObj.value("forcast_date0").toString();
    m_preferences->forecast0.cond_code_d = forecastObj.value("cond_code_d0").toString();
    m_preferences->forecast0.cond_code_n = forecastObj.value("cond_code_n0").toString();
    m_preferences->forecast0.cond_txt_d = forecastObj.value("cond_txt_d0").toString();
    m_preferences->forecast0.cond_txt_n = forecastObj.value("cond_txt_n0").toString();
    m_preferences->forecast0.hum = forecastObj.value("hum0").toString();
    m_preferences->forecast0.mr_ms = forecastObj.value("mr_ms0").toString();
    m_preferences->forecast0.pcpn = forecastObj.value("pcpn0").toString();
    m_preferences->forecast0.pop = forecastObj.value("pop0").toString();
    m_preferences->forecast0.pres = forecastObj.value("pres0").toString();
    m_preferences->forecast0.sr_ss = forecastObj.value("sr_ss0").toString();
    m_preferences->forecast0.tmp_max = forecastObj.value("tmp_max0").toString();
    m_preferences->forecast0.tmp_min = forecastObj.value("tmp_min0").toString();
    m_preferences->forecast0.uv_index = forecastObj.value("uv_index0").toString();
    m_preferences->forecast0.vis = forecastObj.value("vis0").toString();
    m_preferences->forecast0.wind_deg = forecastObj.value("wind_deg0").toString();
    m_preferences->forecast0.wind_dir = forecastObj.value("wind_dir0").toString();
    m_preferences->forecast0.wind_sc = forecastObj.value("wind_sc0").toString();
    m_preferences->forecast0.wind_spd = forecastObj.value("wind_spd0").toString();

    m_preferences->forecast1.forcast_date = forecastObj.value("forcast_date1").toString();
    m_preferences->forecast1.cond_code_d = forecastObj.value("cond_code_d1").toString();
    m_preferences->forecast1.cond_code_n = forecastObj.value("cond_code_n1").toString();
    m_preferences->forecast1.cond_txt_d = forecastObj.value("cond_txt_d1").toString();
    m_preferences->forecast1.cond_txt_n = forecastObj.value("cond_txt_n1").toString();
    m_preferences->forecast1.hum = forecastObj.value("hum1").toString();
    m_preferences->forecast1.mr_ms = forecastObj.value("mr_ms1").toString();
    m_preferences->forecast1.pcpn = forecastObj.value("pcpn1").toString();
    m_preferences->forecast1.pop = forecastObj.value("pop1").toString();
    m_preferences->forecast1.pres = forecastObj.value("pres1").toString();
    m_preferences->forecast1.sr_ss = forecastObj.value("sr_ss1").toString();
    m_preferences->forecast1.tmp_max = forecastObj.value("tmp_max1").toString();
    m_preferences->forecast1.tmp_min = forecastObj.value("tmp_min1").toString();
    m_preferences->forecast1.uv_index = forecastObj.value("uv_index1").toString();
    m_preferences->forecast1.vis = forecastObj.value("vis1").toString();
    m_preferences->forecast1.wind_deg = forecastObj.value("wind_deg1").toString();
    m_preferences->forecast1.wind_dir = forecastObj.value("wind_dir1").toString();
    m_preferences->forecast1.wind_sc = forecastObj.value("wind_sc1").toString();
    m_preferences->forecast1.wind_spd = forecastObj.value("wind_spd1").toString();

    m_preferences->forecast2.forcast_date = forecastObj.value("forcast_date2").toString();
    m_preferences->forecast2.cond_code_d = forecastObj.value("cond_code_d2").toString();
    m_preferences->forecast2.cond_code_n = forecastObj.value("cond_code_n2").toString();
    m_preferences->forecast2.cond_txt_d = forecastObj.value("cond_txt_d2").toString();
    m_preferences->forecast2.cond_txt_n = forecastObj.value("cond_txt_n2").toString();
    m_preferences->forecast2.hum = forecastObj.value("hum2").toString();
    m_preferences->forecast2.mr_ms = forecastObj.value("mr_ms2").toString();
    m_preferences->forecast2.pcpn = forecastObj.value("pcpn2").toString();
    m_preferences->forecast2.pop = forecastObj.value("pop2").toString();
    m_preferences->forecast2.pres = forecastObj.value("pres2").toString();
    m_preferences->forecast2.sr_ss = forecastObj.value("sr_ss2").toString();
    m_preferences->forecast2.tmp_max = forecastObj.value("tmp_max2").toString();
    m_preferences->forecast2.tmp_min = forecastObj.value("tmp_min2").toString();
    m_preferences->forecast2.uv_index = forecastObj.value("uv_index2").toString();
    m_preferences->forecast2.vis = forecastObj.value("vis2").toString();
    m_preferences->forecast2.wind_deg = forecastObj.value("wind_deg2").toString();
    m_preferences->forecast2.wind_dir = forecastObj.value("wind_dir2").toString();
    m_preferences->forecast2.wind_sc = forecastObj.value("wind_sc2").toString();
    m_preferences->forecast2.wind_spd = forecastObj.value("wind_spd2").toString();

    m_preferences->lifestyle.air_brf = lifestyleObj.value("air_brf").toString();
    m_preferences->lifestyle.air_txt = lifestyleObj.value("air_txt").toString();
    m_preferences->lifestyle.comf_brf = lifestyleObj.value("comf_brf").toString();
    m_preferences->lifestyle.comf_txt = lifestyleObj.value("comf_txt").toString();
    m_preferences->lifestyle.cw_brf = lifestyleObj.value("cw_brf").toString();
    m_preferences->lifestyle.cw_txt = lifestyleObj.value("cw_txt").toString();
    m_preferences->lifestyle.drsg_brf = lifestyleObj.value("drsg_brf").toString();
    m_preferences->lifestyle.drsg_txt = lifestyleObj.value("drsg_txt").toString();
    m_preferences->lifestyle.flu_brf = lifestyleObj.value("flu_brf").toString();
    m_preferences->lifestyle.flu_txt = lifestyleObj.value("flu_txt").toString();
    m_preferences->lifestyle.sport_brf = lifestyleObj.value("sport_brf").toString();
    m_preferences->lifestyle.sport_txt = lifestyleObj.value("sport_txt").toString();
    m_preferences->lifestyle.trav_brf = lifestyleObj.value("trav_brf").toString();
    m_preferences->lifestyle.trav_txt = lifestyleObj.value("trav_txt").toString();
    m_preferences->lifestyle.uv_brf = lifestyleObj.value("uv_brf").toString();
    m_preferences->lifestyle.uv_txt = lifestyleObj.value("uv_txt").toString();

    QList<ForecastWeather> forecastDatas;
    forecastDatas.append(m_preferences->forecast0);
    forecastDatas.append(m_preferences->forecast1);
    forecastDatas.append(m_preferences->forecast2);
    emit this->forecastDataRefreshed(forecastDatas, m_preferences->lifestyle);


    /*ForecastWeather forecastData[3];
    for (int i = 0; i < 3; i++) {
        forecastData[i].cond_code_d = "N/A";
        forecastData[i].cond_code_n = "N/A";
        forecastData[i].cond_txt_d = "N/A";
        forecastData[i].cond_txt_n = "N/A";
        forecastData[i].forcast_date = "N/A";
        forecastData[i].hum = "N/A";
        forecastData[i].mr_ms = "N/A";
        forecastData[i].pcpn = "N/A";
        forecastData[i].pop = "N/A";
        forecastData[i].pres = "N/A";
        forecastData[i].sr_ss = "N/A";
        forecastData[i].tmp_max = "N/A";
        forecastData[i].tmp_min = "N/A";
        forecastData[i].uv_index = "N/A";
        forecastData[i].vis = "N/A";
        forecastData[i].wind_deg = "N/A";
        forecastData[i].wind_dir = "N/A";
        forecastData[i].wind_sc = "N/A";
        forecastData[i].wind_spd = "N/A";
    }*/

    /*QList<ForecastWeather> forecastDatas;
    ForecastWeather data0;
    data0.forcast_date = forecastObj.value("forcast_date0").toString();
    data0.cond_code_d = forecastObj.value("cond_code_d0").toString();
    data0.cond_code_n = forecastObj.value("cond_code_n0").toString();
    data0.cond_txt_d = forecastObj.value("cond_txt_d0").toString();
    data0.cond_txt_n = forecastObj.value("cond_txt_n0").toString();
    data0.hum = forecastObj.value("hum0").toString();
    data0.mr_ms = forecastObj.value("mr_ms0").toString();
    data0.pcpn = forecastObj.value("pcpn0").toString();
    data0.pop = forecastObj.value("pop0").toString();
    data0.pres = forecastObj.value("pres0").toString();
    data0.sr_ss = forecastObj.value("sr_ss0").toString();
    data0.tmp_max = forecastObj.value("tmp_max0").toString();
    data0.tmp_min = forecastObj.value("tmp_min0").toString();
    data0.uv_index = forecastObj.value("uv_index0").toString();
    data0.vis = forecastObj.value("vis0").toString();
    data0.wind_deg = forecastObj.value("wind_deg0").toString();
    data0.wind_dir = forecastObj.value("wind_dir0").toString();
    data0.wind_sc = forecastObj.value("wind_sc0").toString();
    data0.wind_spd = forecastObj.value("wind_spd0").toString();
    ForecastWeather data1;
    data1.forcast_date = forecastObj.value("forcast_date1").toString();
    ForecastWeather data2;
    data2.forcast_date = forecastObj.value("forcast_date2").toString();
    forecastDatas.append(data0);
    forecastDatas.append(data1);
    forecastDatas.append(data2);
    emit this->forecastDataRefreshed(forecastDatas);*/
}
/**
 *  Called after response from twitter
 */
void QTweetNetBase::reply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

    // prep m_response for finished() signal
    if (reply) {
    	m_response = reply->readAll();
    } else {
        m_response.clear();
    }

    // ALWAYS emit a finished signal no matter what happens
	emit finished(m_response);


	// now analyze the response
    if (reply) {

    	QString rateLimit(reply->rawHeader("X-Rate-Limit-Limit"));
    	QString rateRemaining(reply->rawHeader("X-Rate-Limit-Remaining"));
    	QString limitRest(reply->rawHeader("X-Rate-Limit-Reset"));

    	uint timeToReset = limitRest.toLongLong()- QDateTime::currentDateTime().toTime_t();

    	QString contentType(reply->rawHeader("content-type"));
    	bool contentTypeHasJson = contentType.contains("application/json", Qt::CaseInsensitive);

        if (reply->error() == QNetworkReply::NoError) {
        	if (isJsonParsingEnabled() && contentTypeHasJson) {
        		parseJson(m_response);
        	}
        } else {
            //dump error
            qDebug() << "Network error: " << reply->error();
            qDebug() << "Error string: " << reply->errorString();
            qDebug() << "Error response: " << m_response;

            //HTTP status code
            int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

            //prep error
            QTweetNetError* err = 0;

            if (!contentTypeHasJson) {
            	err = new QTweetHttpError(httpStatus, m_response);
            } else {
				//try to json parse the error response
				QJson::Parser parser;
				bool ok;
				QVariant json = parser.parse(m_response, &ok);
				QVariantMap errMsgMap = json.toMap();
				QMap<int, QString> twitterErrors;

				if (ok) {
					// here are a few sample responses we've seen:
					//{"request":"\/1\/users\/search.json?q=&per_page=20&page=1","error":"Client must provide a 'q' parameter with a value."}
					//{"error":"You must enter a query."}
					//{"errors":[{"message": "...", "code": 34}]}
					QList<QVariant> errors = errMsgMap["errors"].toList();
					QList<QVariant>::iterator it = errors.begin();

					while (it != errors.end()) {
						QVariantMap error = (*it).toMap();
						int errorCode = error["code"].toInt();
						QString errorMessage = error["message"].toString();

						twitterErrors[errorCode] = errorMessage;

						it++;
					}

					if (twitterErrors.size() > 0) {
						err = new QTweetServiceErrors(httpStatus, m_response, json, twitterErrors);
					} else {
						qDebug() << "Parsing json ok but twitter errors not found";
						err = new QTweetRawServiceError(httpStatus, m_response, json);
					}
				}
				else {
					qDebug() << "Unable to parse json in response";
					err = new QTweetHttpError(httpStatus, m_response);
				}
            }

            //finally emit the error signal
            if (err) {
            	emit error(*err);
            	err->deleteLater();
            } else {
            	Q_ASSERT(false);
            }
		}
        reply->deleteLater();
    }
}
Beispiel #30
0
bool autobots_toutiao::Login(const QString& name, const QString& password)
{
  //1.检验验证码
  QString vcode, code_sign;
  bool need_code = NeedValidateCode(name, vcode, code_sign);
  QString str_need_code = need_code ? "true" : "";

  QString str_url1 = "https://sso.toutiao.com/account_login/";

  QUrl url1(str_url1);

  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Referer", "text/javascript, text/html, application/xml, text/xml, */*"));
  header_list.push_back(HttpParamItem("Connection","Keep-Alive"));
  header_list.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded"));
  //header_list.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
  header_list.push_back(HttpParamItem("Accept-Language","zh-CN"));
  header_list.push_back(HttpParamItem("Host", "sso.toutiao.com"));
  header_list.push_back(HttpParamItem("Referer", "https://sso.toutiao.com/login/"));
  header_list.push_back(HttpParamItem("X-CSRFToken", m_csrf_token));
  header_list.push_back(HttpParamItem("X-Requested-With", "XMLHttpRequest"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

  HttpParamList post_data;
  post_data.push_back(HttpParamItem("account",name));
  post_data.push_back(HttpParamItem("captcha",vcode));
  post_data.push_back(HttpParamItem("code", ""));
  post_data.push_back(HttpParamItem("is_30_days_no_login","false"));
  post_data.push_back(HttpParamItem("mobile",""));
  post_data.push_back(HttpParamItem("password",password));
  post_data.push_back(HttpParamItem("service","http://www.toutiao.com/"));

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

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

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

  int n = statusCodeV.toInt();

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

  QByteArray data = reply->readAll();

  int res = GetResult(data);

  if (res == 0)
  {
	  return true;
  }
  else if (res == -1)
  {
	  VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
	  obj->ReportError("bestsalt", code_sign);
	  return false;
  }
  else
  {
	  return false;
  }

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

  //  QUrl red_url = redirectionTarget.toUrl();

  //  QString str = red_url.toString();

  //  int r = ProcessRedirectLoginGet(str);

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

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

  //return res;
}