diff --git a/plugins/feature/ais/CMakeLists.txt b/plugins/feature/ais/CMakeLists.txt index 119d5a38d..4ad9d0d44 100644 --- a/plugins/feature/ais/CMakeLists.txt +++ b/plugins/feature/ais/CMakeLists.txt @@ -31,7 +31,7 @@ if(NOT SERVER_MODE) ) set(TARGET_NAME ${PLUGINS_PREFIX}featureais) - set(TARGET_LIB Qt::Widgets) + set(TARGET_LIB Qt::Widgets Qt::Charts) set(TARGET_LIB_GUI "sdrgui") set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR}) else() diff --git a/plugins/feature/ais/ais.qrc b/plugins/feature/ais/ais.qrc index a3b220ef9..c3ee0b05b 100644 --- a/plugins/feature/ais/ais.qrc +++ b/plugins/feature/ais/ais.qrc @@ -1,5 +1,6 @@ + ../../channelrx/demodadsb/icons/chart.png map/aircraft.png map/helicopter.png map/ship.png diff --git a/plugins/feature/ais/aisgui.cpp b/plugins/feature/ais/aisgui.cpp index e21aa4363..0133de2bd 100644 --- a/plugins/feature/ais/aisgui.cpp +++ b/plugins/feature/ais/aisgui.cpp @@ -23,12 +23,14 @@ #include #include #include +#include #include "feature/featureuiset.h" #include "feature/featurewebapiutils.h" #include "gui/basicfeaturesettingsdialog.h" #include "gui/tabletapandhold.h" #include "gui/dialogpositioner.h" +#include "gui/crightclickenabler.h" #include "util/mmsi.h" #include "maincore.h" @@ -158,6 +160,7 @@ bool AISGUI::handleMessage(const Message& message) if (ais) { updateVessels(ais, report.getDateTime()); + m_messageCount++; delete ais; } @@ -196,7 +199,16 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur m_pluginAPI(pluginAPI), m_featureUISet(featureUISet), m_doApplySettings(true), - m_lastFeatureState(0) + m_lastFeatureState(0), + m_messageRateTime(QDateTime::currentDateTime()), + m_messageCount(0), + m_chartTickCount(0), + m_chart(nullptr), + m_messageSeries(nullptr), + m_shipSeries(nullptr), + m_chartXAxis(nullptr), + m_messageYAxis(nullptr), + m_shipYAxis(nullptr) { m_feature = feature; setAttribute(Qt::WA_DeleteOnClose, true); @@ -216,6 +228,8 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur connect(&m_timer, SIGNAL(timeout()), this, SLOT(removeOldVessels())); m_timer.start(60*1000); + connect(&m_chartTimer, &QTimer::timeout, this, &AISGUI::updateChart); + // Resize the table using dummy data resizeTable(); // Allow user to reorder columns @@ -239,27 +253,326 @@ AISGUI::AISGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *featur connect(ui->vessels, SIGNAL(customContextMenuRequested(QPoint)), SLOT(vessels_customContextMenuRequested(QPoint))); TableTapAndHold *tableTapAndHold = new TableTapAndHold(ui->vessels); connect(tableTapAndHold, &TableTapAndHold::tapAndHold, this, &AISGUI::vessels_customContextMenuRequested); + connect(ui->vessels, &QTableWidget::currentCellChanged, this, &AISGUI::vesselSelectionChanged); + connect(&m_vesselFinder, &VesselFinder::shipPhoto, this, &AISGUI::shipPhoto); + connect(ui->hidePhoto, &QToolButton::clicked, this, &AISGUI::hideShipPhotoClicked); + + CRightClickEnabler *displayChartClickEnabler = new CRightClickEnabler(ui->displayChart); + connect(displayChartClickEnabler, &CRightClickEnabler::rightClick, this, &AISGUI::clearChart); + + ui->photoCredit->setOpenExternalLinks(true); + hideShipPhoto(); + ui->chart->setRenderHint(QPainter::Antialiasing); + plotChart(); + m_chartTimer.start(1000); m_settings.setRollupState(&m_rollupState); displaySettings(); applySettings(true); + makeUIConnections(); m_resizer.enableChildMouseTracking(); } -AISGUI::~AISGUI() +void AISGUI::makeUIConnections() +{ + QObject::connect( + ui->vessels, + &QTableWidget::cellDoubleClicked, + this, + &AISGUI::on_vessels_cellDoubleClicked + ); + QObject::connect( + ui->displayChart, + &ButtonSwitch::clicked, + this, + &AISGUI::on_displayChart_clicked + ); + QObject::connect( + ui->deleteVessels, + &QToolButton::clicked, + this, + &AISGUI::on_deleteVessels_clicked + ); +} + +void AISGUI::hideShipPhoto() +{ + ui->shipPhoto->clear(); + ui->photoCredit->clear(); + ui->photoPanel->setVisible(false); +} + +void AISGUI::hideShipPhotoClicked() +{ + // Prevent an outstanding download from showing the photo again. + m_selectedPhotoId.clear(); + hideShipPhoto(); +} + +void AISGUI::on_displayChart_clicked(bool checked) { - // Remove all ships from map + m_settings.m_displayChart = checked; + m_settingsKeys.append("displayChart"); + applySettings(); + ui->chart->setVisible(checked); +} + +void AISGUI::on_deleteVessels_clicked() +{ + deleteAllVessels(); +} + +void AISGUI::deleteAllVessels() +{ + m_selectedPhotoId.clear(); + hideShipPhoto(); + for (int row = ui->vessels->rowCount() - 1; row >= 0; row--) { - QString mmsi = ui->vessels->item(row, VESSEL_COL_MMSI)->text(); + const QString mmsi = ui->vessels->item(row, VESSEL_COL_MMSI)->text(); sendToMap(mmsi, "", "", "", "", 0.0f, 0.0f, 0.0f, 0.0f, QDateTime(), 0.0f); } + + ui->vessels->setRowCount(0); qDeleteAll(m_vessels); + m_vessels.clear(); +} + +int AISGUI::countShips() const +{ + int ships = 0; + + for (int row = 0; row < ui->vessels->rowCount(); row++) + { + const QTableWidgetItem *typeItem = ui->vessels->item(row, VESSEL_COL_TYPE); + + if (typeItem && (typeItem->text() == "Vessel")) { + ships++; + } + } + + return ships; +} + +void AISGUI::clearChart(const QPoint& p) +{ + (void) p; + + m_messageSeries->clear(); + m_shipSeries->clear(); + m_messageCount = 0; + m_chartTickCount = 0; + m_averageTime = QDateTime(); + m_messageRateTime = QDateTime::currentDateTime(); + resetChartAxes(); +} + +void AISGUI::resetChartAxes() +{ + const QDateTime now = QDateTime::currentDateTime(); + m_chartXAxis->setMin(now.addSecs(-60)); + m_chartXAxis->setMax(now); + m_messageYAxis->setRange(0.0, 10.0); + m_shipYAxis->setRange(0.0, 10.0); +} + +void AISGUI::plotChart() +{ + QChart *oldChart = m_chart; + m_chart = new QChart(); + m_chart->layout()->setContentsMargins(0, 0, 0, 0); + m_chart->setMargins(QMargins(1, 1, 1, 1)); + m_chart->setTheme(QChart::ChartThemeDark); + m_chart->legend()->setAlignment(Qt::AlignRight); + + m_messageSeries = new QLineSeries(); + m_messageSeries->setName("Messages"); + m_shipSeries = new QLineSeries(); + m_shipSeries->setName("Ships"); + + m_chartXAxis = new QDateTimeAxis(); + m_chartXAxis->setFormat("hh:mm:ss"); + m_messageYAxis = new QValueAxis(); + m_messageYAxis->setTitleText("Messages/s"); + m_shipYAxis = new QValueAxis(); + m_shipYAxis->setTitleText("Ships"); + + m_chart->addAxis(m_chartXAxis, Qt::AlignBottom); + m_chart->addAxis(m_messageYAxis, Qt::AlignLeft); + m_chart->addAxis(m_shipYAxis, Qt::AlignRight); + m_chart->addSeries(m_messageSeries); + m_chart->addSeries(m_shipSeries); + m_messageSeries->attachAxis(m_chartXAxis); + m_messageSeries->attachAxis(m_messageYAxis); + m_shipSeries->attachAxis(m_chartXAxis); + m_shipSeries->attachAxis(m_shipYAxis); + resetChartAxes(); + + ui->chart->setChart(m_chart); + delete oldChart; +} + +void AISGUI::updateChart() +{ + const QDateTime now = QDateTime::currentDateTime(); + const qint64 elapsedMS = m_messageRateTime.msecsTo(now); + + if (elapsedMS <= 0) { + return; + } + + const double messageRate = m_messageCount / (elapsedMS / 1000.0); + const int ships = countShips(); + const bool xAtMax = (m_messageSeries->count() == 0) + || (m_messageSeries->at(m_messageSeries->count() - 1).x() == m_chartXAxis->max().toMSecsSinceEpoch()); + + m_messageSeries->append(now.toMSecsSinceEpoch(), messageRate); + m_shipSeries->append(now.toMSecsSinceEpoch(), ships); + + if (xAtMax) { + m_chartXAxis->setMax(now); + } + if (m_messageYAxis->max() < messageRate) { + m_messageYAxis->setMax(std::ceil(messageRate) + 1.0); + } + if (m_shipYAxis->max() < ships + 1) { + m_shipYAxis->setMax(ships + 1); + } + + m_messageCount = 0; + m_messageRateTime = now; + m_chartTickCount++; + + // Average one-second samples after ten minutes to limit long-running chart growth. + if ((m_chartTickCount % 60) == 0) + { + QDateTime startTime; + QDateTime endTime; + + if (m_averageTime.isValid()) + { + startTime = m_averageTime; + endTime = startTime.addSecs(60); + } + else + { + endTime = now.addSecs(-10 * 60); + startTime = endTime.addSecs(-60); + } + + averageSeries(m_messageSeries, startTime, endTime); + averageSeries(m_shipSeries, startTime, endTime); + m_averageTime = endTime; + } +} + +void AISGUI::averageSeries(QLineSeries *series, const QDateTime& startTime, const QDateTime& endTime) +{ + int startIndex = 0; + int endIndex = -1; + + for (int i = series->count() - 1; i >= 0; i--) + { + const QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(series->at(i).x()); + + if ((endIndex == -1) && (dateTime <= endTime)) { + endIndex = i; + } else if (dateTime < startTime) { + startIndex = i + 1; + break; + } + } + + const int count = endIndex - startIndex + 1; + + if ((endIndex != -1) && (count > 1)) + { + double sum = 0.0; + + for (int i = startIndex; i <= endIndex; i++) { + sum += series->at(i).y(); + } + + const double average = sum / count; + const qint64 midpoint = startTime.toMSecsSinceEpoch() + + (endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch()) / 2; + series->removePoints(startIndex, count); + series->insert(startIndex, QPointF(midpoint, average)); + } +} + +void AISGUI::vesselSelectionChanged(int currentRow, int currentColumn, int previousRow, int previousColumn) +{ + (void) currentColumn; + (void) previousRow; + (void) previousColumn; + + m_selectedPhotoId.clear(); + hideShipPhoto(); + + if ((currentRow < 0) || (currentRow >= ui->vessels->rowCount())) { + return; + } + + const QTableWidgetItem *mmsiItem = ui->vessels->item(currentRow, VESSEL_COL_MMSI); + const QTableWidgetItem *imoItem = ui->vessels->item(currentRow, VESSEL_COL_IMO); + const QString mmsi = mmsiItem ? mmsiItem->text().trimmed() : QString(); + const QString imo = imoItem ? imoItem->text().trimmed() : QString(); + bool imoOk = false; + bool mmsiOk = false; + const qulonglong imoNumber = imo.toULongLong(&imoOk); + const qulonglong mmsiNumber = mmsi.toULongLong(&mmsiOk); + + if (imoOk && (imoNumber != 0)) { + m_selectedPhotoId = QString("imo:%1").arg(imoNumber); + } else if (mmsiOk && (mmsiNumber != 0)) { + m_selectedPhotoId = QString("mmsi:%1").arg(mmsiNumber); + } else { + return; + } + + m_vesselFinder.getShipPhoto(imo, mmsi); +} + +void AISGUI::shipPhoto(const VesselFinderPhoto *photo) +{ + // A request can complete after another row has been selected. + if (!photo || (photo->m_id != m_selectedPhotoId)) { + return; + } + + if (photo->m_pixmap.isNull()) + { + hideShipPhoto(); + return; + } + + ui->shipPhoto->setPixmap(photo->m_pixmap.scaled( + 320, + 320, + Qt::KeepAspectRatio, + Qt::SmoothTransformation + )); + + const QString link = photo->m_link.toHtmlEscaped(); + const QString credit = photo->m_photographer.isEmpty() + ? QString("View on VesselFinder") + : QString("Photo by %1").arg(photo->m_photographer.toHtmlEscaped()); + ui->photoCredit->setText(QString("%2").arg(link, credit)); + ui->photoPanel->setVisible(true); +} + +AISGUI::~AISGUI() +{ + m_chartTimer.stop(); + m_timer.stop(); + disconnect(&m_vesselFinder, &VesselFinder::shipPhoto, this, &AISGUI::shipPhoto); + deleteAllVessels(); delete ui; } @@ -281,6 +594,9 @@ void AISGUI::displaySettings() setTitle(m_settings.m_title); blockApplySettings(true); + ui->displayChart->setChecked(m_settings.m_displayChart); + ui->chart->setVisible(m_settings.m_displayChart); + // Order and size columns QHeaderView *header = ui->vessels->horizontalHeader(); for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) diff --git a/plugins/feature/ais/aisgui.h b/plugins/feature/ais/aisgui.h index f21f8e12e..b2bba06b4 100644 --- a/plugins/feature/ais/aisgui.h +++ b/plugins/feature/ais/aisgui.h @@ -27,10 +27,12 @@ #include #include #include +#include #include "feature/featuregui.h" #include "util/messagequeue.h" #include "util/ais.h" +#include "util/vesselfinder.h" #include "settings/rollupstate.h" #include "aissettings.h" @@ -43,6 +45,10 @@ namespace Ui { class AISGUI; } +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +using namespace QtCharts; +#endif + class AISGUI : public FeatureGUI { Q_OBJECT @@ -77,10 +83,24 @@ private: AIS* m_ais; MessageQueue m_inputMessageQueue; QTimer m_timer; + QTimer m_chartTimer; int m_lastFeatureState; + QDateTime m_messageRateTime; + int m_messageCount; + int m_chartTickCount; + QDateTime m_averageTime; + + QChart *m_chart; + QLineSeries *m_messageSeries; + QLineSeries *m_shipSeries; + QDateTimeAxis *m_chartXAxis; + QValueAxis *m_messageYAxis; + QValueAxis *m_shipYAxis; QRandomGenerator m_random; QHash m_vessels; // Hash of mmsi to vessels + VesselFinder m_vesselFinder; + QString m_selectedPhotoId; static QStringList m_shipModels; static QStringList m_sailboatModels; static QHash m_labelOffset; @@ -95,6 +115,7 @@ private: void applySettings(bool force = false); void displaySettings(); bool handleMessage(const Message& message); + void makeUIConnections(); void sendToMap(const QString &name, const QString &label, const QString &image, const QString &text, @@ -104,6 +125,13 @@ private: ); void updateVessels(AISMessage *ais, QDateTime dateTime); void getImageAndModel(const QString &type, const QString &shipType, int length, const QString &status, Vessel *vessel); + void hideShipPhoto(); + void hideShipPhotoClicked(); + void deleteAllVessels(); + int countShips() const; + void plotChart(); + void resetChartAxes(); + void averageSeries(QLineSeries *series, const QDateTime& startTime, const QDateTime& endTime); void resizeTable(); QAction *createCheckableItem(QString& text, int idx, bool checked, const char *slot); @@ -132,6 +160,12 @@ private slots: void onMenuDialogCalled(const QPoint &p); void onWidgetRolled(QWidget* widget, bool rollDown); void handleInputMessages(); + void on_displayChart_clicked(bool checked); + void on_deleteVessels_clicked(); + void clearChart(const QPoint& p); + void updateChart(); + void vesselSelectionChanged(int currentRow, int currentColumn, int previousRow, int previousColumn); + void shipPhoto(const VesselFinderPhoto *photo); void on_vessels_cellDoubleClicked(int row, int column); void vessels_customContextMenuRequested(QPoint pos); void vessels_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex); diff --git a/plugins/feature/ais/aisgui.ui b/plugins/feature/ais/aisgui.ui index 68918a104..126650d61 100644 --- a/plugins/feature/ais/aisgui.ui +++ b/plugins/feature/ais/aisgui.ui @@ -57,7 +57,7 @@ Vessels, Base stations and Aids-to-navigation - + 3 @@ -70,11 +70,78 @@ 2 - - 2 - - - + + 2 + + + + + + + Display chart. Right click to reset data + + + + + + + :/ais/chart.png:/ais/chart.png + + + true + + + + + + + Delete all vessels and table items + + + + + + + :/bin.png:/bin.png + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + + 0 + + + 0 + + + 0 + + + 0 + + + Vessels @@ -212,19 +279,133 @@ - + + + + + 330 + 16777215 + + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + Hide ship photograph + + + × + + + true + + + + + + + + 180 + 120 + + + + + 320 + 320 + + + + QFrame::StyledPanel + + + Qt::AlignCenter + + + + + + + Qt::RichText + + + Qt::AlignCenter + + + true + + + true + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + 300 + 160 + + + + AIS messages per second and ships over time + + + + + + + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
RollupContents QWidget
gui/rollupcontents.h
1
+ + QChartView + QGraphicsView +
QtCharts
+
+ diff --git a/plugins/feature/ais/aissettings.cpp b/plugins/feature/ais/aissettings.cpp index 526b16ba2..f9bcc23e2 100644 --- a/plugins/feature/ais/aissettings.cpp +++ b/plugins/feature/ais/aissettings.cpp @@ -50,6 +50,7 @@ void AISSettings::resetToDefaults() m_reverseAPIFeatureSetIndex = 0; m_reverseAPIFeatureIndex = 0; m_workspaceIndex = 0; + m_displayChart = false; for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) { @@ -76,6 +77,7 @@ QByteArray AISSettings::serialize() const s.writeS32(28, m_workspaceIndex); s.writeBlob(29, m_geometryBytes); + s.writeBool(30, m_displayChart); for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) { s.writeS32(300 + i, m_vesselColumnIndexes[i]); @@ -128,6 +130,7 @@ bool AISSettings::deserialize(const QByteArray& data) d.readS32(28, &m_workspaceIndex, 0); d.readBlob(29, &m_geometryBytes); + d.readBool(30, &m_displayChart, false); for (int i = 0; i < AIS_VESSEL_COLUMNS; i++) { d.readS32(300 + i, &m_vesselColumnIndexes[i], i); @@ -172,6 +175,9 @@ void AISSettings::applySettings(const QStringList& settingsKeys, const AISSettin if (settingsKeys.contains("workspaceIndex")) { m_workspaceIndex = settings.m_workspaceIndex; } + if (settingsKeys.contains("displayChart")) { + m_displayChart = settings.m_displayChart; + } if (settingsKeys.contains("vesselColumnIndexes")) { @@ -216,6 +222,9 @@ QString AISSettings::getDebugString(const QStringList& settingsKeys, bool force) if (settingsKeys.contains("workspaceIndex") || force) { ostr << " m_workspaceIndex: " << m_workspaceIndex; } + if (settingsKeys.contains("displayChart") || force) { + ostr << " m_displayChart: " << m_displayChart; + } if (settingsKeys.contains("vesselColumnIndexes")) { diff --git a/plugins/feature/ais/aissettings.h b/plugins/feature/ais/aissettings.h index 9b0d48d26..9480f5a43 100644 --- a/plugins/feature/ais/aissettings.h +++ b/plugins/feature/ais/aissettings.h @@ -41,6 +41,7 @@ struct AISSettings Serializable *m_rollupState; int m_workspaceIndex; QByteArray m_geometryBytes; + bool m_displayChart; int m_vesselColumnIndexes[AIS_VESSEL_COLUMNS]; int m_vesselColumnSizes[AIS_VESSEL_COLUMNS]; diff --git a/plugins/feature/ais/readme.md b/plugins/feature/ais/readme.md index 8ee748930..60e392b02 100644 --- a/plugins/feature/ais/readme.md +++ b/plugins/feature/ais/readme.md @@ -34,6 +34,10 @@ The vessels table displays the current status for each vessel, base station or a * Updated - Gives the date and time the last message was received. * Messages - Displays the number of messages received. +* Selecting a vessel displays its first available VesselFinder gallery image to the right of the table. The photographer credit below the image links to the vessel's gallery. + +The chart button displays the received AIS message rate and number of ships over time. Right click the chart button to reset the collected chart data. The delete button removes every table item and its corresponding object from the Map feature. + Right clicking on the table header allows you to select which columns to show. The columns can be reordered by left clicking and dragging the column header. Right clicking on a table cell allows you to copy the cell contents, view the vessel on a variety of websites or find the vessel on the map. @@ -54,3 +58,5 @@ Selecting an AIS item on the map will display a text bubble containing informati Map icons are by Maarten van der Werf, DE Alvida Biersack, ID and jokokerto, MY, from the Noun Project https://thenounproject.com/ Map icons are from http://all-free-download.com. + +Vessel photographs and photographer credits are provided by https://www.vesselfinder.com/ diff --git a/sdrbase/CMakeLists.txt b/sdrbase/CMakeLists.txt index 646518c89..120d05599 100644 --- a/sdrbase/CMakeLists.txt +++ b/sdrbase/CMakeLists.txt @@ -261,6 +261,7 @@ set(sdrbase_SOURCES util/ourairportsdb.cpp util/peakfinder.cpp util/planespotters.cpp + util/vesselfinder.cpp util/png.cpp util/prettyprint.cpp util/profiler.cpp @@ -530,6 +531,7 @@ set(sdrbase_HEADERS util/outairportsdb.h util/peakfinder.h util/planespotters.h + util/vesselfinder.h util/png.h util/prettyprint.h util/profiler.h diff --git a/sdrbase/util/vesselfinder.cpp b/sdrbase/util/vesselfinder.cpp new file mode 100644 index 000000000..fc9481b70 --- /dev/null +++ b/sdrbase/util/vesselfinder.cpp @@ -0,0 +1,284 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "vesselfinder.h" + +#include +#include +#include +#include +#include +#include +#include + +const char *VesselFinder::m_userAgent = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) SDRangel/1.0"; + +VesselFinder::VesselFinder(QObject *parent) : + QObject(parent), + m_networkManager(new QNetworkAccessManager(this)) +{ + connect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &VesselFinder::handleReply + ); +} + +VesselFinder::~VesselFinder() +{ + disconnect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &VesselFinder::handleReply + ); + qDeleteAll(m_photos); +} + +void VesselFinder::setCommonHeaders(QNetworkRequest& request) +{ + request.setRawHeader("User-Agent", m_userAgent); + request.setRawHeader("Accept-Language", "en-US,en;q=0.8"); + request.setAttribute( + QNetworkRequest::RedirectPolicyAttribute, + QNetworkRequest::NoLessSafeRedirectPolicy + ); +} + +QString VesselFinder::identifier(const QString& imo, const QString& mmsi) +{ + bool imoOk = false; + bool mmsiOk = false; + const qulonglong imoNumber = imo.trimmed().toULongLong(&imoOk); + const qulonglong mmsiNumber = mmsi.trimmed().toULongLong(&mmsiOk); + + if (imoOk && (imoNumber != 0)) { + return QString("imo:%1").arg(imoNumber); + } + if (mmsiOk && (mmsiNumber != 0)) { + return QString("mmsi:%1").arg(mmsiNumber); + } + + return QString(); +} + +void VesselFinder::getShipPhoto(const QString& imo, const QString& mmsi) +{ + const QString id = identifier(imo, mmsi); + + if (id.isEmpty()) { + return; + } + + if (m_photos.contains(id)) + { + VesselFinderPhoto *photo = m_photos.value(id); + + if (photo->m_complete) { + emit shipPhoto(photo); + } + + return; + } + + VesselFinderPhoto *photo = new VesselFinderPhoto(); + photo->m_id = id; + photo->m_imo = imo.trimmed(); + photo->m_mmsi = mmsi.trimmed(); + m_photos.insert(id, photo); + + requestGallery(photo, id.startsWith("imo:")); +} + +void VesselFinder::requestGallery(VesselFinderPhoto *photo, bool useIMO) +{ + QUrl url("https://www.vesselfinder.com/gallery"); + QUrlQuery query; + query.addQueryItem(useIMO ? "imo" : "mmsi", useIMO ? photo->m_imo : photo->m_mmsi); + url.setQuery(query); + + photo->m_queryUsesIMO = useIMO; + photo->m_link = url.toString(QUrl::FullyEncoded); + + QNetworkRequest request(url); + setCommonHeaders(request); + request.setRawHeader("Accept", "text/html,application/xhtml+xml"); + request.setAttribute(QNetworkRequest::User, GalleryRequest); + request.setOriginatingObject(photo); + m_networkManager->get(request); +} + +void VesselFinder::handleReply(QNetworkReply *reply) +{ + if (!reply) { + return; + } + + VesselFinderPhoto *photo = qobject_cast( + reply->request().originatingObject() + ); + const RequestType requestType = static_cast( + reply->request().attribute(QNetworkRequest::User).toInt() + ); + + if (!photo) + { + qDebug() << "VesselFinder::handleReply: missing photo request context"; + reply->deleteLater(); + return; + } + + if (reply->error() != QNetworkReply::NoError) + { + qDebug() << "VesselFinder::handleReply:" << reply->url() << reply->errorString(); + + if ((requestType != GalleryRequest) || !tryMMSIFallback(photo)) { + finish(photo); + } + + reply->deleteLater(); + return; + } + + const QByteArray bytes = reply->readAll(); + + if (requestType == GalleryRequest) + { + if (!parseGallery(photo, bytes) && !tryMMSIFallback(photo)) { + finish(photo); + } + } + else + { + parseImage(photo, bytes); + } + + reply->deleteLater(); +} + +bool VesselFinder::parseGallery(VesselFinderPhoto *photo, const QByteArray& bytes) +{ + const QString html = QString::fromUtf8(bytes); + const QRegularExpression photoLinkExpression( + "]*href\\s*=\\s*[\\\"']/ship-photos/(\\d+)[\\\"'][^>]*>", + QRegularExpression::CaseInsensitiveOption + ); + const QRegularExpressionMatch photoLinkMatch = photoLinkExpression.match(html); + + if (!photoLinkMatch.hasMatch()) { + return false; + } + + const int linkStart = photoLinkMatch.capturedStart(); + const int linkEnd = html.indexOf("", photoLinkMatch.capturedEnd(), Qt::CaseInsensitive); + + if (linkEnd < 0) { + return false; + } + + const QString photoAnchor = html.mid(linkStart, linkEnd - linkStart); + const QRegularExpression imageExpression( + "]*src\\s*=\\s*[\\\"']([^\\\"']+)[\\\"']", + QRegularExpression::CaseInsensitiveOption + ); + const QRegularExpressionMatch imageMatch = imageExpression.match(photoAnchor); + + if (!imageMatch.hasMatch()) { + return false; + } + + photo->m_imageUrl = imageMatch.captured(1); + photo->m_imageUrl.replace("&", "&"); + + const int nextPicture = html.indexOf("class=\"picture", linkEnd, Qt::CaseInsensitive); + const QString cardTail = html.mid( + linkEnd, + nextPicture < 0 ? -1 : nextPicture - linkEnd + ); + const QRegularExpression photographerExpression( + "]*class\\s*=\\s*[\\\"'][^\\\"']*photographer[^\\\"']*[\\\"'][^>]*>(.*?)", + QRegularExpression::CaseInsensitiveOption | QRegularExpression::DotMatchesEverythingOption + ); + const QRegularExpressionMatch photographerMatch = photographerExpression.match(cardTail); + + if (photographerMatch.hasMatch()) { + photo->m_photographer = htmlToPlainText(photographerMatch.captured(1)); + } + + QUrl imageUrl(photo->m_imageUrl); + + if (imageUrl.isRelative()) { + imageUrl = QUrl(photo->m_link).resolved(imageUrl); + } + + QNetworkRequest request(imageUrl); + setCommonHeaders(request); + request.setRawHeader("Accept", "image/avif,image/webp,image/png,image/jpeg,*/*;q=0.8"); + request.setRawHeader("Referer", photo->m_link.toUtf8()); + request.setAttribute(QNetworkRequest::User, ImageRequest); + request.setOriginatingObject(photo); + m_networkManager->get(request); + + return true; +} + +QString VesselFinder::htmlToPlainText(QString html) +{ + html.remove(QRegularExpression("<[^>]*>")); + html.replace(" ", " ", Qt::CaseInsensitive); + html.replace(" ", " ", Qt::CaseInsensitive); + html.replace("&", "&", Qt::CaseInsensitive); + html.replace(""", "\"", Qt::CaseInsensitive); + html.replace("'", "'", Qt::CaseInsensitive); + html.replace("'", "'", Qt::CaseInsensitive); + html.replace("<", "<", Qt::CaseInsensitive); + html.replace(">", ">", Qt::CaseInsensitive); + return html.simplified(); +} + +void VesselFinder::parseImage(VesselFinderPhoto *photo, const QByteArray& bytes) +{ + if (!photo->m_pixmap.loadFromData(bytes)) { + qDebug() << "VesselFinder::parseImage: unable to decode" << bytes.size() << "bytes"; + } + + finish(photo); +} + +bool VesselFinder::tryMMSIFallback(VesselFinderPhoto *photo) +{ + bool mmsiOk = false; + const qulonglong mmsi = photo->m_mmsi.toULongLong(&mmsiOk); + + if (photo->m_queryUsesIMO && mmsiOk && (mmsi != 0)) + { + requestGallery(photo, false); + return true; + } + + return false; +} + +void VesselFinder::finish(VesselFinderPhoto *photo) +{ + photo->m_complete = true; + emit shipPhoto(photo); +} diff --git a/sdrbase/util/vesselfinder.h b/sdrbase/util/vesselfinder.h new file mode 100644 index 000000000..b2efa63fc --- /dev/null +++ b/sdrbase/util/vesselfinder.h @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_VESSELFINDER_H +#define INCLUDE_VESSELFINDER_H + +#include +#include +#include +#include + +#include "export.h" + +class QNetworkAccessManager; +class QNetworkReply; +class QNetworkRequest; + +class SDRBASE_API VesselFinderPhoto : public QObject +{ + Q_OBJECT + +public: + QString m_id; + QString m_imo; + QString m_mmsi; + QString m_imageUrl; + QString m_link; + QString m_photographer; + QPixmap m_pixmap; + bool m_queryUsesIMO = false; + bool m_complete = false; +}; + +// VesselFinder gallery wrapper. Gallery results and images are cached in memory so +// selecting the same vessel repeatedly does not generate additional web requests. +class SDRBASE_API VesselFinder : public QObject +{ + Q_OBJECT + +public: + explicit VesselFinder(QObject *parent = nullptr); + ~VesselFinder(); + + void getShipPhoto(const QString& imo, const QString& mmsi); + +signals: + void shipPhoto(const VesselFinderPhoto *photo); + +private slots: + void handleReply(QNetworkReply *reply); + +private: + enum RequestType + { + GalleryRequest = 1, + ImageRequest + }; + + static const char *m_userAgent; + static void setCommonHeaders(QNetworkRequest& request); + static QString identifier(const QString& imo, const QString& mmsi); + static QString htmlToPlainText(QString html); + void requestGallery(VesselFinderPhoto *photo, bool useIMO); + bool parseGallery(VesselFinderPhoto *photo, const QByteArray& bytes); + void parseImage(VesselFinderPhoto *photo, const QByteArray& bytes); + bool tryMMSIFallback(VesselFinderPhoto *photo); + void finish(VesselFinderPhoto *photo); + + QNetworkAccessManager *m_networkManager; + QHash m_photos; +}; + +#endif // INCLUDE_VESSELFINDER_H