Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2021 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 : #include "networkmanager.h"
23 :
24 : #include "network/offlinenetworkreply.h"
25 :
26 : #include <QNetworkAccessManager>
27 : #include <QNetworkReply>
28 : #include <QUrl>
29 :
30 : #include "networkerrors.h"
31 :
32 : #include "log.h"
33 :
34 : using namespace muse;
35 : using namespace muse::network;
36 : using namespace muse::async;
37 :
38 0 : static bool openDevice(QIODevicePtr& device, QIODevice::OpenModeFlag flags)
39 : {
40 0 : IF_ASSERT_FAILED(device) {
41 0 : return false;
42 : }
43 :
44 0 : if (device->isOpen()) {
45 0 : device->close();
46 : }
47 :
48 0 : return device->open(flags);
49 : }
50 :
51 0 : static void closeDevice(QIODevicePtr& device)
52 : {
53 0 : if (device && device->isOpen()) {
54 0 : device->close();
55 : }
56 0 : }
57 :
58 0 : static Ret retFromReply(const QNetworkReply* reply)
59 : {
60 0 : if (!reply) {
61 0 : return make_ret(Err::NetworkError);
62 : }
63 :
64 0 : Ret ret = muse::make_ok();
65 :
66 0 : if (reply->error() == QNetworkReply::TimeoutError) {
67 0 : ret = make_ret(Err::Timeout);
68 0 : } else if (reply->error() == QNetworkReply::OperationCanceledError) {
69 0 : ret = make_ret(Err::Abort);
70 0 : } else if (reply->error() != QNetworkReply::NoError) {
71 0 : ret.setCode(static_cast<int>(Err::NetworkError));
72 : }
73 :
74 0 : QString errorString = reply->errorString();
75 0 : if (!errorString.isEmpty()) {
76 0 : ret.setText(errorString.toStdString());
77 : }
78 :
79 0 : QVariant status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
80 0 : if (status.isValid()) {
81 0 : ret.setData("status", status.toInt());
82 : }
83 :
84 0 : QVariant statusText = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
85 0 : if (statusText.isValid()) {
86 0 : ret.setData("statusText", statusText.toString().toStdString());
87 : }
88 :
89 0 : QVariantMap headers;
90 0 : const QList<QNetworkReply::RawHeaderPair> pairs = reply->rawHeaderPairs();
91 0 : for (const QNetworkReply::RawHeaderPair& pair : pairs) {
92 0 : const QString name = QString::fromUtf8(pair.first).toLower();
93 0 : const QString value = QString::fromUtf8(pair.second);
94 0 : if (headers.contains(name)) {
95 0 : headers[name] = headers[name].toString() + QStringLiteral(", ") + value;
96 : } else {
97 0 : headers.insert(name, value);
98 : }
99 0 : }
100 0 : ret.setData("headers", headers);
101 :
102 0 : return ret;
103 0 : }
104 :
105 0 : NetworkManager::NetworkManager(QObject* parent)
106 0 : : QObject(parent)
107 : {
108 0 : m_manager = new QNetworkAccessManager(this);
109 0 : m_manager->setTransferTimeout(); // Use Qt's default timeout (30s)
110 0 : }
111 :
112 0 : RetVal<Progress> NetworkManager::get(const QUrl& url, IncomingDevicePtr incomingData, const RequestHeaders& headers)
113 : {
114 0 : return execRequest(GET_REQUEST, url, incomingData, NoOutgoingDevice(), headers);
115 : }
116 :
117 0 : RetVal<Progress> NetworkManager::head(const QUrl& url, const RequestHeaders& headers)
118 : {
119 0 : return execRequest(HEAD_REQUEST, url, nullptr, NoOutgoingDevice(), headers);
120 : }
121 :
122 0 : RetVal<Progress> NetworkManager::post(const QUrl& url, OutgoingDeviceVar outgoingData, IncomingDevicePtr incomingData,
123 : const RequestHeaders& headers)
124 : {
125 0 : return execRequest(POST_REQUEST, url, incomingData, outgoingData, headers);
126 : }
127 :
128 0 : RetVal<Progress> NetworkManager::put(const QUrl& url, OutgoingDeviceVar outgoingData, IncomingDevicePtr incomingData,
129 : const RequestHeaders& headers)
130 : {
131 0 : return execRequest(PUT_REQUEST, url, incomingData, outgoingData, headers);
132 : }
133 :
134 0 : RetVal<Progress> NetworkManager::patch(const QUrl& url, OutgoingDeviceVar outgoingData, IncomingDevicePtr incomingData,
135 : const RequestHeaders& headers)
136 : {
137 0 : return execRequest(PATCH_REQUEST, url, incomingData, outgoingData, headers);
138 : }
139 :
140 0 : RetVal<Progress> NetworkManager::del(const QUrl& url, IncomingDevicePtr incomingData, const RequestHeaders& headers)
141 : {
142 0 : return execRequest(DELETE_REQUEST, url, incomingData, NoOutgoingDevice(), headers);
143 : }
144 :
145 0 : RetVal<Progress> NetworkManager::execRequest(RequestType requestType, const QUrl& url,
146 : IncomingDevicePtr incomingData,
147 : OutgoingDeviceVar outgoingData,
148 : const RequestHeaders& headers)
149 : {
150 0 : if (std::holds_alternative<QIODevicePtr>(outgoingData)) {
151 0 : if (!openDevice(std::get<QIODevicePtr>(outgoingData), QIODevice::ReadOnly)) {
152 0 : return RetVal<Progress>::make_ret((int)Err::FiledOpenIODeviceRead);
153 : }
154 : }
155 :
156 0 : if (incomingData) {
157 0 : if (!openDevice(incomingData, QIODevice::WriteOnly)) {
158 0 : return RetVal<Progress>::make_ret((int)Err::FiledOpenIODeviceWrite);
159 : }
160 : }
161 :
162 0 : const QNetworkRequest request = prepareRequest(url, headers);
163 0 : QNetworkReply* reply = sendRequest(requestType, request, outgoingData);
164 0 : IF_ASSERT_FAILED(reply) {
165 0 : return RetVal<Progress>::make_ret((int)Err::NetworkError);
166 : }
167 :
168 0 : const size_t requestId = m_lastRequestId++;
169 0 : RequestData& requestData = m_requestDataMap[requestId];
170 0 : requestData.incomingData = incomingData;
171 0 : requestData.outgoingData = outgoingData;
172 0 : requestData.reply = reply;
173 0 : requestData.progress.start();
174 0 : requestData.progress.canceled().onNotify(this, [this, requestId]() {
175 0 : auto it = m_requestDataMap.find(requestId);
176 0 : IF_ASSERT_FAILED(it != m_requestDataMap.end() && it->second.reply) {
177 0 : return;
178 : }
179 :
180 0 : it->second.reply->abort();
181 : });
182 :
183 0 : if (!std::holds_alternative<NoOutgoingDevice>(outgoingData)) {
184 0 : connect(reply, &QNetworkReply::uploadProgress, this, [this, requestId](qint64 curr, qint64 total) {
185 0 : auto it = m_requestDataMap.find(requestId);
186 0 : IF_ASSERT_FAILED(it != m_requestDataMap.end()) {
187 0 : return;
188 : }
189 :
190 0 : it->second.progress.progress(curr, total);
191 : });
192 : }
193 :
194 0 : if (incomingData) {
195 0 : connect(reply, &QNetworkReply::downloadProgress, this, [this, requestId](qint64 curr, qint64 total) {
196 0 : auto it = m_requestDataMap.find(requestId);
197 0 : IF_ASSERT_FAILED(it != m_requestDataMap.end()) {
198 0 : return;
199 : }
200 :
201 0 : it->second.progress.progress(curr, total);
202 : });
203 :
204 0 : connect(reply, &QNetworkReply::readyRead, this, [this, requestId]() {
205 0 : auto it = m_requestDataMap.find(requestId);
206 0 : IF_ASSERT_FAILED(it != m_requestDataMap.end()) {
207 0 : return;
208 : }
209 :
210 0 : RequestData& data = it->second;
211 0 : IF_ASSERT_FAILED(data.incomingData && data.reply) {
212 0 : return;
213 : }
214 :
215 0 : const QByteArray chunk = data.reply->readAll();
216 0 : if (data.incomingData->write(chunk) != chunk.size()) {
217 0 : LOGE() << "failed to store incoming data: " << data.incomingData->errorString();
218 0 : data.reply->abort();
219 : }
220 0 : });
221 : }
222 :
223 0 : connect(reply, &QNetworkReply::finished, this, [this, requestId]() {
224 0 : auto it = m_requestDataMap.find(requestId);
225 0 : IF_ASSERT_FAILED(it != m_requestDataMap.end() && it->second.reply) {
226 0 : return;
227 : }
228 :
229 0 : RequestData& data = it->second;
230 0 : data.progress.canceled().disconnect(this);
231 :
232 0 : if (std::holds_alternative<QIODevicePtr>(data.outgoingData)) {
233 0 : closeDevice(std::get<QIODevicePtr>(data.outgoingData));
234 : }
235 :
236 0 : closeDevice(data.incomingData);
237 :
238 0 : const Ret ret = retFromReply(data.reply);
239 0 : data.reply->deleteLater();
240 :
241 0 : Progress progress = data.progress;
242 0 : m_requestDataMap.erase(it);
243 0 : progress.finish(ret);
244 0 : });
245 :
246 0 : return RetVal<Progress>::make_ok(requestData.progress);
247 0 : }
248 :
249 0 : QNetworkRequest NetworkManager::prepareRequest(const QUrl& url, const RequestHeaders& headers) const
250 : {
251 0 : QNetworkRequest request(url);
252 0 : request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true);
253 :
254 0 : RequestHeaders _headers = headers;
255 0 : if (_headers.isEmpty()) {
256 0 : _headers = configuration()->defaultHeaders();
257 : }
258 :
259 0 : for (auto it = _headers.knownHeaders.cbegin(); it != _headers.knownHeaders.cend(); ++it) {
260 0 : request.setHeader(it.key(), it.value());
261 : }
262 :
263 0 : for (auto it = _headers.rawHeaders.cbegin(); it != _headers.rawHeaders.cend(); ++it) {
264 0 : request.setRawHeader(it.key(), it.value());
265 : }
266 :
267 0 : return request;
268 0 : }
269 :
270 0 : QNetworkReply* NetworkManager::sendRequest(RequestType type, const QNetworkRequest& request, const OutgoingDeviceVar& device)
271 : {
272 0 : if (configuration()->isOffline() && isNetworkUrl(request.url())) {
273 0 : LOGW() << "offline mode, the request is blocked: " << request.url().toString();
274 0 : return new OfflineNetworkReply(QNetworkAccessManager::CustomOperation, request, m_manager);
275 : }
276 :
277 0 : switch (type) {
278 0 : case GET_REQUEST: return m_manager->get(request);
279 0 : case HEAD_REQUEST: return m_manager->head(request);
280 0 : case DELETE_REQUEST: return m_manager->deleteResource(request);
281 0 : case PUT_REQUEST: {
282 0 : if (std::holds_alternative<QIODevicePtr>(device)) {
283 0 : return m_manager->put(request, std::get<QIODevicePtr>(device).get());
284 0 : } else if (std::holds_alternative<QHttpMultiPartPtr>(device)) {
285 0 : return m_manager->put(request, std::get<QHttpMultiPartPtr>(device).get());
286 : }
287 0 : break;
288 : }
289 0 : case PATCH_REQUEST: {
290 0 : if (std::holds_alternative<QIODevicePtr>(device)) {
291 0 : return m_manager->sendCustomRequest(request, "PATCH", std::get<QIODevicePtr>(device).get());
292 0 : } else if (std::holds_alternative<QHttpMultiPartPtr>(device)) {
293 0 : return m_manager->sendCustomRequest(request, "PATCH", std::get<QHttpMultiPartPtr>(device).get());
294 : }
295 0 : break;
296 : }
297 0 : case POST_REQUEST: {
298 0 : if (std::holds_alternative<QIODevicePtr>(device)) {
299 0 : return m_manager->post(request, std::get<QIODevicePtr>(device).get());
300 0 : } else if (std::holds_alternative<QHttpMultiPartPtr>(device)) {
301 0 : return m_manager->post(request, std::get<QHttpMultiPartPtr>(device).get());
302 : }
303 0 : break;
304 : }
305 : }
306 :
307 0 : UNREACHABLE;
308 : return nullptr;
309 : }
|