-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinecraftService.cs
More file actions
383 lines (332 loc) · 14.6 KB
/
MinecraftService.cs
File metadata and controls
383 lines (332 loc) · 14.6 KB
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
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO.Compression;
namespace JustLauncher;
public class MinecraftService
{
public static MinecraftService Instance { get; } = new MinecraftService();
private const string ManifestUrl = "https://launchermeta.mojang.com/mc/game/version_manifest_v2.json";
private readonly string _baseDir;
public MinecraftService() : this(PlatformManager.GetMinecraftDirectory())
{
}
public MinecraftService(string baseDir)
{
_baseDir = baseDir;
}
public async Task<VersionManifest> GetVersionManifestAsync()
{
string json = await HttpClientManager.Instance.GetStringAsync(ManifestUrl);
return JsonSerializer.Deserialize<VersionManifest>(json) ?? new();
}
public async Task<VersionInfo> GetVersionInfoAsync(string url)
{
string json = await HttpClientManager.Instance.GetStringAsync(url);
return JsonSerializer.Deserialize<VersionInfo>(json) ?? new();
}
public async Task<VersionInfo> GetVersionInfoFromLocalAsync(string versionId)
{
string jsonPath = Path.Combine(_baseDir, "versions", versionId, $"{versionId}.json");
if (!File.Exists(jsonPath)) throw new FileNotFoundException($"Version JSON not found: {jsonPath}");
string json = await File.ReadAllTextAsync(jsonPath);
var info = JsonSerializer.Deserialize<VersionInfo>(json) ?? new();
if (!string.IsNullOrEmpty(info.InheritsFrom))
{
var manifest = await GetVersionManifestAsync();
var parentVer = manifest.Versions.FirstOrDefault(v => v.Id == info.InheritsFrom);
if (parentVer != null)
{
var parentInfo = await GetVersionInfoAsync(parentVer.Url);
MergeVersionInfo(info, parentInfo);
}
}
return info;
}
private void MergeVersionInfo(VersionInfo child, VersionInfo parent)
{
child.Libraries.AddRange(parent.Libraries);
if (child.AssetIndex == null || string.IsNullOrEmpty(child.AssetIndex.Id))
{
child.AssetIndex = parent.AssetIndex;
}
if (child.Downloads == null || child.Downloads.Client == null || string.IsNullOrEmpty(child.Downloads.Client.Url))
{
child.Downloads = parent.Downloads;
}
if (child.JavaVersion == null || child.JavaVersion.MajorVersion == 0)
{
child.JavaVersion = parent.JavaVersion;
}
if (parent.Arguments != null)
{
if (child.Arguments == null) child.Arguments = new Arguments();
child.Arguments.Game.InsertRange(0, parent.Arguments.Game);
child.Arguments.Jvm.InsertRange(0, parent.Arguments.Jvm);
}
}
public async Task DownloadFileAsync(string url, string path, Action<long, long>? progressCallback = null)
{
string? directory = Path.GetDirectoryName(path);
if (directory != null && !Directory.Exists(directory)) Directory.CreateDirectory(directory);
string tempPath = path + ".tmp";
try
{
using var response = await HttpClientManager.Instance.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
long totalBytes = response.Content.Headers.ContentLength ?? -1L;
using var source = await response.Content.ReadAsStreamAsync();
using (var destination = File.Create(tempPath))
{
byte[] buffer = new byte[8192];
long totalRead = 0;
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destination.WriteAsync(buffer, 0, bytesRead);
totalRead += bytesRead;
progressCallback?.Invoke(totalRead, totalBytes);
}
}
if (File.Exists(path)) File.Delete(path);
File.Move(tempPath, path);
}
finally
{
if (File.Exists(tempPath)) File.Delete(tempPath);
}
}
public async Task DownloadVersionJarAsync(VersionInfo info, string versionId)
{
if (info.Downloads?.Client != null && !string.IsNullOrEmpty(info.Downloads.Client.Url))
{
string path = Path.Combine(_baseDir, "versions", versionId, $"{versionId}.jar");
if (!File.Exists(path) || new FileInfo(path).Length == 0)
{
ConsoleService.Instance.Log($"Downloading client jar for {versionId}...");
await DownloadFileAsync(info.Downloads.Client.Url, path);
}
}
}
public async Task DownloadLibrariesAsync(VersionInfo info, Action<int, int>? progressCallback = null)
{
var currentOs = GetCurrentOsName();
var libraries = info.Libraries.Where(lib => lib.IsAllowed(currentOs)).ToList();
int completed = 0;
foreach (var lib in libraries)
{
string libPath = lib.GetPath();
string fullPath = Path.Combine(_baseDir, "libraries", libPath);
if (!File.Exists(fullPath) || new FileInfo(fullPath).Length == 0)
{
string? url = null;
if (lib.Downloads?.Artifact != null && !string.IsNullOrEmpty(lib.Downloads.Artifact.Url))
{
url = lib.Downloads.Artifact.Url;
}
else if (!string.IsNullOrEmpty(lib.Url))
{
url = lib.Url.TrimEnd('/') + "/" + libPath;
}
else
{
if (lib.Name.Contains("forge") || lib.Name.Contains("minecraftforge"))
{
url = "https://maven.minecraftforge.net/" + libPath;
}
else
{
url = "https://libraries.minecraft.net/" + libPath;
}
}
if (url != null)
{
try
{
await DownloadFileAsync(url, fullPath);
}
catch (Exception ex)
{
ConsoleService.Instance.Log($"[ERROR] Failed to download library {lib.Name}: {ex.Message}");
}
}
}
if (lib.Natives != null && lib.Natives.TryGetValue(currentOs, out string? legacyClassifier))
{
if (lib.Downloads?.Classifiers != null && lib.Downloads.Classifiers.TryGetValue(legacyClassifier, out var nativeArtifact))
{
string path = Path.Combine(_baseDir, "libraries", nativeArtifact.Path);
if (!File.Exists(path))
{
ConsoleService.Instance.Log($"Downloading legacy native: {lib.Name} ({legacyClassifier})");
await DownloadFileAsync(nativeArtifact.Url, path);
}
}
}
if (lib.Downloads?.Classifiers != null)
{
foreach (var classifier in lib.Downloads.Classifiers)
{
if (classifier.Key.Contains($"natives-{currentOs}") && PlatformManager.IsArchitectureMatch(classifier.Key, currentOs))
{
string path = Path.Combine(_baseDir, "libraries", classifier.Value.Path);
if (!File.Exists(path))
{
ConsoleService.Instance.Log($"Downloading modern native: {lib.Name} ({classifier.Key})");
await DownloadFileAsync(classifier.Value.Url, path);
}
}
}
}
completed++;
progressCallback?.Invoke(completed, libraries.Count);
}
}
public async Task ExtractNativesAsync(VersionInfo info, string versionId)
{
var currentOs = GetCurrentOsName();
string nativesDir = Path.Combine(_baseDir, "versions", versionId, "natives");
ConsoleService.Instance.Log($"Extraction OS: {currentOs}");
ConsoleService.Instance.Log($"Extracting natives to: {nativesDir}");
ConsoleService.Instance.Log($"Total libraries in version info: {info.Libraries.Count}");
if (!Directory.Exists(nativesDir)) Directory.CreateDirectory(nativesDir);
else
{
foreach (var file in Directory.GetFiles(nativesDir)) File.Delete(file);
}
foreach (var lib in info.Libraries)
{
if (!lib.IsAllowed(currentOs)) continue;
var candidates = new List<Artifact>();
if (lib.Natives != null && lib.Natives.TryGetValue(currentOs, out string? classifier))
{
if (lib.Downloads.Classifiers != null && lib.Downloads.Classifiers.TryGetValue(classifier, out var nativeArtifact))
{
candidates.Add(nativeArtifact);
}
}
if (lib.Downloads.Classifiers != null)
{
foreach (var entry in lib.Downloads.Classifiers)
{
if (entry.Key.Contains($"natives-{currentOs}") && PlatformManager.IsArchitectureMatch(entry.Key, currentOs))
{
candidates.Add(entry.Value);
}
}
}
if (lib.Name.Contains($"natives-{currentOs}") && PlatformManager.IsArchitectureMatch(lib.Name, currentOs))
{
if (lib.Downloads.Artifact != null)
{
candidates.Add(lib.Downloads.Artifact);
}
}
foreach (var artifact in candidates.Where(a => !string.IsNullOrEmpty(a.Url)).GroupBy(a => a.Path).Select(g => g.First()))
{
string jarPath = Path.Combine(_baseDir, "libraries", artifact.Path);
if (File.Exists(jarPath))
{
ConsoleService.Instance.Log($"Extracting from: {Path.GetFileName(jarPath)}");
try
{
using (var archive = ZipFile.OpenRead(jarPath))
{
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith(".so") || entry.FullName.EndsWith(".dll") || entry.FullName.EndsWith(".dylib"))
{
string destPath = Path.Combine(nativesDir, entry.Name);
entry.ExtractToFile(destPath, true);
ConsoleService.Instance.Log($" -> Extracted: {entry.Name}");
}
}
}
}
catch (Exception ex)
{
ConsoleService.Instance.Log($"[ERROR] Failed to extract {Path.GetFileName(jarPath)}: {ex.Message}");
}
}
else
{
ConsoleService.Instance.Log($"[WARNING] Native jar not found on disk: {artifact.Path}");
}
}
}
}
public async Task DownloadAssetsAsync(VersionInfo info, Action<int, int>? progressCallback = null)
{
string indexPath = Path.Combine(_baseDir, "assets", "indexes", $"{info.AssetIndex.Id}.json");
string indexJson;
if (!File.Exists(indexPath))
{
indexJson = await HttpClientManager.Instance.GetStringAsync(info.AssetIndex.Url);
string? indexDir = Path.GetDirectoryName(indexPath);
if (indexDir != null && !Directory.Exists(indexDir)) Directory.CreateDirectory(indexDir);
File.WriteAllText(indexPath, indexJson);
}
else
{
indexJson = File.ReadAllText(indexPath);
}
var manifest = JsonSerializer.Deserialize<AssetManifest>(indexJson);
if (manifest == null) return;
int completed = 0;
int total = manifest.Objects.Count;
foreach (var asset in manifest.Objects)
{
string hash = asset.Value.Hash;
string prefix = hash.Substring(0, 2);
string url = $"https://resources.download.minecraft.net/{prefix}/{hash}";
string path = Path.Combine(_baseDir, "assets", "objects", prefix, hash);
if (!File.Exists(path))
{
await DownloadFileAsync(url, path);
}
completed++;
if (completed % 10 == 0 || completed == total)
{
progressCallback?.Invoke(completed, total);
}
}
}
public async Task<string> EnsureAuthlibInjectorAsync()
{
string toolsDir = Path.Combine(_baseDir, "tools");
if (!Directory.Exists(toolsDir)) Directory.CreateDirectory(toolsDir);
string injectorPath = Path.Combine(toolsDir, "authlib-injector.jar");
if (!File.Exists(injectorPath))
{
ConsoleService.Instance.Log("Fetching latest authlib-injector version from GitHub...");
string url = "https://github.com/yushijinhun/authlib-injector/releases/download/v1.2.7/authlib-injector-1.2.7.jar"; // Fallback
try
{
string apiUrl = "https://api.github.com/repos/yushijinhun/authlib-injector/releases/latest";
string json = await HttpClientManager.Instance.GetStringAsync(apiUrl);
var release = JsonSerializer.Deserialize<GitHubRelease>(json);
var jarAsset = release?.Assets.FirstOrDefault(a => a.Name.EndsWith(".jar"));
if (jarAsset != null)
{
url = jarAsset.BrowserDownloadUrl;
ConsoleService.Instance.Log($"Found latest version: {release?.TagName}");
}
}
catch (Exception ex)
{
ConsoleService.Instance.Log($"[WARNING] Failed to fetch latest authlib-injector version: {ex.Message}. Using fallback.");
}
ConsoleService.Instance.Log("Downloading authlib-injector...");
await DownloadFileAsync(url, injectorPath);
}
return injectorPath;
}
private string GetCurrentOsName()
{
return PlatformManager.GetCurrentOsName();
}
}