summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/modplatform/modrinth/ModrinthInstanceCreationTask.cpp
blob: 7e9c732eb663c7df748b071f86219690fb6accbe (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
#include "ModrinthInstanceCreationTask.h"

#include "Application.h"
#include "FileSystem.h"
#include "InstanceList.h"
#include "Json.h"

#include "QObjectPtr.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"

#include "minecraft/mod/Mod.hpp"
#include "modplatform/EnsureMetadataTask.h"
#include "modplatform/helpers/OverrideUtils.h"

#include "net/ChecksumValidator.h"

#include "net/ApiDownload.h"
#include "net/NetJob.h"
#include "settings/INISettingsObject.h"

#include "ui/dialogs/CustomMessageBox.h"
#include "ui/pages/modplatform/OptionalModDialog.h"

#include <QAbstractButton>
#include <QFileInfo>
#include <QHash>
#include <vector>

#include "tasks/MultipleOptionsTask.h"

bool ModrinthCreationTask::abort()
{
	if (!canAbort())
		return false;

	if (m_task)
		m_task->abort();
	return InstanceCreationTask::abort();
}

bool ModrinthCreationTask::updateInstance()
{
	auto instance_list = APPLICATION->instances();

	// Note: Duplicate modpack detection uses managed name or instance ID lookup.
	// If multiple installations exist, the first match is updated.
	InstancePtr inst;
	if (auto original_id = originalInstanceID(); !original_id.isEmpty())
	{
		inst = instance_list->getInstanceById(original_id);
		Q_ASSERT(inst);
	}
	else
	{
		// Duplicate Detection: Check for duplicates before assuming
		auto all_instances = instance_list->getAllInstancesByManagedName(originalName());

		if (all_instances.size() > 1)
		{
			emitFailed(tr("Multiple instances found for this modpack. Please update the specific instance you want to "
						  "modify to avoid ambiguity."));
			return false;
		}

		if (all_instances.size() == 1)
		{
			inst = all_instances.first();
		}
		else
		{
			// Fallback to name-based lookup if not found by managed ID (e.g. legacy/broken instances)
			inst = instance_list->getInstanceById(originalName());
		}

		if (!inst)
		{
			// New instance creation flow continues...
			return true;
		}
	}

	QString index_path = FS::PathCombine(m_stagingPath, "modrinth.index.json");
	if (!parseManifest(index_path, m_files, true, false))
		return false;

	auto version_name = inst->getManagedPackVersionName();
	m_root_path		  = QFileInfo(inst->gameRoot()).fileName();
	auto version_str  = !version_name.isEmpty() ? tr(" (version %1)").arg(version_name) : "";

	if (shouldConfirmUpdate())
	{
		auto should_update = askIfShouldUpdate(m_parent, version_str);
		if (should_update == ShouldUpdate::SkipUpdating)
			return false;
		if (should_update == ShouldUpdate::Cancel)
		{
			m_abort = true;
			return false;
		}
	}

	// Remove repeated files, we don't need to download them!
	QDir old_inst_dir(inst->instanceRoot());

	QString old_index_folder(FS::PathCombine(old_inst_dir.absolutePath(), "mrpack"));

	QString old_index_path(FS::PathCombine(old_index_folder, "modrinth.index.json"));
	QFileInfo old_index_file(old_index_path);
	if (old_index_file.exists())
	{
		std::vector<File> old_files;
		parseManifest(old_index_path, old_files, false, false);

		// Let's remove all duplicated, identical resources!
		auto files_iterator = m_files.begin();
	begin:
		while (files_iterator != m_files.end())
		{
			auto const& file = *files_iterator;

			auto old_files_iterator = old_files.begin();
			while (old_files_iterator != old_files.end())
			{
				auto const& old_file = *old_files_iterator;

				if (old_file.hash == file.hash)
				{
					qDebug() << "Removed file at" << file.path << "from list of downloads";
					files_iterator	   = m_files.erase(files_iterator);
					old_files_iterator = old_files.erase(old_files_iterator);
					goto begin; // Sorry :c
				}

				old_files_iterator++;
			}

			files_iterator++;
		}

		QDir old_minecraft_dir(inst->gameRoot());

		// Some files were removed from the old version, and some will be downloaded in an updated version,
		// so we're fine removing them!
		if (!old_files.empty())
		{
			for (auto const& file : old_files)
			{
				if (file.path.isEmpty())
					continue;
				qDebug() << "Scheduling" << file.path << "for removal";
				m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(file.path));
				if (file.path.endsWith(".disabled"))
				{ // remove it if it was enabled/disabled by user
					m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(file.path.chopped(9)));
				}
				else
				{
					m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(file.path + ".disabled"));
				}
			}
		}

		// We will remove all the previous overrides, to prevent duplicate files!
		// Note: Overrides intentionally replace all files on update - this matches modpack author expectations.
		// Disabled mods (.disabled extension) are handled by the file exclusion logic above.
		auto old_overrides = Override::readOverrides("overrides", old_index_folder);
		for (const auto& entry : old_overrides)
		{
			if (entry.isEmpty())
				continue;

			// Skip removal of .disabled files (user-disabled mods should be preserved)
			if (entry.endsWith(".disabled", Qt::CaseInsensitive))
			{
				qDebug() << "Preserving disabled mod:" << entry;
				continue;
			}

			qDebug() << "Scheduling" << entry << "for removal";
			m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry));
		}

		auto old_client_overrides = Override::readOverrides("client-overrides", old_index_folder);
		for (const auto& entry : old_client_overrides)
		{
			if (entry.isEmpty())
				continue;

			// Skip removal of .disabled files (user-disabled mods should be preserved)
			if (entry.endsWith(".disabled", Qt::CaseInsensitive))
			{
				qDebug() << "Preserving disabled mod:" << entry;
				continue;
			}

			qDebug() << "Scheduling" << entry << "for removal";
			m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry));
		}
	}
	else
	{
		// We don't have an old index file, so we may duplicate stuff!
		auto dialog = CustomMessageBox::selectable(
			m_parent,
			tr("No index file."),
			tr("We couldn't find a suitable index file for the older version. This may cause some "
			   "of the files to be duplicated. Do you want to continue?"),
			QMessageBox::Warning,
			QMessageBox::Ok | QMessageBox::Cancel);

		if (dialog->exec() == QDialog::DialogCode::Rejected)
		{
			m_abort = true;
			return false;
		}
	}

	setOverride(true, inst->id());
	qDebug() << "Will override instance!";

	m_instance = inst;

	// We let it go through the createInstance() stage, just with a couple modifications for updating
	return false;
}

