Esempio n. 1
0
void SearchEnginesManager::replyFinished()
{
    qApp->restoreOverrideCursor();

    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) {
        return;
    }

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

    OpenSearchReader reader;
    OpenSearchEngine* engine = reader.read(reply);
    engine->setNetworkAccessManager(mApp->networkManager());

    reply->close();
    reply->deleteLater();

    if (checkEngine(engine)) {
        addEngine(engine);
        QMessageBox::information(0, tr("Search Engine Added"), tr("Search Engine \"%1\" has been successfully added.").arg(engine->name()));
    }
}
Esempio n. 2
0
void RipperCC::parseRipperDb()
{
    _timer->start();

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

    // Occurs error
    if(reply->error() != QNetworkReply::NoError) {
        qDebug() << "RippperCC Plugin:" << reply->errorString();
        reply->close();
        return;
    }

    // No errors
    QByteArray ba = reply->readAll();

    QVariantMap ripperMap = QJsonWrapper::parseJson(ba).toMap();
    if (!ripperMap.contains(QLatin1String("rippers")))
        return;

    QVariantList ripperList = ripperMap.value(QLatin1String("rippers")).toList();
    if (ripperList.isEmpty())
        return;

    _rippers.clear();
    foreach (const QVariant &item, ripperList) {
        Ripper ripper;
        ripper.jid = item.toMap().value(QLatin1String("jabber")).toString();
        ripper.url = item.toMap().value(QLatin1String("link")).toString();
        _rippers << ripper;
    }
void tst_QNetworkAccessManager::alwaysCacheRequest()
{
    QNetworkAccessManager manager;

    QNetworkRequest req;
    req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
    QNetworkReply *reply = manager.get(req);
    reply->close();
    delete reply;
}
Esempio n. 4
0
void DownloadHelper::onDownloadFinished()
{
   QNetworkReply* pReply = static_cast<QNetworkReply*>(sender());

   if (!handleReplyError(pReply))
      return;

   writeReply(pReply, fileName_);

   downloadFinished(fileName_);

   pReply->close();
   pReply->deleteLater();
   deleteLater();
}
Esempio n. 5
0
void
MainWindow::htmlIconDownloaded()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString url = reply->url().toString();
    QString savePath = reply->request().attribute(QNetworkRequest::User).toString();
    if (reply->error())
    {
        reply->close();
        qDebug() << "Couldn't get an icon or HTML for " << url << " so I'm giving up: " << reply->errorString();
        return;
    }

    QString html(reply->readAll());
    QRegExp reg("<link (rel=\"([^\"]+)\")?\\s*(type=\"([^\"]+)\")?\\s*(href=\"([^\"]+)\")?\\s*/?>");
    QString iconPath = "";
    // Look for the first match
    int pos = 0;
    while ((pos = reg.indexIn(html, pos)) != -1)
    {
        if (reg.cap(2).endsWith("icon"))
        {
            iconPath = reg.cap(6);
            break;
        }

        pos += reg.matchedLength();
    }

    if (iconPath.isEmpty())
    {
        qDebug() << "Couldn't find an icon in " << url;
        return;
    }

    if (!iconPath.startsWith("http"))
    {
        qDebug() << "Path was wrong, fixing";
        iconPath= "https://" + QUrl(url).host() + "/" + iconPath;
    }
    qDebug() << "Going to fetch " << iconPath;

    QNetworkRequest req = QNetworkRequest(QUrl(iconPath));
    req.setAttribute(QNetworkRequest::User, QVariant(savePath));
    QNetworkReply *rep = pManager->get(req);
    connect(rep, SIGNAL(finished()),
            this, SLOT(iconDownloaded()));
}
Esempio n. 6
0
void CBaiduTranslater::translate(const QString &src, const QString from, const QString to)
{
    //if (m_networkAccessManager == nullptr)
        //return;

    /* create query url */
    QUrl url(m_url);
    QUrlQuery query;
    query.addQueryItem("from", from);
    query.addQueryItem("to", to);
    query.addQueryItem("client_id", m_client_id);
    query.addQueryItem("q", src);
    url.setQuery(query);

    // create http request header
    QNetworkRequest request(url);

    // send GET request to get result
    QNetworkReply *reply = m_networkAccessManager->get(request);

    /* return data */
    connect(reply, &QNetworkReply::readyRead, [=]{
        QByteArray data = reply->readAll();
        //qDebug(data);
        CBaiduTranslateResult result = decodeJsonData(data);

        emit finished(result);

        if (isCli)
        {
            tmpResult = result;
            returnResult();
        }

        reply->close();
    });

    /* finish request */
    connect(reply, &QNetworkReply::finished, [=]{
        reply->deleteLater();
    });

    /* error */
    auto pError = static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error);
    connect(reply, pError, [=](QNetworkReply::NetworkError){
        reply->deleteLater();
    });
}
Esempio n. 7
0
void
YouTubeAuthenticator::authFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply *>( sender() );
    QByteArray data = reply->readAll();

    if( setAuthData( data ) )
        m_service->m_state = AuthFinish;

    disconnect( reply, SIGNAL( finished() ), this, SLOT( authFinished() ) );
    disconnect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),
                m_service, SLOT( networkError( QNetworkReply::NetworkError ) ) );

    reply->close();
    reply->deleteLater();
}
Esempio n. 8
0
void Toasty::slotNotify(Snore::Notification notification)
{
    QString key = settingsValue(ToastyConstants::DeviceID).toString();
    if (key.isEmpty()) {
        return;
    }
    QNetworkRequest request(QUrl::fromUserInput(QLatin1String("http://api.supertoasty.com/notify/") + key));
    QHttpMultiPart *mp = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart title;
    title.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"title\"")));
    title.setBody(notification.title().toUtf8().constData());
    mp->append(title);

    QHttpPart text;
    text.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"text\"")));
    text.setBody(notification.text().toUtf8().constData());
    mp->append(text);

    QHttpPart app;
    app.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"sender\"")));
    app.setBody(notification.application().name().toUtf8().constData());
    mp->append(app);

    QHttpPart icon;

    icon.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"image\"; filename=\"") + notification.icon().localUrl(QSize(128, 128)) + QLatin1Char('"')));
    icon.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QLatin1String("image/png")));
    QFile *file = new QFile(notification.icon().localUrl(QSize(128, 128)));
    file->open(QIODevice::ReadOnly);
    icon.setBodyDevice(file);
    mp->append(icon);

    QNetworkReply *reply =  m_manager.post(request, mp);
    mp->setParent(reply);
    file->setParent(reply);

    connect(reply, &QNetworkReply::finished, [reply]() {
        qCDebug(SNORE) << reply->error();
        qCDebug(SNORE) << reply->readAll();
        reply->close();
        reply->deleteLater();
    });

}
bool QgsGlobePluginDialog::validateRemoteUri( const QString &uri, QString &errMsg ) const
{
  QUrl url( uri );
  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkReply *reply = nullptr;

  while ( true )
  {
    QNetworkRequest req( url );
    req.setRawHeader( "User-Agent", "Wget/1.13.4" );
    reply = nam->get( req );
    QTimer timer;
    QEventLoop loop;
    QObject::connect( &timer, SIGNAL( timeout() ), &loop, SLOT( quit() ) );
    QObject::connect( reply, SIGNAL( finished() ), &loop, SLOT( quit() ) );
    timer.setSingleShot( true );
    timer.start( 500 );
    loop.exec();
    if ( reply->isRunning() )
    {
      // Timeout
      reply->close();
      delete reply;
      errMsg = tr( "Timeout" );
      return false;
    }

    QUrl redirectUrl = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl();
    if ( redirectUrl.isValid() && url != redirectUrl )
    {
      delete reply;
      url = redirectUrl;
    }
    else
    {
      break;
    }
  }

  errMsg = reply->error() == QNetworkReply::NoError ? QString() : reply->errorString();
  delete reply;
  return errMsg.isEmpty();
}
Esempio n. 10
0
void OpenSearchEngine::imageObtained()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

    if (!reply) {
        return;
    }

    QByteArray response = reply->readAll();

    reply->close();
    reply->deleteLater();

    if (response.isEmpty()) {
        return;
    }

    m_image.loadFromData(response);
    emit imageChanged();
}
void DownloadHelper::onDownloadFinished()
{
   QNetworkReply* pReply = static_cast<QNetworkReply*>(sender());

   if (pReply->error() != QNetworkReply::NoError)
   {
      showWarning(NULL,
                  QString::fromUtf8("Download Failed"),
                  QString::fromUtf8("An error occurred during download:\n\n")
                  + pReply->errorString());
      return;
   }

   QFile file(fileName_);
   if (file.open(QFile::ReadWrite))
      file.write(pReply->readAll());

   downloadFinished(fileName_);

   pReply->close();
   pReply->deleteLater();
   deleteLater();
}
Esempio n. 12
0
// 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();
}
Esempio n. 13
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::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);*/
}
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);
}
void QNetworkReplyProto::close()
{
  QNetworkReply *item = qscriptvalue_cast<QNetworkReply*>(thisObject());
  if (item)
    item->close();
}