summaryrefslogtreecommitdiffstats
path: root/api/logic/InstanceImportTask.cpp
blob: f3e0858dab6d913fbafe2a1c62980b1110e25403 (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include "InstanceImportTask.h"
#include "BaseInstance.h"
#include "BaseInstanceProvider.h"
#include "FileSystem.h"
#include "Env.h"
#include "MMCZip.h"
#include "NullInstance.h"
#include "settings/INISettingsObject.h"
#include "icons/IIconList.h"
#include <QtConcurrentRun>

// FIXME: this does not belong here, it's Minecraft/Flame specific
#include "minecraft/MinecraftInstance.h"
#include "minecraft/ComponentList.h"
#include "modplatform/flame/FileResolvingTask.h"
#include "modplatform/flame/PackManifest.h"
#include "Json.h"

InstanceImportTask::InstanceImportTask(const QUrl sourceUrl)
{
    m_sourceUrl = sourceUrl;
}

void InstanceImportTask::executeTask()
{
    InstancePtr newInstance;

    if (m_sourceUrl.isLocalFile())
    {
        m_archivePath = m_sourceUrl.toLocalFile();
        processZipPack();
    }
    else
    {
        setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString()));
        m_downloadRequired = true;

        const QString path = m_sourceUrl.host() + '/' + m_sourceUrl.path();
        auto entry = ENV.metacache()->resolveEntry("general", path);
        entry->setStale(true);
        m_filesNetJob.reset(new NetJob(tr("Modpack download")));
        m_filesNetJob->addNetAction(Net::Download::makeCached(m_sourceUrl, entry));
        m_archivePath = entry->getFullPath();
        auto job = m_filesNetJob.get();
        connect(job, &NetJob::succeeded, this, &InstanceImportTask::downloadSucceeded);
        connect(job, &NetJob::progress, this, &InstanceImportTask::downloadProgressChanged);
        connect(job, &NetJob::failed, this, &InstanceImportTask::downloadFailed);
        m_filesNetJob->start();
    }
}

void InstanceImportTask::downloadSucceeded()
{
    processZipPack();
    m_filesNetJob.reset();
}

void InstanceImportTask::downloadFailed(QString reason)
{
    emitFailed(reason);
    m_filesNetJob.reset();
}

void InstanceImportTask::downloadProgressChanged(qint64 current, qint64 total)
{
    setProgress(current / 2, total);
}

void InstanceImportTask::processZipPack()
{
    setStatus(tr("Extracting modpack"));
    QDir extractDir(m_stagingPath);
    qDebug() << "Attempting to create instance from" << m_archivePath;

    // open the zip and find relevant files in it
    m_packZip.reset(new QuaZip(m_archivePath));
    if (!m_packZip->open(QuaZip::mdUnzip))
    {
        emitFailed(tr("Unable to open supplied modpack zip file."));
        return;
    }

    QStringList blacklist = {"instance.cfg", "manifest.json"};
    QString mmcFound = MMCZip::findFolderOfFileInZip(m_packZip.get(), "instance.cfg");
    QString flameFound = MMCZip::findFolderOfFileInZip(m_packZip.get(), "manifest.json");
    QString root;
    if(!mmcFound.isNull())
    {
        // process as MultiMC instance/pack
        qDebug() << "MultiMC:" << mmcFound;
        root = mmcFound;
        m_modpackType = ModpackType::MultiMC;
    }
    else if(!flameFound.isNull())
    {
        // process as Flame pack
        qDebug() << "Flame:" << flameFound;
        root = flameFound;
        m_modpackType = ModpackType::Flame;
    }

    if(m_modpackType == ModpackType::Unknown)
    {
        emitFailed(tr("Archive does not contain a recognized modpack type."));
        return;
    }

    // make sure we extract just the pack
    m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), MMCZip::extractSubDir, m_packZip.get(), root, extractDir.absolutePath());
    connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &InstanceImportTask::extractFinished);
    connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &InstanceImportTask::extractAborted);
    m_extractFutureWatcher.setFuture(m_extractFuture);
}