// https://docs.modrinth.com/docs/modpacks/format_definition/
std::unique_ptr<MinecraftInstance> ModrinthCreationTask::createInstance()
{
	QEventLoop loop;

	QString parent_folder(FS::PathCombine(m_stagingPath, "mrpack"));

	QString index_path = FS::PathCombine(m_stagingPath, "modrinth.index.json");
	if (m_files.empty() && !parseManifest(index_path, m_files, true, true))
		return nullptr;

	// Keep index file in case we need it some other time (like when changing versions)
	QString new_index_place(FS::PathCombine(parent_folder, "modrinth.index.json"));
	FS::ensureFilePathExists(new_index_place);
	FS::move(index_path, new_index_place);

	auto mcPath = FS::PathCombine(m_stagingPath, m_root_path);

	auto override_path = FS::PathCombine(m_stagingPath, "overrides");
	if (QFile::exists(override_path))
	{
		// Create a list of overrides in "overrides.txt" inside mrpack/
		Override::createOverrides("overrides", parent_folder, override_path);

		// Apply the overrides
		if (!FS::move(override_path, mcPath))
		{
			setError(tr("Could not rename the overrides folder:\n") + "overrides");
			return nullptr;
		}
	}

	// Do client overrides
	auto client_override_path = FS::PathCombine(m_stagingPath, "client-overrides");
	if (QFile::exists(client_override_path))
	{
		// Create a list of overrides in "client-overrides.txt" inside mrpack/
		Override::createOverrides("client-overrides", parent_folder, client_override_path);

		// Apply the overrides
		if (!FS::overrideFolder(mcPath, client_override_path))
		{
			setError(tr("Could not rename the client overrides folder:\n") + "client overrides");
			return nullptr;
		}
	}

	QString configPath	  = FS::PathCombine(m_stagingPath, "instance.cfg");
	auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
	auto createdInstance  = std::make_unique<MinecraftInstance>(m_globalSettings, instanceSettings, m_stagingPath);
	auto& instance		  = *createdInstance;

	auto components = instance.getPackProfile();
	components->buildingFromScratch();
	components->setComponentVersion("net.minecraft", m_minecraft_version, true);

	if (!m_fabric_version.isEmpty())
		components->setComponentVersion("net.fabricmc.fabric-loader", m_fabric_version);
	if (!m_quilt_version.isEmpty())
		components->setComponentVersion("org.quiltmc.quilt-loader", m_quilt_version);
	if (!m_forge_version.isEmpty())
		components->setComponentVersion("net.minecraftforge", m_forge_version);
	if (!m_neoForge_version.isEmpty())
		components->setComponentVersion("net.neoforged", m_neoForge_version);

	if (m_instIcon != "default")
	{
		instance.setIconKey(m_instIcon);
	}
	else if (!m_managed_id.isEmpty())
	{
		instance.setIconKey("modrinth");
	}

	// Don't add managed info to packs without an ID (most likely imported from ZIP)
	if (!m_managed_id.isEmpty())
		instance.setManagedPack("modrinth", m_managed_id, m_managed_name, m_managed_version_id, version());
	else
		instance.setManagedPack("modrinth", "", name(), "", "");

	instance.setName(name());
	instance.saveNow();

	auto downloadMods = makeShared<NetJob>(tr("Mod Download Modrinth"), APPLICATION->network());

	// Clear any previous alternative URLs tracking
	m_alternativeUrls.clear();

	auto root_modpack_path = FS::PathCombine(m_stagingPath, m_root_path);
	auto root_modpack_url  = QUrl::fromLocalFile(root_modpack_path);
	// Note: Currently handles mods, resource packs, and shader packs.
	// Additional resource types can be added by extending the path prefix checks below.
	QHash<QString, Resource*> resources;
	for (auto& file : m_files)
	{
		auto fileName  = file.path;
		fileName	   = FS::RemoveInvalidPathChars(fileName);
		auto file_path = FS::PathCombine(root_modpack_path, fileName);
		if (!root_modpack_url.isParentOf(QUrl::fromLocalFile(file_path)))
		{
			// This means we somehow got out of the root folder, so abort here to prevent exploits
			setError(tr("One of the files has a path that leads to an arbitrary location (%1). This is a security risk "
						"and isn't allowed.")
						 .arg(fileName));
			return nullptr;
		}
		if (fileName.startsWith("mods/"))
		{
			auto mod = new Mod(file_path);
			ModDetails d;
			d.mod_id = file_path;
			mod->setDetails(d);
			resources[file.hash.toHex()] = mod;
		}
		if (file.downloads.empty())
		{
			setError(tr("The file '%1' is missing a download link. This is invalid in the pack format.").arg(fileName));
			return nullptr;
		}

		auto fileTask = makeShared<MultipleOptionsTask>(tr("Download %1").arg(fileName));

		for (const auto& url : file.downloads)
		{
			auto dl = Net::ApiDownload::makeFile(QUrl(url.toString()), file_path);
			dl->addValidator(new Net::ChecksumValidator(file.hashAlgorithm, file.hash));
			fileTask->addTask(dl);
		}

		downloadMods->addTask(fileTask);
	}

	bool ended_well = false;

	connect(downloadMods.get(), &NetJob::succeeded, this, [&ended_well]() { ended_well = true; });
	connect(downloadMods.get(),
			&NetJob::failed,
			[this, &ended_well](const QString& reason)
			{
				ended_well = false;
				setError(reason);
			});
	connect(downloadMods.get(), &NetJob::finished, &loop, &QEventLoop::quit);
	connect(downloadMods.get(),
			&NetJob::progress,
			[this](qint64 current, qint64 total)
			{
				setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
				setProgress(current, total);
			});
	connect(downloadMods.get(), &NetJob::stepProgress, this, &ModrinthCreationTask::propagateStepProgress);

	setStatus(tr("Downloading mods..."));
	downloadMods->start();
	m_task = downloadMods;

	loop.exec();

	if (!ended_well)
	{
		for (auto resource : resources)
		{
			delete resource;
		}
		return nullptr;
	}

	QEventLoop ensureMetaLoop;
	QDir folder = FS::PathCombine(instance.modsRoot(), ".index");
	auto ensureMetadataTask =
		makeShared<EnsureMetadataTask>(resources, folder, ModPlatform::ResourceProvider::MODRINTH);
	connect(ensureMetadataTask.get(), &Task::succeeded, this, [&ended_well]() { ended_well = true; });
	connect(ensureMetadataTask.get(), &Task::finished, &ensureMetaLoop, &QEventLoop::quit);
	connect(ensureMetadataTask.get(),
			&Task::progress,
			[this](qint64 current, qint64 total)
			{
				setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
				setProgress(current, total);
			});
	connect(ensureMetadataTask.get(), &Task::stepProgress, this, &ModrinthCreationTask::propagateStepProgress);

	ensureMetadataTask->start();
	m_task = ensureMetadataTask;

	ensureMetaLoop.exec();
	for (auto resource : resources)
	{
		delete resource;
	}
	resources.clear();

	// Update information of the already installed instance, if any.
	if (m_instance && ended_well)
	{
		setAbortable(false);
		auto inst = m_instance.value();

		// Only change the name if it didn't use a custom name, so that the previous custom name
		// is preserved, but if we're using the original one, we update the version string.
		// NOTE: This needs to come before the copyManagedPack call!
		if (inst->name().contains(inst->getManagedPackVersionName()) && inst->name() != instance.name())
		{
			if (askForChangingInstanceName(m_parent, inst->name(), instance.name()) == InstanceNameChange::ShouldChange)
				inst->setName(instance.name());
		}

		inst->copyManagedPack(instance);
	}

	if (ended_well)
	{
		return createdInstance;
	}
	return nullptr;
}

