aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/3rdparty/syntax-highlighting/src/lib/definitiondownloader.cpp
blob: 35bb29f82f10e609b1d62349f5b94e1cb99d8c20 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*
    SPDX-FileCopyrightText: 2016 Volker Krause <vkrause@kde.org>

    SPDX-License-Identifier: MIT
*/

#include "definitiondownloader.h"
#include "definition.h"
#include "ksyntaxhighlighting_logging.h"
#include "ksyntaxhighlighting_version.h"
#include "repository.h"

#include <QDir>
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QStandardPaths>
#include <QTimer>
#include <QXmlStreamReader>

using namespace KSyntaxHighlighting;

class KSyntaxHighlighting::DefinitionDownloaderPrivate
{
public:
    DefinitionDownloader *q;
    Repository *repo;
    QNetworkAccessManager *nam;
    QString downloadLocation;
    int pendingDownloads;
    bool needsReload;

    void definitionListDownloadFinished(QNetworkReply *reply);
    void updateDefinition(QXmlStreamReader &parser);
    void downloadDefinition(const QUrl &url);
    void downloadDefinitionFinished(QNetworkReply *reply);
    void checkDone();
};

void DefinitionDownloaderPrivate::definitionListDownloadFinished(QNetworkReply *reply)
{
    const auto networkError = reply->error();
    if (networkError != QNetworkReply::NoError) {
        qCWarning(Log) << networkError;
        emit q->done(); // TODO return error
        return;
    }

    QXmlStreamReader parser(reply);
    while (!parser.atEnd()) {
        switch (parser.readNext()) {
        case QXmlStreamReader::StartElement:
            if (parser.name() == QLatin1String("Definition"))
                updateDefinition(parser);
            break;
        default:
            break;
        }
    }

    if (pendingDownloads == 0)
        emit q->informationMessage(QObject::tr("All syntax definitions are up-to-date."));
    checkDone();
}

void DefinitionDownloaderPrivate::updateDefinition(QXmlStreamReader &parser)
{
    const auto name = parser.attributes().value(QLatin1String("name"));
    if (name.isEmpty())
        return;

    auto localDef = repo->definitionForName(name.toString());
    if (!localDef.isValid()) {
        emit q->informationMessage(QObject::tr("Downloading new syntax definition for '%1'...").arg(name.toString()));
        downloadDefinition(QUrl(parser.attributes().value(QLatin1String("url")).toString()));
        return;
    }

    const auto version = parser.attributes().value(QLatin1String("version"));
    if (localDef.version() < version.toFloat()) {
        emit q->informationMessage(QObject::tr("Updating syntax definition for '%1' to version %2...").arg(name.toString(), version.toString()));
        downloadDefinition(QUrl(parser.attributes().value(QLatin1String("url")).toString()));
    }
}

void DefinitionDownloaderPrivate::downloadDefinition(const QUrl &downloadUrl)
{
    if (!downloadUrl.isValid())
        return;
    auto url = downloadUrl;
    if (url.scheme() == QLatin1String("http"))
        url.setScheme(QStringLiteral("https"));

    QNetworkRequest req(url);
    auto reply = nam->get(req);
    QObject::connect(reply, &QNetworkReply::finished, q, [this, reply]() { downloadDefinitionFinished(reply); });
    ++pendingDownloads;
    needsReload = true;
}

void DefinitionDownloaderPrivate::downloadDefinitionFinished(QNetworkReply *reply)
{
    --pendingDownloads;

    const auto networkError = reply->error();
    if (networkError != QNetworkReply::NoError) {
        qCWarning(Log) << "Failed to download definition file" << reply->url() << networkError;
        checkDone();
        return;
    }

    // handle redirects
    // needs to be done manually, download server redirects to unsafe http links
    const auto redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redirectUrl.isEmpty()) {
        downloadDefinition(reply->url().resolved(redirectUrl));
        checkDone();
        return;
    }

    QFile file(downloadLocation + QLatin1Char('/') + reply->url().fileName());
    if (!file.open(QFile::WriteOnly)) {
        qCWarning(Log) << "Failed to open" << file.fileName() << file.error();
    } else {
        file.write(reply->readAll());
    }
    checkDone();
}

void DefinitionDownloaderPrivate::checkDone()
{
    if (pendingDownloads == 0) {
        if (needsReload)
            repo->reload();

        emit QTimer::singleShot(0, q, &DefinitionDownloader::done);
    }
}

DefinitionDownloader::DefinitionDownloader(Repository *repo, QObject *parent)
    : QObject(parent)
    , d(new DefinitionDownloaderPrivate())
{
    Q_ASSERT(repo);

    d->q = this;
    d->repo = repo;
    d->nam = new QNetworkAccessManager(this);
    d->pendingDownloads = 0;
    d->needsReload = false;

    d->downloadLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/org.kde.syntax-highlighting/syntax");
    QDir().mkpath(d->downloadLocation);
    Q_ASSERT(QFile::exists(d->downloadLocation));
}

DefinitionDownloader::~DefinitionDownloader()
{
}

void DefinitionDownloader::start()
{
    const QString url = QLatin1String("https://www.kate-editor.org/syntax/update-") + QString::number(SyntaxHighlighting_VERSION_MAJOR) + QLatin1Char('.') + QString::number(SyntaxHighlighting_VERSION_MINOR) + QLatin1String(".xml");
    auto req = QNetworkRequest(QUrl(url));
    req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
                     QNetworkRequest::NoLessSafeRedirectPolicy);
    auto reply = d->nam->get(req);
    QObject::connect(reply, &QNetworkReply::finished, this, [=]() { d->definitionListDownloadFinished(reply); });
}