summaryrefslogtreecommitdiffstats
path: root/logic/minecraft/MinecraftVersionList.cpp
blob: 44be281b9cb27d9de1a9821d97c0b5ff95c1924f (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
669
670
671
672
673
674
675
676
677
678
679
/* Copyright 2013-2015 MultiMC Contributors
 *
 * 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 <QtXml>
#include "Json.h"
#include <QtAlgorithms>
#include <QtNetwork>

#include "Env.h"
#include "Exception.h"

#include "MinecraftVersionList.h"
#include "net/URLConstants.h"

#include "ParseUtils.h"
#include "ProfileUtils.h"
#include "VersionFilterData.h"

#include <pathutils.h>

static const char * localVersionCache = "versions/versions.dat";

class MCVListLoadTask : public Task
{
	Q_OBJECT

public:
	explicit MCVListLoadTask(MinecraftVersionList *vlist);
	virtual ~MCVListLoadTask() override{};

	virtual void executeTask() override;

protected
slots:
	void list_downloaded();

protected:
	QNetworkReply *vlistReply;
	MinecraftVersionList *m_list;
	MinecraftVersion *m_currentStable;
};

class MCVListVersionUpdateTask : public Task
{
	Q_OBJECT

public:
	explicit MCVListVersionUpdateTask(MinecraftVersionList *vlist, QString updatedVersion);
	virtual ~MCVListVersionUpdateTask() override{};
	virtual void executeTask() override;

protected
slots:
	void json_downloaded();

protected:
	NetJobPtr specificVersionDownloadJob;
	QString versionToUpdate;
	MinecraftVersionList *m_list;
};

class ListLoadError : public Exception
{
public:
	ListLoadError(QString cause) : Exception(cause) {};
	virtual ~ListLoadError() noexcept
	{
	}
};

MinecraftVersionList::MinecraftVersionList(QObject *parent) : BaseVersionList(parent)
{
	loadBuiltinList();
	loadCachedList();
}

Task *MinecraftVersionList::getLoadTask()
{
	return new MCVListLoadTask(this);
}

bool MinecraftVersionList::isLoaded()
{
	return m_loaded;
}

const BaseVersionPtr MinecraftVersionList::at(int i) const
{
	return m_vlist.at(i);
}

int MinecraftVersionList::count() const
{
	return m_vlist.count();
}

static bool cmpVersions(BaseVersionPtr first, BaseVersionPtr second)
{
	auto left = std::dynamic_pointer_cast<MinecraftVersion>(first);
	auto right = std::dynamic_pointer_cast<MinecraftVersion>(second);
	return left->m_releaseTime > right->m_releaseTime;
}

void MinecraftVersionList::sortInternal()
{
	qSort(m_vlist.begin(), m_vlist.end(), cmpVersions);
}

void MinecraftVersionList::loadCachedList()
{
	QFile localIndex(localVersionCache);
	if (!localIndex.exists())
	{
		return;
	}
	if (!localIndex.open(QIODevice::ReadOnly))
	{
		// FIXME: this is actually a very bad thing! How do we deal with this?
		qCritical() << "The minecraft version cache can't be read.";
		return;
	}
	auto data = localIndex.readAll();
	try
	{
		localIndex.close();
		QJsonDocument jsonDoc = QJsonDocument::fromBinaryData(data);
		if (jsonDoc.isNull())
		{
			throw ListLoadError(tr("Error reading the version list."));
		}
		loadMojangList(jsonDoc, Local);
	}
	catch (Exception &e)
	{
		// the cache has gone bad for some reason... flush it.
		qCritical() << "The minecraft version cache is corrupted. Flushing cache.";
		localIndex.remove();
		return;
	}
	m_hasLocalIndex = true;
}

void MinecraftVersionList::loadBuiltinList()
{
	qDebug() << "Loading builtin version list.";
	// grab the version list data from internal resources.
	const QJsonDocument doc =
		Json::ensureDocument(QString(":/versions/minecraft.json"), "builtin version list");
	const QJsonObject root = doc.object();

	// parse all the versions
	for (const auto version : Json::ensureArray(root.value("versions")))
	{
		QJsonObject versionObj = version.toObject();
		QString versionID = versionObj.value("id").toString("");
		QString versionTypeStr = versionObj.value("type").toString("");
		if (versionID.isEmpty() || versionTypeStr.isEmpty())
		{
			qCritical() << "Parsed version is missing ID or type";
			continue;
		}

		if (g_VersionFilterData.legacyBlacklist.contains(versionID))
		{
			qWarning() << "Blacklisted legacy version ignored: " << versionID;
			continue;
		}

		// Now, we construct the version object and add it to the list.
		std::shared_ptr<MinecraftVersion> mcVersion(new MinecraftVersion());
		mcVersion->m_name = mcVersion->m_descriptor = versionID;

		// Parse the timestamp.
		if (!parse_timestamp(versionObj.value("releaseTime").toString(""),
							 mcVersion->m_releaseTimeString, mcVersion->m_releaseTime))
		{
			qCritical() << "Error while parsing version" << versionID
						 << ": invalid version timestamp";
			continue;
		}

		// Get the download URL.
		mcVersion->download_url =
			"http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + versionID + "/";

		mcVersion->m_versionSource = Builtin;
		mcVersion->m_type = versionTypeStr;
		mcVersion->m_appletClass = versionObj.value("appletClass").toString("");
		mcVersion->m_mainClass = versionObj.value("mainClass").toString("");
		mcVersion->m_jarChecksum = versionObj.value("checksum").toString("");
		mcVersion->m_processArguments = versionObj.value("processArguments").toString("legacy");
		if (versionObj.contains("+traits"))
		{
			for (auto traitVal : Json::ensureArray(versionObj.value("+traits")))
			{
				mcVersion->m_traits.insert(Json::ensureString(traitVal));
			}
		}
		m_lookup[versionID] = mcVersion;
		m_vlist.append(mcVersion);
	}
}

void MinecraftVersionList::loadMojangList(QJsonDocument jsonDoc, VersionSource source)
{
	qDebug() << "Loading" << ((source == Remote) ? "remote" : "local") << "version list.";

	if (!jsonDoc.isObject())
	{
		throw ListLoadError(tr("Error parsing version list JSON: jsonDoc is not an object"));
	}

	QJsonObject root = jsonDoc.object();

	try
	{
		QJsonObject latest = Json::ensureObject(root.value("latest"));
		m_latestReleaseID = Json::ensureString(latest.value("release"));
		m_latestSnapshotID = Json::ensureString(latest.value("snapshot"));
	}
	catch (Exception &err)
	{
		qCritical()
			<< tr("Error parsing version list JSON: couldn't determine latest versions");
	}

	// Now, get the array of versions.
	if (!root.value("versions").isArray())
	{
		throw ListLoadError(tr("Error parsing version list JSON: version list object is "
							   "missing 'versions' array"));
	}
	QJsonArray versions = root.value("versions").toArray();

	QList<BaseVersionPtr> tempList;
	for (auto version : versions)
	{
		// Load the version info.
		if (!version.isObject())
		{
			qCritical() << "Error while parsing version list : invalid JSON structure";
			continue;
		}

		QJsonObject versionObj = version.toObject();
		QString versionID = versionObj.value("id").toString("");
		if (versionID.isEmpty())
		{
			qCritical() << "Error while parsing version : version ID is missing";
			continue;
		}

		if (g_VersionFilterData.legacyBlacklist.contains(versionID))
		{
			qWarning() << "Blacklisted legacy version ignored: " << versionID;
			continue;
		}

		// Now, we construct the version object and add it to the list.
		std::shared_ptr<MinecraftVersion> mcVersion(new MinecraftVersion());
		mcVersion->m_name = mcVersion->m_descriptor = versionID;

		if (!parse_timestamp(versionObj.value("releaseTime").toString(""),
							 mcVersion->m_releaseTimeString, mcVersion->m_releaseTime))
		{
			qCritical() << "Error while parsing version" << versionID
						 << ": invalid release timestamp";
			continue;
		}
		if (!parse_timestamp(versionObj.value("time").toString(""),
							 mcVersion->m_updateTimeString, mcVersion->m_updateTime))
		{
			qCritical() << "Error while parsing version" << versionID
						 << ": invalid update timestamp";
			continue;
		}

		if (mcVersion->m_releaseTime < g_VersionFilterData.legacyCutoffDate)
		{
			continue;
		}

		// depends on where we load the version from -- network request or local file?
		mcVersion->m_versionSource = source;

		QString dlUrl = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + versionID + "/";
		mcVersion->download_url = dlUrl;
		QString versionTypeStr = versionObj.value("type").toString("");
		if (versionTypeStr.isEmpty())
		{
			qCritical() << "Ignoring" << versionID
						 << "because it doesn't have the version type set.";
			continue;
		}
		// OneSix or Legacy. use filter to determine type
		if (versionTypeStr == "release")
		{
		}
		else if (versionTypeStr == "snapshot") // It's a snapshot... yay
		{
		}
		else if (versionTypeStr == "old_alpha")
		{
		}
		else if (versionTypeStr == "old_beta")
		{
		}
		else
		{
			qCritical() << "Ignoring" << versionID
						 << "because it has an invalid version type.";
			continue;
		}
		mcVersion->m_type = versionTypeStr;
		qDebug() << "Loaded version" << versionID << "from"
					<< ((source == Remote) ? "remote" : "local") << "version list.";
		tempList.append(mcVersion);
	}
	updateListData(tempList);
	if(source == Remote)
	{
		m_loaded = true;
	}
}

void MinecraftVersionList::sort()
{
	beginResetModel();
	sortInternal();
	endResetModel();
}

QVariant MinecraftVersionList::data(const QModelIndex& index, int role) const
{
	if (!index.isValid())
		return QVariant();

	if (index.row() > count())
		return QVariant();

	auto version = std::dynamic_pointer_cast<MinecraftVersion>(m_vlist[index.row()]);
	switch (role)
	{
	case VersionPointerRole:
		return qVariantFromValue(m_vlist[index.row()]);

	case VersionRole:
		return version->name();

	case VersionIdRole:
		return version->descriptor();

	case RecommendedRole:
		return version->descriptor() == m_latestReleaseID;

	case LatestRole:
	{
		if(version->descriptor() != m_latestSnapshotID)
			return false;
		MinecraftVersionPtr latestRelease = std::dynamic_pointer_cast<MinecraftVersion>(getLatestStable());
		/*
		if(latestRelease && latestRelease->m_releaseTime > version->m_releaseTime)
		{
			return false;
		}
		*/
		return true;
	}

	case TypeRole:
		return version->typeString();

	default:
		return QVariant();
	}
}

