swift
Loading...
Searching...
No Matches
airportdatareader.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2016 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QElapsedTimer>
7#include <QFileInfo>
8#include <QNetworkReply>
9#include <QPointer>
10#include <QStringBuilder>
11
12#include "core/application.h"
14#include "misc/logmessage.h"
16
17using namespace swift::misc;
18using namespace swift::misc::aviation;
19using namespace swift::misc::network;
20using namespace swift::misc::db;
21
23{
25 : CDatabaseReader(parent, config, QStringLiteral("CAirportDataReader"))
26 {
27 // void
28 }
29
31
33 {
34 return this->getAirports().findFirstByIcao(CAirportIcaoCode(designator));
35 }
36
38 {
39 return this->getAirports().findFirstByNameOrLocation(nameOrLocation);
40 }
41
42 int CAirportDataReader::getAirportsCount() const { return this->getAirports().size(); }
43
44 bool CAirportDataReader::readFromJsonFilesInBackground(const QString &dir, CEntityFlags::Entity whatToRead,
45 bool overrideNewerOnly)
46 {
47 if (dir.isEmpty() || whatToRead == CEntityFlags::NoEntity)
48 {
49 return false;
50 }
51
53 QTimer::singleShot(0, this, [=, this]() {
54 if (!myself)
55 {
56 return;
57 }
58 const CStatusMessageList msgs = this->readFromJsonFiles(dir, whatToRead, overrideNewerOnly);
59 if (msgs.isFailure())
60 {
62 }
63 });
64 return true;
65 }
66
67 CStatusMessageList CAirportDataReader::readFromJsonFiles(const QString &dir, CEntityFlags::Entity whatToRead,
68 bool overrideNewerOnly)
69 {
70 const QDir directory(dir);
71 if (!directory.exists())
72 {
73 return CStatusMessage(this).error(u"Missing directory '%1'") << dir;
74 }
75
76 whatToRead &= CEntityFlags::AirportEntity; // can handle these entities
77 if (whatToRead == CEntityFlags::NoEntity)
78 {
79 return CStatusMessage(this).info(u"'%1' No entity for this reader")
80 << CEntityFlags::entitiesToString(whatToRead);
81 }
82
83 CEntityFlags::Entity reallyRead = CEntityFlags::NoEntity;
84
86 const QString fileName = CFileUtils::appendFilePaths(dir, "airports.json");
87 const QFileInfo fi(fileName);
88 if (!fi.exists())
89 {
90 msgs.push_back(CStatusMessage(this).warning(u"File '%1' does not exist") << fileName);
91 }
92 else if (!this->overrideCacheFromFile(overrideNewerOnly, fi, CEntityFlags::AirportEntity, msgs))
93 {
94 // void
95 }
96 else
97 {
100 if (!airportsJson.isEmpty())
101 {
102 try
103 {
104 const CAirportList airports = CAirportList::fromMultipleJsonFormats(airportsJson);
105 const int c = airports.size();
106 msgs.push_back(m_airportCache.set(airports, fi.birthTime().toUTC().toMSecsSinceEpoch()));
107
109 reallyRead |= CEntityFlags::AirportEntity;
110 }
111 catch (const CJsonException &ex)
112 {
115 ex, this, QStringLiteral("Reading airports from '%1'").arg(fileName));
116 }
117 }
118 }
119 return msgs;
120 }
121
123
124 QDateTime CAirportDataReader::getCacheTimestamp(CEntityFlags::Entity entities) const
125 {
126 return entities == CEntityFlags::AirportEntity ? m_airportCache.getAvailableTimestamp() : QDateTime();
127 }
128
129 int CAirportDataReader::getCacheCount(CEntityFlags::Entity entity) const
130 {
131 return entity == CEntityFlags::AirportEntity ? m_airportCache.get().size() : 0;
132 }
133
135 {
136 CEntityFlags::Entity entities = CEntityFlags::NoEntity;
138 {
139 entities |= CEntityFlags::AirportEntity;
140 }
141 return entities;
142 }
143
145 {
146 CEntityFlags::Entity entities = CEntityFlags::NoEntity;
148 {
149 entities |= CEntityFlags::AirportEntity;
150 }
151 return entities;
152 }
153
154 void CAirportDataReader::synchronizeCaches(CEntityFlags::Entity entities)
155 {
156 if (entities.testFlag(CEntityFlags::AirportEntity))
157 {
158 if (m_syncedAirportCache)
159 {
160 return;
161 }
162 m_syncedAirportCache = true;
163 m_airportCache.synchronize();
164 }
165 }
166
167 void CAirportDataReader::admitCaches(CEntityFlags::Entity entities)
168 {
169 if (entities.testFlag(CEntityFlags::AirportEntity))
170 {
171 m_airportCache.admit();
172 }
173 }
174
175 void CAirportDataReader::invalidateCaches(CEntityFlags::Entity entities)
176 {
177 if (entities.testFlag(CEntityFlags::AirportEntity))
178 {
179 CDataCache::instance()->clearAllValues(m_airportCache.getKey());
180 }
181 }
182
183 bool CAirportDataReader::hasChangedUrl(CEntityFlags::Entity entity, CUrl &oldUrlInfo, CUrl &newUrlInfo) const
184 {
185 Q_UNUSED(entity)
186 oldUrlInfo = m_readerUrlCache.get();
187 newUrlInfo = this->getBaseUrl(CDbFlags::DbReading);
188 return CDatabaseReader::isChangedUrl(oldUrlInfo, newUrlInfo);
189 }
190
191 CUrl CAirportDataReader::getDbServiceBaseUrl() const { return sApp->getGlobalSetup().getDbAirportReaderUrl(); }
192
193 CUrl CAirportDataReader::getAirportsUrl(CDbFlags::DataRetrievalModeFlag mode) const
194 {
196 }
197
198 void CAirportDataReader::parseAirportData(QNetworkReply *nwReplyPtr)
199 {
200 // wrap pointer, make sure any exit cleans up reply
201 // required to use delete later as object is created in a different thread
203 if (!this->doWorkCheck())
204 {
205 return;
206 }
207
208 const CDatabaseReader::JsonDatastoreResponse res =
210 const QUrl url = nwReply->url();
211
212 if (res.hasErrorMessage())
213 {
214 CLogMessage::preformatted(res.lastWarningOrAbove());
216 return;
217 }
218
219 // parsing
221 CAirportList airports;
222 CAirportList inconsistent;
223 if (res.isRestricted())
224 {
225 const CAirportList incrementalAirports(CAirportList::fromDatabaseJson(res, &inconsistent));
226 if (incrementalAirports.isEmpty())
227 {
228 return;
229 } // currently ignored
230 airports = this->getAirports();
231 airports.replaceOrAddObjectsByKey(incrementalAirports);
232 }
233 else
234 {
235 QElapsedTimer time;
236 time.start();
237 airports = CAirportList::fromDatabaseJson(res, &inconsistent);
238 this->logParseMessage("airports", airports.size(), static_cast<int>(time.elapsed()), res);
239 }
240
241 if (!inconsistent.isEmpty())
242 {
244 u"Inconsistent airports: " % inconsistent.dbKeysAsString(", ")),
245 Q_FUNC_INFO);
246 }
247
248 if (!this->doWorkCheck())
249 {
250 return;
251 }
252 const int size = airports.size();
253 qint64 latestTimestamp = airports.latestTimestampMsecsSinceEpoch();
254 if (size > 0 && latestTimestamp < 0)
255 {
256 CLogMessage(this).error(u"No timestamp in airport list, setting to last modified value");
257 latestTimestamp = lastModifiedMsSinceEpoch(nwReply.data());
258 }
259
260 m_airportCache.set(airports, latestTimestamp);
261 this->updateReaderUrl(getBaseUrl(CDbFlags::DbReading));
262
264 }
265
266 void CAirportDataReader::read(CEntityFlags::Entity entity, CDbFlags::DataRetrievalModeFlag mode,
267 const QDateTime &newerThan)
268 {
269 this->threadAssertCheck();
270 if (!this->doWorkCheck())
271 {
272 return;
273 }
275
276 if (entity.testFlag(CEntityFlags::AirportEntity))
277 {
278 CUrl url = this->getAirportsUrl(mode);
279 if (!url.isEmpty())
280 {
281 url.appendQuery(queryLatestTimestamp(newerThan));
282 this->getFromNetworkAndLog(url, { this, &CAirportDataReader::parseAirportData });
284 }
285 else
286 {
288 }
289 }
290 }
291
292 void CAirportDataReader::airportCacheChanged() { this->cacheHasChanged(CEntityFlags::AirportEntity); }
293
294 void CAirportDataReader::baseUrlCacheChanged()
295 {
296 // void
297 }
298
299 void CAirportDataReader::updateReaderUrl(const CUrl &url)
300 {
301 const CUrl current = m_readerUrlCache.get();
302 if (current == url)
303 {
304 return;
305 }
306 const CStatusMessage m = m_readerUrlCache.set(url);
307 if (m.isFailure())
308 {
310 }
311 }
312} // namespace swift::core::db
static void logInconsistentData(const swift::misc::CStatusMessage &msg, const char *funcInfo=nullptr)
Use this to log inconsistent data.
void threadAssertCheck() const
Make sure everything runs correctly in own thread.
QNetworkReply * getFromNetworkAndLog(const swift::misc::network::CUrl &url, const swift::misc::CSlot< void(QNetworkReply *)> &callback)
Get request from network, and log with m_urlReadLog.
bool doWorkCheck() const
Still enabled etc.?
qint64 lastModifiedMsSinceEpoch(QNetworkReply *nwReply) const
When was reply last modified, -1 if N/A.
bool readFromJsonFilesInBackground(const QString &dir, swift::misc::network::CEntityFlags::Entity whatToRead, bool overrideNewerOnly)
Data read from local data.
swift::misc::network::CEntityFlags::Entity getSupportedEntities() const
Supported entities by this reader.
swift::misc::aviation::CAirport getAirportForIcaoDesignator(const QString &designator) const
Returns airport for designator (or default).
CAirportDataReader(QObject *parent, const CDatabaseReaderConfigList &config)
Constructor.
swift::misc::network::CUrl getDbServiceBaseUrl() const
Get the service URL, individual for each reader.
swift::misc::network::CEntityFlags::Entity getEntitiesWithCacheTimestampNewerThan(const QDateTime &threshold) const
Entities already having data in cache (based on timestamp assumption).
void invalidateCaches(swift::misc::network::CEntityFlags::Entity entities)
Invalidate the caches for given entities.
int getAirportsCount() const
Returns a list of all airports in the database.
swift::misc::aviation::CAirport getAirportForNameOrLocation(const QString &location) const
Get airports for location.
void synchronizeCaches(swift::misc::network::CEntityFlags::Entity entities)
Admit caches for given entities.
bool hasChangedUrl(swift::misc::network::CEntityFlags::Entity entity, swift::misc::network::CUrl &oldUrlInfo, swift::misc::network::CUrl &newUrlInfo) const
Changed URL, means the cache values have been read from elsewhere.
swift::misc::aviation::CAirportList getAirports() const
Returns a list of all airports in the database.
int getCacheCount(swift::misc::network::CEntityFlags::Entity entity) const
Cache`s number of entities.
swift::misc::CStatusMessageList readFromJsonFiles(const QString &dir, swift::misc::network::CEntityFlags::Entity whatToRead, bool overrideNewerOnly)
Data read from local data.
void admitCaches(swift::misc::network::CEntityFlags::Entity entities)
Admit caches for given entities.
QDateTime getCacheTimestamp(swift::misc::network::CEntityFlags::Entity entities) const
Get cache timestamp.
swift::misc::network::CEntityFlags::Entity getEntitiesWithCacheCount() const
Entities already having data in cache.
Value object encapsulating a list of reader configs.
void emitAndLogDataRead(swift::misc::network::CEntityFlags::Entity entity, int number, const JsonDatastoreResponse &res)
Emit signal and log when data have been read.
static QString queryLatestTimestamp(const QDateTime &ts)
Latest timestamp query for DB.
virtual void cacheHasChanged(swift::misc::network::CEntityFlags::Entity entities)
Cache for given entity has changed.
void logNoWorkingUrl(swift::misc::network::CEntityFlags::Entity entity)
Log if no working URL exists, using m_noWorkingUrlSeverity.
CDatabaseReader(QObject *owner, const CDatabaseReaderConfigList &config, const QString &name)
Constructor.
bool overrideCacheFromFile(bool overrideNewerOnly, const QFileInfo &fileInfo, swift::misc::network::CEntityFlags::Entity entity, swift::misc::CStatusMessageList &msgs) const
Override cache from file.
swift::misc::network::CUrl getBaseUrl(swift::misc::db::CDbFlags::DataRetrievalModeFlag mode) const
Base URL for mode (either a shared or DB URL).
void dataRead(swift::misc::network::CEntityFlags::Entity entities, swift::misc::network::CEntityFlags::ReadState state, int number, const QUrl &url)
Combined read signal.
static bool isChangedUrl(const swift::misc::network::CUrl &oldUrl, const swift::misc::network::CUrl &currentUrl)
Has URL been changed? Means we load from a different server.
static QString fileNameForMode(swift::misc::network::CEntityFlags::Entity entity, swift::misc::db::CDbFlags::DataRetrievalModeFlag mode)
File name for given mode, either php service or shared file name.
CDatabaseReader::JsonDatastoreResponse setStatusAndTransformReplyIntoDatastoreResponse(QNetworkReply *nwReply)
Check if terminated or error, otherwise split into array of objects.
void logParseMessage(const QString &entity, int size, int msElapsed, const JsonDatastoreResponse &response) const
Parsing info message.
bool hasCacheTimestampNewerThan(swift::misc::network::CEntityFlags::Entity entity, const QDateTime &threshold) const
Has entity a valid and newer timestamp.
static QJsonObject readQJsonObjectFromDatabaseFile(const QString &filename)
QJsonObject from database JSON file (normally shared file).
static CDataCache * instance()
Return the singleton instance.
static QString appendFilePaths(const QString &path1, const QString &path2)
Append file paths.
Thrown when a convertFromJson method encounters an unrecoverable error in JSON data.
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
size_type size() const
Returns number of elements in the sequence.
Definition sequence.h:273
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Streamable status message, e.g.
static CStatusMessage fromJsonException(const CJsonException &ex, const CLogCategoryList &categories, const QString &prefix)
Object from JSON exception message.
static constexpr auto SeverityInfo
Status severities.
bool isFailure() const
Operation considered unsuccessful.
Status messages, e.g. from Core -> GUI.
bool isFailure() const
Any message is marked as failure.
void clearAllValues(const QString &keyPrefix={})
Clear all values from the cache.
qint64 latestTimestampMsecsSinceEpoch() const
Latest timestamp.
Value object encapsulating information about an airpot.
Definition airport.h:36
Value object encapsulating information of airport ICAO data.
Value object for a list of airports.
Definition airportlist.h:29
static CAirportList fromDatabaseJson(const QJsonArray &array, CAirportList *inconsistent=nullptr)
From our DB JSON.
CAirport findFirstByIcao(const CAirportIcaoCode &icao) const
Find first station by callsign, if not return default.
CAirport findFirstByNameOrLocation(const QString &nameOrLocation) const
Find first by name or location, if not return default.
DataRetrievalModeFlag
Which data to read, requires corresponding readers.
Definition dbflags.h:25
@ DbReading
directly from DB
Definition dbflags.h:27
int replaceOrAddObjectsByKey(const CONTAINER &container)
Update or insert data (based on DB key).
QString dbKeysAsString(const QString &separator) const
The DB keys as string.
static CAirportList fromMultipleJsonFormats(const QJsonObject &jsonObject)
@ ReadStarted
reading has been started
Definition entityflags.h:62
static QString entitiesToString(CEntityFlags::Entity entities, const QString &separator=", ")
Entities to string list.
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
Definition url.h:27
bool isEmpty() const
Empty.
Definition url.cpp:63
CUrl withAppendedPath(const QString &path) const
Append path.
Definition url.cpp:151
void appendQuery(const QString &queryToAppend)
Append query.
Definition url.cpp:75
Classes interacting with the swift database (aka "datastore").
Free functions in swift::misc.
qint64 toMSecsSinceEpoch() const const
QDateTime toUTC() const const
bool exists() const const
qint64 elapsed() const const
QString absoluteFilePath() const const
QDateTime birthTime() const const
bool exists(const QString &path)
bool isEmpty() const const
QObject(QObject *parent)
QObject * parent() const const
bool isEmpty() const const
QUrl fromLocalFile(const QString &localFile)
QString url(QUrl::FormattingOptions options) const const