void SpotifyBlobDownloader::ReplyFinished() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
  if (reply->error() != QNetworkReply::NoError) {
    // Handle network errors
    ShowError(reply->errorString());
    return;
  }

  // Is everything finished?
  for (QNetworkReply* reply : replies_) {
    if (!reply->isFinished()) {
      return;
    }
  }

  // Read files into memory first.
  QMap<QString, QByteArray> file_data;
  QStringList signature_filenames;

  for (QNetworkReply* reply : replies_) {
    const QString filename = reply->url().path().section('/', -1, -1);

    if (filename.endsWith(kSignatureSuffix)) {
      signature_filenames << filename;
    }

    file_data[filename] = reply->readAll();
  }

#ifdef HAVE_QCA
  // Load the public key
  QCA::ConvertResult conversion_result;
  QCA::PublicKey key = QCA::PublicKey::fromPEMFile(
      ":/clementine-spotify-public.pem", &conversion_result);
  if (QCA::ConvertGood != conversion_result) {
    ShowError("Failed to load Spotify public key");
    return;
  }

  // Verify signatures
  for (const QString& signature_filename : signature_filenames) {
    QString actual_filename = signature_filename;
    actual_filename.remove(kSignatureSuffix);

    qLog(Debug) << "Verifying" << actual_filename << "against"
                << signature_filename;

    if (!key.verifyMessage(file_data[actual_filename],
                           file_data[signature_filename], QCA::EMSA3_SHA1)) {
      ShowError("Invalid signature: " + actual_filename);
      return;
    }
  }
#endif  // HAVE_QCA

  // Make the destination directory and write the files into it
  QDir().mkpath(path_);

  for (const QString& filename : file_data.keys()) {
    const QString dest_path = path_ + "/" + filename;

    if (filename.endsWith(kSignatureSuffix)) continue;

    qLog(Info) << "Writing" << dest_path;

    QFile file(dest_path);
    if (!file.open(QIODevice::WriteOnly)) {
      ShowError("Failed to open " + dest_path + " for writing");
      return;
    }

    file.write(file_data[filename]);
    file.close();
    file.setPermissions(QFile::Permissions(0x7755));

#ifdef Q_OS_UNIX
    const int so_pos = filename.lastIndexOf(".so.");
    if (so_pos != -1) {
      QString link_path = path_ + "/" + filename.left(so_pos + 3);
      QStringList version_parts = filename.mid(so_pos + 4).split('.');

      while (!version_parts.isEmpty()) {
        qLog(Debug) << "Linking" << dest_path << "to" << link_path;
        int ret = symlink(dest_path.toLocal8Bit().constData(),
                          link_path.toLocal8Bit().constData());

        if (ret != 0) {
          qLog(Warning) << "Creating symlink failed with return code" << ret;
        }

        link_path += "." + version_parts.takeFirst();
      }
    }
#endif  // Q_OS_UNIX
  }

  EmitFinished();
}
示例#2
0
/*!
 * \brief Handle doc translation
 */
void Translator::fileTranslate(QString filePath)
{

    QDir outputDocDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    QString dirName = tr("Apertium Translated Documents");
    outputDocDir.mkdir(dirName);
    if (!outputDocDir.cd(dirName)) {
        emit fileTranslateRejected();
        return;
    }
    QFileInfo fileInfo(filePath);
#ifdef Q_OS_LINUX
    auto multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                       QVariant("form-data; filename=\"" + fileInfo.fileName() + "\"; name=\"file\""));
    auto file = new QFile(filePath);
    if (!file->open(QIODevice::ReadOnly)) {
        emit fileTranslateRejected();
        return;
    }
    filePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(filePart);

    QUrlQuery query;
    query.addQueryItem("langpair",
                       parent->getCurrentSourceLang() + "|" + parent->getCurrentTargetLang());
    QUrl url("http://localhost:2737/translateDoc?");
    QNetworkRequest request(QUrl(url.url() + query.query()));
    QNetworkAccessManager mngr;
    QEventLoop loop;
    QNetworkReply *reply = mngr.post(request, multiPart);
    connect(reply, &QNetworkReply::finished, [&]() {
        loop.exit();
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << reply->errorString();
            emit fileTranslateRejected();
            return;
        }
        QFile outDoc(outputDocDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                   parent->getCurrentSourceLang()
                                                   + "-" + parent->getCurrentTargetLang() + "." + fileInfo.completeSuffix()));
        if (!outDoc.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            emit fileTranslateRejected();
            reply->deleteLater();
            return;
        }
        outDoc.write(reply->readAll());
        outDoc.close();
        emit fileTranslated(outDoc.fileName());
        reply->deleteLater();
    });
    loop.exec();
#else
    if (fileInfo.suffix() == "txt")
        translateTxt(filePath, outputDocDir);
    else if (fileInfo.suffix() == "docx")
        translateDocx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "pptx")
        translatePptx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "xlsx")
        translateXlsx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "html")
        translateHtml(filePath, outputDocDir);
    else if (fileInfo.suffix() == "rtf")
        translateRtf(filePath, outputDocDir);