BaseVersionList::RoleList MinecraftVersionList::providesRoles()
{
	return {VersionPointerRole, VersionRole, VersionIdRole, RecommendedRole, LatestRole, TypeRole};
}

BaseVersionPtr MinecraftVersionList::getLatestStable() const
{
	if(m_lookup.contains(m_latestReleaseID))
		return m_lookup[m_latestReleaseID];
	return BaseVersionPtr();
}

BaseVersionPtr MinecraftVersionList::getRecommended() const
{
	return getLatestStable();
}

void MinecraftVersionList::updateListData(QList<BaseVersionPtr> versions)
{
	beginResetModel();
	for (auto version : versions)
	{
		auto descr = version->descriptor();

		if (!m_lookup.contains(descr))
		{
			m_lookup[version->descriptor()] = version;
			m_vlist.append(version);
			continue;
		}
		auto orig = std::dynamic_pointer_cast<MinecraftVersion>(m_lookup[descr]);
		auto added = std::dynamic_pointer_cast<MinecraftVersion>(version);
		// updateListData is called after Mojang list loads. those can be local or remote
		// remote comes always after local
		// any other options are ignored
		if (orig->m_versionSource != Local || added->m_versionSource != Remote)
		{
			continue;
		}
		// alright, it's an update. put it inside the original, for further processing.
		orig->upstreamUpdate = added;
	}
	sortInternal();
	endResetModel();
}

