-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusagereportingmanager.cpp
More file actions
304 lines (260 loc) · 12.2 KB
/
Copy pathusagereportingmanager.cpp
File metadata and controls
304 lines (260 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include "usagereportingmanager.h"
#include <QDebug>
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTimer>
#include <QUuid>
// ─────────────────────────────────────────────────────────────
// Construction
// ─────────────────────────────────────────────────────────────
QString UsageReportingManager::generateSessionId()
{
return QUuid::createUuid().toString(QUuid::WithoutBraces);
}
UsageReportingManager::UsageReportingManager(QObject* parent)
: QObject(parent)
, m_nam(new QNetworkAccessManager(this))
, m_sessionId(generateSessionId())
, m_serverUrl(QString::fromLatin1(kDefaultServerUrl))
{
qDebug() << "TrackClick usage: session id" << m_sessionId;
}
UsageReportingManager::~UsageReportingManager()
{
// Normally a no-op: MainWindow calls shutdown() from aboutToQuit, while the
// event loop is still healthy. This is the safety net for teardown paths
// that never reach that signal.
shutdown();
}
// ─────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────
void UsageReportingManager::sendStartupReport()
{
if (!m_reportingEnabled) return; // user opted out — send nothing
post(QLatin1String(kStartupPath), serializeStartupPayload(), [this](bool success) {
m_startupReportSent = success;
emit startupReportFinished(success, m_lastStartupResponse);
});
}
void UsageReportingManager::sendClickModeReport(const ClickModeReportPayload& payload)
{
// Still track the mode locally so that a user who opts back in later reports
// the mode the session is actually in, but send nothing while opted out.
m_lastClickMode = payload.clickingMode;
if (!m_reportingEnabled) return;
post(QLatin1String(kClickModePath), serializeClickModePayload(payload), [this](bool success) {
m_clickModeReportSent = success;
emit clickModeReportFinished(success, m_lastClickModeResponse);
});
}
void UsageReportingManager::shutdown()
{
if (m_shuttingDown)
return;
m_shuttingDown = true;
// Opted out: skip the catch-up posts entirely. Without this the opt-out
// would leak both reports on every quit, since the block below deliberately
// sends whatever has not been reported yet.
if (!m_reportingEnabled)
return;
waitForPending();
if (!m_startupReportSent)
m_startupReportSent = postBlocking(QLatin1String(kStartupPath), serializeStartupPayload());
// Sent even when the user never switched modes: /startup records the mode the
// session opened with, this one records the mode it ended on.
if (!m_clickModeReportSent) {
ClickModeReportPayload payload;
payload.softwareType = m_startupPayload.softwareType;
payload.clickingMode = m_lastClickMode;
m_clickModeReportSent = postBlocking(QLatin1String(kClickModePath),
serializeClickModePayload(payload));
}
}
// ─────────────────────────────────────────────────────────────
// Request plumbing
// ─────────────────────────────────────────────────────────────
QUrl UsageReportingManager::urlFor(const QString& path) const
{
QString spec = m_serverUrl.trimmed();
if (spec.isEmpty())
return QUrl();
if (!spec.contains(QLatin1String("://")))
spec.prepend(QLatin1String("http://"));
QUrl url(spec, QUrl::StrictMode);
if (!url.isValid() || url.host().isEmpty())
return QUrl();
// Keep any base path the endpoint carries, then append the report path.
QString base = url.path();
while (base.endsWith(QLatin1Char('/')))
base.chop(1);
url.setPath(base + path);
url.setQuery(QString());
url.setFragment(QString());
return url;
}
QNetworkReply* UsageReportingManager::startPost(const QString& path, const QByteArray& body,
int timeoutMs)
{
const QUrl url = urlFor(path);
if (!url.isValid()) {
qWarning() << "TrackClick usage: invalid server URL:" << m_serverUrl;
return nullptr;
}
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
qDebug() << "TrackClick usage: POST" << url.toString() << body;
QNetworkReply* reply = m_nam->post(request, body);
if (!reply)
return nullptr;
// Qt's own transfer timeout only exists from 5.15, and TrackClick still
// builds against 5.12 — abort on our own timer instead so a hung server
// can never wedge the caller (or app exit).
QTimer* abortTimer = new QTimer(reply);
abortTimer->setSingleShot(true);
connect(abortTimer, &QTimer::timeout, reply, &QNetworkReply::abort);
abortTimer->start(timeoutMs);
return reply;
}
void UsageReportingManager::post(const QString& path, const QByteArray& body,
std::function<void(bool)> done)
{
QNetworkReply* reply = startPost(path, body, kRequestTimeoutMs);
if (!reply) {
done(false);
return;
}
m_pending.insert(reply);
connect(reply, &QNetworkReply::finished, this,
[this, path, reply, done = std::move(done)]() mutable {
m_pending.remove(reply);
const bool success = handleReply(path, reply);
reply->deleteLater();
done(success);
});
}
bool UsageReportingManager::postBlocking(const QString& path, const QByteArray& body)
{
QNetworkReply* reply = startPost(path, body, kShutdownTimeoutMs);
if (!reply)
return false;
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
if (!reply->isFinished())
loop.exec(QEventLoop::ExcludeUserInputEvents);
const bool success = handleReply(path, reply);
reply->deleteLater(); // owned by m_nam either way, so never leaked
return success;
}
void UsageReportingManager::waitForPending()
{
if (m_pending.isEmpty())
return;
QEventLoop loop;
QTimer budget;
budget.setSingleShot(true);
connect(&budget, &QTimer::timeout, &loop, &QEventLoop::quit);
budget.start(kShutdownTimeoutMs);
// The replies' finished handlers run inside this loop; poll for the set
// draining rather than tracking each one individually.
QTimer drained;
connect(&drained, &QTimer::timeout, &loop, [this, &loop] {
if (m_pending.isEmpty())
loop.quit();
});
drained.start(25);
loop.exec(QEventLoop::ExcludeUserInputEvents);
// Give up on anything still in flight (iterating a copy: aborting completes
// the reply, whose handler mutates m_pending).
const QSet<QNetworkReply*> stragglers = m_pending;
for (QNetworkReply* reply : stragglers)
reply->abort();
}
bool UsageReportingManager::handleReply(const QString& path, QNetworkReply* reply)
{
const QVariant statusAttr = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
const QByteArray responseBody = reply->readAll();
// No status at all means the request never reached the server (DNS, refused
// connection, our abort timer, …).
if (!statusAttr.isValid()) {
qWarning() << "TrackClick usage: POST" << path << "failed:" << reply->errorString();
return false;
}
const int status = statusAttr.toInt();
if (status != 200 && status != 201) {
qWarning() << "TrackClick usage: POST" << path << "returned status" << status;
return false;
}
qDebug() << "TrackClick usage: POST" << path << "ok:" << responseBody;
// A malformed or empty body is not a delivery failure — the report landed.
if (path == QLatin1String(kStartupPath))
parseStartupResponse(responseBody, m_lastStartupResponse);
else if (path == QLatin1String(kClickModePath))
parseClickModeResponse(responseBody, m_lastClickModeResponse);
return true;
}
// ─────────────────────────────────────────────────────────────
// JSON
// ─────────────────────────────────────────────────────────────
bool UsageReportingManager::parseStartupResponse(const QByteArray& json,
StartupReportResponse& out)
{
QJsonParseError error{};
const QJsonDocument doc = QJsonDocument::fromJson(json, &error);
if (error.error != QJsonParseError::NoError || !doc.isObject()) {
qWarning() << "TrackClick usage: failed to parse startup response:" << error.errorString();
return false;
}
const QJsonObject object = doc.object();
out.latestSoftwareVersion = object.value(QLatin1String("latestSoftwareVersion")).toString();
out.softwareDownloadUrl = object.value(QLatin1String("softwareDownloadUrl")).toString();
out.newerVersionAvailable = object.value(QLatin1String("newerVersionAvailable")).toBool();
out.minimumSoftwareVersion = object.value(QLatin1String("minimumSoftwareVersion")).toString();
out.latestGameslistDownloadUrl = object.value(QLatin1String("latestGameslistDownloadUrl")).toString();
out.latestGameslistVersion = object.value(QLatin1String("latestGameslistVersion")).toInt();
out.newsUrl = object.value(QLatin1String("newsUrl")).toString();
out.newsVersion = object.value(QLatin1String("newsVersion")).toInt();
return true;
}
bool UsageReportingManager::parseClickModeResponse(const QByteArray& json,
ClickModeReportResponse& out)
{
QJsonParseError error{};
const QJsonDocument doc = QJsonDocument::fromJson(json, &error);
if (error.error != QJsonParseError::NoError || !doc.isObject()) {
qWarning() << "TrackClick usage: failed to parse click-mode response:" << error.errorString();
return false;
}
out.success = doc.object().value(QLatin1String("success")).toBool();
return true;
}
QByteArray UsageReportingManager::serializeStartupPayload() const
{
QJsonObject json;
json[QLatin1String("sessionId")] = m_sessionId;
// Omitted rather than sent empty when the caller never set one, so the
// backend can tell "this build does not report it" from a real value.
if (!m_userId.isEmpty())
json[QLatin1String("userId")] = m_userId;
json[QLatin1String("operatingSystem")] = m_startupPayload.operatingSystem;
json[QLatin1String("softwareType")] = m_startupPayload.softwareType;
json[QLatin1String("softwareVersion")] = m_startupPayload.softwareVersion;
json[QLatin1String("statusId")] = m_startupPayload.statusId;
json[QLatin1String("trackingMode")] = m_startupPayload.trackingMode;
json[QLatin1String("trackingClip")] = m_startupPayload.trackingClip;
json[QLatin1String("clickingMode")] = static_cast<int>(m_startupPayload.clickingMode);
return QJsonDocument(json).toJson(QJsonDocument::Compact);
}
QByteArray UsageReportingManager::serializeClickModePayload(const ClickModeReportPayload& payload) const
{
QJsonObject json;
json[QLatin1String("sessionId")] = m_sessionId;
json[QLatin1String("softwareType")] = payload.softwareType;
json[QLatin1String("clickingMode")] = static_cast<int>(payload.clickingMode);
return QJsonDocument(json).toJson(QJsonDocument::Compact);
}