bool ModrinthCreationTask::parseManifest(const QString& index_path,
										 std::vector<File>& files,
										 bool set_internal_data,
										 bool show_optional_dialog)
{
	try
	{
		auto doc		  = Json::requireDocument(index_path);
		auto obj		  = Json::requireObject(doc, "modrinth.index.json");
		int formatVersion = Json::requireInteger(obj, "formatVersion", "modrinth.index.json");
		if (formatVersion == 1)
		{
			auto game = Json::requireString(obj, "game", "modrinth.index.json");
			if (game != "minecraft")
			{
				throw JSONValidationError("Unknown game: " + game);
			}

			if (set_internal_data)
			{
				if (m_managed_version_id.isEmpty())
					m_managed_version_id = Json::ensureString(obj, "versionId", {}, "Managed ID");
				m_managed_name = Json::ensureString(obj, "name", {}, "Managed Name");
			}

			auto jsonFiles = Json::requireIsArrayOf<QJsonObject>(obj, "files", "modrinth.index.json");
			std::vector<File> optionalFiles;
			for (const auto& modInfo : jsonFiles)
			{
				File file;
				file.path = Json::requireString(modInfo, "path").replace("\\", "/");

				auto env = Json::ensureObject(modInfo, "env");
				// 'env' field is optional
				if (!env.isEmpty())
				{
					QString support = Json::ensureString(env, "client", "unsupported");
					if (support == "unsupported")
					{
						continue;
					}
					else if (support == "optional")
					{
						file.required = false;
					}
				}

				QJsonObject hashes = Json::requireObject(modInfo, "hashes");
				file.hash		   = QByteArray::fromHex(Json::requireString(hashes, "sha512").toLatin1());
				file.hashAlgorithm = QCryptographicHash::Sha512;

				// Do not use requireUrl, which uses StrictMode, instead use QUrl's default TolerantMode
				// (as Modrinth seems to incorrectly handle spaces)

				auto download_arr = Json::ensureArray(modInfo, "downloads");
				for (auto download : download_arr)
				{
					qWarning() << download.toString();
					bool is_last = download.toString() == download_arr.last().toString();

					auto download_url = QUrl(download.toString());

					if (!download_url.isValid())
					{
						qDebug() << QString("Download URL (%1) for %2 is not a correctly formatted URL")
										.arg(download_url.toString(), file.path);
						if (is_last && file.downloads.isEmpty())
							throw JSONValidationError(
								tr("Download URL for %1 is not a correctly formatted URL").arg(file.path));
					}
					else
					{
						file.downloads.push_back(download_url);
					}
				}

				(file.required ? files : optionalFiles).push_back(file);
			}

			if (!optionalFiles.empty())
			{
				if (show_optional_dialog)
				{
					QStringList oFiles;
					for (auto file : optionalFiles)
						oFiles.push_back(file.path);
					OptionalModDialog optionalModDialog(m_parent, oFiles);
					if (optionalModDialog.exec() == QDialog::Rejected)
					{
						emitAborted();
						return false;
					}

					auto selectedMods = optionalModDialog.getResult();
					for (auto file : optionalFiles)
					{
						if (selectedMods.contains(file.path))
						{
							file.required = true;
						}
						else
						{
							file.path += ".disabled";
						}
						files.push_back(file);
					}
				}
				else
				{
					for (auto file : optionalFiles)
					{
						file.path += ".disabled";
						files.push_back(file);
					}
				}
			}
			if (set_internal_data)
			{
				auto dependencies = Json::requireObject(obj, "dependencies", "modrinth.index.json");
				for (auto it = dependencies.begin(), end = dependencies.end(); it != end; ++it)
				{
					QString name = it.key();
					if (name == "minecraft")
					{
						m_minecraft_version = Json::requireString(*it, "Minecraft version");
					}
					else if (name == "fabric-loader")
					{
						m_fabric_version = Json::requireString(*it, "Fabric Loader version");
					}
					else if (name == "quilt-loader")
					{
						m_quilt_version = Json::requireString(*it, "Quilt Loader version");
					}
					else if (name == "forge")
					{
						m_forge_version = Json::requireString(*it, "Forge version");
					}
					else if (name == "neoforge")
					{
						m_neoForge_version = Json::requireString(*it, "NeoForge version");
					}
					else
					{
						throw JSONValidationError("Unknown dependency type: " + name);
					}
				}
			}
		}
		else
		{
			throw JSONValidationError(QStringLiteral("Unknown format version: %s").arg(formatVersion));
		}
	}
	catch (const JSONValidationError& e)
	{
		setError(tr("Could not understand pack index:\n") + e.cause());
		return false;
	}

	return true;
}

