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

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

			mManifestJson.write((const char *)mBuffer, old_avail_out - mZstream.avail_out);
			mZstream.avail_out = mBufferSize;
			mZstream.next_out = mBuffer;
			Q_ASSERT(mZstream.avail_in == 0);
		}
		else
		{
			reply->abort();
			info.critical(tr("Manifest"), tr("Error while getting manifest (1).\n%1").arg(reply->errorString()));
		}
	}
}
    void DownloadManager::stopDownloadImpl( QString const & url, bool pause )
    {
        QNetworkReply *reply = m_urlHash[url];

        if( reply ) {
            QObject::disconnect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( downloadProgress( qint64, qint64 )));
            QObject::disconnect( reply, SIGNAL( finished() ), this, SLOT( downloadFinished() ));
            QObject::disconnect( reply, SIGNAL( readyRead() ), this, SLOT( downloadReadyRead() ) );
            QObject::disconnect( reply, SIGNAL( error( QNetworkReply::NetworkError )), this, SLOT( downloadError( QNetworkReply::NetworkError )));

            Downloads item = m_downloadHash[ reply ];
            reply->abort();
            if( !item.m_file) return;

            item.m_file->write( reply->readAll() );
            item.m_file->close();

            if ( !pause ) {
                QFile::remove( item.m_tempFile );
            }

            m_downloadHash.remove( reply );
            m_urlHash.remove( url );
            startNextDownload();

            reply->deleteLater();
        }
    }
