swift
Loading...
Searching...
No Matches
vatsimstatusfilereader.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QByteArray>
7#include <QDateTime>
8#include <QList>
9#include <QMetaObject>
10#include <QNetworkReply>
11#include <QScopedPointer>
12#include <QScopedPointerDeleteLater>
13#include <QString>
14#include <QStringList>
15#include <QTimer>
16#include <QUrl>
17#include <QtGlobal>
18
19#include "core/application.h"
21#include "misc/logmessage.h"
22#include "misc/network/url.h"
23#include "misc/statusmessage.h"
24
25using namespace swift::misc;
26using namespace swift::misc::aviation;
27using namespace swift::misc::network;
28using namespace swift::misc::simulation;
29using namespace swift::misc::physical_quantities;
30using namespace swift::core::data;
31
32namespace swift::core::vatsim
33{
35 {
36 // do not connect with time, will be read once at startup
37 }
38
40 {
41 Q_ASSERT_X(hasStarted(), Q_FUNC_INFO, "Thread was not started yet!");
43 QTimer::singleShot(0, this, [=] {
44 if (!myself)
45 {
46 return;
47 }
48 myself->read();
49 });
50 }
51
52 CUrl CVatsimStatusFileReader::getMetarFileUrl() const { return m_lastGoodSetup.get().getMetarFileUrl(); }
53
54 CUrl CVatsimStatusFileReader::getDataFileUrl() const { return m_lastGoodSetup.get().getDataFileUrl(); }
55
56 void CVatsimStatusFileReader::read()
57 {
58 this->threadAssertCheck();
59 if (!this->doWorkCheck())
60 {
61 return;
62 }
63
64 Q_ASSERT_X(sApp, Q_FUNC_INFO, "Missing application");
65 const CUrl url(sApp->getGlobalSetup().getVatsimStatusFileUrl());
66 if (url.isEmpty())
67 {
68 return;
69 }
70 CLogMessage(this).info(u"Trigger read of VATSIM status file from '%1'") << url.toQString(true);
71 this->getFromNetworkAndLog(url, { this, &CVatsimStatusFileReader::parseVatsimFile });
72 }
73
74 void CVatsimStatusFileReader::parseVatsimFile(QNetworkReply *nwReplyPtr)
75 {
76 // wrap pointer, make sure any exit cleans up reply
77 // required to use delete later as object is created in a different thread
78 QScopedPointer<QNetworkReply, QScopedPointerDeleteLater> nwReply(nwReplyPtr);
79
80 // Worker thread, make sure to write only synced here!
81 this->threadAssertCheck();
82 if (!this->doWorkCheck())
83 {
84 CLogMessage(this).debug() << Q_FUNC_INFO;
85 CLogMessage(this).info(u"Terminated VATSIM status file parsing process"); // for users
86 return; // stop, terminate straight away, ending thread
87 }
88
89 this->logNetworkReplyReceived(nwReplyPtr);
90 const QString urlString = nwReply->url().toString();
91
92 if (nwReply->error() == QNetworkReply::NoError)
93 {
94 const QString statusFileData = nwReply->readAll();
95 nwReply->close(); // close asap
96
97 if (statusFileData.isEmpty()) return;
98 auto jsonDoc = QJsonDocument::fromJson(statusFileData.toUtf8());
99 if (jsonDoc.isEmpty())
100 {
101 return;
102 }
103
104 CUrl dataFileUrl;
105 CUrl serverFileUrl;
106 CUrl metarFileUrl;
107
108 // Always taking the first URL from the file
109 // (at the time of writing, also only one URL per service is available anyway)
110 if (const QJsonArray dataUrls = jsonDoc["data"]["v3"].toArray(); !dataUrls.empty())
111 {
112 dataFileUrl = QUrl(dataUrls.at(0).toString());
113 }
114
115 if (const QJsonArray serverFileUrls = jsonDoc["data"]["servers"].toArray(); !serverFileUrls.empty())
116 {
117 serverFileUrl = QUrl(serverFileUrls.at(0).toString());
118 }
119
120 if (const QJsonArray metarUrls = jsonDoc["metar"].toArray(); !metarUrls.empty())
121 {
122 metarFileUrl = QUrl(metarUrls.at(0).toString());
123 }
124
125 // cache itself is thread safe, avoid writing with unchanged data
126 CVatsimSetup vs(m_lastGoodSetup.get());
127 const bool changed = vs.setUrls(dataFileUrl, serverFileUrl, metarFileUrl);
128 vs.setUtcTimestamp(QDateTime::currentDateTime());
129 const CStatusMessage cacheMsg = m_lastGoodSetup.set(vs);
130 if (cacheMsg.isFailure())
131 {
133 }
134 else
135 {
136 CLogMessage(this).info(u"Read VATSIM status file from '%1'") << urlString;
137 }
138 Q_UNUSED(changed);
139
140 // data read finished
141 emit this->statusFileRead(statusFileData.size());
143 }
144 else
145 {
146 // network error
147 CLogMessage(this).warning(u"Reading VATSIM status file failed '%1' '%2'")
148 << nwReply->errorString() << urlString;
149 nwReply->abort();
151 }
152 }
153} // namespace swift::core::vatsim
void threadAssertCheck() const
Make sure everything runs correctly in own thread.
void logNetworkReplyReceived(QNetworkReply *reply)
Network reply received, mark in m_urlReadLog.
CThreadedReader(const CThreadedReader &)=delete
Copy constructor.
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.?
swift::misc::network::CUrl getDataFileUrl() const
Data file URL.
swift::misc::network::CUrl getMetarFileUrl() const
METAR URL.
void readInBackgroundThread()
Start reading in own thread.
void dataRead(swift::misc::network::CEntityFlags::Entity entity, swift::misc::network::CEntityFlags::ReadState state, int bytes)
Data have been read.
void statusFileRead(int bytes)
Data have been read.
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
bool isFailure() const
Operation considered unsuccessful.
bool hasStarted() const
True if the worker has started.
Definition worker.h:200
@ VatsimStatusFile
the VATSIM status file (URLs for data files etc.)
Definition entityflags.h:38
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
Definition url.h:27
Core data traits (aka cached values) and classes.
Free functions in swift::misc.
QDateTime currentDateTime()
QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error)
QObject(QObject *parent)
bool isEmpty() const const
qsizetype size() const const
QByteArray toUtf8() const const