#endif
}
示例#3
0
void MainWindow::on_downloadElevationButton_clicked()
{

    double latMin = ui->minLatField->text().toDouble();
    double latMax = ui->maxLatField->text().toDouble();
    double lonMin = ui->minLonField->text().toDouble();
    double lonMax = ui->maxLonField->text().toDouble();

    QString tileLat;
    QString tileLon;

    // reset progress bar
    ui->downloadElevationProgressBar->setValue(0);
    double totalDouble = (latMax-latMin)*(lonMax-lonMin);
    QString totalString;
    totalString.sprintf("%.0f", totalDouble);
    int totalTiles = totalString.toInt();
    if (totalTiles == 0)
        totalTiles = 1;
    ui->downloadElevationProgressBar->setMaximum(totalTiles);

    // disable button during download
    ui->downloadElevationButton->setEnabled(0);

    QString sourceElev = ui->elevationSourceSelect->currentText();
    QString urlElev;
    if (sourceElev == "usgs.gov (SRTM-1)"){
        urlElev = "http://dds.cr.usgs.gov/srtm/version2_1/SRTM1/";
    } else if (sourceElev == "usgs.gov (SRTM-3)"){
        urlElev = "http://dds.cr.usgs.gov/srtm/version2_1/SRTM3/";

    }

    if (lonMin < 0)
        lonMin = lonMin - 1;
    if (lonMax < 0)
        lonMax = lonMax - 1;
    if (latMin < 0)
        latMin = latMin - 1;
    if (latMax < 0)
        latMax = latMax - 1;
    for (int lat=static_cast<int>(latMin); lat<=static_cast<int>(latMax); lat++) {
        for (int lon=static_cast<int>(lonMin); lon<=static_cast<int>(lonMax); lon++) {
            QString tile = "";
            if (lat < 0) {
                tile += "S";
            } else {
                tile += "N";
            }
            tileLat.sprintf("%02d",abs(lat));
            tile += tileLat;
            if (lon < 0) {
                tile += "W";
            } else {
                tile += "E";
            }
            tileLon.sprintf("%03d",abs(lon));
            tile += tileLon;

            QList<QString> folders;
            if (sourceElev.contains("SRTM-1")) {
                folders << "Region_01" << "Region_02" << "Region_03" << "Region_04" << "Region_05" << "Region_06" << "Region_07";
            } else {
                folders << "Africa" << "Australia" << "Eurasia" << "Islands" << "North_America" << "South_America";
            }
            int i = 0;
            bool succes = 0;
            while (!succes && i < 6) {
                QUrl url(urlElev+folders.at(i)+"/"+tile+".hgt.zip");
                QNetworkReply *reply = _manager->get(QNetworkRequest(url));
                if (reply->error()) {
                    GUILog( url.toString() + "\n", "download" );
                    succes = 1;
                }
                i++;
            }
        }
    }
}
示例#4
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;
}
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);*/
}
示例#6
0
bool autobots_toutiao::DoAction()
{
  //http://www.toutiao.com/api/comment/digg/
  QString str_url1 = "http://www.toutiao.com/api/comment/digg/";

  QUrl url1;
  url1.setUrl(str_url1);

  QList<int> remove_list;

  for(int i = 0; i <m_comment_list.size(); ++i)
  {
     QString str_id = m_comment_list[i]->text(0);
// 	QString str_d_id;
// 	if (m_id_dongtaiid.find(str_id) != m_id_dongtaiid.end())
// 	{
// 		str_d_id = m_id_dongtaiid[str_id];
// 	}
// 	else
// 	{
// 		continue;
// 	}

	 HttpParamList header_list;
	 header_list.push_back(HttpParamItem("Accept", "text/javascript, text/html, application/xml, text/xml, */*"));
	 header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	 header_list.push_back(HttpParamItem("Accept-Encoding", "deflate"));
	 header_list.push_back(HttpParamItem("Accept-Language", "zh-cn"));
	 header_list.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
	 header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
	 header_list.push_back(HttpParamItem("X-CSRFToken", m_csrf_token));
	 header_list.push_back(HttpParamItem("Host", "www.toutiao.com"));
	 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)"));
	 header_list.push_back(HttpParamItem("X-Requested-With", "XMLHttpRequest"));

    HttpParamList post_data;
    post_data.push_back(HttpParamItem("action", "digg"));
    post_data.push_back(HttpParamItem("comment_id", str_id));
	//post_data.push_back(HttpParamItem("dongtai_id", str_d_id));
    post_data.push_back(HttpParamItem("group_id", m_group_id));
	//post_data.push_back(HttpParamItem("item_id", m_item_id));

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

    QTime _t;
    _t.start();

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

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

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

    int n = statusCodeV.toInt();

    QByteArray data = reply->readAll();

    int count = 0;
    bool res = UpdateDiggCount(data, count);

    if (res)
    {
      QString ct = QString::number(count);
      m_comment_list[i]->setText(1, ct);

      int max = m_comment_list[i]->text(2).toInt();

      if (count >= max)
      {
        remove_list.push_back(i);
      }  
    }
  }
  
  for (int j = 0; j < remove_list.size(); ++j)
  {
    m_comment_list.removeAt(remove_list[j]);
  }

  return true;
}
示例#7
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;
}
示例#8
0
bool autobots_toutiao::AuthorByRenren(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://graph.renren.com/oauth/grant";

	QUrl url1(str_url1);

	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";

	HttpParamList header_list;
	//header_list.push_back(HttpParamItem("(Request-Line)",	"GET /auth/connect/?type=toutiao&platform=renren_sns HTTP/1.1"));
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list.push_back(HttpParamItem("Host", "graph.renren.com"));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//Referer	
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	HttpParamList post_data;
	QString t = QString("http://api.snssdk.com/auth/login_success/") + "&client_id=" + m_client_id;
	//post_data.push_back(HttpParamItem("authFeed","true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	//post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "touch"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", vcode));
	post_data.push_back(HttpParamItem("isNeedIcode", str_need_code));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", password));
	post_data.push_back(HttpParamItem("porigin", "80103"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", t));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", m_state_id));
	post_data.push_back(HttpParamItem("username", name));

	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)
	{
		reply->deleteLater();
		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();

		int r = ProcessRedirectLoginGet(str);

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

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

	return res;
}
示例#9
0
void SubscribeThread::processSubscribeDanmakuResponse()
{

    QNetworkReply *reply = (QNetworkReply *)sender();
    int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
    if(reply->hasRawHeader("Location")){
        QString strLocation = reply->header(QNetworkRequest::LocationHeader).toString();

        this->subscribeDanmaku(strLocation);

    }else if(statusCode == 200){

        QByteArray responseData = reply->readAll();
//        qDebug()<<"response data:"<<responseData;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        if(jsonDoc.isNull() ||!jsonDoc.isArray())
        {//  null or not array format
            goto out;
        }
        QJsonArray jsonArray = jsonDoc.array();
        for(int i = 0; i < jsonArray.count();i++){
            QJsonValue jsonValue = jsonArray[i];
            if(jsonValue.isUndefined()||jsonValue.isNull())
            {
                goto out;
            }
            QString text = jsonValue.toObject().value("text").toString();
            QString position = jsonValue.toObject().value("position").toString();
            QString style = jsonValue.toObject().value("style").toString();


            if(text.size()>128){
                text.resize(128);
            }
            Danmaku_Msg msg;
            msg.msg = text;
            if(style=="blue"){
                msg.color = QColor("#0000FF");
            }else if(style=="white"){
                msg.color = QColor("#FFFFFF");
            }else if(style=="red"){
                msg.color = QColor("#FF0000");
            }else if(style=="yellow"){
                msg.color = QColor("yellow");
            }else if(style=="cyan"){
                msg.color = QColor("cyan");
            }else if(style=="green"){
                msg.color = QColor("#00FF00");
            }else if(style=="purple"){
                msg.color = QColor("#871F78");
            }else{
                msg.color = QColor("black");
            }



            if(position=="top"){
                msg.positon = BULLET_TOP;
            }else if(position == "bottom")
            {
                msg.positon = BULLET_BOTTOM;
            }else
            {
                msg.positon = BULLET_FLY;
            }

            emit this->receivedDamanku(msg);
        }
    }
out:
    qApp->processEvents(QEventLoop::AllEvents);
    if(reply->error() == QNetworkReply::NoError){
        this->pullDanmaku();
    }else
    {
        QTimer::singleShot(2000,this,SLOT(pullDanmaku()));
    }
    reply->deleteLater();
    return;
}
示例#10
0
bool autobots_toutiao::NeedValidateCode(const QString& name, QString& vcode, QString& code_sign)
{
	QString str_url1 = "http://graph.renren.com/icode/check";

	QUrl url1(str_url1);
	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";
	HttpParamList header_list;
	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"));
	header_list.push_back(HttpParamItem("Host", "graph.renren.com"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//network.GetManager().setCookieJar(new QNetworkCookieJar(this));

	HttpParamList post_data;
	post_data.push_back(HttpParamItem("authFeed", "true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "page"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", ""));
	post_data.push_back(HttpParamItem("isNeedIcode", ""));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", ""));
	post_data.push_back(HttpParamItem("porigin", "80100"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", "http://api.snssdk.com/auth/login_success/"));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", "renren_sns__0____toutiao____2__0__24"));
	post_data.push_back(HttpParamItem("username", name));

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

	QTime _t;
	_t.start();

	bool _timeout = false;

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

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

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

	int n = statusCodeV.toInt();

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

	QString str = reply->readAll();

	reply->deleteLater();

	if (str.toInt() == 0)
	{
		return false;
	}

	// 获取验证码

	QUrl url2("http://icode.renren.com/getcode.do?t=openplatform");
	HttpParamList header_list2;
	header_list2.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//  header_list2.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
	header_list2.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list2.push_back(HttpParamItem("Host", "icode.renren.com"));
	header_list2.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list2.push_back(HttpParamItem("Referer", str_temp));

	QNetworkReply* reply2 = network.GetRequest(url2, header_list2);

	_t.restart();

	_timeout = false;

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

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

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

	n = statusCodeV.toInt();

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

	QByteArray data = reply2->readAll();

	QImage image_ = QImage::fromData(data);//(data.data(),100,40,QImage::Format_RGB32);

	if (m_code_online)
	{
		// 在线验证
		//bool result = image_.save("e:\\1.jpg");
		VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
		int res = obj->GetRecResults(data, "bestsalt", "hh610520;;", "bestsalt", vcode, code_sign);
	}
	else
	{
		// 手动验证
		ValidateDlg dlg(this, image_);
		if (dlg.exec() == QDialog::Accepted)
		{
			vcode = dlg.getCode();
		}
	}

	return true;
}
示例#11
0
bool autobots_toutiao::DoSupport()
{

	for (size_t i = 0; i < m_comment_list.size(); i++)
	{
		QString str_url1 = QString("http://isub.snssdk.com/2/relation/follow/v2/?ab_client=a1%2Cf2%2Cf7%2Ce1&ab_feature=z2&ab_group=z2&ab_version=112577%2C101786%2C112146%2C111547%2C101533%2C109464%2C110341%2C109891%2C112474%2C112070%2C106784%2C97142%2C31646%2C111339%2C101605%2C101558%2C112164%2C94046%2C112403%2C112532%2C105610%2C112343%2C105822%2C112578%2C108978%2C111796%2C108489%2C111897%2C110795%2C98042%2C105475&ac=WIFI&aid=13&app_name=news_article&channel=App%20Store&device_id=3135986566&device_platform=iphone&device_type=iPhone%206&idfa=86E011D2-C2DA-40CB-AB9D-DB1E1F9D668A&idfv=674FB6B1-60E9-4315-88FC-AAC84BEFAB46&iid=7730017535&live_sdk_version=1.6.5&new_reason=0&new_source=25&openudid=0d919477efbefb99dfe7a02a2df34d9127ecc947&os_version=9.3.5&resolution=750%2A1334&ssmix=a&user_id=51817712863&version_code=6.0.1&vid=674FB6B1-60E9-4315-88FC-AAC84BEFAB46")
			.arg(m_comment_list[i]);

		QUrl url1;
		url1.setUrl(str_url1);

		HttpParamList header_list;
		header_list.push_back(HttpParamItem("Accept", "*/*"));
		//header_list.push_back(HttpParamItem("Proxy - Connection", "Keep-Alive"));
		header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
		//  header_list.push_back(HttpParamItem("Accept-Encoding","deflate"));
		header_list.push_back(HttpParamItem("Accept-Language", "zh-cn"));
		header_list.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
		header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
		//header_list.push_back(HttpParamItem("X-CSRFToken", m_csrf_token));
		header_list.push_back(HttpParamItem("Host", "isub.snssdk.com"));
		//header_list.push_back(HttpParamItem("Referer", m_url));
		header_list.push_back(HttpParamItem("tt-request-time", GetTimeStr()));
		//header_list.push_back(HttpParamItem("User-Agent", "News/5.8.3 (iPhone; iOS 9.3.5; Scale/2.00)"));
		header_list.push_back(HttpParamItem("User-Agent", "News/6.0.1 (iPhone; iOS 9.3.5; Scale/2.00)"));

		//HttpParamList post_data;
		//post_data.push_back(HttpParamItem("thread_id", m_group_id));

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

		QTime _t;
		_t.start();

		bool _timeout = false;

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

		if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
		{
			QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
			int n = statusCodeV.toInt();
			QString ss = reply->errorString();
			ui.lineEdit_msg->setText(ss);
			reply->deleteLater();
			//return false;
			continue;
		}

		QByteArray rp_data = reply->readAll();

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

		QString type = content_type.toString();

		if (type.contains("json"))
		{
			//bool res = GetSupportStatus(rp_data);
			//return res;
			if (rp_data.contains("success"))
			{
				ui.lineEdit_msg->setText(QStringLiteral("操作成功"));
			}
		}
		else
		{
			ui.lineEdit_msg->setText(QStringLiteral("操作失败"));
		}
	}
	return true;
}
示例#12
0
void Twitter::onDataReceived()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    QString response;
    bool success = false;
    if (reply)
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            int available = reply->bytesAvailable();
            if (available > 0)
            {
                int bufSize = sizeof(char) * available + sizeof(char);
                QByteArray buffer(bufSize, 0);
                reply->read(buffer.data(), available);
                response = QString(buffer);
                success = true;
            }
        }
        else
        {
            response =  QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
            emit tweetParseComplete(false, "We can't connect to the internet");
        }
        reply->deleteLater();
    }
    if (success )
    {
    	if (response != "[]") {
    		bb::data::JsonDataAccess jda;
    		QVariant jsonva = jda.loadFromBuffer(response);
    		QVariantMap map = jsonva.toMap();
    		QVariantList results = map.value("results").toList();
    		//okay let's get the news items

    		int numTweets = 0;
    		foreach (QVariant v, results) {
    			QVariantMap map = v.toMap();

    			Tweet *tweet = new Tweet();
    			tweet->parse(v);

    			QVariant q = QVariant::fromValue(tweet);

        		_tweetList.append(q); //to go from a QVariant back to a Tweet* item: Tweet *Tweet = q.value<Tweet*>();

    			QVariantList path;
				path.append(_tweetList.indexOf(q));

				emit  itemAdded (path);
				numTweets++;
    		}

        	if (numTweets > 0) {
        		emit tweetParseComplete(true, "Parsed successfully");
        	} else {
        		if (_tweetList.count() == 0) {
        			emit tweetParseComplete(false, "No Tweets yet");
        		}
        	}
    	}
示例#13
0
void PomfUploader::upload(const QString &fileName)
{
    QString pomfUrl = mSettings["pomf_url"].toString();

    if (pomfUrl.isEmpty()) {
        emit error(ImageUploader::HostError, tr("Invalid pomf uploader URL!"), fileName);
        return;
    }

    QUrl url = QUrl::fromUserInput(pomfUrl + "/upload.php");

    QFile *file = new QFile(fileName);

    if (!file->open(QIODevice::ReadOnly)) {
        emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName);
        file->deleteLater();
        return;
    }

    QNetworkRequest request(url);

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

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name());
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"files[]\"; filename=\"%1\"").arg(QFileInfo(fileName).fileName()));
    imagePart.setBodyDevice(file);

    file->setParent(multiPart);
    multiPart->append(imagePart);

    QNetworkReply *reply = Uploader::network()->post(request, multiPart);
    this->setProperty("fileName", fileName);
    multiPart->setParent(reply);

    connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::abort);
    connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::deleteLater);

    connect(reply, &QNetworkReply::uploadProgress, this, [&](qint64 bytesSent, qint64 bytesTotal) {
        float b = (float) bytesSent / bytesTotal;
        int p = qRound(b * 100);
        setProgress(p);
    });

    connect(reply, &QNetworkReply::finished, this, [&, reply, fileName] {
        const QJsonObject pomfResponse = QJsonDocument::fromJson(reply->readAll()).object();

        if (reply->error() != QNetworkReply::NoError && pomfResponse.isEmpty()) {
            emit error(ImageUploader::NetworkError, tr("Error reaching uploader"), fileName);
            return;
        }

        if (!pomfResponse.contains("success") || !pomfResponse.contains("files")) {
            emit error(ImageUploader::HostError, tr("Invalid response from uploader"), fileName);
            return;
        }

        if (pomfResponse["success"].toBool()) {
            emit uploaded(fileName, pomfResponse["files"].toArray().at(0).toObject()["url"].toString(), "");
        } else {
            QString description;

            if (pomfResponse.contains("description")) {
                description = pomfResponse["description"].toString();
            }

            if (description.isEmpty()) {
                description = tr("Host error");
            }

            emit error(ImageUploader::HostError, description, fileName);
        }
    });

    connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        if (QSysInfo::WindowsVersion == QSysInfo::WV_XP) {
            reply->ignoreSslErrors();
        }
    });
}
示例#14
0
void FvUpdater::httpUpdateDownloadFinished()
{
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	if(reply==NULL)
	{
		qWarning()<<"The slot httpUpdateDownloadFinished() should only be invoked by S&S.";
		return;
	}

	if(reply->error() == QNetworkReply::NoError)
	{
		int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();

		// no error received?
		if (reply->error() == QNetworkReply::NoError)
		{
			if (reply->isReadable())
			{
#ifdef Q_OS_MAC
                CFURLRef appURLRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
                char path[PATH_MAX];
                if (!CFURLGetFileSystemRepresentation(appURLRef, TRUE, (UInt8 *)path, PATH_MAX)) {
                    // error!
                }

                CFRelease(appURLRef);
                QString filePath = QString(path);
                QString rootDirectory = filePath.left(filePath.lastIndexOf("/"));
#else
                QString rootDirectory = QCoreApplication::applicationDirPath() + "/";
#endif
                
				// Write download into File
				QFileInfo fileInfo=reply->url().path();
				QString fileName = rootDirectory + fileInfo.fileName();
				//qDebug()<<"Writing downloaded file into "<<fileName;
	
				QFile file(fileName);
				file.open(QIODevice::WriteOnly);
				file.write(reply->readAll());
				file.close();

				// Retrieve List of updated files (Placed in an extra scope to avoid QuaZIP handles the archive permanently and thus avoids the deletion.)
				{	
					QuaZip zip(fileName);
					if (!zip.open(QuaZip::mdUnzip)) {
						qWarning("testRead(): zip.open(): %d", zip.getZipError());
						return;
					}
					zip.setFileNameCodec("IBM866");
					QList<QuaZipFileInfo> updateFiles = zip.getFileInfoList();
		
					// Rename all current files with available update.
					for (int i=0;i<updateFiles.size();i++)
					{
						QString sourceFilePath = rootDirectory + "\\" + updateFiles[i].name;
						QDir appDir( QCoreApplication::applicationDirPath() );

						QFileInfo file(	sourceFilePath );
						if(file.exists())
						{
							//qDebug()<<tr("Moving file %1 to %2").arg(sourceFilePath).arg(sourceFilePath+".oldversion");
							appDir.rename( sourceFilePath, sourceFilePath+".oldversion" );
						}
					}
				}

				// Install updated Files
				unzipUpdate(fileName, rootDirectory);

				// Delete update archive
                while(QFile::remove(fileName) )
                {
                };

				// Restart ap to clean up and start usual business
				restartApplication();

			}
			else qDebug()<<"Error: QNetworkReply is not readable!";
		}
		else 
		{
			qDebug()<<"Download errors ocurred! HTTP Error Code:"<<httpstatuscode;
		}

		reply->deleteLater();
    }	// If !reply->error END
}	// httpUpdateDownloadFinished END
示例#15
0
// 0 正常,-1 未知错误, -2 验证码错误
int autobots_toutiao::ProcessRedirectLoginGetTemp(const QString& str)
{
  WaitforSeconds(2);

  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("Referer","http://graph.renren.com/oauth/grant?client_id=394e2173327e4ead8302dc27f4ae8879&redirect_uri=http%3A%2F%2Fapi.snssdk.com%2Fauth%2Flogin_success%2F&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000"));
  //header_list.push_back(HttpParamItem("",""));
  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 || _timeout)
  {
   
    reply->deleteLater();
    return -1;
  }

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

  if ((reply->error() != QNetworkReply::NoError) && n != 500)
  {
     QString t = reply->errorString();
     return -1;
  }
  
  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 = ProcessRedirectLoginGetTemp2(str);
  }

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

  return res;
}
示例#16
0
	// The QHttp object retrieved data.
	void Service::slotRequestFinished()
	{
		QNetworkReply * reply = qobject_cast<QNetworkReply *>(sender());

		qDebug() << "UPnP::Service: received HTTP response for request " << endl;

		if(!reply)
		{
			qWarning() << "UPnP::Service - HTTP Request failed: " << reply->errorString() << endl;
			m_iPendingRequests--;
			emit queryFinished(true);
			return;
		}

		if(reply->error() != QNetworkReply::NoError)
		{
			qWarning() << "UPnP::Service - HTTP Request failed: " << reply->errorString() << endl;
			m_iPendingRequests--;
			emit queryFinished(true);
			reply->deleteLater();
			return;
		}

		// Get the XML content
		QByteArray response = reply->readAll();
		QDomDocument xml;

		qDebug() << "Response:\n"
		         << response << "\n---\n";

		// Parse the XML
		QString errorMessage;
		bool error = !xml.setContent(response, false, &errorMessage);

		if(!error)
		{
			QString baseNamespace = xml.documentElement().tagName();

			if(baseNamespace.length() > 0)
			{
				int cutAt = baseNamespace.indexOf(':');
				if(cutAt > -1)
				{
					baseNamespace.truncate(cutAt);
					qDebug() << "Device is using " << baseNamespace << " as XML namespace" << endl;
					m_szBaseXmlPrefix = baseNamespace;
				}
			}

			// Determine how to process the data
			if(xml.namedItem(m_szBaseXmlPrefix + ":Envelope").isNull())
			{
				qDebug() << "UPnP::Service: plain XML detected, calling gotInformationResponse()." << endl;
				// No SOAP envelope found, this is a normal response to callService()
				gotInformationResponse(xml.lastChild());
			}
			else
			{
				qDebug() << xml.toString() << endl;
				// Got a SOAP message response to callAction()
				QDomNode resultNode = XmlFunctions::getNode(xml, "/" + m_szBaseXmlPrefix + ":Envelope/" + m_szBaseXmlPrefix + ":Body").firstChild();

				error = (resultNode.nodeName() == m_szBaseXmlPrefix + ":Fault");

				if(!error)
				{
					if(resultNode.nodeName().startsWith("m:") || resultNode.nodeName().startsWith("u:"))
					{
						qDebug() << "UPnP::Service: SOAP envelope detected, calling gotActionResponse()." << endl;
						// Action success, return SOAP body
						QMap<QString, QString> resultValues;

						// Parse all parameters
						// It's possible to pass the entire QDomNode object to the gotActionResponse()
						// function, but this is somewhat nicer, and reduces code boat in the subclasses
						QDomNodeList children = resultNode.childNodes();
						for(int i = 0; i < children.count(); i++)
						{
							QString key = children.item(i).nodeName();
							resultValues[key] = children.item(i).toElement().text();
						}

						// Call the gotActionResponse()
						gotActionResponse(resultNode.nodeName().mid(2), resultValues);
					}
				}
				else
				{
					qDebug() << "UPnP::Service: SOAP error detected, calling gotActionResponse()." << endl;

					// Action failed
					gotActionErrorResponse(resultNode);
				}
			}
		}
		else
		{
			qWarning() << "UPnP::Service - XML parsing failed: " << errorMessage << endl;
		}

		// Only emit when bytes>0
		m_iPendingRequests--;
		emit queryFinished(error);
	}
