summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/modplatform/EnsureMetadataTask.cpp
blob: 460e9473ed4441c7a2c04cb492327b58e0a7d46e (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 "EnsureMetadataTask.h"

#include <MurmurHash2.h>
#include <QDebug>

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

#include "QObjectPtr.h"
#include "minecraft/mod/Mod.hpp"
#include "minecraft/mod/tasks/LocalResourceUpdateTask.hpp"

#include "modplatform/flame/FlameAPI.h"
#include "modplatform/flame/FlameModIndex.h"
#include "modplatform/helpers/HashUtils.h"
#include "modplatform/modrinth/ModrinthAPI.h"
#include "modplatform/modrinth/ModrinthPackIndex.h"

static ModrinthAPI modrinth_api;
static FlameAPI flame_api;

EnsureMetadataTask::EnsureMetadataTask(Resource* resource, QDir dir, ModPlatform::ResourceProvider prov)
	: Task(),
	  m_indexDir(dir),
	  m_provider(prov),
	  m_hashingTask(nullptr),
	  m_currentTask(nullptr)
{
	auto hashTask = createNewHash(resource);
	if (!hashTask)
		return;
	connect(hashTask.get(),
			&Hashing::Hasher::resultsReady,
			[this, resource](QString hash) { m_resources.insert(hash, resource); });
	connect(hashTask.get(), &Task::failed, [this, resource] { emitFail(resource, "", RemoveFromList::No); });
	m_hashingTask = hashTask;
}

EnsureMetadataTask::EnsureMetadataTask(QList<Resource*>& resources, QDir dir, ModPlatform::ResourceProvider prov)
	: Task(),
	  m_indexDir(dir),
	  m_provider(prov),
	  m_currentTask(nullptr)
{
	auto hashTask =
		makeShared<ConcurrentTask>("MakeHashesTask", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt());
	m_hashingTask = hashTask;
	for (auto* resource : resources)
	{
		auto hash_task = createNewHash(resource);
		if (!hash_task)
			continue;
		connect(hash_task.get(),
				&Hashing::Hasher::resultsReady,
				[this, resource](QString hash) { m_resources.insert(hash, resource); });
		connect(hash_task.get(), &Task::failed, [this, resource] { emitFail(resource, "", RemoveFromList::No); });
		hashTask->addTask(hash_task);
	}
}

EnsureMetadataTask::EnsureMetadataTask(QHash<QString, Resource*>& resources,
									   QDir dir,
									   ModPlatform::ResourceProvider prov)
	: Task(),
	  m_resources(resources),
	  m_indexDir(dir),
	  m_provider(prov),
	  m_currentTask(nullptr)
{}

Hashing::Hasher::Ptr EnsureMetadataTask::createNewHash(Resource* resource)
{
	if (!resource || !resource->valid() || resource->type() == ResourceType::FOLDER)
		return nullptr;

	return Hashing::createHasher(resource->fileinfo().absoluteFilePath(), m_provider);
}

QString EnsureMetadataTask::getExistingHash(Resource* resource)
{
	// Check for already computed hashes
	// (linear on the number of mods vs. linear on the size of the mod's JAR)
	auto it = m_resources.keyValueBegin();
	while (it != m_resources.keyValueEnd())
	{
		if ((*it).second == resource)
			break;
		it++;
	}

	// We already have the hash computed
	if (it != m_resources.keyValueEnd())
	{
		return (*it).first;
	}

	// No existing hash
	return {};
}

bool EnsureMetadataTask::abort()
{
	// Prevent sending signals to a dead object
	disconnect(this, 0, 0, 0);

	if (m_currentTask)
		return m_currentTask->abort();
	return true;
}

void EnsureMetadataTask::executeTask()
{
	setStatus(tr("Checking if resources have metadata..."));

	for (auto* resource : m_resources)
	{
		if (!resource->valid())
		{
			qDebug() << "Resource" << resource->name() << "is invalid!";
			emitFail(resource);
			continue;
		}

		// They already have the right metadata :o
		if (resource->status() != ResourceStatus::NO_METADATA && resource->metadata()
			&& resource->metadata()->provider == m_provider)
		{
			qDebug() << "Resource" << resource->name() << "already has metadata!";
			emitReady(resource);
			continue;
		}

		// Folders don't have metadata
		if (resource->type() == ResourceType::FOLDER)
		{
			emitReady(resource);
		}
	}

	Task::Ptr version_task;

	switch (m_provider)
	{
		case (ModPlatform::ResourceProvider::MODRINTH): version_task = modrinthVersionsTask(); break;
		case (ModPlatform::ResourceProvider::FLAME): version_task = flameVersionsTask(); break;
	}

	auto invalidade_leftover = [this]
	{
		for (auto resource = m_resources.constBegin(); resource != m_resources.constEnd(); resource++)
			emitFail(resource.value(), resource.key(), RemoveFromList::No);
		m_resources.clear();

		emitSucceeded();
	};

	connect(version_task.get(),
			&Task::finished,
			this,
			[this, invalidade_leftover]
			{
				Task::Ptr project_task;

				switch (m_provider)
				{
					case (ModPlatform::ResourceProvider::MODRINTH): project_task = modrinthProjectsTask(); break;
					case (ModPlatform::ResourceProvider::FLAME): project_task = flameProjectsTask(); break;
				}

				if (!project_task)
				{
					invalidade_leftover();
					return;
				}

				connect(project_task.get(),
						&Task::finished,
						this,
						[this, invalidade_leftover, project_task]
						{
							invalidade_leftover();
							project_task->deleteLater();
							if (m_currentTask)
								m_currentTask.reset();
						});
				connect(project_task.get(), &Task::failed, this, &EnsureMetadataTask::emitFailed);

				m_currentTask = project_task;
				project_task->start();
			});

	if (m_resources.size() > 1)
		setStatus(tr("Requesting metadata information from %1...")
					  .arg(ModPlatform::ProviderCapabilities::readableName(m_provider)));
	else if (!m_resources.empty())
		setStatus(
			tr("Requesting metadata information from %1 for '%2'...")
				.arg(ModPlatform::ProviderCapabilities::readableName(m_provider), m_resources.begin().value()->name()));

	m_currentTask = version_task;
	version_task->start();
}

void EnsureMetadataTask::emitReady(Resource* resource, QString key, RemoveFromList remove)
{
	if (!resource)
	{
		qCritical() << "Tried to mark a null resource as ready.";
		if (!key.isEmpty())
			m_resources.remove(key);

		return;
	}

	qDebug() << QString("Generated metadata for %1").arg(resource->name());
	emit metadataReady(resource);

	if (remove == RemoveFromList::Yes)
	{
		if (key.isEmpty())
			key = getExistingHash(resource);
		m_resources.remove(key);
	}
}

void EnsureMetadataTask::emitFail(Resource* resource, QString key, RemoveFromList remove)
{
	if (!resource)
	{
		qCritical() << "Tried to mark a null resource as failed.";
		if (!key.isEmpty())
			m_resources.remove(key);

		return;
	}

	qDebug() << QString("Failed to generate metadata for %1").arg(resource->name());
	emit metadataFailed(resource);

	if (remove == RemoveFromList::Yes)
	{
		if (key.isEmpty())
			key = getExistingHash(resource);
		m_resources.remove(key);
	}
}

// Modrinth

Task::Ptr EnsureMetadataTask::modrinthVersionsTask()
{
	auto hash_type = ModPlatform::ProviderCapabilities::hashType(ModPlatform::ResourceProvider::MODRINTH).first();

	auto response = std::make_shared<QByteArray>();
	auto ver_task = modrinth_api.currentVersions(m_resources.keys(), hash_type, response);

	// Prevents unfortunate timings when aborting the task
	if (!ver_task)
		return Task::Ptr{ nullptr };

	connect(ver_task.get(),
			&Task::succeeded,
			this,
			[this, response]
			{
				QJsonParseError parse_error{};
				QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
				if (parse_error.error != QJsonParseError::NoError)
				{
					qWarning() << "Error while parsing JSON response from Modrinth::CurrentVersions at "
							   << parse_error.offset << " reason: " << parse_error.errorString();
					qWarning() << *response;

					failed(parse_error.errorString());
					return;
				}

				try
				{
					auto entries = Json::requireObject(doc);
					for (auto& hash : m_resources.keys())
					{
						auto resource = m_resources.find(hash).value();
						try
						{
							auto entry = Json::requireObject(entries, hash);

							setStatus(tr("Parsing API response from Modrinth for '%1'...").arg(resource->name()));
							qDebug() << "Getting version for" << resource->name() << "from Modrinth";

							m_tempVersions.insert(hash, Modrinth::loadIndexedPackVersion(entry));
						}
						catch (Json::JsonException& e)
						{
							qDebug() << e.cause();
							qDebug() << entries;

							emitFail(resource);
						}
					}
				}
				catch (Json::JsonException& e)
				{
					qDebug() << e.cause();
					qDebug() << doc;
				}
			});

	return ver_task;
}

Task::Ptr EnsureMetadataTask::modrinthProjectsTask()
{
	QHash<QString, QString> addonIds;
	for (auto const& data : m_tempVersions)
		addonIds.insert(data.addonId.toString(), data.hash);

	auto response = std::make_shared<QByteArray>();
	Task::Ptr proj_task;

	if (addonIds.isEmpty())
	{
		qWarning() << "No addonId found!";
	}
	else if (addonIds.size() == 1)
	{
		proj_task = modrinth_api.getProject(*addonIds.keyBegin(), response);
	}
	else
	{
		proj_task = modrinth_api.getProjects(addonIds.keys(), response);
	}

	// Prevents unfortunate timings when aborting the task
	if (!proj_task)
		return Task::Ptr{ nullptr };

	connect(proj_task.get(),
			&Task::succeeded,
			this,
			[this, response, addonIds]
			{
				QJsonParseError parse_error{};
				auto doc = QJsonDocument::fromJson(*response, &parse_error);
				if (parse_error.error != QJsonParseError::NoError)
				{
					qWarning() << "Error while parsing JSON response from Modrinth projects task at "
							   << parse_error.offset << " reason: " << parse_error.errorString();
					qWarning() << *response;
					return;
				}

				QJsonArray entries;

				try
				{
					if (addonIds.size() == 1)
						entries = { doc.object() };
					else
						entries = Json::requireArray(doc);
				}
				catch (Json::JsonException& e)
				{
					qDebug() << e.cause();
					qDebug() << doc;
				}

				for (auto entry : entries)
				{
					ModPlatform::IndexedPack pack;

					try
					{
						auto entry_obj = Json::requireObject(entry);

						Modrinth::loadIndexedPack(pack, entry_obj);
					}
					catch (Json::JsonException& e)
					{
						qDebug() << e.cause();
						qDebug() << doc;

						// Skip this entry, since it has problems
						continue;
					}

					auto hashIt = addonIds.find(pack.addonId.toString());
					if (hashIt == addonIds.end())
					{
						qWarning() << "Invalid project id from the API response.";
						continue;
					}
					const auto& hash = hashIt.value();

					auto resource_iter = m_resources.find(hash);
					if (resource_iter == m_resources.end())
					{
						qWarning() << "Invalid project id from the API response.";
						continue;
					}

					auto* resource	 = resource_iter.value();
					auto versionIter = m_tempVersions.find(hash);
					if (versionIter == m_tempVersions.end())
					{
						qWarning() << "Missing temporary version data for Modrinth project.";
						continue;
					}

					setStatus(tr("Parsing API response from Modrinth for '%1'...").arg(resource->name()));

					updateMetadata(pack, versionIter.value(), resource);
				}
			});

	return proj_task;
}

// Flame
Task::Ptr EnsureMetadataTask::flameVersionsTask()
{
	auto response = std::make_shared<QByteArray>();

	QList<uint> fingerprints;
	for (auto& murmur : m_resources.keys())
	{
		fingerprints.push_back(murmur.toUInt());
	}

	auto ver_task = flame_api.matchFingerprints(fingerprints, response);

	connect(ver_task.get(),
			&Task::succeeded,
			this,
			[this, response]
			{
				QJsonParseError parse_error{};
				QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
				if (parse_error.error != QJsonParseError::NoError)
				{
					qWarning() << "Error while parsing JSON response from Modrinth::CurrentVersions at "
							   << parse_error.offset << " reason: " << parse_error.errorString();
					qWarning() << *response;

					failed(parse_error.errorString());
					return;
				}

				try
				{
					auto doc_obj  = Json::requireObject(doc);
					auto data_obj = Json::requireObject(doc_obj, "data");
					auto data_arr = Json::requireArray(data_obj, "exactMatches");

					if (data_arr.isEmpty())
					{
						qWarning() << "No matches found for fingerprint search!";

						return;
					}

					for (auto match : data_arr)
					{
						auto match_obj = Json::ensureObject(match, {});
						auto file_obj  = Json::ensureObject(match_obj, "file", {});

						if (match_obj.isEmpty() || file_obj.isEmpty())
						{
							qWarning() << "Fingerprint match is empty!";

							return;
						}

						auto fingerprint = QString::number(Json::ensureVariant(file_obj, "fileFingerprint").toUInt());
						auto resource	 = m_resources.find(fingerprint);
						if (resource == m_resources.end())
						{
							qWarning() << "Invalid fingerprint from the API response.";
							continue;
						}

						setStatus(tr("Parsing API response from CurseForge for '%1'...").arg((*resource)->name()));

						m_tempVersions.insert(fingerprint, FlameMod::loadIndexedPackVersion(file_obj));
					}
				}
				catch (Json::JsonException& e)
				{
					qDebug() << e.cause();
					qDebug() << doc;
				}
			});

	return ver_task;
}

Task::Ptr EnsureMetadataTask::flameProjectsTask()
{
	QHash<QString, QString> addonIds;
	for (auto const& hash : m_resources.keys())
	{
		if (m_tempVersions.contains(hash))
		{
			auto data = m_tempVersions.find(hash).value();

			auto id_str = data.addonId.toString();
			if (!id_str.isEmpty())
				addonIds.insert(data.addonId.toString(), hash);
		}
	}

	auto response = std::make_shared<QByteArray>();
	Task::Ptr proj_task;

	if (addonIds.isEmpty())
	{
		qWarning() << "No addonId found!";
	}
	else if (addonIds.size() == 1)
	{
		proj_task = flame_api.getProject(*addonIds.keyBegin(), response);
	}
	else
	{
		proj_task = flame_api.getProjects(addonIds.keys(), response);
	}

	// Prevents unfortunate timings when aborting the task
	if (!proj_task)
		return Task::Ptr{ nullptr };

	connect(proj_task.get(),
			&Task::succeeded,
			this,
			[this, response, addonIds]
			{
				QJsonParseError parse_error{};
				auto doc = QJsonDocument::fromJson(*response, &parse_error);
				if (parse_error.error != QJsonParseError::NoError)
				{
					qWarning() << "Error while parsing JSON response from Modrinth projects task at "
							   << parse_error.offset << " reason: " << parse_error.errorString();
					qWarning() << *response;
					return;
				}

				try
				{
					QJsonArray entries;
					if (addonIds.size() == 1)
						entries = { Json::requireObject(Json::requireObject(doc), "data") };
					else
						entries = Json::requireArray(Json::requireObject(doc), "data");

					for (auto entry : entries)
					{
						auto entry_obj = Json::requireObject(entry);

						auto id		= QString::number(Json::requireInteger(entry_obj, "id"));
						auto hashIt = addonIds.find(id);
						if (hashIt == addonIds.end())
						{
							qWarning() << "Invalid project id from the API response.";
							continue;
						}
						const auto& hash = hashIt.value();
						auto resourceIt	 = m_resources.find(hash);
						if (resourceIt == m_resources.end())
						{
							qWarning() << "Invalid fingerprint from the API response.";
							continue;
						}
						auto resource	 = resourceIt.value();
						auto versionIter = m_tempVersions.find(hash);
						if (versionIter == m_tempVersions.end())
						{
							qWarning() << "Missing temporary version data for CurseForge project.";
							continue;
						}

						ModPlatform::IndexedPack pack;
						try
						{
							setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(resource->name()));

							FlameMod::loadIndexedPack(pack, entry_obj);
						}
						catch (Json::JsonException& e)
						{
							qDebug() << e.cause();
							qDebug() << entries;

							emitFail(resource);
						}
						updateMetadata(pack, versionIter.value(), resource);
					}
				}
				catch (Json::JsonException& e)
				{
					qDebug() << e.cause();
					qDebug() << doc;
				}
			});

	return proj_task;
}