inline QDomElement getDomElementByTagName(QDomElement parent, QString tagname)
{
	QDomNodeList elementList = parent.elementsByTagName(tagname);
	if (elementList.count())
		return elementList.at(0).toElement();
	else
		return QDomElement();
}

MCVListLoadTask::MCVListLoadTask(MinecraftVersionList *vlist)
{
	m_list = vlist;
	m_currentStable = NULL;
	vlistReply = nullptr;
}

void MCVListLoadTask::executeTask()
{
	setStatus(tr("Loading instance version list..."));
	auto worker = ENV.qnam();
	vlistReply = worker->get(QNetworkRequest(
		QUrl("http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + "versions.json")));
	connect(vlistReply, SIGNAL(finished()), this, SLOT(list_downloaded()));
}

void MCVListLoadTask::list_downloaded()
{
	if (vlistReply->error() != QNetworkReply::NoError)
	{
		vlistReply->deleteLater();
		emitFailed("Failed to load Minecraft main version list" + vlistReply->errorString());
		return;
	}

	auto data = vlistReply->readAll();
	vlistReply->deleteLater();
	try
	{
		QJsonParseError jsonError;
		QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
		if (jsonError.error != QJsonParseError::NoError)
		{
			throw ListLoadError(
				tr("Error parsing version list JSON: %1").arg(jsonError.errorString()));
		}
		m_list->loadMojangList(jsonDoc, Remote);
	}
	catch (Exception &e)
	{
		emitFailed(e.cause());
		return;
	}

	emitSucceeded();
	return;
}

MCVListVersionUpdateTask::MCVListVersionUpdateTask(MinecraftVersionList *vlist,
												   QString updatedVersion)
	: Task()
{
	m_list = vlist;
	versionToUpdate = updatedVersion;
}

void MCVListVersionUpdateTask::executeTask()
{
	QString urlstr = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + versionToUpdate + "/" +
					 versionToUpdate + ".json";
	auto job = new NetJob("Version index");
	job->addNetAction(ByteArrayDownload::make(QUrl(urlstr)));
	specificVersionDownloadJob.reset(job);
	connect(specificVersionDownloadJob.get(), SIGNAL(succeeded()), SLOT(json_downloaded()));
	connect(specificVersionDownloadJob.get(), SIGNAL(failed(QString)), SIGNAL(failed(QString)));
	connect(specificVersionDownloadJob.get(), SIGNAL(progress(qint64, qint64)),
			SIGNAL(progress(qint64, qint64)));
	specificVersionDownloadJob->start();
}

void MCVListVersionUpdateTask::json_downloaded()
{
	NetActionPtr DlJob = specificVersionDownloadJob->first();
	auto data = std::dynamic_pointer_cast<ByteArrayDownload>(DlJob)->m_data;
	specificVersionDownloadJob.reset();

	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

	if (jsonError.error != QJsonParseError::NoError)
	{
		emitFailed(tr("The download version file is not valid."));
		return;
	}
	VersionFilePtr file;
	try
	{
		file = VersionFile::fromJson(jsonDoc, "net.minecraft.json", false);
	}
	catch (Exception &e)
	{
		emitFailed(tr("Couldn't process version file: %1").arg(e.cause()));
		return;
	}

	// Strip LWJGL from the version file. We use our own.
	ProfileUtils::removeLwjglFromPatch(file);

	// TODO: recognize and add LWJGL versions here.

	file->fileId = "net.minecraft";

	// now dump the file to disk
	auto doc = file->toJson(false);
	auto newdata = doc.toBinaryData();
	QString targetPath = "versions/" + versionToUpdate + "/" + versionToUpdate + ".dat";
	ensureFilePathExists(targetPath);
	QSaveFile vfile1(targetPath);
	if (!vfile1.open(QIODevice::Truncate | QIODevice::WriteOnly))
	{
		emitFailed(tr("Can't open %1 for writing.").arg(targetPath));
		return;
	}
	qint64 actual = 0;
	if ((actual = vfile1.write(newdata)) != newdata.size())
	{
		emitFailed(tr("Failed to write into %1. Written %2 out of %3.")
					   .arg(targetPath)
					   .arg(actual)
					   .arg(newdata.size()));
		return;
	}
	if (!vfile1.commit())
	{
		emitFailed(tr("Can't commit changes to %1").arg(targetPath));
		return;
	}

	m_list->finalizeUpdate(versionToUpdate);
	emitSucceeded();
}

std::shared_ptr<Task> MinecraftVersionList::createUpdateTask(QString version)
{
	return std::shared_ptr<Task>(new MCVListVersionUpdateTask(this, version));
}

void MinecraftVersionList::saveCachedList()
{
	// FIXME: throw.
	if (!ensureFilePathExists(localVersionCache))
		return;
	QSaveFile tfile(localVersionCache);
	if (!tfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
		return;
	QJsonObject toplevel;
	QJsonArray entriesArr;
	for (auto version : m_vlist)
	{
		auto mcversion = std::dynamic_pointer_cast<MinecraftVersion>(version);
		// do not save the remote versions.
		if (mcversion->m_versionSource != Local)
			continue;
		QJsonObject entryObj;

		entryObj.insert("id", mcversion->descriptor());
		entryObj.insert("version", mcversion->descriptor());
		entryObj.insert("time", mcversion->m_updateTimeString);
		entryObj.insert("releaseTime", mcversion->m_releaseTimeString);
		entryObj.insert("type", mcversion->m_type);
		entriesArr.append(entryObj);
	}
	toplevel.insert("versions", entriesArr);

	{
		bool someLatest = false;
		QJsonObject latestObj;
		if(!m_latestReleaseID.isNull())
		{
			latestObj.insert("release", m_latestReleaseID);
			someLatest = true;
		}
		if(!m_latestSnapshotID.isNull())
		{
			latestObj.insert("snapshot", m_latestSnapshotID);
			someLatest = true;
		}
		if(someLatest)
		{
			toplevel.insert("latest", latestObj);
		}
	}

	QJsonDocument doc(toplevel);
	QByteArray jsonData = doc.toBinaryData();
	qint64 result = tfile.write(jsonData);
	if (result == -1)
		return;
	if (result != jsonData.size())
		return;
	tfile.commit();
}

void MinecraftVersionList::finalizeUpdate(QString version)
{
	int idx = -1;
	for (int i = 0; i < m_vlist.size(); i++)
	{
		if (version == m_vlist[i]->descriptor())
		{
			idx = i;
			break;
		}
	}
	if (idx == -1)
	{
		return;
	}

	auto updatedVersion = std::dynamic_pointer_cast<MinecraftVersion>(m_vlist[idx]);

	// reject any updates to builtin versions.
	if (updatedVersion->m_versionSource == Builtin)
		return;

	// if we have an update for the version, replace it, make the update local
	if (updatedVersion->upstreamUpdate)
	{
		auto updatedWith = updatedVersion->upstreamUpdate;
		updatedWith->m_versionSource = Local;
		m_vlist[idx] = updatedWith;
		m_lookup[version] = updatedWith;
	}
	else
	{
		// otherwise, just set the version as local;
		updatedVersion->m_versionSource = Local;
	}

	dataChanged(index(idx), index(idx));

	saveCachedList();
}

#include "MinecraftVersionList.moc"