aboutsummaryrefslogtreecommitdiff
path: root/launcher/ui/pages/modplatform/ftb/FtbListModel.cpp
blob: e806541585e562a1606149cb35acfdb3e12ce20e (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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
 * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "FtbListModel.h"

#include "BuildConfig.h"
#include "Application.h"
#include "Json.h"

#include <QPainter>

namespace Ftb {

ListModel::ListModel(QObject *parent) : QAbstractListModel(parent)
{
}

ListModel::~ListModel()
{
}

int ListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : modpacks.size();
}

int ListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : 1;
}

QVariant ListModel::data(const QModelIndex &index, int role) const
{
    int pos = index.row();
    if(pos >= modpacks.size() || pos < 0 || !index.isValid())
    {
        return QString("INVALID INDEX %1").arg(pos);
    }

    ModpacksCH::Modpack pack = modpacks.at(pos);
    if(role == Qt::DisplayRole)
    {
        return pack.name;
    }
    else if (role == Qt::ToolTipRole)
    {
        return pack.synopsis;
    }
    else if(role == Qt::DecorationRole)
    {
        QIcon placeholder = APPLICATION->getThemedIcon("screenshot-placeholder");

        auto iter = m_logoMap.find(pack.name);
        if (iter != m_logoMap.end()) {
            auto & logo = *iter;
            if(!logo.result.isNull()) {
                return logo.result;
            }
            return placeholder;
        }

        for(auto art : pack.art) {
            if(art.type == "square") {
                ((ListModel *)this)->requestLogo(pack.name, art.url);
            }
        }
        return placeholder;
    }
    else if(role == Qt::UserRole)
    {
        QVariant v;
        v.setValue(pack);
        return v;
    }

    return QVariant();
}

void ListModel::getLogo(const QString &logo, const QString &logoUrl, LogoCallback callback)
{
    if(m_logoMap.contains(logo))
    {
        callback(APPLICATION->metacache()->resolveEntry("ModpacksCHPacks", QString("logos/%1").arg(logo.section(".", 0, 0)))->getFullPath());
    }
    else
    {
        requestLogo(logo, logoUrl);
    }
}

void ListModel::request()
{
    m_aborted = false;

    beginResetModel();
    modpacks.clear();
    endResetModel();

    auto netJob = makeShared<NetJob>("Ftb::Request", APPLICATION->network());
    auto url = QString(BuildConfig.MODPACKSCH_API_BASE_URL + "public/modpack/all");
    netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), &response));
    jobPtr = netJob;
    jobPtr->start();

    QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::requestFinished);
    QObject::connect(netJob.get(), &NetJob::failed, this, &ListModel::requestFailed);
}

void ListModel::abortRequest()
{
    m_aborted = jobPtr->abort();
    jobPtr.reset();
}

void ListModel::requestFinished()
{
    jobPtr.reset();
    remainingPacks.clear();

    QJsonParseError parse_error {};
    QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
    if(parse_error.error != QJsonParseError::NoError) {
        qWarning() << "Error while parsing JSON response from ModpacksCH at " << parse_error.offset << " reason: " << parse_error.errorString();
        qWarning() << response;
        return;
    }

    auto packs = doc.object().value("packs").toArray();
    for(auto pack : packs) {
        auto packId = pack.toInt();
        remainingPacks.append(packId);
    }

    if(!remainingPacks.isEmpty()) {
        currentPack = remainingPacks.at(0);
        requestPack();
    }
}

void ListModel::requestFailed(QString reason)
{
    jobPtr.reset();
    remainingPacks.clear();
}

void ListModel::requestPack()
{
    auto netJob = makeShared<NetJob>("Ftb::Search", APPLICATION->network());
    auto searchUrl = QString(BuildConfig.MODPACKSCH_API_BASE_URL + "public/modpack/%1").arg(currentPack);
    netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
    jobPtr = netJob;
    jobPtr->start();

    QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::packRequestFinished);
    QObject::connect(netJob.get(), &NetJob::failed, this, &ListModel::packRequestFailed);
}