void EnsureMetadataTask::updateMetadata(ModPlatform::IndexedPack& pack,
										ModPlatform::IndexedVersion& ver,
										Resource* resource)
{
	try
	{
		// Prevent file name mismatch
		ver.fileName = resource->fileinfo().fileName();
		if (ver.fileName.endsWith(".disabled"))
			ver.fileName.chop(9);

		auto task = makeShared<LocalResourceUpdateTask>(m_indexDir, pack, ver);

		connect(task.get(), &Task::finished, this, [this, &pack, resource] { updateMetadataCallback(pack, resource); });

		m_updateMetadataTasks[ModPlatform::ProviderCapabilities::name(pack.provider) + pack.addonId.toString()] = task;
		task->start();
	}
	catch (Json::JsonException& e)
	{
		qDebug() << e.cause();

		emitFail(resource);
	}
}

void EnsureMetadataTask::updateMetadataCallback(ModPlatform::IndexedPack& pack, Resource* resource)
{
	QDir tmpIndexDir(m_indexDir);
	auto metadata = Metadata::get(tmpIndexDir, pack.slug);
	if (!metadata.isValid())
	{
		qCritical() << "Failed to generate metadata at last step!";
		emitFail(resource);
		return;
	}

	resource->setMetadata(metadata);

	emitReady(resource);
}