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
|
#include "network/jsonwebtask.h"
#include "moc_jsonwebtask.cpp"
#if QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
#include <QBuffer>
#endif
#include <QMetaMethod>
#include <QMimeDatabase>
#include <QNetworkRequest>
#include <QTimerEvent>
#include <mutex> // std::once_flag
#include "util/assert.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 7, 0)
#include "util/compatibility.h"
#endif
#include "util/counter.h"
#include "util/logger.h"
#include "util/thread_affinity.h"
namespace mixxx {
namespace network {
namespace {
const Logger kLogger("mixxx::network::JsonWebTask");
std::once_flag registerMetaTypesOnceFlag;
void registerMetaTypesOnce() {
JsonWebResponse::registerMetaType();
}
const QString JSON_CONTENT_TYPE = "application/json";
const QMimeType JSON_MIME_TYPE = QMimeDatabase().mimeTypeForName(JSON_CONTENT_TYPE);
/// If parsing fails the functions returns std::nullopt and optionally
/// the response content in pInvalidResponseContent for further processing.
std::optional<QJsonDocument> readJsonContent(
QNetworkReply* reply,
std::pair<QMimeType, QByteArray>* pInvalidResponseContent = nullptr) {
DEBUG_ASSERT(reply);
DEBUG_ASSERT(JSON_MIME_TYPE.isValid());
auto contentType = WebTask::readContentType(*reply);
auto optContentData = WebTask::readContentData(reply);
if (contentType != JSON_MIME_TYPE) {
kLogger.debug()
<< "Received content type"
<< contentType
<< "instead of"
<< JSON_MIME_TYPE;
if (pInvalidResponseContent) {
*pInvalidResponseContent = std::make_pair(
std::move(contentType),
optContentData.value_or(QByteArray{}));
}
return std::nullopt;
}
if (!optContentData || optContentData->isEmpty()) {
kLogger.debug() << "Empty JSON network reply";
return QJsonDocument{};
}
QJsonParseError parseError;
auto jsonDocument = QJsonDocument::fromJson(
*optContentData,
&parseError);
// QJsonDocument::fromJson() returns a non-null document
// if parsing succeeds and otherwise null on error. The
// parse error must only be evaluated if the returned
// document is null!
if (jsonDocument.isNull() &&
parseError.error != QJsonParseError::NoError) {
kLogger.warning()
<< "Failed to parse JSON data:"
<< parseError.errorString()
<< "at offset"
<< parseError.offset;
if (pInvalidResponseContent) {
*pInvalidResponseContent = std::make_pair(
std::move(contentType),
std::move(*optContentData));
}
return std::nullopt;
}
return jsonDocument;
}
// TODO: Allow to customize headers and attributes?
QNetworkRequest newRequest(
const QUrl& url) {
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, JSON_CONTENT_TYPE);
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy);
return request;
}
} // anonymous namespace
/*static*/ void JsonWebResponse::registerMetaType() {
qRegisterMetaType<JsonWebResponse>("mixxx::network::JsonWebResponse");
}
QDebug operator<<(QDebug dbg, const JsonWebResponse& arg) {
return dbg
<< "WebResponseWithContent{"
<< arg.m_response
<< arg.m_content
<< '}';
}
JsonWebTask::JsonWebTask(
QNetworkAccessManager* networkAccessManager,
QUrl baseUrl,
JsonWebRequest&& request,
QObject* parent)
: WebTask(networkAccessManager, parent),
m_baseUrl(std::move(baseUrl)),
m_request(request) {
std::call_once(registerMetaTypesOnceFlag, registerMetaTypesOnce);
DEBUG_ASSERT(!m_baseUrl.isEmpty());
}
void JsonWebTask::onFinished(
const JsonWebResponse& jsonResponse) {
kLogger.info()
<< this
<< "Received JSON response"
<< jsonResponse;
deleteLater();
}
void JsonWebTask::onFinishedCustom(
const WebResponseWithContent& customResponse) {
kLogger.info()
<< this
<< "Received custom response"
<< customResponse;
deleteLater();
}
QNetworkReply* JsonWebTask::sendNetworkRequest(
QNetworkAccessManager* networkAccessManager,
HttpRequestMethod method,
const QUrl& url,
const QJsonDocument& content) {
switch (method) {
case HttpRequestMethod::Get: {
DEBUG_ASSERT(m_request.content.isEmpty());
if (kLogger.debugEnabled()) {
kLogger.debug()
<< this
<< "GET"
<< url;
}
return networkAccessManager->get(
QNetworkRequest(url));
}
case HttpRequestMethod::Put: {
const auto body = content.toJson(QJsonDocument::Compact);
if (kLogger.debugEnabled()) {
kLogger.debug()
<< this
<< "PUT"
<< url
<< body;
}
return networkAccessManager->put(
newRequest(url),
body);
}
case HttpRequestMethod::Post: {
const auto body = content.toJson(QJsonDocument::Compact);
if (kLogger.debugEnabled()) {
kLogger.debug()
<< this
<< "POST"
<< url
<< body;
}
return networkAccessManager->post(
newRequest(url),
body);
}
case HttpRequestMethod::Patch: {
const auto body = m_request.content.toJson(QJsonDocument::Compact);
if (kLogger.debugEnabled()) {
kLogger.debug()
<< this
<< "PATCH"
<< url
<< body;
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
return networkAccessManager->sendCustomRequest(
newRequest(url),
"PATCH",
body);
#else
auto* buffer = new QBuffer(this);
buffer->setData(body);
return networkAccessManager->sendCustomRequest(
newRequest(url),
"PATCH",
buffer);
#endif
}
case HttpRequestMethod::Delete: {
DEBUG_ASSERT(content.isEmpty());
if (kLogger.debugEnabled()) {
kLogger.debug()
<< this
<< "DELETE"
<< url;
}
return networkAccessManager->deleteResource(
QNetworkRequest(url));
}
}
DEBUG_ASSERT(!"unreachable");
return nullptr;
}
QNetworkReply* JsonWebTask::doStartNetworkRequest(
QNetworkAccessManager* networkAccessManager,
int parentTimeoutMillis) {
Q_UNUSED(parentTimeoutMillis);
DEBUG_ASSERT_QOBJECT_THREAD_AFFINITY(this);
DEBUG_ASSERT(networkAccessManager);
VERIFY_OR_DEBUG_ASSERT(m_baseUrl.isValid()) {
kLogger.warning() << "Invalid base URL" << m_baseUrl;
return nullptr;
}
QUrl url = m_baseUrl;
url.setPath(m_request.path);
VERIFY_OR_DEBUG_ASSERT(url.isValid()) {
kLogger.warning() << "Invalid request path" << m_request.path;
return nullptr;
}
if (!m_request.query.isEmpty()) {
url.setQuery(m_request.query);
VERIFY_OR_DEBUG_ASSERT(url.isValid()) {
kLogger.warning() << "Invalid query string" << m_request.query.toString();
return nullptr;
}
}
// Already validated while composing (see above)
DEBUG_ASSERT(url.isValid());
return sendNetworkRequest(
networkAccessManager,
m_request.method,
url,
m_request.content);
}
void JsonWebTask::doNetworkReplyFinished(
QNetworkReply* finishedNetworkReply,
HttpStatusCode statusCode) {
DEBUG_ASSERT(finishedNetworkReply);
std::optional<QJsonDocument> optJsonContent;
auto webResponse = WebResponse{
finishedNetworkReply->url(),
finishedNetworkReply->request().url(),
statusCode};
if (statusCode != kHttpStatusCodeInvalid) {
std::pair<QMimeType, QByteArray> contentTypeAndBytes;
optJsonContent = readJsonContent(finishedNetworkReply, &contentTypeAndBytes);
if (!optJsonContent) {
// Failed to read JSON content
onFinishedCustom(WebResponseWithContent{
std::move(webResponse),
std::move(contentTypeAndBytes.first),
std::move(contentTypeAndBytes.second)});
return;
}
}
onFinished(JsonWebResponse{
std::move(webResponse),
optJsonContent.value_or(QJsonDocument{})});
}
void JsonWebTask::emitFailed(
const network::JsonWebResponse& response) {
VERIFY_OR_DEBUG_ASSERT(
isSignalFuncConnected(&JsonWebTask::failed)) {
kLogger.warning()
<< this
<< "Unhandled failed signal"
<< response
|