-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeedfavicon.cpp
76 lines (63 loc) · 2.3 KB
/
feedfavicon.cpp
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
#include "feedfavicon.h"
#include "feed.h"
#include <QFile>
#include <QImage>
#include <QNetworkAccessManager>
#include <QNetworkReply>
static const char *storageFormat = "png";
static const char maxRedirectCount = 5;
void probeHtmlForFavicon(const QByteArray &body, Feed &feed);
FeedFavicon::FeedFavicon(Feed &feed)
: QObject(&feed)
, m_feed(feed)
{
}
QUrl FeedFavicon::url() const
{
QString path = storagePath();
if (QFile::exists(path))
return QUrl(QStringLiteral("file:") + path);
return QUrl(QStringLiteral("qrc:/icons/feed.png"));
}
QString FeedFavicon::storagePath() const
{
return m_feed.storagePrefix() + QStringLiteral(".") + QString::fromLatin1(storageFormat);
}
void FeedFavicon::fetch(const QUrl &url)
{
QNetworkRequest request(url);
QNetworkReply *reply = m_feed.m_network->get(request);
m_fetchCount++;
m_feed.setRemoteFaviconUrl(url);
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
unsigned int status = reply->attribute(QNetworkRequest::Attribute::HttpStatusCodeAttribute).toUInt();
if ((status == 301 || status == 307 || status == 302) && m_fetchCount < maxRedirectCount) {
fetch(QUrl(reply->header(QNetworkRequest::LocationHeader).toString()));
return;
} else if (status >= 200 && status < 300) {
QImage image;
if (image.loadFromData(reply->readAll())) {
image.save(storagePath(), storageFormat);
Q_EMIT m_feed.faviconUrlChanged();
}
}
reply->deleteLater();
deleteLater();
});
}
void FeedFavicon::fetchFromHtmlPage(const QUrl &remoteUrl)
{
QNetworkReply *reply = m_feed.m_network->get(QNetworkRequest(remoteUrl));
reply->ignoreSslErrors();
m_fetchCount++;
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
unsigned int status = reply->attribute(QNetworkRequest::Attribute::HttpStatusCodeAttribute).toUInt();
reply->deleteLater();
if (status > 300 && status < 304 && m_fetchCount < maxRedirectCount) {
fetchFromHtmlPage(QUrl(reply->header(QNetworkRequest::LocationHeader).toString()));
return;
} else if (status >= 200 && status < 300)
probeHtmlForFavicon(reply->readAll(), m_feed);
deleteLater();
});
}