foxygit / TV-Launcher Log in
commits tags

/src/iconfetcher.cpp · 4.28 KB

raw
#include "iconfetcher.h"

#include <QDir>
#include <QNetworkReply>
#include <QRegularExpression>
#include <QStandardPaths>

static constexpr int kGoodEnough = 128;

static QNetworkRequest makeRequest(const QUrl &url)
{
    QNetworkRequest req(url);
    req.setHeader(QNetworkRequest::UserAgentHeader,
                  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/130.0 Safari/537.36");
    req.setTransferTimeout(8000);
    return req;
}

// Plockar ut ikonlänkar ur HTML; apple-touch-icon först eftersom de är stora.
static QList<QUrl> iconLinks(const QString &html, const QUrl &base)
{
    static const QRegularExpression linkRe(QStringLiteral("<link\\b[^>]*>"),
                                           QRegularExpression::CaseInsensitiveOption);
    static const QRegularExpression relRe(QStringLiteral("rel\\s*=\\s*[\"']([^\"']+)[\"']"),
                                          QRegularExpression::CaseInsensitiveOption);
    static const QRegularExpression hrefRe(QStringLiteral("href\\s*=\\s*[\"']([^\"']+)[\"']"),
                                           QRegularExpression::CaseInsensitiveOption);
    QList<QUrl> touch, icons;
    auto it = linkRe.globalMatch(html);
    while (it.hasNext()) {
        const QString tag = it.next().captured(0);
        const QString rel = relRe.match(tag).captured(1).toLower();
        const QString href = hrefRe.match(tag).captured(1);
        if (href.isEmpty())
            continue;
        const QUrl resolved = base.resolved(QUrl(href));
        if (rel.contains("apple-touch-icon"))
            touch << resolved;
        else if (rel.split(' ').contains("icon"))
            icons << resolved;
    }
    return touch + icons;
}

IconFetcher::IconFetcher(QObject *parent) : QObject(parent) {}

void IconFetcher::fetch(const QString &id, const QString &urlString)
{
    const QUrl url(urlString);
    if (!url.isValid() || url.host().isEmpty())
        return;

    auto *job = new Job;
    job->id = id;
    job->pages << url;
    QUrl root = url.resolved(QUrl("/"));
    if (root != url)
        job->pages << root;
    nextPage(job);
}

void IconFetcher::nextPage(Job *job)
{
    if (job->pages.isEmpty()) {
        nextCandidate(job);
        return;
    }
    const QUrl page = job->pages.takeFirst();
    QNetworkReply *reply = m_nam.get(makeRequest(page));
    connect(reply, &QNetworkReply::finished, this, [this, reply, job, page] {
        reply->deleteLater();
        const QUrl base = reply->url().isValid() ? reply->url() : page;
        if (reply->error() == QNetworkReply::NoError) {
            const QString html = QString::fromUtf8(reply->read(512 * 1024));
            for (const QUrl &u : iconLinks(html, base))
                if (!job->candidates.contains(u))
                    job->candidates << u;
        }
        // Standardplatserna sist, en gång per webbplats.
        for (const char *path : {"/apple-touch-icon.png", "/favicon.ico"}) {
            const QUrl u = base.resolved(QUrl(QString::fromLatin1(path)));
            if (job->pages.isEmpty() && !job->candidates.contains(u))
                job->candidates << u;
        }
        nextPage(job);
    });
}

void IconFetcher::nextCandidate(Job *job)
{
    if (job->candidates.isEmpty() || job->best.width() >= kGoodEnough) {
        finish(job);
        return;
    }
    const QUrl next = job->candidates.takeFirst();
    QNetworkReply *reply = m_nam.get(makeRequest(next));
    connect(reply, &QNetworkReply::finished, this, [this, reply, job] {
        reply->deleteLater();
        if (reply->error() == QNetworkReply::NoError) {
            const QImage img = QImage::fromData(reply->readAll());
            if (!img.isNull() && img.width() > job->best.width())
                job->best = img;
        }
        nextCandidate(job);
    });
}

void IconFetcher::finish(Job *job)
{
    QImage img = job->best;
    if (!img.isNull()) {
        const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/icons";
        QDir().mkpath(dir);
        const QString path = dir + "/" + job->id + ".png";
        if (img.width() > 256 || img.height() > 256)
            img = img.scaled(256, 256, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        if (img.save(path, "PNG"))
            emit iconReady(job->id, path);
    }
    delete job;
}