示例#17
0
int autobots_toutiao::ProcessRedirectLoginGetTemp2(const QString& str)
{
  //http://api.snssdk.com/auth/login_success/?code=vM988uwAJr91qLN7Yh4tKCxw4alqNDDz&state=renren_sns__0____toutiao____2__0__24
  int pos1 = str.indexOf("code=");
  int pos2 = str.indexOf("&",pos1);
  QString t = str.mid(pos1, pos2-pos1);
  QString s_url = "http://toutiao.com/auth/connected/?state=renren_sns__0____toutiao____2__0__24&" + t;

  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","toutiao.com"));
  //header_list.push_back(HttpParamItem("Referer","http://graph.renren.com/oauth/grant?client_id=394e2173327e4ead8302dc27f4ae8879&redirect_uri=http%3A%2F%2Fapi.snssdk.com%2Fauth%2Flogin_success%2F&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000"));
  //header_list.push_back(HttpParamItem("",""));
  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(s_url), 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 || _timeout )
  {
   
    reply->deleteLater();
    return -1;
  }

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

  if ((reply->error() != QNetworkReply::NoError) && n != 500)
  {
     QString temp = reply->errorString();
     return -1;
  }
  
  int res = -1;

  if (n != 200)
  {
    return -1;
  }

  QByteArray data = reply->readAll();

  QString temp_s = data;
  if (temp_s.contains("window.opener.user.connected") 
    || temp_s.contains("window.parent.user.connected") )
  {
    return 0;
  }


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

  return res;
}
示例#18
0
bool auto_dirvers_fatie::getCode(QString& vcode, QString& code_sign)
{
	int n = rand() % 9;
	double d = 0.987654321235647 / n;
	QString str_r = QString::number(d, 'f', 17);


	QString str_url = "http://passport.mydrivers.com/modules/yanzhengma.aspx?" + str_r;

	QUrl url1;
	url1.setUrl(str_url);

	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "image/webp,image/*,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//header_list.push_back(HttpParamItem("Accept-Encoding", "deflate"));
	header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
	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("DNT", "1"));
	header_list.push_back(HttpParamItem("Host", "passport.mydrivers.com"));
	header_list.push_back(HttpParamItem("Referer", "http://www.mydrivers.com/"));
	header_list.push_back(HttpParamItem("User-Agent", S_UA));

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

	bool _timeout = false;

	QTime _t;
	_t.start();

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

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

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

	int status = statusCodeV.toInt();

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

	QByteArray rp_data = reply->readAll();
	reply->deleteLater();
	//   QVariant var = reply2->header(QNetworkRequest::ContentTypeHeader);
	// 
	//   QString type = var.toString();

	
		// 在线验证

	