void ListModel::packRequestFinished()
{
    if (!jobPtr || m_aborted)
        return;

    jobPtr.reset();
    remainingPacks.removeOne(currentPack);

    QJsonParseError parse_error;
    QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);

    if(parse_error.error != QJsonParseError::NoError) {
        qWarning() << "Error while parsing JSON response from ModpacksCH at " << parse_error.offset << " reason: " << parse_error.errorString();
        qWarning() << response;
        return;
    }

    auto obj = doc.object();

    ModpacksCH::Modpack pack;
    try
    {
        ModpacksCH::loadModpack(pack, obj);
    }
    catch (const JSONValidationError &e)
    {
        qDebug() << QString::fromUtf8(response);
        qWarning() << "Error while reading pack manifest from ModpacksCH: " << e.cause();
        return;
    }

    // Since there is no guarantee that packs have a version, this will just
    // ignore those "dud" packs.
    if (pack.versions.empty())
    {
        qWarning() << "ModpacksCH Pack " << pack.id << " ignored. reason: lacking any versions";
    }
    else
    {
        beginInsertRows(QModelIndex(), modpacks.size(), modpacks.size());
        modpacks.append(pack);
        endInsertRows();
    }

    if(!remainingPacks.isEmpty()) {
        currentPack = remainingPacks.at(0);
        requestPack();
    }
}

void ListModel::packRequestFailed(QString reason)
{
    jobPtr.reset();
    remainingPacks.removeOne(currentPack);
}

void ListModel::logoLoaded(QString logo, bool stale)
{
    auto & logoObj = m_logoMap[logo];
    logoObj.downloadJob.reset();
    QString smallPath = logoObj.fullpath + ".small";

    QFileInfo smallInfo(smallPath);

    if(stale || !smallInfo.exists()) {
        QImage image(logoObj.fullpath);
        if (image.isNull())
        {
            logoObj.failed = true;
            return;
        }
        QImage small;
        if (image.width() > image.height()) {
            small = image.scaledToWidth(512).scaledToWidth(256, Qt::SmoothTransformation);
        }
        else {
            small = image.scaledToHeight(512).scaledToHeight(256, Qt::SmoothTransformation);
        }
        QPoint offset((256 - small.width()) / 2, (256 - small.height()) / 2);
        QImage square(QSize(256, 256), QImage::Format_ARGB32);
        square.fill(Qt::transparent);

        QPainter painter(&square);
        painter.drawImage(offset, small);
        painter.end();

        square.save(logoObj.fullpath + ".small", "PNG");
    }

    logoObj.result = QIcon(logoObj.fullpath + ".small");
    for(int i = 0; i < modpacks.size(); i++) {
        if(modpacks[i].name == logo) {
            emit dataChanged(createIndex(i, 0), createIndex(i, 0), {Qt::DecorationRole});
        }
    }
}

void ListModel::logoFailed(QString logo)
{
    m_logoMap[logo].failed = true;
    m_logoMap[logo].downloadJob.reset();
}

void ListModel::requestLogo(QString logo, QString url)
{
    if(m_logoMap.contains(logo)) {
        return;
    }

    MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("ModpacksCHPacks", QString("logos/%1").arg(logo.section(".", 0, 0)));

    bool stale = entry->isStale();

    auto job = makeShared<NetJob>(QString("ModpacksCH Icon Download %1").arg(logo), APPLICATION->network());
    job->addNetAction(Net::Download::makeCached(QUrl(url), entry));

    auto fullPath = entry->getFullPath();
    QObject::connect(job.get(), &NetJob::finished, this, [this, logo, fullPath, stale]
    {
        logoLoaded(logo, stale);
    });

    QObject::connect(job.get(), &NetJob::failed, this, [this, logo]
    {
        logoFailed(logo);
    });

    auto &newLogoEntry = m_logoMap[logo];
    newLogoEntry.downloadJob = job;
    newLogoEntry.fullpath = fullPath;
    job->start();
}

}