Beispiel #3
0
void WebLoadManager::onMeta() {
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	if (!reply) return;

	Replies::iterator j = _replies.find(reply);
	if (j == _replies.cend()) { // handled already
		return;
	}
	webFileLoaderPrivate *loader = j.value();

	typedef QList<QNetworkReply::RawHeaderPair> Pairs;
	Pairs pairs = reply->rawHeaderPairs();
	for (Pairs::iterator i = pairs.begin(), e = pairs.end(); i != e; ++i) {
		if (QString::fromUtf8(i->first).toLower() == "content-range") {
			QRegularExpressionMatch m = QRegularExpression(qsl("/(\\d+)([^\\d]|$)")).match(QString::fromUtf8(i->second));
			if (m.hasMatch()) {
				loader->setProgress(qMax(qint64(loader->data().size()), loader->already()), m.captured(1).toLongLong());
				if (!handleReplyResult(loader, WebReplyProcessProgress)) {
					_replies.erase(j);
					_loaders.remove(loader);
					delete loader;

					reply->abort();
					reply->deleteLater();
				}
			}
		}
	}
}
void RemoteDatabase::updateProgress(qint64 bytesTransmitted, qint64 bytesTotal)
{
    // Find out to which pending reply this progress update belongs
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender());

    // Update progress dialog
    if(bytesTotal == -1)
    {
        // We don't know anything about the current progress, but it's still downloading
        m_progress->setMinimum(0);
        m_progress->setMaximum(0);
        m_progress->setValue(0);
    } else if(bytesTransmitted == bytesTotal) {
        // The download has finished
        m_progress->reset();
    } else {
        // It's still downloading and we know the current progress

        // Were using a range 0 to 10000 here, the progress dialog will calculate 0% to 100% values from that. The reason we're not using
        // the byte counts as-is is that they're 64bit wide while the progress dialog takes only 32bit values, so for large files the values
        // would lose precision. The reason why we're not using a range 0 to 100 is that our range increases the precision a bit and this way
        // we're prepared if the progress dialog will show decimal numbers one day on one platform.
        m_progress->setMinimum(0);
        m_progress->setMaximum(10000);
        m_progress->setValue(static_cast<int>((static_cast<float>(bytesTransmitted) / static_cast<float>(bytesTotal)) * 10000.0f));
    }

    // Check if the Cancel button has been pressed
    if(reply && m_progress->wasCanceled())
    {
        reply->abort();
        m_progress->reset();
    }
}
Beispiel #5
0
QByteArray
CRestWorker::send_request(const QNetworkRequest &req,
                          bool get,
                          int& http_status_code,
                          int& err_code,
                          int &network_error,
                          bool ignore_ssl_errors) {

  if (m_network_manager->networkAccessible() != QNetworkAccessManager::Accessible) {
    CApplicationLog::Instance()->LogError("Network isn't accessible : %d", (int)m_network_manager->networkAccessible());
    m_network_manager->setNetworkAccessible(QNetworkAccessManager::Accessible);
  }

  err_code = RE_SUCCESS;
  network_error = 0;
  http_status_code = -1;

  QEventLoop loop;
  QTimer timer(&loop);
  timer.setSingleShot(true);
  timer.start(15000);

  QNetworkReply* reply =
      get ? m_network_manager->get(req) : m_network_manager->post(req, QByteArray());

  connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  if (!ignore_ssl_errors) {
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(ssl_errors_appeared(QList<QSslError>)));
  }
  else {
    QList<QSslError> errors2ignore;
    errors2ignore << QSslError(QSslError::CertificateUntrusted);
    errors2ignore << QSslError(QSslError::SelfSignedCertificate);
    errors2ignore << QSslError(QSslError::HostNameMismatch);
    reply->ignoreSslErrors();
  }

  loop.exec();

  //timer active if timeout didn't fire
  if (!timer.isActive()) {
    reply->abort();
    err_code = RE_TIMEOUT;
    return QByteArray();
  }

  timer.stop();
  if (reply->error() != QNetworkReply::NoError) {
    network_error = reply->error();
    CApplicationLog::Instance()->LogError("Send request network error : %s",
                              reply->errorString().toStdString().c_str());
    err_code = RE_NETWORK_ERROR;
    return QByteArray();
  }

  bool parsed = false;
  http_status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(&parsed);
  return reply->readAll();
}
void CloudControl::uploadCancelled() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *> (sender());
    if (reply != NULL) {
        reply->abort();
    }
    uploadProgress->close();
    uploadProgress->deleteLater();
}
void QNetworkReplyHandler::abort()
{
    m_resourceHandle = 0;
    if (m_reply) {
        QNetworkReply* reply = release();
        reply->abort();
        reply->deleteLater();
        deleteLater();
    }
}
void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) {
  QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
  if (!reply) return;
  if (bytesTotal > 0) {
    // Total number of bytes is available
    if (bytesTotal > 1048576*10) {
      // More than 10MB, this is probably not a torrent file, aborting...
      reply->abort();
      reply->deleteLater();
    } else {
      disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(checkDownloadSize(qint64,qint64)));
    }
  } else {
    if (bytesReceived  > 1048576*10) {
      // More than 10MB, this is probably not a torrent file, aborting...
      reply->abort();
      reply->deleteLater();
    }
  }
}
Beispiel #9
0
// --------------------------------------------------------------------------
void qMidasAPIPrivate::queryTimeOut()
{
  Q_Q(qMidasAPI);
  QTimer* timer = qobject_cast<QTimer*>(this->sender());
  Q_ASSERT(timer);
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(timer->parent());
  Q_ASSERT(reply);
  reply->abort();
  //reply->setError(QNetworkReply::TimeoutError,
  //   q->tr("Time out: No progress for %1 seconds.").arg(timer->interval()));
}
Beispiel #10
0
void NetworkTimeouts::timerEvent(QTimerEvent* e) {
  QNetworkReply* reply = timers_.key(e->timerId());
  if (reply) {
    reply->abort();
  }

  RedirectFollower* redirect = redirect_timers_.key(e->timerId());
  if (redirect) {
    redirect->abort();
  }
}
void DownloadManager::stopDownload() {
    DownloadData* d = ((DownloadData*)sender());
    QNetworkReply* reply = mDownloads[d];
    reply->abort();
    d->mIsFinished = true;
    d->mIsStopped = true;
    d->mBytesReceived = -1;
    mModel.informOfChange(d);
//	QFile* fileDest = mActiveDownloads[reply];
//	fileDest->close();
}
Beispiel #12
0
void Updater::headerChanged()
{
    QNetworkReply *reply = ( QNetworkReply * )sender();
    QUrl newUrl = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl();
    if ( !newUrl.isEmpty() && reply->url() != newUrl )
    {
        disconnect( reply, SIGNAL( finished() ), this, SLOT( downloadFinished() ) );
        reply->abort();
        reply->deleteLater();
        getFile( newUrl );
    }
}
void
PlaydarCometRequest::onReadyRead()
{
    QNetworkReply* reply = (QNetworkReply*) sender();
    QByteArray ba = reply->readAll();
    if (!m_parser->push(ba)) {
        qDebug() << "json comet parse problem";
        qDebug() << ba;
        reply->abort();     // can't recover from this
        onFinished();       // assuming abort() doesn't emit finished
    }
}
Beispiel #14
0
void WebLoadManager::onProgress(qint64 already, qint64 size) {
	QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
	if (!reply) return;

	Replies::iterator j = _replies.find(reply);
	if (j == _replies.cend()) { // handled already
		return;
	}
	webFileLoaderPrivate *loader = j.value();

	WebReplyProcessResult result = WebReplyProcessProgress;
	QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	int32 status = statusCode.isValid() ? statusCode.toInt() : 200;
	if (status != 200 && status != 206 && status != 416) {
		if (status == 301 || status == 302) {
			QString loc = reply->header(QNetworkRequest::LocationHeader).toString();
			if (!loc.isEmpty()) {
				if (loader->oneMoreRedirect()) {
					sendRequest(loader, loc);
					return;
				} else {
					LOG(("Network Error: Too many HTTP redirects in onFinished() for web file loader: %1").arg(loc));
					result = WebReplyProcessError;
				}
			}
		} else {
			LOG(("Network Error: Bad HTTP status received in WebLoadManager::onProgress(): %1").arg(statusCode.toInt()));
			result = WebReplyProcessError;
		}
	} else {
		loader->setProgress(already, size);
		QByteArray r = reply->readAll();
		if (!r.isEmpty()) {
			loader->addData(r);
		}
		if (size == 0) {
			LOG(("Network Error: Zero size received for HTTP download progress in WebLoadManager::onProgress(): %1 / %2").arg(already).arg(size));
			result = WebReplyProcessError;
		}
	}
	if (!handleReplyResult(loader, result)) {
		_replies.erase(j);
		_loaders.remove(loader);
		delete loader;

		reply->abort();
		reply->deleteLater();
	}
}
Beispiel #15
0
void FrameLoaderClientQt::download(WebCore::ResourceHandle* handle, const WebCore::ResourceRequest&, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&)
{
    if (!m_webFrame)
        return;

    QNetworkReplyHandler* handler = handle->getInternal()->m_job;
    QNetworkReply* reply = handler->release();
    if (reply) {
        QWebPage *page = m_webFrame->page();
        if (page->forwardUnsupportedContent())
            emit page->unsupportedContent(reply);
        else
            reply->abort();
    }
}
Beispiel #16
0
void WebLoadManager::sendRequest(webFileLoaderPrivate *loader, const QString &redirect) {
	Replies::iterator j = _replies.find(loader->reply());
	if (j != _replies.cend()) {
		QNetworkReply *r = j.key();
		_replies.erase(j);

		r->abort();
		r->deleteLater();
	}

	QNetworkReply *r = loader->request(_manager, redirect);
	connect(r, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onProgress(qint64, qint64)));
	connect(r, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onFailed(QNetworkReply::NetworkError)));
	connect(r, SIGNAL(metaDataChanged()), this, SLOT(onMeta()));
	_replies.insert(r, loader);
}
Beispiel #17
0
void DataFetcher::fetchWorksheet(const QDate &startDate, const QDate &endDate)
{
	// Cleanup
	m_workLog.clear();
	m_lastError.clear();
	if(m_reply != NULL)
	{
		QNetworkReply* oldReply = m_reply;
		m_reply = NULL;

		oldReply->abort();
		oldReply->deleteLater();
	}

	if(m_credentialsProvider != NULL && (m_login.isNull() || m_password.isNull()))
	{
		QString newLogin, newPassword;
		if(m_credentialsProvider->getCredentials(&newLogin, &newPassword))
		{
			m_login = newLogin;
			m_password = newPassword;
		}
	}

	QUrl url;
	url.setScheme("https");
	url.setHost(m_host);
	url.setPath("rest/timesheet-gadget/1.0/raw-timesheet.json");
	url.addQueryItem("userId", m_login);

	static const QLocale locale(QLocale::English, QLocale::UnitedKingdom);
	static const QString jiraDateFormat("dd/MMM/yyyy");
	url.addQueryItem("startDate", locale.toString(startDate, jiraDateFormat));
	url.addQueryItem("endDate", locale.toString(endDate, jiraDateFormat));

	const QByteArray authorization = "Basic " + QString("%1:%2").arg(m_login).arg(m_password).toUtf8().toBase64();


	QNetworkRequest req;
	req.setUrl(url);
	req.setRawHeader("Authorization", authorization);
	req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

	m_reply = m_manager->get(req);
	connect(m_reply, SIGNAL(finished()), SLOT(processReply()));
}
Beispiel #18
0
void Updater::writeToFile()
{
    QNetworkReply *reply = ( QNetworkReply * )sender();
    QByteArray arr = reply->readAll();
    bool err = false;
    if ( firstChunk )
    {
#if defined Q_OS_WIN
        err = arr.left( 2 ) != "MZ";
#elif defined Q_OS_LINUX
        err = arr.left( 4 ) != "\x7F""ELF" && arr.left( 2 ) != "#!";
#endif
        firstChunk = false;
    }
    if ( err || updateFile.write( arr ) != arr.size() )
        reply->abort();
}
Beispiel #19
0
void ServicesBase::abortPendingRequests()
{
    for (QMap<QNetworkReply *, CallbackType>::iterator it = _pending.begin(); it != _pending.end(); )
    {
        QNetworkReply *reply = it.key();

        if (reply)
        {
            disconnect(reply, SIGNAL(finished()), this, SLOT(onRequestFinished()));
            disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestFinished()));

            reply->abort();
            reply->deleteLater();
        }

        _pending.remove(reply);
    }
}
Beispiel #20
0
void DataModelGUI::miriamDownloadProgress(qint64 received, qint64 total)
{
  if (total != -1)
    {
      mDownloadedBytes = 100 * double(received) / double(total);
    }
  else
    {
      ++mDownloadedBytes;
    }

  if (!mpProgressBar->progressItem(mUpdateItem))
    {
      QNetworkReply *reply = dynamic_cast<QNetworkReply*>(sender());

      if (reply != NULL) reply->abort();
    }
}
Beispiel #21
0
void ChooseFileDlg::onFileSelect(bool)
{
	QString path = QFileDialog::getOpenFileName(this, tr("Open File"), NULL, tr("All files *.*"));

	QFile *file = new QFile(path);
	if (!file->exists() || !file->open(QIODevice::ReadOnly))
		return;

	QProgressDialog progress(tr("Uploading..."), tr("Abort"), 0, 100, this);
	progress.setMinimumDuration(0);

	QHttpPart httpFilePart;
	httpFilePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(QFileInfo(path).fileName())));
	httpFilePart.setBodyDevice(file);

	QHttpMultiPart *httpMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
	httpMultiPart->append(httpFilePart);

	QNetworkAccessManager manager;
	QNetworkReply *reply = manager.post(QNetworkRequest(QUrl("http://127.0.0.1:3000/media/upload")), httpMultiPart);
	connect(reply, &QNetworkReply::uploadProgress, [&](qint64 bytesSent, qint64 bytesTotal){
		if (bytesSent && bytesTotal) progress.setValue((100 * bytesSent) / bytesTotal);
	});

	file->setParent(httpMultiPart);
	httpMultiPart->setParent(reply);

	connect(&progress, &QProgressDialog::canceled, [&]() {
		reply->abort();
	});

	while (reply->isRunning()) {
		QCoreApplication::processEvents();
	}

	if (reply->error() != QNetworkReply::NoError) {
		if (reply->error() != QNetworkReply::OperationCanceledError)
			QMessageBox::warning(this, tr("Failed to upload"), reply->errorString());
		return;
	}

	QByteArray content = reply->readAll();
	qDebug() << content;
}
void TelechargerFichier::annulerTelechargement()
{
	QPushButton *bouton;
		bouton = qobject_cast<QPushButton *>(sender());
		bouton->setDisabled(true);

	QString toolTip = bouton->toolTip();
		toolTip = toolTip.replace(QRegExp("Téléchargement n°(.+)"), "\\1");

	int ligne = toolTip.toInt() - 1;

	QNetworkReply *reponse = reponses.value(ligne);
		reponse->abort();

	QProgressBar *progression = progressionsTelechargements.value(ligne);
		progression->setValue(progression->maximum());

	listeTelechargements->item(ligne, 3)->setText("Annulé");
}
Beispiel #23
0
double donationDialog::EUR2BTC()
{
	QNetworkReply *rep = ((MainWindow*)parent())->mgr->get(QNetworkRequest(QUrl("https://blockchain.info/de/tobtc?currency=EUR&value=1")));
	QByteArray raw;

	rep->ignoreSslErrors();

	lineEdit_payment2->setText(tr("getting current exchange rate..."));
	comboBox->setEnabled(false);
	horizontalSlider->setEnabled(false);
	pushButton->setEnabled(false);

	((MainWindow*)parent())->timeout.start();

	while(rep->isRunning())
	{
		QCoreApplication::processEvents();

		if(((MainWindow*)parent())->timeout.hasExpired(3000))
		{
			rep->abort();
		}
	}

	comboBox->setEnabled(true);
	horizontalSlider->setEnabled(true);
	pushButton->setEnabled(true);

	if(rep->error())
	{
		QMessageBox::warning(this, APPNAME, tr("Current exchange rate could not be determined!\n\nPlease specify the desired amount manually..."));

		return 0.0;
	}

	raw = rep->readAll();

	rep->deleteLater();

	return raw.toDouble();
}
Beispiel #24
0
void
OsmTileSource::cancelTileRequest(const OsmIndex &index)
{
    OsmIndexSet::const_iterator i = _pendingRequests.find(index);
    if (i == _pendingRequests.end())
        return; // it's not a pending request
    _pendingRequests.erase(i);
    for (OsmReplyMap::Iterator i=_pendingReplies.begin();
         i != _pendingReplies.end(); )
    {
        if (i.value() == index) {
            QNetworkReply *reply = i.key();
            _pendingReplies.remove(reply);
            reply->abort();
            break;
        } else {
            ++i;
        }
    }
    
}
  std::pair<QNetworkReply::NetworkError, QString> NetworkProxyDialog::testProxyConnection(const QNetworkProxy &t_proxy, QWidget *t_parent)
  {
    QProgressDialog dlg("Verifying Proxy Connection", "Cancel",0, 1000, t_parent);
    dlg.setWindowModality(Qt::WindowModal);
    dlg.setValue(0);
    dlg.setMinimumDuration(1000);

    QNetworkAccessManager nam;
    nam.setProxy(t_proxy);
    QNetworkReply *head = nam.head(QNetworkRequest(QUrl("https://bcl.nrel.gov/")));

    if (!head) return std::make_pair(QNetworkReply::UnknownNetworkError, QString("Unknown error creating connection to proxy."));

    boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
    while ( !head->isFinished()
            && (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds() < 10000
            && !dlg.wasCanceled())
    {
      int time = (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds();
      dlg.setValue(time);
      if (time >= 950 && dlg.maximum() < 10000)
      {
        dlg.setMaximum(10000);
      }
    }
    dlg.reset();
    Application::instance().processEvents();

    head->deleteLater();

    if (!head->isFinished()) 
    {
      head->abort();
      return std::make_pair(QNetworkReply::TimeoutError, QString("Timed out while attempting to verify proxy connection"));
    }

    LOG(Debug, " errorString from proxy test " << toString(head->errorString()) << " " << head->error());

    return std::make_pair(head->error(), head->errorString());
  }
Beispiel #26
0
QString MLNetwork::httpGetBinaryFile(const QString& url)
{
    if (MLUtil::inGuiThread()) {
        qCritical() << "Cannot call MLNetwork::httpGetBinaryFile from within the GUI thread: " + url;
        exit(-1);
    }

    //TaskProgress task("Downloading binary file");
    //task.log(url);
    QTime timer;
    timer.start();
    QString fname = get_temp_fname();
    QNetworkAccessManager manager; // better make it a singleton
    QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));
    QEventLoop loop;
    QFile temp(fname);
    int num_bytes = 0;
    temp.open(QIODevice::WriteOnly);
    QObject::connect(reply, &QNetworkReply::readyRead, [&]() {
        if (MLUtil::threadInterruptRequested()) {
            TaskProgress errtask("Download halted");
            errtask.error("Thread interrupt requested");
            errtask.log(url);
            reply->abort();
        }
        QByteArray X=reply->readAll();
        temp.write(X);
        num_bytes+=X.count();
    });
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    //task.setLabel(QString("Downloaded %1 MB in %2 sec").arg(num_bytes * 1.0 / 1e6).arg(timer.elapsed() * 1.0 / 1000));
    printf("RECEIVED BINARY (%d ms, %d bytes) from %s\n", timer.elapsed(), num_bytes, url.toLatin1().data());
    TaskManager::TaskProgressMonitor::globalInstance()->incrementQuantity("bytes_downloaded", num_bytes);
    if (MLUtil::threadInterruptRequested()) {
        return "";
    }
    return fname;
}
Beispiel #27
0
void NetworkTimeouts::timerEvent(QTimerEvent* e) {
  QNetworkReply* reply = timers_.key(e->timerId());
  if (reply) {
    reply->abort();
  }
}
bool weatherStation::update()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkRequest netRequest(*apiLink);
    QNetworkReply *netReply;

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

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

    timer.start(10000);

    loop.exec();

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

    weatherTempData.open(QFile::ReadWrite);

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

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

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


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

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

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

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


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

                    }

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

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

                            continue;
                    }

            }
    }
    if(xmlReader->hasError()) return false;
    return true;
}
void ReverseGeoLookupThread::run() {
	if (geo_lookup_data.isEmpty())
		return;

	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	QEventLoop loop;
	QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3");
	QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50");
	QTimer timer;

	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

	Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) {
		struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site;

		// first check the findNearbyPlaces API from geonames - that should give us country, state, city
		request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));

		QNetworkReply *reply = rgl->get(request);
		timer.setSingleShot(true);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();

		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant geoNamesObject = obj.value("geonames").toVariant();
			QVariantList geoNames = geoNamesObject.toList();
			if (geoNames.count() > 0) {
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();
		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant oceanObject = obj.value("ocean").toVariant();
			QVariantMap oceanName = oceanObject.toMap();
			if (oceanName["name"].isValid()) {
				int idx;
				if (ds->taxonomy.category == NULL)
					ds->taxonomy.category = alloc_taxonomy();
				idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN);
				if (idx == -1)
					idx = ds->taxonomy.nr;
				if (idx < TC_NR_CATEGORIES) {
					ds->taxonomy.category[idx].category = TC_OCEAN;
					ds->taxonomy.category[idx].origin = taxonomy::GEOCODED;
					ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString()));
					if (idx == ds->taxonomy.nr)
						ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}

clear_reply:
		reply->deleteLater();
	}
	rgl->deleteLater();
}
Beispiel #30
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();
}