summaryrefslogtreecommitdiff
path: root/Network/wsprnet.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'Network/wsprnet.cpp')
-rw-r--r--Network/wsprnet.cpp699
1 files changed, 582 insertions, 117 deletions
diff --git a/Network/wsprnet.cpp b/Network/wsprnet.cpp
index 14dce13d..a785acd7 100644
--- a/Network/wsprnet.cpp
+++ b/Network/wsprnet.cpp
@@ -5,6 +5,7 @@
#include "wsprnet.h"
#include <cmath>
+#include <limits>
#include <QTimer>
#include <QFile>
@@ -15,12 +16,45 @@
#include <QNetworkReply>
#include <QUrl>
#include <QDebug>
+#include <QtGlobal>
+#include <QCryptographicHash>
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+#include <QRandomGenerator>
+#endif
#include "moc_wsprnet.cpp"
namespace
{
+ class QNetworkAccessManagerTransport final
+ : public QObject
+ , public WSPRNet::Transport
+ {
+ public:
+ explicit QNetworkAccessManagerTransport (QObject *parent = nullptr)
+ : QObject {parent}
+ , network_manager_ {new QNetworkAccessManager {this}}
+ {
+ }
+
+ QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override
+ {
+#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0)
+ if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) {
+ // try and recover network access for QNAM
+ network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
+ }
+#endif
+ return network_manager_->post (request, body);
+ }
+
+ private:
+ QNetworkAccessManager * network_manager_;
+ };
+
char const * const wsprNetUrl = "http://wsprnet.org/post/";
+ char const * const wsprNetUrl2 = "http://wsprnet.eu:3000/post/";
//char const * const wsprNetUrl = "http://127.0.0.1:5000/post/";
//
@@ -62,151 +96,566 @@ with app.test_request_context ():
};
WSPRNet::WSPRNet(QObject *parent)
+ : WSPRNet {nullptr, RetryPolicy {}, false, parent}
+{
+}
+
+WSPRNet::WSPRNet (Transport *transport, RetryPolicy retry_policy,
+ bool take_transport_ownership, QObject *parent)
: QObject {parent}
- , network_manager_ {new QNetworkAccessManager(this)}
- , spots_to_send_ {0}
+ , transport_ {transport ? transport : new QNetworkAccessManagerTransport {this}}
+ , owns_transport_ {transport && take_transport_ownership}
+ , retry_policy_ {retry_policy}
+ , TR_period_ {0.F}
+ , uploads_started_ {0}
+ , next_file_batch_id_ {1}
+ , next_logical_upload_id_ {1}
+ , upload_session_active_ {false}
{
+ upload_timer_.setSingleShot (true);
connect (&upload_timer_, &QTimer::timeout, this, &WSPRNet::work);
}
+WSPRNet::~WSPRNet ()
+{
+ if (owns_transport_)
+ {
+ delete transport_;
+ }
+}
+
void WSPRNet::upload (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& fileName)
{
- m_call = call;
- m_grid = grid;
- m_rfreq = rfreq;
- m_tfreq = tfreq;
- m_mode = mode;
- TR_period_ = TR_period;
- m_tpct = tpct;
- m_dbm = dbm;
- m_vers = version;
- m_file = fileName;
-
- // Open the wsprd.out file
- if (m_uploadType != 3)
- {
- QFile wsprdOutFile (fileName);
- if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
- {
- spot_queue_.enqueue (urlEncodeNoSpot ());
- m_uploadType = 1;
- }
- else
+ StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
+ queueWsprFile (context, fileName);
+ flush (context);
+}
+
+void WSPRNet::queueWsprFile (StationContext const& context, QString const& file_name)
+{
+ applyContext (context);
+ auto const snapshot = snapshotFile (file_name);
+ auto const file_batch_id = beginFileBatch (snapshot);
+
+ QFile wsprdOutFile (file_name);
+ if (!wsprdOutFile.open (QIODevice::ReadOnly | QIODevice::Text) || !wsprdOutFile.size ())
+ {
+ enqueueUpload (urlEncodeNoSpot (), UploadSource::File, PayloadKind::Status, file_name, file_batch_id);
+ }
+ else
+ {
+ while (!wsprdOutFile.atEnd())
{
- // Read the contents
- while (!wsprdOutFile.atEnd())
+ SpotQueue::value_type query;
+ if (decodeLine (wsprdOutFile.readLine(), query))
{
- SpotQueue::value_type query;
- if (decodeLine (wsprdOutFile.readLine(), query))
+ // Prevent reporting data ouside of the current frequency band
+ float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat());
+ if (f < 0.01) // MHz
{
- // Prevent reporting data ouside of the current frequency band
- float f = fabs (m_rfreq.toFloat() - query.queryItemValue ("tqrg", QUrl::FullyDecoded).toFloat());
- if (f < 0.01) // MHz
- {
- spot_queue_.enqueue(urlEncodeSpot (query));
- m_uploadType = 2;
- }
+ enqueueUpload (urlEncodeSpot (query), UploadSource::File, PayloadKind::Spot, file_name, file_batch_id);
}
}
}
}
- spots_to_send_ = spot_queue_.size ();
- upload_timer_.start (200);
+ if (file_uploads_.value (file_batch_id).total == 0)
+ {
+ file_uploads_.remove (file_batch_id);
+ }
}
void WSPRNet::post (QString const& call, QString const& grid, QString const& rfreq, QString const& tfreq,
QString const& mode, float TR_period, QString const& tpct, QString const& dbm,
QString const& version, QString const& decode_text)
{
- m_call = call;
- m_grid = grid;
- m_rfreq = rfreq;
- m_tfreq = tfreq;
- m_mode = mode;
- TR_period_ = TR_period;
- m_tpct = tpct;
- m_dbm = dbm;
- m_vers = version;
+ StationContext context {call, grid, rfreq, tfreq, mode, TR_period, tpct, dbm, version};
if (!decode_text.size ())
{
- if (!spot_queue_.size ())
+ flush (context);
+ }
+ else
+ {
+ queueFst4wDecode (context, decode_text);
+ }
+}
+
+void WSPRNet::queueFst4wDecode (StationContext const& context, QString const& decode_text)
+{
+ applyContext (context);
+ auto const& match = fst4_re.match (decode_text);
+ if (match.hasMatch ())
+ {
+ SpotQueue::value_type query;
+ auto tqrg = match.captured ("freq").toInt ();
+ query.addQueryItem ("function", "wspr");
+ // FST4W reports are intentionally not constrained to WSPR sub-bands.
+ auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-context.TR_period * 3. / 4.).date ();
+ query.addQueryItem ("date", date.toString ("yyMMdd"));
+ query.addQueryItem ("time", match.captured ("time"));
+ query.addQueryItem ("sig", match.captured ("db"));
+ query.addQueryItem ("dt", match.captured ("dt"));
+ query.addQueryItem ("tqrg", QString::number (context.rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6));
+ query.addQueryItem ("tcall", match.captured ("call"));
+ query.addQueryItem ("drift", "0");
+ query.addQueryItem ("tgrid", match.captured ("grid"));
+ query.addQueryItem ("dbm", match.captured ("dBm"));
+ enqueueUpload (urlEncodeSpot (query), UploadSource::Direct, PayloadKind::Spot);
+ }
+}
+
+void WSPRNet::flush (StationContext const& context)
+{
+ applyContext (context);
+ if (pending_primary_uploads_.isEmpty () && !hasOutstanding (UploadTarget::Primary))
+ {
+ enqueueUpload (urlEncodeNoSpot (), UploadSource::Direct, PayloadKind::Status);
+ }
+ startUploadSession ();
+}
+
+void WSPRNet::applyContext (StationContext const& context)
+{
+ m_call = context.call;
+ m_grid = context.grid;
+ m_rfreq = context.rfreq;
+ m_tfreq = context.tfreq;
+ m_mode = context.mode;
+ TR_period_ = context.TR_period;
+ m_tpct = context.tpct;
+ m_dbm = context.dbm;
+ m_vers = context.version;
+}
+
+auto WSPRNet::snapshotFile (QString const& file_name) const -> FileSnapshot
+{
+ FileSnapshot snapshot;
+ snapshot.path = file_name;
+
+ QFile file {file_name};
+ if (!file.open (QIODevice::ReadOnly))
+ {
+ return snapshot;
+ }
+
+ auto const contents = file.readAll ();
+ snapshot.size = contents.size ();
+ snapshot.hash = QCryptographicHash::hash (contents, QCryptographicHash::Sha256);
+ return snapshot;
+}
+
+bool WSPRNet::fileMatchesSnapshot (FileSnapshot const& snapshot) const
+{
+ if (snapshot.path.isEmpty () || snapshot.size < 0)
+ {
+ return false;
+ }
+
+ QFile file {snapshot.path};
+ if (!file.open (QIODevice::ReadOnly))
+ {
+ return false;
+ }
+
+ auto const contents = file.readAll ();
+ if (contents.size () != snapshot.size)
+ {
+ return false;
+ }
+
+ return QCryptographicHash::hash (contents, QCryptographicHash::Sha256) == snapshot.hash;
+}
+
+bool WSPRNet::hasPendingFileLeg (int file_batch_id, int logical_upload_id) const
+{
+ auto is_file_leg = [file_batch_id, logical_upload_id](PendingUpload const& upload)
+ {
+ return UploadSource::File == upload.source
+ && upload.file_batch_id == file_batch_id
+ && upload.logical_upload_id == logical_upload_id;
+ };
+
+ for (auto const& upload : pending_primary_uploads_)
+ {
+ if (is_file_leg (upload))
{
- spot_queue_.enqueue (urlEncodeNoSpot ());
- m_uploadType = 3;
+ return true;
}
}
- else
+ for (auto const& upload : pending_alternate_uploads_)
{
- auto const& match = fst4_re.match (decode_text);
- if (match.hasMatch ())
+ if (is_file_leg (upload))
{
- SpotQueue::value_type query;
- // Prevent reporting data ouside of the current frequency
- // band - removed by G4WJS to accommodate FST4W spots
- // outside of WSPR segments
- auto tqrg = match.captured ("freq").toInt ();
- // if (tqrg >= 1400 && tqrg <= 1600)
- {
- query.addQueryItem ("function", "wspr");
- // use time as at 3/4 of T/R period before current to
- // ensure date is in Rx period
- auto const& date = QDateTime::currentDateTimeUtc ().addSecs (-TR_period * 3. / 4.).date ();
- query.addQueryItem ("date", date.toString ("yyMMdd"));
- query.addQueryItem ("time", match.captured ("time"));
- query.addQueryItem ("sig", match.captured ("db"));
- query.addQueryItem ("dt", match.captured ("dt"));
- query.addQueryItem ("tqrg", QString::number (rfreq.toDouble () + (tqrg - 1500) / 1e6, 'f', 6));
- query.addQueryItem ("tcall", match.captured ("call"));
- query.addQueryItem ("drift", "0");
- query.addQueryItem ("tgrid", match.captured ("grid"));
- query.addQueryItem ("dbm", match.captured ("dBm"));
- spot_queue_.enqueue (urlEncodeSpot (query));
- m_uploadType = 2;
- }
+ return true;
+ }
+ }
+ for (auto const& upload : outstanding_requests_)
+ {
+ if (is_file_leg (upload))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool WSPRNet::hasOutstanding (UploadTarget target) const
+{
+ for (auto const& upload : outstanding_requests_)
+ {
+ if (upload.target == target)
+ {
+ return true;
}
}
+ return false;
}
void WSPRNet::networkReply (QNetworkReply * reply)
{
- // check if request was ours
- if (m_outstandingRequests.removeOne (reply))
+ if (!outstanding_requests_.contains (reply))
{
+ reply->deleteLater ();
+ return;
+ }
+
+ auto upload = outstanding_requests_.take (reply);
+ QString server_response;
+ if (replyAccepted (upload, reply, server_response))
+ {
+ markAccepted (upload);
+ }
+ else
+ {
+ auto const now = QDateTime::currentDateTimeUtc ();
if (QNetworkReply::NoError != reply->error ())
{
- Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->error ()));
- // not clearing queue or halting queuing as it may be a
- // transient one off request error
+ Q_EMIT uploadStatus (QString {"Error: %1"}.arg (reply->errorString ()));
+ }
+ else
+ {
+ Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (server_response));
+ }
+
+ auto const retry_delay_ms = retryDelayMs (upload);
+ if (canRetry (upload, now, retry_delay_ms))
+ {
+ retryUpload (upload, now, retry_delay_ms);
}
else
{
- QString serverResponse = reply->readAll ();
- if (m_uploadType == 2)
+ markFailed (upload);
+ }
+ }
+
+ qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (outstanding_requests_.size ());
+
+ // delete request object instance on return to the event loop otherwise it is leaked
+ reply->deleteLater ();
+ scheduleWork ();
+ maybeFinalize ();
+}
+
+void WSPRNet::enqueueUpload (QUrlQuery const& query, UploadSource source, PayloadKind kind, QString const& source_file, int file_batch_id)
+{
+ auto const now = QDateTime::currentDateTimeUtc ();
+ auto const logical_upload_id = UploadSource::File == source ? next_logical_upload_id_++ : 0;
+ if (UploadSource::File == source)
+ {
+ auto& state = file_uploads_[file_batch_id];
+ ++state.total;
+ }
+ auto enqueue_for_target = [this, &query, source, kind, &source_file, file_batch_id,
+ logical_upload_id, now](UploadTarget target)
+ {
+ auto& uploads = target == UploadTarget::Primary
+ ? pending_primary_uploads_ : pending_alternate_uploads_;
+ uploads.enqueue ({query, source, kind, source_file, file_batch_id, now,
+ now.addMSecs (retry_policy_.ttl_ms), now, 0, target,
+ logical_upload_id});
+ };
+
+ enqueue_for_target (UploadTarget::Primary);
+ if (PayloadKind::Spot == kind
+ && !query.queryItemValue ("tgrid", QUrl::FullyDecoded).isEmpty ())
+ {
+ enqueue_for_target (UploadTarget::Alternate);
+ }
+ pruneExpiredUploads (now);
+ enforcePendingLimit ();
+}
+
+int WSPRNet::beginFileBatch (FileSnapshot const& snapshot)
+{
+ auto const file_batch_id = next_file_batch_id_++;
+ auto& state = file_uploads_[file_batch_id];
+ state.snapshot = snapshot;
+ return file_batch_id;
+}
+
+void WSPRNet::startUploadSession ()
+{
+ upload_session_active_ = true;
+ uploads_started_ = outstanding_requests_.size ();
+ scheduleWork ();
+ maybeFinalize ();
+}
+
+void WSPRNet::scheduleWork ()
+{
+ if (!upload_session_active_)
+ {
+ return;
+ }
+
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+ QDateTime next_attempt_at;
+ auto have_next_attempt = false;
+ auto consider_queue = [this, &next_attempt_at, &have_next_attempt]
+ (QQueue<PendingUpload> const& uploads, UploadTarget target)
+ {
+ if (hasOutstanding (target))
+ {
+ return;
+ }
+ for (auto const& upload : uploads)
+ {
+ if (!have_next_attempt || upload.next_attempt_at < next_attempt_at)
+ {
+ next_attempt_at = upload.next_attempt_at;
+ have_next_attempt = true;
+ }
+ }
+ };
+ consider_queue (pending_primary_uploads_, UploadTarget::Primary);
+ consider_queue (pending_alternate_uploads_, UploadTarget::Alternate);
+ if (!have_next_attempt)
+ {
+ upload_timer_.stop ();
+ return;
+ }
+
+ auto const delay = qMax<qint64> (0, now.msecsTo (next_attempt_at));
+ upload_timer_.start (static_cast<int> (qMin<qint64> (delay, std::numeric_limits<int>::max ())));
+}
+
+void WSPRNet::pruneExpiredUploads (QDateTime const& now)
+{
+ int dropped = 0;
+ auto prune_queue = [this, &now, &dropped](QQueue<PendingUpload>& uploads)
+ {
+ for (int i = 0; i < uploads.size ();)
+ {
+ if (uploads[i].expires_at <= now)
{
- if (!serverResponse.contains(QRegExp("spot\\(s\\) added")))
- {
- Q_EMIT uploadStatus (QString {"Upload Failed: %1"}.arg (serverResponse));
- spot_queue_.clear ();
- upload_timer_.stop ();
- }
+ markFailed (uploads.takeAt (i));
+ ++dropped;
+ }
+ else
+ {
+ ++i;
}
+ }
+ };
+ prune_queue (pending_primary_uploads_);
+ prune_queue (pending_alternate_uploads_);
+ if (dropped)
+ {
+ Q_EMIT uploadStatus (QString {"Dropped %1 expired WSPRNet upload(s)"}.arg (dropped));
+ }
+}
+
+void WSPRNet::enforcePendingLimit ()
+{
+ auto const max_pending = qMax (1, retry_policy_.max_pending);
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+
+ int dropped = 0;
+ auto enforce_queue_limit = [this, max_pending, &dropped](QQueue<PendingUpload>& uploads)
+ {
+ while (uploads.size () > max_pending)
+ {
+ markFailed (uploads.dequeue ());
+ ++dropped;
+ }
+ };
+ enforce_queue_limit (pending_primary_uploads_);
+ enforce_queue_limit (pending_alternate_uploads_);
+ if (dropped)
+ {
+ Q_EMIT uploadStatus (QString {"Dropped %1 oldest pending WSPRNet upload(s)"}.arg (dropped));
+ }
+}
+
+void WSPRNet::sendUpload (PendingUpload upload)
+{
+ auto const url = upload.target == UploadTarget::Primary ? wsprNetUrl : wsprNetUrl2;
+ QNetworkRequest request (QUrl {url});
+ request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+ if (!upload.attempts)
+ {
+ ++uploads_started_;
+ }
+ ++upload.attempts;
+ QNetworkReply *reply = transport_->post (request, upload.query.query (QUrl::FullyEncoded).toUtf8 ());
+ connect (reply, &QNetworkReply::finished, this, [this, reply]() { networkReply (reply); });
+ outstanding_requests_.insert (reply, upload);
+ Q_EMIT uploadStatus (QString {"Uploading Spot %1/%2"}.arg (uploads_started_).arg (uploadsToSend ()));
+}
+
+bool WSPRNet::replyAccepted (PendingUpload const& upload, QNetworkReply *reply, QString& server_response) const
+{
+ if (QNetworkReply::NoError != reply->error ())
+ {
+ return false;
+ }
+ server_response = reply->readAll ();
+ return PayloadKind::Status == upload.kind
+ || server_response.contains (QRegExp ("spot\\(s\\) added"));
+}
+
+bool WSPRNet::canRetry (PendingUpload const& upload, QDateTime const& now, int retry_delay_ms) const
+{
+ return upload.attempts < retry_policy_.max_attempts
+ && now.addMSecs (retry_delay_ms) < upload.expires_at;
+}
+
+int WSPRNet::retryDelayMs (PendingUpload const& upload) const
+{
+ int delay = 0;
+ if (!retry_policy_.retry_delays_ms.isEmpty ())
+ {
+ auto const index = qMin (upload.attempts - 1, retry_policy_.retry_delays_ms.size () - 1);
+ delay = retry_policy_.retry_delays_ms[qMax (0, index)];
+ }
+ if (delay <= 0 || retry_policy_.jitter_fraction <= 0.)
+ {
+ return qMax (0, delay);
+ }
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+ auto const random = QRandomGenerator::global ()->generateDouble ();
+#else
+ auto const random = qrand () / (RAND_MAX + 1.0);
+#endif
+ auto const factor = 1. - retry_policy_.jitter_fraction
+ + random * retry_policy_.jitter_fraction * 2.;
+ return qMax (0, static_cast<int> (delay * factor));
+}
- if (!spot_queue_.size ())
+int WSPRNet::uploadsToSend () const
+{
+ auto total = uploads_started_;
+ auto count_unstarted = [&total](QQueue<PendingUpload> const& uploads)
+ {
+ for (auto const& upload : uploads)
+ {
+ if (!upload.attempts)
{
- Q_EMIT uploadStatus("done");
- QFile f {m_file};
- if (f.exists ()) f.remove ();
- upload_timer_.stop ();
+ ++total;
}
}
+ };
+ count_unstarted (pending_primary_uploads_);
+ count_unstarted (pending_alternate_uploads_);
+ return qMax (uploads_started_, total);
+}
- qDebug () << QString {"WSPRnet.org %1 outstanding requests"}.arg (m_outstandingRequests.size ());
+void WSPRNet::retryUpload (PendingUpload upload, QDateTime const& now, int retry_delay_ms)
+{
+ upload.next_attempt_at = now.addMSecs (retry_delay_ms);
+ auto& uploads = upload.target == UploadTarget::Primary
+ ? pending_primary_uploads_ : pending_alternate_uploads_;
+ uploads.enqueue (upload);
+ Q_EMIT uploadStatus (QString {"Retrying WSPRNet upload in %1 ms"}.arg (retry_delay_ms));
+ enforcePendingLimit ();
+}
- // delete request object instance on return to the event loop otherwise it is leaked
- reply->deleteLater ();
+void WSPRNet::markAccepted (PendingUpload const& upload)
+{
+ if (UploadSource::File == upload.source)
+ {
+ auto state = file_uploads_.find (upload.file_batch_id);
+ if (state == file_uploads_.end ())
+ {
+ return;
+ }
+ state->accepted.insert (upload.logical_upload_id);
+ state->failed.remove (upload.logical_upload_id);
+ maybeRemoveCompletedFile (upload.file_batch_id);
+ maybeRemoveFailedFileBatch (upload.file_batch_id);
+ }
+}
+
+void WSPRNet::markFailed (PendingUpload const& upload)
+{
+ if (UploadSource::File == upload.source)
+ {
+ auto state = file_uploads_.find (upload.file_batch_id);
+ if (state == file_uploads_.end () || state->accepted.contains (upload.logical_upload_id))
+ {
+ return;
+ }
+ if (!hasPendingFileLeg (upload.file_batch_id, upload.logical_upload_id))
+ {
+ state->failed.insert (upload.logical_upload_id);
+ }
+ maybeRemoveFailedFileBatch (upload.file_batch_id);
+ }
+}
+
+void WSPRNet::maybeRemoveFailedFileBatch (int file_batch_id)
+{
+ auto const state = file_uploads_.constFind (file_batch_id);
+ if (state == file_uploads_.constEnd () || state->failed.isEmpty ())
+ {
+ return;
+ }
+
+ if (state->accepted.size () + state->failed.size () >= state->total)
+ {
+ file_uploads_.remove (file_batch_id);
+ }
+}
+
+void WSPRNet::maybeRemoveCompletedFile (int file_batch_id)
+{
+ if (!file_uploads_.contains (file_batch_id))
+ {
+ return;
+ }
+
+ auto const state = file_uploads_.value (file_batch_id);
+ if (state.total > 0 && state.accepted.size () == state.total)
+ {
+ QFile f {state.snapshot.path};
+ // wsprd can rewrite this scratch file between the check and remove.
+ // The snapshot guard prevents deleting known-new contents.
+ if (f.exists () && fileMatchesSnapshot (state.snapshot))
+ {
+ f.remove ();
+ }
+ file_uploads_.remove (file_batch_id);
+ }
+}
+
+void WSPRNet::maybeFinalize ()
+{
+ if (!upload_session_active_)
+ {
+ return;
+ }
+ if (pending_primary_uploads_.isEmpty () && pending_alternate_uploads_.isEmpty ()
+ && outstanding_requests_.isEmpty ())
+ {
+ uploads_started_ = 0;
+ upload_session_active_ = false;
+ upload_timer_.stop ();
+ Q_EMIT uploadStatus ("done");
}
}
@@ -214,6 +663,10 @@ bool WSPRNet::decodeLine (QString const& line, SpotQueue::value_type& query) con
{
auto const& rx_match = wspr_re.match (line);
if (rx_match.hasMatch ()) {
+ if (line.contains ("<...>")) {
+ return false;
+ }
+
int msgType = 0;
QString msg = rx_match.captured (7);
QString call, grid, dbm;
@@ -299,7 +752,7 @@ auto WSPRNet::urlEncodeNoSpot () const -> SpotQueue::value_type
query.addQueryItem ("dbm", m_dbm);
query.addQueryItem ("version", m_vers);
query.addQueryItem ("mode", encode_mode ());
- return query;;
+ return query;
}
auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::value_type
@@ -314,31 +767,43 @@ auto WSPRNet::urlEncodeSpot (SpotQueue::value_type& query) const -> SpotQueue::v
void WSPRNet::work()
{
- if (spots_to_send_ && spot_queue_.size ())
- {
-#if QT_VERSION < QT_VERSION_CHECK (5, 15, 0)
- if (QNetworkAccessManager::Accessible != network_manager_->networkAccessible ()) {
- // try and recover network access for QNAM
- network_manager_->setNetworkAccessible (QNetworkAccessManager::Accessible);
- }
-#endif
- QNetworkRequest request (QUrl {wsprNetUrl});
- request.setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
- auto const& spot = spot_queue_.dequeue ();
- QNetworkReply *reply = network_manager_->post (request, spot.query(QUrl::FullyEncoded).toUtf8());
- connect (reply, &QNetworkReply::finished, this, [this, reply]() { networkReply(reply); });
- m_outstandingRequests << reply;
- Q_EMIT uploadStatus(QString {"Uploading Spot %1/%2"}.arg (spots_to_send_ - spot_queue_.size()).arg (spots_to_send_));
- }
- else
+ auto const now = QDateTime::currentDateTimeUtc ();
+ pruneExpiredUploads (now);
+
+ auto send_ready_upload = [this, &now](QQueue<PendingUpload>& uploads, UploadTarget target)
{
- upload_timer_.stop ();
- }
+ if (hasOutstanding (target))
+ {
+ return;
+ }
+ for (int i = 0; i < uploads.size (); ++i)
+ {
+ if (uploads[i].next_attempt_at <= now)
+ {
+ sendUpload (uploads.takeAt (i));
+ return;
+ }
+ }
+ };
+
+ send_ready_upload (pending_primary_uploads_, UploadTarget::Primary);
+ send_ready_upload (pending_alternate_uploads_, UploadTarget::Alternate);
+
+ scheduleWork ();
+ maybeFinalize ();
}
void WSPRNet::abortOutstandingRequests () {
- spot_queue_.clear ();
- for (auto& request : m_outstandingRequests) {
+ upload_timer_.stop ();
+ pending_primary_uploads_.clear ();
+ pending_alternate_uploads_.clear ();
+ file_uploads_.clear ();
+ uploads_started_ = 0;
+ upload_session_active_ = false;
+
+ auto const requests = outstanding_requests_.keys ();
+ outstanding_requests_.clear ();
+ for (auto& request : requests) {
request->abort ();
}
}