void InstanceImportTask::extractFinished()
{
    m_packZip.reset();
    if (m_extractFuture.result().isEmpty())
    {
        emitFailed(tr("Failed to extract modpack"));
        return;
    }
    QDir extractDir(m_stagingPath);

    qDebug() << "Fixing permissions for extracted pack files...";
    QDirIterator it(extractDir, QDirIterator::Subdirectories);
    while (it.hasNext())
    {
        auto filepath = it.next();
        QFileInfo file(filepath);
        auto permissions = QFile::permissions(filepath);
        auto origPermissions = permissions;
        if(file.isDir())
        {
            // Folder +rwx for current user
            permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser | QFileDevice::Permission::ExeUser;
        }
        else
        {
            // File +rw for current user
            permissions |= QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser;
        }
        if(origPermissions != permissions)
        {
            if(!QFile::setPermissions(filepath, permissions))
            {
                logWarning(tr("Could not fix permissions for %1").arg(filepath));
            }
            else
            {
                qDebug() << "Fixed" << filepath;
            }
        }
    }

    switch(m_modpackType)
    {
        case ModpackType::Flame:
            processFlame();
            return;
        case ModpackType::MultiMC:
            processMultiMC();
            return;
        case ModpackType::Unknown:
            emitFailed(tr("Archive does not contain a recognized modpack type."));
            return;
    }
}

void InstanceImportTask::extractAborted()
{
    emitFailed(tr("Instance import has been aborted."));
    return;
}

