-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinecraftVersionManager.cs
More file actions
334 lines (285 loc) · 13.5 KB
/
Copy pathMinecraftVersionManager.cs
File metadata and controls
334 lines (285 loc) · 13.5 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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace BMPLauncher.Core
{
public class MinecraftVersionManager
{
private readonly string _gameDirectory;
private readonly Action<string> _logAction;
private readonly HttpClient _httpClient;
private const int MAX_PARALLEL_DOWNLOADS = 8;
private const string VERSIONS_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
public MinecraftVersionManager(string gameDirectory, Action<string> logAction)
{
_gameDirectory = gameDirectory;
_logAction = logAction;
_httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
}
public async Task<MinecraftVersionManifest> GetVersionManifestAsync()
{
try
{
var json = await _httpClient.GetStringAsync(VERSIONS_URL);
return JsonConvert.DeserializeObject<MinecraftVersionManifest>(json);
}
catch (Exception ex)
{
_logAction($"❌ Ошибка получения манифеста версий: {ex.Message}");
throw;
}
}
public async Task DownloadVersionAsync(string versionId, Action<double> progressCallback, CancellationToken cancellationToken)
{
try
{
_logAction($"🚀 Начинаем скачивание версии {versionId}");
// Получаем информацию о версии
var versionManifest = await GetVersionManifestAsync();
var versionInfo = versionManifest.Versions.FirstOrDefault(v => v.Id == versionId);
if (versionInfo == null)
{
throw new Exception($"Версия {versionId} не найдена");
}
// Получаем детальную информацию о версии
var versionDetails = await GetVersionDetailsAsync(versionInfo.Url);
// Создаем структуру директорий
string versionDir = Path.Combine(_gameDirectory, "versions", versionId);
CreateVersionDirectoryStructure(versionDir);
// Параллельное скачивание
await DownloadVersionFilesParallelAsync(versionDetails, versionDir, progressCallback, cancellationToken);
_logAction($"✅ Версия {versionId} успешно скачана");
}
catch (OperationCanceledException)
{
_logAction("❌ Скачивание отменено");
throw;
}
catch (Exception ex)
{
_logAction($"❌ Ошибка скачивания версии {versionId}: {ex.Message}");
throw;
}
}
private async Task<VersionInfo> GetVersionDetailsAsync(string versionUrl)
{
try
{
var json = await _httpClient.GetStringAsync(versionUrl);
return JsonConvert.DeserializeObject<VersionInfo>(json);
}
catch (Exception ex)
{
_logAction($"❌ Ошибка получения деталей версии: {ex.Message}");
throw;
}
}
private void CreateVersionDirectoryStructure(string versionDir)
{
Directory.CreateDirectory(versionDir);
Directory.CreateDirectory(Path.Combine(versionDir, "libraries"));
Directory.CreateDirectory(Path.Combine(versionDir, "assets"));
Directory.CreateDirectory(Path.Combine(versionDir, "assets", "objects"));
Directory.CreateDirectory(Path.Combine(versionDir, "assets", "indexes"));
Directory.CreateDirectory(Path.Combine(versionDir, "natives"));
_logAction($"📁 Создана структура директорий: {versionDir}");
}
private async Task DownloadVersionFilesParallelAsync(VersionInfo versionInfo, string versionDir,
Action<double> progressCallback, CancellationToken cancellationToken)
{
var downloadItems = new List<VersionDownloadItem>();
// 1. Клиент JAR
if (versionInfo.Downloads?.Client != null)
{
downloadItems.Add(new VersionDownloadItem
{
Url = versionInfo.Downloads.Client.Url,
Path = Path.Combine(versionDir, $"{Path.GetFileName(versionDir)}.jar"),
Size = versionInfo.Downloads.Client.Size,
Type = "Client"
});
}
// 2. Библиотеки
if (versionInfo.Libraries != null)
{
string librariesDir = Path.Combine(versionDir, "libraries");
foreach (var library in versionInfo.Libraries)
{
if (library.Downloads?.Artifact != null)
{
string libPath = Path.Combine(librariesDir, library.Downloads.Artifact.Path);
Directory.CreateDirectory(Path.GetDirectoryName(libPath));
downloadItems.Add(new VersionDownloadItem
{
Url = library.Downloads.Artifact.Url,
Path = libPath,
Size = library.Downloads.Artifact.Size,
Type = "Library"
});
}
}
}
// 3. Ассеты (если есть)
if (versionInfo.AssetIndex != null)
{
await DownloadAssetsAsync(versionInfo.AssetIndex, versionDir, progressCallback, cancellationToken);
}
_logAction($"📥 Всего файлов для загрузки: {downloadItems.Count}");
// Параллельное скачивание
await DownloadFilesParallelAsync(downloadItems, progressCallback, cancellationToken);
}
private async Task DownloadAssetsAsync(AssetIndex assetIndex, string versionDir,
Action<double> progressCallback, CancellationToken cancellationToken)
{
try
{
_logAction($"📥 Загружаем ассеты: {assetIndex.Id}");
// Загружаем индекс ассетов
var assetsJson = await _httpClient.GetStringAsync(assetIndex.Url);
var assetsIndex = JsonConvert.DeserializeObject<AssetsIndex>(assetsJson);
string assetsDir = Path.Combine(versionDir, "assets");
string objectsDir = Path.Combine(assetsDir, "objects");
string indexesDir = Path.Combine(assetsDir, "indexes");
// Сохраняем индекс
string indexPath = Path.Combine(indexesDir, $"{assetIndex.Id}.json");
File.WriteAllText(indexPath, assetsJson);
var assetDownloads = new List<VersionDownloadItem>();
int totalAssets = assetsIndex.Objects.Count;
int processed = 0;
// Подготавливаем загрузку ассетов
foreach (var asset in assetsIndex.Objects)
{
string hash = asset.Value.Hash;
string hashPrefix = hash.Substring(0, 2);
string assetPath = Path.Combine(objectsDir, hashPrefix, hash);
Directory.CreateDirectory(Path.GetDirectoryName(assetPath));
// Проверяем, не скачан ли уже ассет
if (!File.Exists(assetPath))
{
assetDownloads.Add(new VersionDownloadItem
{
Url = $"https://resources.download.minecraft.net/{hashPrefix}/{hash}",
Path = assetPath,
Size = asset.Value.Size,
Type = "Asset",
Hash = hash
});
}
processed++;
progressCallback?.Invoke((double)processed / totalAssets * 50); // Первые 50% - подготовка
}
_logAction($"📥 Ассетов для загрузки: {assetDownloads.Count}");
// Скачиваем ассеты
await DownloadFilesParallelAsync(assetDownloads,
progress => progressCallback?.Invoke(50 + progress * 0.5), // Вторые 50%
cancellationToken);
}
catch (Exception ex)
{
_logAction($"⚠️ Ошибка загрузки ассетов: {ex.Message}");
}
}
private async Task DownloadFilesParallelAsync(List<VersionDownloadItem> downloads,
Action<double> progressCallback, CancellationToken cancellationToken)
{
if (downloads.Count == 0) return;
var semaphore = new SemaphoreSlim(MAX_PARALLEL_DOWNLOADS);
var tasks = new List<Task>();
int completed = 0;
int total = downloads.Count;
object lockObject = new object();
foreach (var download in downloads)
{
await semaphore.WaitAsync(cancellationToken);
tasks.Add(Task.Run(async () =>
{
try
{
await DownloadFileWithRetryAsync(download, cancellationToken);
lock (lockObject)
{
completed++;
double progress = (double)completed / total * 100;
progressCallback?.Invoke(progress);
if (completed % 10 == 0 || completed == total)
{
_logAction($"📥 Прогресс: {completed}/{total} ({progress:F1}%)");
}
}
}
catch (Exception ex) when (!(ex is OperationCanceledException))
{
_logAction($"❌ Ошибка загрузки {Path.GetFileName(download.Path)}: {ex.Message}");
}
finally
{
semaphore.Release();
}
}, cancellationToken));
}
await Task.WhenAll(tasks);
}
private async Task DownloadFileWithRetryAsync(VersionDownloadItem download, CancellationToken cancellationToken, int maxRetries = 3)
{
for (int retry = 0; retry < maxRetries; retry++)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
using (var response = await _httpClient.GetAsync(download.Url, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
response.EnsureSuccessStatusCode();
using (var fileStream = new FileStream(download.Path, FileMode.Create, FileAccess.Write, FileShare.None, 81920))
using (var stream = await response.Content.ReadAsStreamAsync())
{
await stream.CopyToAsync(fileStream, 81920, cancellationToken);
}
}
return; // Успешно
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex) when (retry < maxRetries - 1)
{
_logAction($"Повторная попытка {retry + 1}/{maxRetries} для {Path.GetFileName(download.Path)}");
await Task.Delay(1000 * (retry + 1), cancellationToken);
if (File.Exists(download.Path))
File.Delete(download.Path);
}
}
throw new Exception($"Не удалось скачать файл после {maxRetries} попыток: {Path.GetFileName(download.Path)}");
}
public bool IsVersionDownloaded(string versionId)
{
string versionDir = Path.Combine(_gameDirectory, "versions", versionId);
string jarPath = Path.Combine(versionDir, $"{versionId}.jar");
return File.Exists(jarPath) && new FileInfo(jarPath).Length > 1024 * 1024;
}
public List<string> GetDownloadedVersions()
{
var versions = new List<string>();
string versionsDir = Path.Combine(_gameDirectory, "versions");
if (Directory.Exists(versionsDir))
{
foreach (var dir in Directory.GetDirectories(versionsDir))
{
string versionId = Path.GetFileName(dir);
if (IsVersionDownloaded(versionId))
{
versions.Add(versionId);
}
}
}
return versions;
}
}
}