-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulateRegistryCache.cs
More file actions
227 lines (196 loc) · 8.78 KB
/
PopulateRegistryCache.cs
File metadata and controls
227 lines (196 loc) · 8.78 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
using BeanModManager.Helpers;
using BeanModManager.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace BeanModManager
{
class PopulateRegistryCache
{
private static readonly HttpClient _httpClient = new HttpClient();
private static int _successCount = 0;
private static int _failCount = 0;
private static int _skippedCount = 0;
private static int _notModifiedCount = 0;
static PopulateRegistryCache()
{
_httpClient.DefaultRequestHeaders.Add("User-Agent", "BeanModManager-CachePopulator");
}
public static async Task Main(string[] args)
{
Console.WriteLine("=== Mod Cache Populator ===");
Console.WriteLine("This script will fetch release data for all mods and create/update mod-cache.json.\n");
var registryPath = "mod-registry.json";
var cachePath = "mod-cache.json";
if (args.Length > 0)
{
registryPath = args[0];
}
if (args.Length > 1)
{
cachePath = args[1];
}
if (!File.Exists(registryPath))
{
Console.WriteLine($"Error: {registryPath} not found!");
Console.WriteLine("Usage: BeanModManager.exe --populate-cache [path-to-mod-registry.json] [path-to-mod-cache.json]");
return;
}
Console.WriteLine($"Reading registry from: {Path.GetFullPath(registryPath)}");
var json = File.ReadAllText(registryPath);
var registry = JsonHelper.Deserialize<ModRegistry>(json);
if (registry == null || registry.mods == null || !registry.mods.Any())
{
Console.WriteLine("Error: No mods found in registry!");
return;
}
var cache = new ModCache
{
version = "1.0",
mods = new Dictionary<string, ModCacheEntry>()
};
if (File.Exists(cachePath))
{
Console.WriteLine($"Loading existing cache from: {Path.GetFullPath(cachePath)}");
try
{
var existingCacheJson = File.ReadAllText(cachePath);
var existingCache = JsonHelper.Deserialize<ModCache>(existingCacheJson);
if (existingCache != null && existingCache.mods != null)
{
cache = existingCache;
Console.WriteLine($"Found existing cache for {cache.mods.Count} mods\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Could not load existing cache: {ex.Message}");
Console.WriteLine("Starting fresh cache...\n");
}
}
Console.WriteLine($"Found {registry.mods.Count} mods in registry.\n");
Console.WriteLine("Starting to fetch release data...\n");
Console.WriteLine("(This may take a few minutes depending on rate limits)\n");
foreach (var mod in registry.mods)
{
if (string.IsNullOrEmpty(mod.githubOwner) || string.IsNullOrEmpty(mod.githubRepo))
{
Console.WriteLine($"⏭ Skipping {mod.id}: No GitHub info");
_skippedCount++;
continue;
}
await UpdateModCache(mod, cache);
await Task.Delay(1000);
}
Console.WriteLine($"\n=== Summary ===");
Console.WriteLine($"✓ Successfully updated: {_successCount}");
Console.WriteLine($"⚡ Not modified (304): {_notModifiedCount}");
Console.WriteLine($"✗ Failed: {_failCount}");
Console.WriteLine($"⏭ Skipped: {_skippedCount}");
Console.WriteLine($"Total processed: {_successCount + _notModifiedCount + _failCount + _skippedCount}");
var cacheJson = JsonHelper.Serialize(cache);
var backupPath = cachePath + ".backup";
if (File.Exists(cachePath))
{
File.Copy(cachePath, backupPath, true);
Console.WriteLine($"\n✓ Backup created: {backupPath}");
}
File.WriteAllText(cachePath, cacheJson);
Console.WriteLine($"✓ Cache saved to: {Path.GetFullPath(cachePath)}");
Console.WriteLine($"✓ Cache contains {cache.mods.Count} mod entries");
Console.WriteLine("\nDone! You can now commit the updated mod-cache.json");
}
static async Task UpdateModCache(ModRegistryEntry mod, ModCache cache)
{
try
{
var apiUrl = $"https://api.github.com/repos/{mod.githubOwner}/{mod.githubRepo}/releases/latest";
Console.Write($"Fetching: {mod.name} ({mod.githubOwner}/{mod.githubRepo})... ");
cache.mods.TryGetValue(mod.id, out var existingCacheEntry);
string existingETag = existingCacheEntry?.cachedETag;
using (var request = new HttpRequestMessage(HttpMethod.Get, apiUrl))
{
if (!string.IsNullOrEmpty(existingETag))
{
request.Headers.TryAddWithoutValidation("If-None-Match", existingETag);
}
using (var response = await _httpClient.SendAsync(request))
{
if (response.StatusCode == System.Net.HttpStatusCode.NotModified)
{
Console.WriteLine($"✓ Not modified (using existing cache)");
_notModifiedCount++;
return;
}
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
Console.WriteLine($"✗ Rate limited! Please wait and try again later.");
_failCount++;
return;
}
response.EnsureSuccessStatusCode();
var etag = GetETagFromResponse(response);
var content = await response.Content.ReadAsStringAsync();
var release = JsonHelper.Deserialize<GitHubRelease>(content);
if (release != null && !string.IsNullOrEmpty(release.tag_name))
{
cache.mods[mod.id] = new ModCacheEntry
{
cachedETag = etag,
cachedReleaseData = content,
cachedLatestVersion = release.tag_name,
lastChecked = DateTime.UtcNow.ToString("o")
};
var etagPreview = etag != null && etag.Length > 20 ? etag.Substring(0, 20) + "..." : etag;
Console.WriteLine($"✓ Updated to {release.tag_name} (ETag: {etagPreview})");
_successCount++;
}
else
{
Console.WriteLine($"✗ No release data found");
_failCount++;
}
}
}
}
catch (HttpRequestException ex) when (ex.Message.Contains("403") || ex.Message.Contains("Forbidden"))
{
Console.WriteLine($"✗ Rate limited! Please wait and try again later.");
_failCount++;
}
catch (Exception ex)
{
Console.WriteLine($"✗ Error: {ex.Message}");
_failCount++;
}
}
static string GetETagFromResponse(HttpResponseMessage response)
{
if (response?.Headers?.ETag != null)
{
var etagValue = response.Headers.ETag.ToString();
if (etagValue.StartsWith("\"") && etagValue.EndsWith("\""))
{
return etagValue.Substring(1, etagValue.Length - 2);
}
return etagValue;
}
return null;
}
class GitHubRelease
{
public string tag_name { get; set; }
public string published_at { get; set; }
public List<GitHubAsset> assets { get; set; }
public bool prerelease { get; set; }
}
class GitHubAsset
{
public string browser_download_url { get; set; }
public string name { get; set; }
}
}
}