void InstanceImportTask::processFlame()
{
    const static QMap<QString,QString> forgemap = {
        {"1.2.5", "3.4.9.171"},
        {"1.4.2", "6.0.1.355"},
        {"1.4.7", "6.6.2.534"},
        {"1.5.2", "7.8.1.737"}
    };
    Flame::Manifest pack;
    try
    {
        QString configPath = FS::PathCombine(m_stagingPath, "manifest.json");
        Flame::loadManifest(pack, configPath);
        QFile::remove(configPath);
    }
    catch (const JSONValidationError &e)
    {
        emitFailed(tr("Could not understand pack manifest:\n") + e.cause());
        return;
    }
    if(!pack.overrides.isEmpty())
    {
        QString overridePath = FS::PathCombine(m_stagingPath, pack.overrides);
        if (QFile::exists(overridePath))
        {
            QString mcPath = FS::PathCombine(m_stagingPath, "minecraft");
            if (!QFile::rename(overridePath, mcPath))
            {
                emitFailed(tr("Could not rename the overrides folder:\n") + pack.overrides);
                return;
            }
        }
        else
        {
            logWarning(tr("The specified overrides folder (%1) is missing. Maybe the modpack was already used before?").arg(pack.overrides));
        }
    }

    QString forgeVersion;
    for(auto &loader: pack.minecraft.modLoaders)
    {
        auto id = loader.id;
        if(id.startsWith("forge-"))
        {
            id.remove("forge-");
            forgeVersion = id;
            continue;
        }
        logWarning(tr("Unknown mod loader in manifest: %1").arg(id));
    }

    QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg");
    auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
    instanceSettings->registerSetting("InstanceType", "Legacy");
    instanceSettings->set("InstanceType", "OneSix");
    MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath);
    auto mcVersion = pack.minecraft.version;
    // Hack to correct some 'special sauce'...
    if(mcVersion.endsWith('.'))
    {
        mcVersion.remove(QRegExp("[.]+$"));
        logWarning(tr("Mysterious trailing dots removed from Minecraft version while importing pack."));
    }
    auto components = instance.getComponentList();
    components->buildingFromScratch();
    components->setComponentVersion("net.minecraft", mcVersion, true);
    if(!forgeVersion.isEmpty())
    {
        // FIXME: dirty, nasty, hack. Proper solution requires dependency resolution and knowledge of the metadata.
        if(forgeVersion == "recommended")
        {
            if(forgemap.contains(mcVersion))
            {
                forgeVersion = forgemap[mcVersion];
            }
            else
            {
                logWarning(tr("Could not map recommended forge version for Minecraft %1").arg(mcVersion));
            }
        }
        components->setComponentVersion("net.minecraftforge", forgeVersion);
    }
    if (m_instIcon != "default")
    {
        instance.setIconKey(m_instIcon);
    }
    else
    {
        if(pack.name.contains("Direwolf20"))
        {
            instance.setIconKey("steve");
        }
        else if(pack.name.contains("FTB") || pack.name.contains("Feed The Beast"))
        {
            instance.setIconKey("ftb_logo");
        }
        else
        {
            // default to something other than the MultiMC default to distinguish these
            instance.setIconKey("flame");
        }
    }
    instance.init();
    QString jarmodsPath = FS::PathCombine(m_stagingPath, "minecraft", "jarmods");
    QFileInfo jarmodsInfo(jarmodsPath);
    if(jarmodsInfo.isDir())
    {
        // install all the jar mods
        qDebug() << "Found jarmods:";
        QDir jarmodsDir(jarmodsPath);
        QStringList jarMods;
        for (auto info: jarmodsDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files))
        {
            qDebug() << info.fileName();
            jarMods.push_back(info.absoluteFilePath());
        }
        auto profile = instance.getComponentList();
        profile->installJarMods(jarMods);
        // nuke the original files
        FS::deletePath(jarmodsPath);
    }
    instance.setName(m_instName);
    m_modIdResolver.reset(new Flame::FileResolvingTask(pack));
    connect(m_modIdResolver.get(), &Flame::FileResolvingTask::succeeded, [&]()
    {
        auto results = m_modIdResolver->getResults();
        m_filesNetJob.reset(new NetJob(tr("Mod download")));
        for(auto result: results.files)
        {
            QString filename = result.fileName;
            if(!result.required)
            {
                filename += ".disabled";
            }

            auto relpath = FS::PathCombine("minecraft", result.targetFolder, filename);
            auto path = FS::PathCombine(m_stagingPath , relpath);

            switch(result.type)
            {
                case Flame::File::Type::Folder:
                {
                    logWarning(tr("This 'Folder' may need extracting: %1").arg(relpath));
                    // fall-through intentional, we treat these as plain old mods and dump them wherever.
                }
                case Flame::File::Type::SingleFile:
                case Flame::File::Type::Mod:
                {
                    qDebug() << "Will download" << result.url << "to" << path;
                    auto dl = Net::Download::makeFile(result.url, path);
                    m_filesNetJob->addNetAction(dl);
                    break;
                }
                case Flame::File::Type::Modpack:
                    logWarning(tr("Nesting modpacks in modpacks is not implemented, nothing was downloaded: %1").arg(relpath));
                    break;
                case Flame::File::Type::Cmod2:
                case Flame::File::Type::Ctoc:
                case Flame::File::Type::Unknown:
                    logWarning(tr("Unrecognized/unhandled PackageType for: %1").arg(relpath));
                    break;
            }
        }
        m_modIdResolver.reset();
        connect(m_filesNetJob.get(), &NetJob::succeeded, this, [&]()
        {
            m_filesNetJob.reset();
            emitSucceeded();
        }
        );
        connect(m_filesNetJob.get(), &NetJob::failed, [&](QString reason)
        {
            m_filesNetJob.reset();
            emitFailed(reason);
        });
        connect(m_filesNetJob.get(), &NetJob::progress, [&](qint64 current, qint64 total)
        {
            setProgress(current, total);
        });
        setStatus(tr("Downloading mods..."));
        m_filesNetJob->start();
    }
    );
    connect(m_modIdResolver.get(), &Flame::FileResolvingTask::failed, [&](QString reason)
    {
        m_modIdResolver.reset();
        emitFailed(tr("Unable to resolve mod IDs:\n") + reason);
    });
    connect(m_modIdResolver.get(), &Flame::FileResolvingTask::progress, [&](qint64 current, qint64 total)
    {
        setProgress(current, total);
    });
    connect(m_modIdResolver.get(), &Flame::FileResolvingTask::status, [&](QString status)
    {
        setStatus(status);
    });
    m_modIdResolver->start();
}

void InstanceImportTask::processMultiMC()
{
    // FIXME: copy from FolderInstanceProvider!!! FIX IT!!!
    QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg");
    auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
    instanceSettings->registerSetting("InstanceType", "Legacy");

    NullInstance instance(m_globalSettings, instanceSettings, m_stagingPath);

    // reset time played on import... because packs.
    instance.resetTimePlayed();

    // set a new nice name
    instance.setName(m_instName);

    // if the icon was specified by user, use that. otherwise pull icon from the pack
    if (m_instIcon != "default")
    {
        instance.setIconKey(m_instIcon);
    }
    else
    {
        m_instIcon = instance.iconKey();
        auto importIconPath = FS::PathCombine(instance.instanceRoot(), m_instIcon + ".png");
        if (QFile::exists(importIconPath))
        {
            // import icon
            auto iconList = ENV.icons();
            if (iconList->iconFileExists(m_instIcon))
            {
                iconList->deleteIcon(m_instIcon);
            }
            iconList->installIcons({importIconPath});
        }
    }
    emitSucceeded();
}