Debian Codegraph @

src/librssguard/network-web/networkfactory.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "network-web/networkfactory.h"
4
5 #include "definitions/definitions.h"
6 #include "miscellaneous/textfactory.h"
7 #include "network-web/downloader.h"
8
9 #include <QEventLoop>
10 #include <QIcon>
11 #include <QMetaEnum>
12 #include <QPixmap>
13 #include <QRegularExpression>
14 #include <QTextDocument>
15 #include <QTimer>
16
17 #define SECS_WHEN_RETRYAFTER_MISSING 120
18
19 QDateTime NetworkFactory::extractRetryAfter(const QString& retry_after_value) {
20 if (retry_after_value.simplified().isEmpty()) {
21 return QDateTime::currentDateTimeUtc().addSecs(SECS_WHEN_RETRYAFTER_MISSING);
22 }
23
24 bool is_int = false;
25 int seconds = retry_after_value.toInt(&is_int, 10);
26
27 if (is_int) {
28 // Some websites (Reddit) somehow return "0" Retry-After header value.
29 // In that case make it at least two minutes to wait.
30 return QDateTime::currentDateTimeUtc().addSecs(seconds <= 0 ? SECS_WHEN_RETRYAFTER_MISSING : seconds);
31 }
32
33 return QDateTime::fromString(retry_after_value.simplified().replace(QSL("GMT"), QSL("+0000")),
34 QSL("ddd, dd MMM yyyy HH:mm:ss tt"));
35 }
36
37 QStringList NetworkFactory::extractFeedLinksFromHtmlPage(const QUrl& url, const QString& html) {
38 QStringList feeds;
39 QRegularExpression rx(QSL(FEED_REGEX_MATCHER), QRegularExpression::PatternOption::CaseInsensitiveOption);
40 QRegularExpression rx_href(QSL(FEED_HREF_REGEX_MATCHER), QRegularExpression::PatternOption::CaseInsensitiveOption);
41
42 rx_href.optimize();
43
44 QRegularExpressionMatchIterator it_rx = rx.globalMatch(html);
45
46 while (it_rx.hasNext()) {
47 QRegularExpressionMatch mat_tx = it_rx.next();
48 QString link_tag = mat_tx.captured();
49 QString feed_link = rx_href.match(link_tag).captured(1);
50
51 if (feed_link.startsWith(QL1S("//"))) {
52 feed_link = QSL(URI_SCHEME_HTTP) + feed_link.mid(2);
53 }
54 else if (feed_link.startsWith(QL1C('/'))) {
55 feed_link = url.toString(QUrl::UrlFormattingOption::RemovePath | QUrl::UrlFormattingOption::RemoveQuery |
56 QUrl::UrlFormattingOption::StripTrailingSlash) +
57 feed_link;
58 }
59
60 feeds.append(feed_link);
61 }
62
63 return feeds;
64 }
65
66 QPair<QByteArray, QByteArray> NetworkFactory::generateBasicAuthHeader(NetworkAuthentication protection,
67 const QString& username,
68 const QString& password) {
69 switch (protection) {
70 case NetworkFactory::NetworkAuthentication::Basic: {
71 if (username.isEmpty()) {
72 return {};
73 }
74 else {
75 QString basic_value = username + QSL(":") + password;
76 QString header_value = QSL("Basic ") + QString(basic_value.toUtf8().toBase64());
77
78 return QPair<QByteArray, QByteArray>(HTTP_HEADERS_AUTHORIZATION, header_value.toLocal8Bit());
79 }
80 }
81
82 case NetworkFactory::NetworkAuthentication::Token: {
83 QString header_value = QSL("Bearer ") + username;
84
85 return QPair<QByteArray, QByteArray>(HTTP_HEADERS_AUTHORIZATION, header_value.toLocal8Bit());
86 }
87
88 case NetworkFactory::NetworkAuthentication::NoAuthentication:
89 default:
90 return {};
91 }
92 }
93
94 QString NetworkFactory::networkErrorText(QNetworkReply::NetworkError error_code) {
95 switch (error_code) {
96 case QNetworkReply::ProtocolUnknownError:
97 case QNetworkReply::ProtocolFailure:
98
99 //: Network status.
100 return tr("protocol error");
101
102 case QNetworkReply::ContentAccessDenied:
103 return tr("access to content was denied");
104
105 case QNetworkReply::HostNotFoundError:
106
107 //: Network status.
108 return tr("host not found");
109
110 case QNetworkReply::OperationCanceledError:
111 case QNetworkReply::TimeoutError:
112 return tr("connection timed out or was cancelled");
113
114 case QNetworkReply::RemoteHostClosedError:
115 case QNetworkReply::ConnectionRefusedError:
116
117 //: Network status.
118 return tr("connection refused");
119
120 case QNetworkReply::ProxyTimeoutError:
121
122 //: Network status.
123 return tr("connection timed out");
124
125 case QNetworkReply::SslHandshakeFailedError:
126
127 //: Network status.
128 return tr("SSL handshake failed");
129
130 case QNetworkReply::ProxyConnectionClosedError:
131 case QNetworkReply::ProxyConnectionRefusedError:
132
133 //: Network status.
134 return tr("proxy server connection refused");
135
136 case QNetworkReply::TemporaryNetworkFailureError:
137
138 //: Network status.
139 return tr("temporary failure");
140
141 case QNetworkReply::AuthenticationRequiredError:
142
143 //: Network status.
144 return tr("authentication failed");
145
146 case QNetworkReply::ProxyAuthenticationRequiredError:
147
148 //: Network status.
149 return tr("proxy authentication required");
150
151 case QNetworkReply::ProxyNotFoundError:
152
153 //: Network status.
154 return tr("proxy server not found");
155
156 case QNetworkReply::NoError:
157
158 //: Network status.
159 return tr("no errors");
160
161 case QNetworkReply::UnknownContentError:
162
163 //: Network status.
164 return tr("unknown content");
165
166 case QNetworkReply::ContentNotFoundError:
167
168 //: Network status.
169 return tr("content not found");
170
171 default: {
172 QMetaEnum enumer = QMetaEnum::fromType<QNetworkReply::NetworkError>();
173
174 //: Network status.
175 return tr("unknown error (%1)").arg(enumer.valueToKey(error_code));
176 }
177 }
178 }
179
180 QString NetworkFactory::sanitizeUrl(const QString& url) {
181 static QRegularExpression reg_non_url(QSL("[^\\w\\-.~:\\/?#\\[\\]@!$&'()*+,;=% \\|]"),
182 QRegularExpression::PatternOption::UseUnicodePropertiesOption);
183
184 return QString(url).replace(reg_non_url, {});
185 }
186
187 QNetworkReply::NetworkError NetworkFactory::downloadIcon(const QList<IconLocation>& urls,
188 int timeout,
189 QPixmap& output,
190 const QList<QPair<QByteArray, QByteArray>>& additional_headers,
191 const QNetworkProxy& custom_proxy,
192 Http2Status http2_status) {
193 QNetworkReply::NetworkError network_result = QNetworkReply::NetworkError::UnknownNetworkError;
194
195 for (const auto& url : urls) {
196 if (url.m_url.isEmpty()) {
197 continue;
198 }
199
200 QByteArray icon_data;
201
202 if (url.m_isDirect) {
203 // Download directly.
204 network_result = performNetworkOperation(url.m_url,
205 timeout,
206 {},
207 icon_data,
208 QNetworkAccessManager::Operation::GetOperation,
209 additional_headers,
210 false,
211 {},
212 {},
213 custom_proxy,
214 http2_status)
215 .m_networkError;
216
217 if (network_result == QNetworkReply::NetworkError::NoError) {
218 QPixmap icon_pixmap;
219
220 icon_pixmap.loadFromData(icon_data);
221 output = icon_pixmap;
222
223 if (!output.isNull()) {
224 if (output.width() > 128) {
225 output = output.scaled(QSize(48, 48),
226 Qt::AspectRatioMode::KeepAspectRatio,
227 Qt::TransformationMode::SmoothTransformation);
228 }
229
230 break;
231 }
232 }
233 }
234 else {
235 // Duck Duck Go.
236 QUrl url_full = QUrl(url.m_url);
237 QString host = url_full.host();
238
239 if (host.startsWith(QSL("www."))) {
240 host = host.mid(4);
241 }
242
243 const QString ddg_icon_service = QSL("https://external-content.duckduckgo.com/ip3/%1.ico").arg(host);
244
245 // Google S2.
246 host = url_full.scheme() + QSL("://") + url_full.host();
247
248 const QString gs2_icon_service = QSL("https://t2.gstatic.com/faviconV2?"
249 "client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&"
250 "url=%1")
251 .arg(host);
252
253 for (const QString& service : {ddg_icon_service, gs2_icon_service}) {
254 network_result = performNetworkOperation(service,
255 timeout,
256 QByteArray(),
257 icon_data,
258 QNetworkAccessManager::Operation::GetOperation,
259 {},
260 false,
261 {},
262 {},
263 custom_proxy,
264 http2_status)
265 .m_networkError;
266
267 if (network_result == QNetworkReply::NetworkError::NoError) {
268 QPixmap icon_pixmap;
269
270 icon_pixmap.loadFromData(icon_data);
271 output = icon_pixmap;
272
273 if (!output.isNull()) {
274 if (output.width() > 128) {
275 output = output.scaled(QSize(48, 48),
276 Qt::AspectRatioMode::KeepAspectRatio,
277 Qt::TransformationMode::SmoothTransformation);
278 }
279
280 break;
281 }
282 }
283 }
284 }
285 }
286
287 return network_result;
288 }
289
290 NetworkResult NetworkFactory::performNetworkOperation(const QString& url,
291 int timeout,
292 const QByteArray& input_data,
293 QByteArray& output,
294 QNetworkAccessManager::Operation operation,
295 const QList<QPair<QByteArray, QByteArray>>& additional_headers,
296 bool protected_contents,
297 const QString& username,
298 const QString& password,
299 const QNetworkProxy& custom_proxy,
300 Http2Status http2_status) {
301 Downloader downloader;
302 QEventLoop loop;
303 NetworkResult result;
304
305 // We need to quit event loop when the download finishes.
306 QObject::connect(&downloader, &Downloader::completed, &loop, &QEventLoop::quit);
307
308 for (const auto& header : additional_headers) {
309 if (!header.first.isEmpty()) {
310 downloader.appendRawHeader(header.first, header.second);
311 }
312 }
313
314 if (custom_proxy.type() != QNetworkProxy::ProxyType::DefaultProxy) {
315 downloader.setProxy(custom_proxy);
316 }
317
318 downloader.setHttp2Status(http2_status);
319 downloader.manipulateData(url, operation, input_data, timeout, protected_contents, username, password);
320 loop.exec();
321
322 output = downloader.lastOutputData();
323
324 result.m_networkError = downloader.lastOutputError();
325 result.m_contentType = downloader.lastContentType();
326 result.m_cookies = downloader.lastCookies();
327 result.m_httpCode = downloader.lastHttpStatusCode();
328 result.m_headers = downloader.lastHeaders();
329 result.m_url = downloader.lastUrl();
330
331 qDebugNN << LOGSEC_NETWORK << "URLS\nRequest: " << url << "\nResponse: " << result.m_url.toString();
332
333 return result;
334 }
335
336 NetworkResult NetworkFactory::performNetworkOperation(const QString& url,
337 int timeout,
338 QHttpMultiPart* input_data,
339 QList<HttpResponse>& output,
340 QNetworkAccessManager::Operation operation,
341 const QList<QPair<QByteArray, QByteArray>>& additional_headers,
342 bool protected_contents,
343 const QString& username,
344 const QString& password,
345 const QNetworkProxy& custom_proxy,
346 Http2Status http2_status) {
347 Downloader downloader;
348 QEventLoop loop;
349 NetworkResult result;
350
351 // We need to quit event loop when the download finishes.
352 QObject::connect(&downloader, &Downloader::completed, &loop, &QEventLoop::quit);
353
354 for (const auto& header : additional_headers) {
355 if (!header.first.isEmpty()) {
356 downloader.appendRawHeader(header.first, header.second);
357 }
358 }
359
360 if (custom_proxy.type() != QNetworkProxy::ProxyType::DefaultProxy) {
361 downloader.setProxy(custom_proxy);
362 }
363
364 downloader.setHttp2Status(http2_status);
365 downloader.manipulateData(url, operation, input_data, timeout, protected_contents, username, password);
366 loop.exec();
367
368 output = downloader.lastOutputMultipartData();
369
370 result.m_networkError = downloader.lastOutputError();
371 result.m_contentType = downloader.lastContentType();
372 result.m_cookies = downloader.lastCookies();
373 result.m_httpCode = downloader.lastHttpStatusCode();
374 result.m_headers = downloader.lastHeaders();
375 result.m_url = downloader.lastUrl();
376
377 qDebugNN << LOGSEC_NETWORK << "URLS\nRequest: " << url << "\nResponse: " << result.m_url.toString();
378
379 return result;
380 }
381
382 NetworkResult::NetworkResult()
383 : m_networkError(QNetworkReply::NetworkError::NoError), m_httpCode(0), m_contentType(QString()), m_cookies({}),
384 m_headers({}), m_url(QUrl()) {}
385
386 NetworkResult::NetworkResult(QNetworkReply::NetworkError err,
387 int http_code,
388 const QString& ct,
389 const QList<QNetworkCookie>& cook)
390 : m_networkError(err), m_httpCode(http_code), m_contentType(ct), m_cookies(cook), m_url(QUrl()) {}