Repository navigation
Expand file tree
/
Copy pathModUpdater.cs
More file actions
355 lines (303 loc) · 15.3 KB
/
Copy pathModUpdater.cs
File metadata and controls
355 lines (303 loc) · 15.3 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using BepInEx.Logging;
using Newtonsoft.Json;
using UnityEngine;
namespace ModUpdater
{
public class ModUpdater
{
private readonly string remoteManifestUrl;
private readonly string pluginsPath;
private readonly Action<UpdateResult> onComplete;
private readonly ModStatusTracker statusTracker;
private readonly ManualLogSource logger;
private volatile string currentStatus = "Idle";
private static readonly WebClient http = CreateNoCacheClient();
private static WebClient CreateNoCacheClient()
{
var client = new WebClient();
client.Headers[HttpRequestHeader.CacheControl] = "no-cache, no-store";
client.Headers[HttpRequestHeader.Pragma] = "no-cache";
client.Headers[HttpRequestHeader.UserAgent] = "ModUpdater/1.0";
client.CachePolicy = new System.Net.Cache.RequestCachePolicy(
System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
return client;
}
public ModUpdater(string remoteManifestUrl,
string pluginsPath,
Action<UpdateResult> onComplete,
ModStatusTracker statusTracker,
ManualLogSource logger)
{
this.remoteManifestUrl = remoteManifestUrl;
this.pluginsPath = pluginsPath;
this.onComplete = onComplete;
this.statusTracker = statusTracker;
this.logger = logger;
}
public void StartUpdate()
{
MainThreadDispatcher.Initialise();
Task.Run(RunUpdatePipeline);
}
public string GetCurrentStatus() => currentStatus;
public ModStatusTracker StatusTracker => statusTracker;
private async Task RunUpdatePipeline()
{
List<string> failedMods = new List<string>();
int updatedCount = 0;
try
{
logger.LogInfo("[Pipeline] Step 1: Update pipeline started.");
currentStatus = "Fetching mod list…";
logger.LogInfo($"[Pipeline] Step 2: Fetching remote manifest from {remoteManifestUrl}");
List<RemoteModEntry> remoteList = await FetchRemoteManifest();
logger.LogInfo("[Pipeline] Step 2: FetchRemoteManifest returned.");
if(remoteList == null)
{
currentStatus = "Remove list didn't deserialize correctly.";
Complete(UpdateResult.WithErrors(new List<string>() { " remote list was NULL"}, 0));
return;
}
if(remoteList.Count == 0)
{
logger.LogInfo("Remote manifest returned no mods.");
currentStatus = "No remote mods found.";
Complete(UpdateResult.AllCurrent());
return;
}
logger.LogInfo($"[Pipeline] Step 2: Remote manifest returned {remoteList.Count} mod(s).");
currentStatus = "Scanning installed plugins…";
logger.LogInfo("[Pipeline] Step 3: Scanning installed plugins…");
Dictionary<string, string> installedPlugins = ScanInstalledPlugins();
logger.LogInfo($"[Pipeline] Step 3: Found {installedPlugins.Count} installed BepInEx plugin(s).");
logger.LogInfo("[Pipeline] Step 4: Computing mods to update…");
List<RemoteModEntry> toUpdate = GetModsToUpdate(remoteList, installedPlugins);
logger.LogInfo($"[Pipeline] Step 4: {toUpdate.Count} mod(s) need updating.");
logger.LogInfo("[Pipeline] Step 5: Populating tracker…");
PopulateTracker(remoteList, toUpdate);
logger.LogInfo("[Pipeline] Step 5: Tracker populated.");
if (toUpdate.Count == 0)
{
logger.LogInfo("All mods are up to date — nothing to download.");
currentStatus = "All mods are up to date.";
Complete(UpdateResult.AllCurrent());
return;
}
logger.LogInfo("[Pipeline] Step 6: Starting downloads…");
for (int i = 0; i < toUpdate.Count; i++)
{
RemoteModEntry mod = toUpdate[i];
currentStatus = $"Downloading {mod.Name} ({i + 1}/{toUpdate.Count})…";
logger.LogInfo($"[Pipeline] Step 6: Downloading {mod.Name} ({i + 1}/{toUpdate.Count})…");
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Downloading);
int progress = i + 1;
int count = toUpdate.Count;
MainThreadDispatcher.Enqueue(() => TextOverlay.SetText($"Downloading mods ({progress}/{count})..."));
DownloadResult downloadResult = await DownloadAndExtract(mod);
if (downloadResult == DownloadResult.Success)
{
logger.LogInfo($"Successfully updated {mod.Name}.");
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Downloaded);
updatedCount++;
}
else if (downloadResult == DownloadResult.Unreachable)
{
logger.LogWarning($"Skipping {mod.Name}: URL was unreachable ({mod.URL}).");
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Skipped);
}
else
{
logger.LogWarning($"Failed to update {mod.Name}.");
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Failed);
failedMods.Add(mod.Name);
}
}
currentStatus = failedMods.Count == 0
? $"Done — {updatedCount} mod(s) updated."
: $"Done with {failedMods.Count} error(s).";
logger.LogInfo($"Update pipeline finished. Updated: {updatedCount}, Failed: {failedMods.Count}.");
}
catch (Exception ex)
{
logger.LogError($"[Pipeline] FATAL: {ex.GetType().Name}: {ex.Message}");
logger.LogError($"[Pipeline] Stack trace: {ex.StackTrace}");
if (ex.InnerException != null)
logger.LogError($"[Pipeline] Inner: {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
currentStatus = "Update failed (see log).";
failedMods.Add("PIPELINE_FATAL");
}
UpdateResult result = failedMods.Count == 0
? UpdateResult.AllGood(updatedCount)
: UpdateResult.WithErrors(failedMods, updatedCount);
Complete(result);
}
// ── Tracker population ──────────────────────────────────────────
private void PopulateTracker(
List<RemoteModEntry> remoteList,
List<RemoteModEntry> toUpdate)
{
var toUpdateUUIDs = new HashSet<string>();
foreach (var mod in toUpdate)
toUpdateUUIDs.Add(mod.UUID);
foreach (var mod in remoteList)
{
if (!toUpdateUUIDs.Contains(mod.UUID))
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Installed);
}
foreach (var mod in toUpdate)
statusTracker.SetMod(mod.Name, mod.ModNumber, ModStatus.Queued);
}
// ── Remote manifest ─────────────────────────────────────────────
private async Task<List<RemoteModEntry>> FetchRemoteManifest()
{
try
{
string bustUrl = remoteManifestUrl
+ (remoteManifestUrl.Contains("?") ? "&" : "?")
+ "_t=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
string json = await http.DownloadStringTaskAsync(bustUrl);
logger.LogInfo($"Fetched remote manifest:\n{json}");
return JsonConvert.DeserializeObject<List<RemoteModEntry>>(json);
}
catch (Exception ex)
{
Debug.LogError($"[ModUpdater] Failed to fetch remote manifest: {ex.Message}");
return null;
}
}
// ── Installed plugin scan ───────────────────────────────────────
private Dictionary<string, string> ScanInstalledPlugins()
{
var installed = new Dictionary<string, string>();
foreach (string dllPath in Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories))
{
try
{
var asm = Assembly.LoadFrom(dllPath);
var guidAttr = (GuidAttribute)Attribute.GetCustomAttribute(asm, typeof(GuidAttribute));
if (guidAttr == null)
continue;
string version = asm.GetName().Version.ToString();
var infoAttr = (AssemblyInformationalVersionAttribute)
Attribute.GetCustomAttribute(asm, typeof(AssemblyInformationalVersionAttribute));
if (infoAttr != null && !string.IsNullOrWhiteSpace(infoAttr.InformationalVersion))
version = infoAttr.InformationalVersion;
installed[guidAttr.Value] = version;
logger.LogInfo($"Found installed plugin: {guidAttr.Value} v{version} at {dllPath}");
}
catch
{
}
}
return installed;
}
// ── Version diff ────────────────────────────────────────────────
private List<RemoteModEntry> GetModsToUpdate(
List<RemoteModEntry> remote,
Dictionary<string, string> installedPlugins)
{
var result = new List<RemoteModEntry>();
foreach (var mod in remote)
{
if (installedPlugins.TryGetValue(mod.UUID, out string installedVersion))
{
if (SemVer.IsNewer(mod.ModNumber, installedVersion))
result.Add(mod);
}
else
{
logger.LogInfo($"{mod.Name}: not found in loaded plugins, queuing install.");
result.Add(mod);
}
}
return result;
}
// ── Download + extract ──────────────────────────────────────────
private async Task<DownloadResult> DownloadAndExtract(RemoteModEntry mod)
{
try
{
logger.LogInfo($"[DownloadAndExtract] Starting for {mod.Name} v{mod.ModNumber}");
logger.LogInfo($"[DownloadAndExtract] URL: {mod.URL}");
byte[] zipBytes = await http.DownloadDataTaskAsync(mod.URL);
logger.LogInfo($"[DownloadAndExtract] Downloaded {zipBytes.Length} bytes for {mod.Name}");
var entries = MiniZip.Extract(zipBytes);
logger.LogInfo($"[DownloadAndExtract] Zip contains {entries.Count} entries");
bool hasBepInExStructure = HasBepInExFolderStructure(entries);
string bepInExRoot = Directory.GetParent(pluginsPath).FullName;
string destDir;
if (hasBepInExStructure)
{
destDir = bepInExRoot;
logger.LogInfo($"[DownloadAndExtract] Detected BepInEx folder structure, extracting to: {destDir}");
}
else
{
destDir = Path.Combine(pluginsPath, SanitiseFolderName(mod.Name));
logger.LogInfo($"[DownloadAndExtract] Standard mod, extracting to: {destDir}");
if (Directory.Exists(destDir))
{
logger.LogInfo($"[DownloadAndExtract] Deleting existing directory: {destDir}");
Directory.Delete(destDir, true);
}
Directory.CreateDirectory(destDir);
}
foreach (var entry in entries)
{
string destPath = Path.Combine(destDir, entry.FileName);
string entryDir = Path.GetDirectoryName(destPath);
if (!Directory.Exists(entryDir))
Directory.CreateDirectory(entryDir);
if (File.Exists(destPath))
File.Delete(destPath);
logger.LogInfo($"[DownloadAndExtract] Extracting: {entry.FileName} -> {destPath}");
File.WriteAllBytes(destPath, entry.Data);
}
logger.LogInfo($"[DownloadAndExtract] Successfully installed {mod.Name} v{mod.ModNumber}");
return DownloadResult.Success;
}
catch (WebException ex)
{
logger.LogWarning($"[DownloadAndExtract] URL unreachable for {mod.Name}: {ex.Message}");
logger.LogWarning($"[DownloadAndExtract] ---- DID YOU REMEMBER TO MAKE THE REPO PUBILC?? ----");
return DownloadResult.Unreachable;
}
catch (Exception ex)
{
logger.LogError($"[DownloadAndExtract] Failed for {mod.Name}: {ex.GetType().Name}: {ex.Message}");
logger.LogError($"[DownloadAndExtract] Stack trace: {ex.StackTrace}");
if (ex.InnerException != null)
logger.LogError($"[DownloadAndExtract] Inner: {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
return DownloadResult.Failed;
}
}
// ── Helpers ─────────────────────────────────────────────────────
private void Complete(UpdateResult result)
{
MainThreadDispatcher.Enqueue(() => onComplete?.Invoke(result));
}
private static bool HasBepInExFolderStructure(List<MiniZip.ZipEntry> entries)
{
foreach (var entry in entries)
{
if (entry.FileName.StartsWith("plugins/") || entry.FileName.StartsWith("plugins\\") ||
entry.FileName.StartsWith("config/") || entry.FileName.StartsWith("config\\"))
return true;
}
return false;
}
private static string SanitiseFolderName(string name)
{
char[] invalid = Path.GetInvalidFileNameChars();
return new string(name.Select(c => invalid.Contains(c) ? '_' : c).ToArray());
}
}
}