File indexing completed on 2024-05-19 05:37:49

0001 /*
0002     SPDX-FileCopyrightText: 2007 Tobias Koenig <tokoe@kde.org>
0003     SPDX-FileCopyrightText: 2008 Marco Martin <notmart@gmail.com>
0004     SPDX-FileCopyrightText: 2013 Andrea Scarpino <scarpino@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-or-later
0007 */
0008 
0009 #include "faviconprovider.h"
0010 
0011 #include <QImage>
0012 #include <QStandardPaths>
0013 #include <QUrl>
0014 
0015 #include <KIO/Job>
0016 #include <KIO/StoredTransferJob>
0017 #include <KJob>
0018 
0019 class FaviconProvider::Private
0020 {
0021 public:
0022     Private(FaviconProvider *parent)
0023         : q(parent)
0024     {
0025     }
0026 
0027     void imageRequestFinished(KIO::StoredTransferJob *job);
0028 
0029     FaviconProvider *q;
0030     QImage image;
0031     QString cachePath;
0032 };
0033 
0034 void FaviconProvider::Private::imageRequestFinished(KIO::StoredTransferJob *job)
0035 {
0036     if (job->error()) {
0037         Q_EMIT q->error(q);
0038         return;
0039     }
0040 
0041     image = QImage::fromData(job->data());
0042     if (!image.isNull()) {
0043         image.save(cachePath, "PNG");
0044     }
0045     Q_EMIT q->finished(q);
0046 }
0047 
0048 FaviconProvider::FaviconProvider(QObject *parent, const QString &url)
0049     : QObject(parent)
0050     , m_url(url)
0051     , d(new Private(this))
0052 {
0053     QUrl faviconUrl = QUrl::fromUserInput(url);
0054     const QString fileName = KIO::favIconForUrl(faviconUrl);
0055 
0056     if (!fileName.isEmpty()) {
0057         d->cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + '/' + fileName + ".png";
0058         d->image.load(d->cachePath, "PNG");
0059     } else {
0060         d->cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/favicons/" + faviconUrl.host() + ".png";
0061         faviconUrl.setPath(QStringLiteral("/favicon.ico"));
0062 
0063         if (faviconUrl.isValid()) {
0064             KIO::StoredTransferJob *job = KIO::storedGet(faviconUrl, KIO::NoReload, KIO::HideProgressInfo);
0065             // job->setProperty("uid", id);
0066             connect(job, &KJob::result, this, [this, job]() {
0067                 d->imageRequestFinished(job);
0068             });
0069         }
0070     }
0071 }
0072 
0073 FaviconProvider::~FaviconProvider()
0074 {
0075     delete d;
0076 }
0077 
0078 QImage FaviconProvider::image() const
0079 {
0080     return d->image;
0081 }
0082 
0083 QString FaviconProvider::identifier() const
0084 {
0085     return m_url;
0086 }
0087 
0088 #include "moc_faviconprovider.cpp"