void ModrinthCreationTask::attachRetryHandler(Net::Download::Ptr dl, shared_qobject_ptr<NetJob> downloadMods)
{
	// Connect to failed signal for retry logic
	connect(dl.get(),
			&Task::failed,
			this,
			[this, downloadMods, dl](QString reason)
			{
				Q_UNUSED(reason);
				auto it = m_alternativeUrls.find(dl.get());
				if (it == m_alternativeUrls.end())
				{
					return;
				}

				FileDownloadInfo info = it.value();
				if (info.remainingUrls.isEmpty())
				{
					m_alternativeUrls.remove(dl.get());
					return;
				}

				QString nextUrl = info.remainingUrls.dequeue();
				qDebug() << "Retrying download with alternative URL:" << nextUrl;

				auto newDl = Net::ApiDownload::makeFile(QUrl(nextUrl), info.filePath);
				newDl->addValidator(new Net::ChecksumValidator(info.hashAlgorithm, info.hash));

				if (!info.remainingUrls.isEmpty())
				{
					m_alternativeUrls[newDl.get()] = info;
				}

				m_alternativeUrls.remove(dl.get());
				attachRetryHandler(newDl, downloadMods);
				downloadMods->addNetAction(newDl);
			});

	// Clean up map entry on success
	connect(dl.get(), &Task::succeeded, this, [this, dl]() { m_alternativeUrls.remove(dl.get()); });
}