summaryrefslogtreecommitdiff
path: root/Network
diff options
context:
space:
mode:
Diffstat (limited to 'Network')
-rw-r--r--Network/LiveCQUpload.cpp119
-rw-r--r--Network/LiveCQUpload.hpp53
-rw-r--r--Network/LotWUsers.cpp171
3 files changed, 295 insertions, 48 deletions
diff --git a/Network/LiveCQUpload.cpp b/Network/LiveCQUpload.cpp
new file mode 100644
index 00000000..e8bab2ad
--- /dev/null
+++ b/Network/LiveCQUpload.cpp
@@ -0,0 +1,119 @@
+#include "LiveCQUpload.hpp"
+
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+
+namespace
+{
+ class QNetworkAccessManagerTransport final
+ : public QObject
+ , public LiveCQUpload::Transport
+ {
+ public:
+ explicit QNetworkAccessManagerTransport (QObject *parent = nullptr)
+ : QObject {parent}
+ {
+ }
+
+ QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override
+ {
+ return manager_.post (request, body);
+ }
+
+ private:
+ QNetworkAccessManager manager_;
+ };
+}
+
+LiveCQUpload::LiveCQUpload (QObject *parent)
+ : LiveCQUpload {new QNetworkAccessManagerTransport, true, parent}
+{
+}
+
+LiveCQUpload::LiveCQUpload (Transport *transport, bool take_transport_ownership,
+ QObject *parent)
+ : QObject {parent}
+ , transport_ {transport}
+ , owns_transport_ {take_transport_ownership}
+{
+}
+
+LiveCQUpload::~LiveCQUpload ()
+{
+ abortOutstandingRequests ();
+ if (owns_transport_)
+ {
+ delete transport_;
+ }
+}
+
+bool LiveCQUpload::setEndpoint (QUrl const& endpoint)
+{
+ if (!endpoint.isValid ()
+ || endpoint.scheme ().compare ("https", Qt::CaseInsensitive) != 0)
+ {
+ Q_EMIT errorOccurred (
+ QString {"LiveCQ endpoint must be a valid https URL: %1"}
+ .arg (endpoint.toString ()));
+ return false;
+ }
+ endpoint_ = endpoint;
+ return true;
+}
+
+void LiveCQUpload::postSpot (QUrlQuery const& query)
+{
+ if (!endpoint_.isValid ())
+ {
+ Q_EMIT errorOccurred (QStringLiteral ("LiveCQ endpoint is not configured"));
+ return;
+ }
+
+ QNetworkRequest request {endpoint_};
+ request.setHeader (QNetworkRequest::ContentTypeHeader,
+ "application/x-www-form-urlencoded");
+ if (!user_agent_.isEmpty ())
+ {
+ request.setRawHeader ("User-Agent", user_agent_);
+ }
+
+ auto *reply = transport_->post (request, query.query (QUrl::FullyEncoded).toUtf8 ());
+ outstanding_.insert (reply);
+ connect (reply, &QNetworkReply::finished, this,
+ [this, reply] () { handleReply (reply); });
+}
+
+void LiveCQUpload::abortOutstandingRequests ()
+{
+ auto const replies = outstanding_;
+ for (auto *reply : replies)
+ {
+ if (reply)
+ {
+ disconnect (reply, nullptr, this, nullptr);
+ reply->abort ();
+ }
+ }
+ outstanding_.clear ();
+}
+
+void LiveCQUpload::handleReply (QNetworkReply *reply)
+{
+ outstanding_.remove (reply);
+ int const http_status
+ = reply->attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt ();
+ if (reply->error () != QNetworkReply::NoError)
+ {
+ Q_EMIT errorOccurred (QString {"LiveCQ upload failed: %1"}.arg (reply->errorString ()));
+ }
+ else if (http_status >= 400)
+ {
+ Q_EMIT errorOccurred (QString {"LiveCQ upload failed: HTTP %1"}.arg (http_status));
+ }
+ else
+ {
+ Q_EMIT spotPosted ();
+ }
+ reply->deleteLater ();
+}
diff --git a/Network/LiveCQUpload.hpp b/Network/LiveCQUpload.hpp
new file mode 100644
index 00000000..a213c2d8
--- /dev/null
+++ b/Network/LiveCQUpload.hpp
@@ -0,0 +1,53 @@
+#ifndef LIVE_CQ_UPLOAD_HPP
+#define LIVE_CQ_UPLOAD_HPP
+
+#include <QByteArray>
+#include <QNetworkRequest>
+#include <QObject>
+#include <QSet>
+#include <QString>
+#include <QUrl>
+#include <QUrlQuery>
+
+class QNetworkReply;
+
+class LiveCQUpload final
+ : public QObject
+{
+ Q_OBJECT
+
+public:
+ class Transport
+ {
+ public:
+ virtual ~Transport () = default;
+ virtual QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) = 0;
+ };
+
+ explicit LiveCQUpload (QObject *parent = nullptr);
+ LiveCQUpload (Transport *transport, bool take_transport_ownership,
+ QObject *parent = nullptr);
+ ~LiveCQUpload () override;
+
+ bool setEndpoint (QUrl const& endpoint);
+ QUrl endpoint () const { return endpoint_; }
+
+ void setUserAgent (QByteArray const& user_agent) { user_agent_ = user_agent; }
+
+ void postSpot (QUrlQuery const& query);
+ void abortOutstandingRequests ();
+
+ Q_SIGNAL void errorOccurred (QString const& reason);
+ Q_SIGNAL void spotPosted ();
+
+private:
+ void handleReply (QNetworkReply *reply);
+
+ Transport *transport_;
+ bool owns_transport_;
+ QUrl endpoint_;
+ QByteArray user_agent_;
+ QSet<QNetworkReply *> outstanding_;
+};
+
+#endif
diff --git a/Network/LotWUsers.cpp b/Network/LotWUsers.cpp
index 10a9a4d8..7503ff86 100644
--- a/Network/LotWUsers.cpp
+++ b/Network/LotWUsers.cpp
@@ -1,11 +1,12 @@
#include "LotWUsers.hpp"
-#include <future>
-#include <chrono>
+#include <exception>
+#include <utility>
#include <QHash>
#include <QString>
#include <QDate>
+#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QDir>
@@ -16,6 +17,8 @@
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
+#include <QFutureWatcher>
+#include <QtConcurrent/QtConcurrentRun>
#include "qt_helpers.hpp"
#include "Logger.hpp"
#include "FileDownload.hpp"
@@ -27,6 +30,47 @@ namespace
{
// Dictionary mapping call sign to date of last upload to LotW
using dictionary = QHash<QString, QDate>;
+
+ struct load_result
+ {
+ dictionary users;
+ QString error;
+ };
+
+ // Upload times and any additional fields are not needed for date lookups.
+ load_result load_dictionary (QString const& lotw_csv_file)
+ {
+ load_result result;
+ try
+ {
+ QFile f {lotw_csv_file};
+ if (!f.open (QFile::ReadOnly | QFile::Text))
+ {
+ result.error = QObject::tr ("Failed to open LotW users CSV file: '%1'").arg (f.fileName ());
+ return result;
+ }
+ QTextStream s {&f};
+ for (auto l = s.readLine (); !l.isNull (); l = s.readLine ())
+ {
+ auto const pos = l.indexOf (',');
+ if (pos <= 0) continue;
+ auto const date_end = l.indexOf (',', pos + 1);
+ auto const date_field = date_end < 0 ? l.mid (pos + 1) : l.mid (pos + 1, date_end - pos - 1);
+ auto const call = l.left (pos).trimmed ();
+ auto const date = QDate::fromString (date_field.trimmed (), "yyyy-MM-dd");
+ if (!call.isEmpty () && date.isValid ()) result.users[call] = date;
+ }
+ if (f.error () != QFileDevice::NoError)
+ {
+ result.error = QObject::tr ("Failed to read LotW users CSV file: '%1'").arg (f.fileName ());
+ }
+ }
+ catch (std::exception const& e)
+ {
+ result.error = QString::fromUtf8 (e.what ());
+ }
+ return result;
+ }
}
class LotWUsers::impl final
@@ -36,21 +80,63 @@ class LotWUsers::impl final
public:
impl (LotWUsers * self, QNetworkAccessManager * network_manager)
- : self_ {self}
+ : QObject {self}
+ , self_ {self}
, network_manager_ {network_manager}
, url_valid_ {false}
, redirect_count_ {0}
, age_constraint_ {365}
, connected_ {false}
{
+ lotw_downloader_.setParent (this);
+ connect (&loader_watcher_, &QFutureWatcher<load_result>::finished, this, [this] {
+ loading_ = false;
+ if (!pending_file_.isEmpty ())
+ {
+ if (active_generation_ == load_generation_)
+ {
+ auto result = loader_watcher_.result ();
+ if (result.error.isEmpty ())
+ {
+ // Keep the cached snapshot available while the downloaded file is parsed.
+ last_uploaded_ = std::move (result.users);
+ }
+ }
+ auto const next_file = std::exchange (pending_file_, QString {});
+ start_load (next_file);
+ return;
+ }
+ if (active_generation_ != load_generation_) return;
+
+ auto result = loader_watcher_.result ();
+ auto const should_finish = !download_active_;
+ QPointer<LotWUsers> owner {self_};
+ if (result.error.isEmpty ())
+ {
+ last_uploaded_ = std::move (result.users);
+ LOG_INFO (QString {"LotWUsers: Loaded %1 records from %2"}.arg (last_uploaded_.size ()).arg (active_file_));
+ Q_EMIT owner->progress (QString {"Loaded %1 records from LotW."}.arg (last_uploaded_.size ()));
+ }
+ else
+ {
+ Q_EMIT owner->LotW_users_error (result.error);
+ }
+ if (owner && should_finish) Q_EMIT owner->load_finished ();
+ });
}
void load (QString const& url, bool fetch, bool forced_fetch)
{
- abort (); // abort any active download
auto csv_file_name = csv_file_.fileName ();
auto exists = QFileInfo::exists (csv_file_name);
- if (fetch && (!exists || forced_fetch))
+ auto const downloading = fetch && (!exists || forced_fetch);
+ auto const preserve_cache_load = downloading && exists && loading_ && active_file_ == csv_file_name
+ && active_generation_ == load_generation_;
+ if (!preserve_cache_load) ++load_generation_;
+ pending_file_.clear ();
+ download_active_ = false;
+ abort (); // abort any active download
+ if (downloading)
{
current_url_.setUrl(url);
if (current_url_.isValid() && !QSslSocket::supportsSsl())
@@ -67,27 +153,32 @@ public:
"WSJT-X LotW User Downloader");
if (!connected_)
{
- connect(&lotw_downloader_, &FileDownload::complete, [this, csv_file_name] {
- LOG_INFO(QString{"LotWUsers: Loading LotW file %1"}.arg(csv_file_name));
- future_load_ = std::async(std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name);
+ connect(&lotw_downloader_, &FileDownload::complete, this, [this] (QString const& file_name) {
+ download_active_ = false;
+ request_load (file_name);
});
- connect(&lotw_downloader_, &FileDownload::error, [this] (QString const& msg) {
+ connect(&lotw_downloader_, &FileDownload::download_error, this, [this] (QString const& msg) {
LOG_INFO(QString{"LotWUsers: Error downloading LotW file: %1"}.arg(msg));
Q_EMIT self_->LotW_users_error (msg);
});
+ connect(&lotw_downloader_, &FileDownload::load_finished, this, [this] {
+ if (!download_active_) return;
+ download_active_ = false;
+ if (!loading_) Q_EMIT self_->load_finished ();
+ });
connect( &lotw_downloader_, &FileDownload::progress, [this] (QString const& msg) {
Q_EMIT self_->progress (msg);
});
connected_ = true;
}
+ download_active_ = true;
lotw_downloader_.start_download();
}
else
{
if (exists)
{
- // load the database asynchronously
- future_load_ = std::async (std::launch::async, &LotWUsers::impl::load_dictionary, this, csv_file_name);
+ request_load (csv_file_name);
}
}
}
@@ -97,32 +188,24 @@ public:
lotw_downloader_.abort();
}
- // Load the database from the given file name
- //
- // Expects the file to be in CSV format with no header with one
- // record per line. Record fields are call sign followed by upload
- // date in yyyy-MM-dd format followed by upload time (ignored)
- dictionary load_dictionary (QString const& lotw_csv_file)
+ void request_load (QString const& file_name)
{
- dictionary result;
- QFile f {lotw_csv_file};
- if (f.open (QFile::ReadOnly | QFile::Text))
+ if (loading_)
{
- QTextStream s {&f};
- for (auto l = s.readLine (); !l.isNull (); l = s.readLine ())
- {
- auto pos = l.indexOf (',');
- result[l.left (pos)] = QDate::fromString (l.mid (pos + 1, l.indexOf (',', pos + 1) - pos - 1), "yyyy-MM-dd");
- }
+ pending_file_ = file_name;
}
else
{
- throw std::runtime_error {QObject::tr ("Failed to open LotW users CSV file: '%1'").arg (f.fileName ()).toStdString ()};
+ start_load (file_name);
}
- LOG_INFO(QString{"LotWUsers: Loaded %1 records from %2"}.arg(result.size()).arg(lotw_csv_file));
- Q_EMIT self_->progress (QString{"Loaded %1 records from LotW."}.arg(result.size()));
- Q_EMIT self_->load_finished();
- return result;
+ }
+
+ void start_load (QString const& file_name)
+ {
+ loading_ = true;
+ active_generation_ = load_generation_;
+ active_file_ = file_name;
+ loader_watcher_.setFuture (QtConcurrent::run ([file_name] { return load_dictionary (file_name); }));
}
LotWUsers * self_;
@@ -132,7 +215,13 @@ public:
QUrl current_url_; // may be a redirect
int redirect_count_;
QPointer<QNetworkReply> reply_;
- std::future<dictionary> future_load_;
+ QFutureWatcher<load_result> loader_watcher_ {this};
+ bool loading_ {false};
+ bool download_active_ {false};
+ quint64 load_generation_ {0};
+ quint64 active_generation_ {0};
+ QString active_file_;
+ QString pending_file_;
dictionary last_uploaded_;
qint64 age_constraint_; // days
FileDownload lotw_downloader_;
@@ -169,27 +258,13 @@ void LotWUsers::set_age_constraint (qint64 uploaded_since_days)
bool LotWUsers::user (QString const& call) const
{
- // check if a pending asynchronous load is ready
- if (m_->future_load_.valid ()
- && std::future_status::ready == m_->future_load_.wait_for (std::chrono::seconds {0}))
- {
- try
- {
- // wait for the load to finish if necessary
- const_cast<dictionary&> (m_->last_uploaded_) = const_cast<std::future<dictionary>&> (m_->future_load_).get ();
- }
- catch (std::exception const& e)
- {
- Q_EMIT LotW_users_error (e.what ());
- }
- Q_EMIT load_finished ();
- }
if (m_->last_uploaded_.size ())
{
auto p = m_->last_uploaded_.constFind (call);
if (p != m_->last_uploaded_.end ())
{
- return p.value ().daysTo (QDate::currentDate ()) <= m_->age_constraint_;
+ auto const age = p.value ().daysTo (QDateTime::currentDateTimeUtc ().date ());
+ return p.value ().isValid () && age >= 0 && age <= m_->age_constraint_;
}
}
return false;