#ifdef _DEBUG
	QImage image_ = QImage::fromData(rp_data);//(data.data(),100,40,QImage::Format_RGB32);
	image_.save("e:\\1.jpg");
#endif
	
	VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
	int res = obj->GetRecResults(rp_data, "bestsalt", "hh610520;;", "bestsalt", vcode, code_sign);

	if (res==0 && !vcode.isEmpty())
	{
		return true;
	}
	//obj->ReportError("bestsalt", code_sign); 
	return false;
}
示例#19
0
bool autobots_toutiao::RequestForRenren()
{
  QString str_url1 = "http://www.toutiao.com/auth/connect/?type=toutiao&platform=renren_sns";

  QUrl url1(str_url1);

  HttpParamList header_list;
  //header_list.push_back(HttpParamItem("(Request-Line)",	"GET /auth/connect/?type=toutiao&platform=renren_sns HTTP/1.1"));
  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"));
  header_list.push_back(HttpParamItem("Host", "www.toutiao.com"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

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

  if (reply == NULL || (reply->error() != QNetworkReply::NoError) || _timeout)
  {
	QString s =  reply->errorString();
	int n = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    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 = ProcessRedirectSSL(str);
  }
  else
  {
    res = false;
  }

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

  return res;
}
示例#20
0
bool auto_dirvers_fatie::Login(const QString& _id, const QString& _password, int depth)
{

	//1. 获取验证码
/*	QString vcode, vcode_sign;
	if (!getCode(vcode, vcode_sign))
	{
		if (!getCode(vcode, vcode_sign))
		{
			emitMsgBar(QStringLiteral("获取验证码失败"));
			return false;
		}
	}*/
    
	//2. 登录
	QString str_url = "http://passport.mydrivers.com/comments/FastCheck_Login.aspx?fr=2";

	QUrl url1;
	url1.setUrl(str_url);

	//QString post_data_str = "password="******"&username="******"&yzm=" + vcode;

	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("Cache-Control", "no-cache"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-Hans-CN;q=1"));
	header_list.push_back(HttpParamItem("Content-Type", "application/x-www-form-urlencoded"));
	header_list.push_back(HttpParamItem("Cache-Control", "no-cache"));
	//header_list.push_back(HttpParamItem("X-Requested-With", "XMLHttpRequest"));
	//header_list.push_back(HttpParamItem("DNT", "1"));
	header_list.push_back(HttpParamItem("Host", "passport.mydrivers.com"));
	//header_list.push_back(HttpParamItem("Referer", "http://www.mydrivers.com/"));
	header_list.push_back(HttpParamItem("User-Agent", S_UA));


    /*brand	iPhone
        model	6
        password	610520
        sdk	0
        sign	572098795
        skey	be8b7a235e3776bea8c7d6e0fe
        udid	5507240564344282355
        username	gycsjf123
        version	3 % 2e0%2e6
        xaid	20ff00569e1795a434ee41a361fc98545a63313a*/

    QString s_skey = calKey(_id, _password);

	HttpParamList post_data;
	post_data.push_back(HttpParamItem("brand", "iPhone"));
	post_data.push_back(HttpParamItem("model", "6"));
	post_data.push_back(HttpParamItem("password", _password));
    post_data.push_back(HttpParamItem("sdk", "0"));
    post_data.push_back(HttpParamItem("sign", "572098795"));
    post_data.push_back(HttpParamItem("skey", s_skey));
    post_data.push_back(HttpParamItem("udid", "5507240564344282355"));
    post_data.push_back(HttpParamItem("username", _id));
    post_data.push_back(HttpParamItem("version", "3%2e0%2e6"));
    post_data.push_back(HttpParamItem("xaid", "20ff00569e1795a434ee41a361fc98545a63313a"));

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

	bool _timeout = false;

	QTime _t;
	_t.start();

	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 status = statusCodeV.toInt();

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

	QByteArray rp_data = reply->readAll();

	QString rt_msg = QString::fromLocal8Bit(rp_data);

	reply->deleteLater();

	if (rt_msg.contains("user_id"))
	{
		return true;
	}

/*	if (rt_msg.contains(QStringLiteral("验证码")))
	{
		VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
		obj->ReportError("bestsalt", vcode_sign);

		if (depth < 5)
		{
			// 控制递归深度
			return Login(_id, _password, depth++);
		}	
	}*/

	return false;
}
示例#21
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;
}
示例#22
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 mMissingSvg;
    }
  }

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

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

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

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

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

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

  return ba;
}
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);
}
示例#24
0
void UpdateManager::requestReceived()
{
	bool haveNewVersion = false;
	QMessageBox msgbox;
	QString msgTitle = tr("Check for updates.");
	QString msgText = "<h3>" + tr("Subsurface was unable to check for updates.") + "</h3>";

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
	if (reply->error() != QNetworkReply::NoError) {
		//Network Error
		msgText = msgText + "<br/><b>" + tr("The following error occurred:") + "</b><br/>" + reply->errorString()
				+ "<br/><br/><b>" + tr("Please check your internet connection.") + "</b>";
	} else {
		//No network error
		QString responseBody(reply->readAll());
		QString responseLink;
		if (responseBody.contains('"'))
			responseLink = responseBody.split("\"").at(1);

		msgbox.setIcon(QMessageBox::Information);
		if (responseBody == "OK") {
			msgText = tr("You are using the latest version of Subsurface.");
		} else if (responseBody.startsWith("[\"http")) {
			haveNewVersion = true;
			msgText = tr("A new version of Subsurface is available.<br/>Click on:<br/><a href=\"%1\">%1</a><br/> to download it.")
					.arg(responseLink);
		} else if (responseBody.startsWith("Latest version")) {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			haveNewVersion = true;
			msgText = QString("<b>") + tr("A new version of Subsurface is available.") + QString("</b><br/><br/>") +
					tr("Latest version is %1, please check %2 our download page %3 for information in how to update.")
					.arg(responseLink).arg("<a href=\"http://subsurface-divelog.org/download\">").arg("</a>");
		} else {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			if (!responseBody.contains("latest development") &&
			    !responseBody.contains("newer") &&
			    !responseBody.contains("beta", Qt::CaseInsensitive))
				haveNewVersion = true;
			if (responseBody.contains("Newest release version is "))
				responseBody.replace("Newest release version is ", tr("Newest release version is "));
			msgText = tr("The server returned the following information:").append("<br/><br/>").append(responseBody);
			msgbox.setIcon(QMessageBox::Warning);
		}
	}
#ifndef SUBSURFACE_MOBILE
	if (haveNewVersion || !isAutomaticCheck) {
		msgbox.setWindowTitle(msgTitle);
		msgbox.setWindowIcon(QIcon(":/subsurface-icon"));
		msgbox.setText(msgText);
		msgbox.setTextFormat(Qt::RichText);
		msgbox.exec();
	}
	if (isAutomaticCheck) {
		QSettings settings;
		settings.beginGroup("UpdateManager");
		if (!settings.contains("DontCheckForUpdates")) {
			// we allow an opt out of future checks
			QMessageBox response(MainWindow::instance());
			QString message = tr("Subsurface is checking every two weeks if a new version is available. If you don't want Subsurface to continue checking, please click Decline.");
			response.addButton(tr("Decline"), QMessageBox::RejectRole);
			response.addButton(tr("Accept"), QMessageBox::AcceptRole);
			response.setText(message);
			response.setWindowTitle(tr("Automatic check for updates"));
			response.setIcon(QMessageBox::Question);
			response.setWindowModality(Qt::WindowModal);
			int ret = response.exec();
			if (ret == QMessageBox::Accepted)
				settings.setValue("DontCheckForUpdates", "FALSE");
			else
				settings.setValue("DontCheckForUpdates", "TRUE");
		}
	}
#endif
}
示例#25
0
    void UrlFactory::TryCorrectGoogleVersions()
    {
        QMutexLocker locker(&mutex);
        if(CorrectGoogleVersions && !IsCorrectGoogleVersions())
        {
            QNetworkReply *reply;
            QNetworkRequest qheader;
            QNetworkAccessManager network;
            QEventLoop q;
            QTimer tT;
            tT.setSingleShot(true);
            connect(&network, SIGNAL(finished(QNetworkReply*)),
                    &q, SLOT(quit()));
            connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
            network.setProxy(Proxy);
#ifdef DEBUG_URLFACTORY
            qDebug()<<"Correct GoogleVersion";
#endif //DEBUG_URLFACTORY
            setIsCorrectGoogleVersions(true);
            QString url = "https://maps.google.com";

            qheader.setUrl(QUrl(url));
            qheader.setRawHeader("User-Agent",UserAgent);
            reply=network.get(qheader);
            tT.start(Timeout);
            q.exec();
            if(!tT.isActive())
                return;
            tT.stop();
            if( (reply->error()!=QNetworkReply::NoError))
            {
#ifdef DEBUG_URLFACTORY
                qDebug()<<"Try corrected version withou abort or error:"<<reply->errorString();
#endif //DEBUG_URLFACTORY
                return;
            }
            QString html=QString(reply->readAll());
            QRegExp reg("\"*https://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleMap = QString("m@%1").arg(gc[1]);
                VersionGoogleMapChina = VersionGoogleMap;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap;
#endif //DEBUG_URLFACTORY
            }

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

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

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

        }
示例#26
0
    void httpFinished() {
        DEBUG("httpFinished()");
        QVariant redirectionTarget = qreply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (!redirectionTarget.isNull())
        {
            QUrl newUrl = url.resolved(redirectionTarget.toUrl());
            DEBUG("Handled redirect to: " << newUrl.toString());
            qreply->deleteLater();
            qreply = nullptr;
            doOperation(newUrl);
            return;
        }
        else if (qreply->error())
        {
            WARN("HTTP ERROR:" << qreply->error() << qreply->errorString());

            httpStatus = HTTPInvocationDefinition::UNDEFINED;
            invocationStatus = Invocation::ERROR;
            result << InvocationErrors::CONNECTION_FAILED
                   << Result::Meta("qnetworkreply_error_string", qreply->errorString())
                   << Result::Meta("qnetworkreply_error_number", qreply->error());

            QNetworkReply::NetworkError err = qreply->error();
            result << NetworkErrorReasons::from(err, qreply->errorString());

            // get possible return data
            replyData = qreply->readAll();
            if (!replyData.isEmpty())
                result << Result::Meta("response_data", replyData);

            emit q->finishedError(q);
        }
        else
        {
            // we have data
            replyData = qreply->readAll();
            QVariant statusCode = qreply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
            if (statusCode.isValid())
            {
                // TODO: handle more codes!
                switch (statusCode.toInt())
                {
                case 200:
                    httpStatus = HTTPInvocationDefinition::OK_200;
                    break;
                default:
                    httpStatus = HTTPInvocationDefinition::UNDEFINED;
                }
            } else {
                result << InvocationErrors::INVOCATION_FAILED
                       << Result::reasonFromDesc("Invalid http status code");
            }

            invocationStatus = Invocation::RESPONSE_RECEIVED;
            TRACE("DATA:" << replyData);
            emit q->finishedOK(q);
        }

        qreply->deleteLater();
        qreply = nullptr;
    }
示例#27
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();
}
示例#28
0
bool autobots_toutiao::NeedValidateCode(const QString& name, QString& vcode, QString& code_sign)
{
  QString str_url1 = "https://sso.toutiao.com/login/";

  QUrl url1(str_url1);
  HttpParamList header_list;
  header_list.push_back(HttpParamItem("Accept", "text/html, application/xhtml+xml, */*"));
  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"));
  header_list.push_back(HttpParamItem("Host", "sso.toutiao.com"));
  header_list.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
//  header_list.push_back(HttpParamItem("Referer",str_temp));

//   HttpParamList post_data;
//   post_data.push_back(HttpParamItem("authFeed","true"));
//   post_data.push_back(HttpParamItem("authorizeOrigin","00000"));
//   post_data.push_back(HttpParamItem("client_id", m_client_id));
//   post_data.push_back(HttpParamItem("display","page"));
//   post_data.push_back(HttpParamItem("follow","true"));
//   post_data.push_back(HttpParamItem("icode",""));
//   post_data.push_back(HttpParamItem("isNeedIcode",""));
//   post_data.push_back(HttpParamItem("login_type","false"));
//   post_data.push_back(HttpParamItem("password",""));
//   post_data.push_back(HttpParamItem("porigin","80100"));
//   post_data.push_back(HttpParamItem("post_form_id", m_post_id));
//   post_data.push_back(HttpParamItem("redirect_uri","http://api.snssdk.com/auth/login_success/"));
//   post_data.push_back(HttpParamItem("response_type","code"));
//   post_data.push_back(HttpParamItem("scope","status_update photo_upload create_album"));
//   post_data.push_back(HttpParamItem("secure","true"));
//   post_data.push_back(HttpParamItem("state","renren_sns__0____toutiao____2__0__24"));
//   post_data.push_back(HttpParamItem("username",name));

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

  QTime _t;
  _t.start();

  bool _timeout = false;

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

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

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

  int n = statusCodeV.toInt();

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

  QByteArray data = reply->readAll();

  bool res = GetValidateCode(data, vcode, code_sign);

  reply->deleteLater();

  return res;

  // 获取验证码
//    QUrl url2("http://icode.renren.com/getcode.do?t=openplatform");
//    HttpParamList header_list2;
//    header_list2.push_back(HttpParamItem("Connection","Keep-Alive"));
//    header_list2.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
//    header_list2.push_back(HttpParamItem("Accept-Language","zh-CN"));
//    header_list2.push_back(HttpParamItem("Host", "icode.renren.com"));
//    header_list2.push_back(HttpParamItem("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"));
// //   header_list2.push_back(HttpParamItem("Referer",str_temp));
//  
//    QNetworkReply* reply2 = network->GetRequest(url2, header_list2);
//  
//    _t.restart();
//  
//    _timeout = false;
//  
//    while (reply2 && !reply2->isFinished())
//    {
//      QCoreApplication::processEvents();
//      if (_t.elapsed() >= TIMEOUT) {
//        _timeout = true;
//        break;
//      }
//    }
//  
//    if (reply2 == NULL || (reply2->error() != QNetworkReply::NoError) || _timeout)
//    {
//      return false;
//    }
//  
//    if (n != 200)
//    {
//      return false;
//    }
//  
//    QByteArray data = reply2->readAll();
//  
//    QImage image_ = QImage::fromData(data);//(data.data(),100,40,QImage::Format_RGB32);
// 
//    if (m_code_online)
//    {
//      // 在线验证
//      //bool result = image_.save("e:\\1.jpg");
//      VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
//      int res = obj->GetRecResults(data, "bestsalt", "hh610520;;", "bestsalt", vcode, code_sign);
//    }
//    else
//    {
//      // 手动验证
//      ValidateDlg dlg(this, image_);
//      if (dlg.exec() == QDialog::Accepted)
//      {
//        vcode = dlg.getCode();
//      }
//    }

/*  return true;*/
}
示例#29
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); 
 
}
void QBNetwork::onRequestUsers() {
	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);

				QFile destFile("app/native/assets/users.json");
				if (!destFile.open(QIODevice::WriteOnly))
					return;
				destFile.write(response.toAscii());
				destFile.close();

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "user") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "id") {
									break;
								}
							}
						}
					}
				}

				successLoad = true;
				emit loadingChanged();
				emit completeLogin();

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