-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHSInstallable.cs
More file actions
408 lines (368 loc) · 15.2 KB
/
Copy pathHSInstallable.cs
File metadata and controls
408 lines (368 loc) · 15.2 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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace HalfSwordModInstaller
{
public abstract class HSInstallable //: INotifyPropertyChanged
{
/*
// This is way overkill for what we need. Nope.
// let's just refresh the datagridview when needed
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
*/
// This is a name without spaces
public string Name { get; set; }
// Github repo URL
public string Url { get; set; }
// A downloaded ZIP file of the mod stored locally
protected string LocalZipPath;
public string ReleaseArtifactName;
// The logic around Downloaded/Installed/Enabled is to enforce detection of the actual state on disk
// The user may manually manipulate mods and we have to reflect that outside changes.
// Downloaded means "latest known version downloaded"
// TODO implement downloading of other versions
protected bool _isDownloaded = false;
public bool IsDownloaded
{
get
{
if (string.IsNullOrEmpty(LocalZipPath))
{
if (!string.IsNullOrEmpty(LatestVersion))
{
string downloadsFolder = Path.Combine(HSUtils.HSModInstallerDirPath, "downloads", Name, LatestVersion);
if (!IsExperimental)
{
string releaseZip = $"{Name}_{LatestVersion}.zip";
string releaseZipPath = Path.Combine(downloadsFolder, releaseZip);
if (File.Exists(releaseZipPath))
{
_isDownloaded = true;
LocalZipPath = releaseZipPath;
return _isDownloaded;
}
}
else // experimental
{
if (string.IsNullOrEmpty(ReleaseArtifactName))
{
// very rough guess
if (Directory.Exists(downloadsFolder) && Directory.GetFiles(downloadsFolder).Length > 0)
{
_isDownloaded = true;
LocalZipPath = Directory.GetFiles(downloadsFolder).First();
return _isDownloaded;
}
}
else
{
string releaseZip = ReleaseArtifactName;
string releaseZipPath = Path.Combine(downloadsFolder, releaseZip);
if (File.Exists(releaseZipPath))
{
_isDownloaded = true;
LocalZipPath = releaseZipPath;
return _isDownloaded;
}
}
}
}
}
else
{
if (File.Exists(LocalZipPath))
{
_isDownloaded = true;
return _isDownloaded;
}
}
_isDownloaded = false;
return _isDownloaded;
}
set
{
_isDownloaded |= value;
//OnPropertyChanged(nameof(IsDownloaded));
}
}
protected bool _isInstalled = false;
public virtual bool IsInstalled { get; set; }
protected bool _isBroken = false;
public virtual bool IsBroken { get; set; }
protected bool _isEnabled = false;
public virtual bool IsEnabled { get; set; }
protected HSUtils.HSGameType _compatibleGameType;
// TODO add validation here
public virtual HSUtils.HSGameType CompatibleGameType
{
get
{
return _compatibleGameType;
}
set
{
_compatibleGameType = value;
if (value == HSUtils.HSGameType.Playtest)
{
// technically this only applies to UE4SS, not mods?
//_isExperimental = true;
}
else if (value == HSUtils.HSGameType.Demo)
{
//_isExperimental = false;
}
else if (value == HSUtils.HSGameType.Demo04)
{
//_isExperimental = true;
}
}
}
protected bool _isExperimental = false;
public virtual bool IsExperimental {
get
{
return _isExperimental;
}
set {
var forceRefresh = false;
if (value != _isExperimental)
{
forceRefresh = true;
IsDownloaded = false;
IsInstalled = false;
IsEnabled = false;
}
_isExperimental |= value;
LatestVersion = GetLatestVersion();
}
}
// This is supposed to be a relative path from the game binary path
// For mods in old UE4SS this was Mods/<ModName>,
// for new UE4SS this is ue4ss/Mods/<ModName>.
// For UE4SS this is always empty as we unzip directly to game binary directory.
protected string RelativePath = string.Empty;
// Latest known version from the internet
public string LatestVersion { get; set; }
// For rare cases when we can infer installed version from disk
public string InstalledVersion { get; set; }
public List<HSInstallable> dependencyGraph;
public HSInstallable(string name, string url, HSUtils.HSGameType compatibleGameType, List<HSInstallable> dependencyGraph = null)
{
this.Name = name;
this.Url = url;
this.CompatibleGameType = compatibleGameType;
this.LatestVersion = GetLatestVersion();
this.dependencyGraph = dependencyGraph;
}
public void LogMe()
{
HSUtils.Log($"Installable object=\"{Name}\", Url=\"{Url}\", Version=\"{LatestVersion}\", " +
$"Experimental=\"{IsExperimental}\", " +
$"CompatibleGameType=\"{CompatibleGameType}\", " +
$"Downloaded={IsDownloaded}, Installed={IsInstalled}, " +
$"InstalledVersion={(string.IsNullOrEmpty(InstalledVersion) ? "null" : "\"" + InstalledVersion + "\"")}, " +
$"Enabled={IsEnabled}"
);
}
public static string GetRedirectUrl(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.AllowAutoRedirect = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
return response.Headers["Location"];
}
}
public string GetLatestVersion()
{
try
{
// Using the internal property _isExperimental as this gets called in the setter of IsExperimental, yes, this is bad
if (_isExperimental)
{
string sha = GetLatestCommit(Url);
if (sha != null)
{
string tag = sha.Substring(0, 7);
return tag;
}
return "error";
}
else
{
string latestUrl = Url + "/releases/latest";
string releaseUrl = GetRedirectUrl(latestUrl);
string tag = releaseUrl.Substring(releaseUrl.LastIndexOf("/") + 1);
return tag;
}
}
catch (Exception ex)
{
HSUtils.Log($"[ERROR] Checking version of mod \"{Name}\" from \"{Url}\" failed:");
HSUtils.Log(ex.Message);
HSUtils.Log(ex.StackTrace);
return null;
}
}
public virtual string GetLatestCommit(string repoUrl)
{
HttpClient client = new HttpClient();
// Extract the repo owner and name from the URL
var uri = new Uri(repoUrl);
var segments = uri.Segments;
if (segments.Length < 3)
{
HSUtils.Log($"[ERROR] Invalid GitHub repository URL \"{repoUrl}\"");
return null;
}
string repoOwner = segments[1].TrimEnd('/');
string repoName = segments[2].TrimEnd('/');
string apiUrl = $"https://api.github.com/repos/{repoOwner}/{repoName}/commits";
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("CSharpApp", "1.0"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync(apiUrl).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
var serializer = new JavaScriptSerializer();
var json = serializer.Deserialize<dynamic>(responseBody);
var latestCommit = json[0];
var commitSha = latestCommit["sha"];
// var commitMessage = latestCommit["commit"]["message"];
// var commitDate = latestCommit["commit"]["committer"]["date"];
return commitSha;
}
catch (Exception ex)
{
HSUtils.Log($"[ERROR] Checking latest commit version from \"{repoUrl}\" failed:");
HSUtils.Log(ex.Message);
HSUtils.Log(ex.StackTrace);
return null;
}
}
// Always retrieves latest version and downloads it
public virtual void Download()
{
string tag = GetLatestVersion();
if (tag != null)
{
Download(tag);
}
else
{
HSUtils.Log($"[ERROR] Aborting download of mod \"{Name}\", unknown version");
}
}
// Download specific release version by known tag
public void Download(string tag)
{
// Example:
// HalfSwordTrainerMod_v0.8.zip
string releaseZip = $"{Name}_{tag}.zip";
ReleaseArtifactName = releaseZip;
// Example:
// https://github.com/massclown/HalfSwordTrainerMod/releases/download/v0.8/HalfSwordTrainerMod_v0.8.zip
string downloadUrl = $"{Url}/releases/download/{tag}/{releaseZip}";
string downloadsFolder = Path.Combine(HSUtils.HSModInstallerDirPath, "downloads", Name, tag);
if (!Directory.Exists(downloadsFolder))
{
Directory.CreateDirectory(downloadsFolder);
}
string releaseZipPath = Path.Combine(downloadsFolder, releaseZip);
using (var client = new WebClient())
{
try
{
client.DownloadFile(downloadUrl, releaseZipPath);
LocalZipPath = releaseZipPath;
_isDownloaded = true;
LatestVersion = tag;
HSUtils.Log($"Downloaded mod \"{Name}\" from \"{downloadUrl}\" to \"{releaseZipPath}\"");
}
catch (Exception ex)
{
HSUtils.Log($"[ERROR] Downloading of mod \"{Name}\" from \"{downloadUrl}\" to \"{releaseZipPath}\" failed:");
HSUtils.Log(ex.Message);
HSUtils.Log(ex.StackTrace);
}
}
}
// Download latest main branch, set tag to latest truncated commit hash
public void DownloadLatestBranch()
{
// Example:
// main.zip
string releaseZip = $"main.zip";
ReleaseArtifactName = releaseZip;
string tag = GetLatestVersion();
// Example:
// https://github.com/UE4SS-RE/RE-UE4SS/archive/refs/heads/main.zip
string downloadUrl = $"{Url}/archive/refs/heads/{releaseZip}";
string downloadsFolder = Path.Combine(HSUtils.HSModInstallerDirPath, "downloads", Name, tag);
if (!Directory.Exists(downloadsFolder))
{
Directory.CreateDirectory(downloadsFolder);
}
string releaseZipPath = Path.Combine(downloadsFolder, releaseZip);
using (var client = new WebClient())
{
try
{
client.DownloadFile(downloadUrl, releaseZipPath);
LocalZipPath = releaseZipPath;
_isDownloaded = true;
LatestVersion = tag;
HSUtils.Log($"Downloaded mod \"{Name}\" from \"{downloadUrl}\" to \"{releaseZipPath}\"");
}
catch (Exception ex)
{
HSUtils.Log($"[ERROR] Downloading of mod \"{Name}\" from \"{downloadUrl}\" to \"{releaseZipPath}\" failed:");
HSUtils.Log(ex.Message);
HSUtils.Log(ex.StackTrace);
}
}
}
public abstract void Install();
public virtual void InstallAll()
{
Install(true);
}
public abstract void Install(bool forceInstallDependencies = false);
public void Install(string tag)
{
Download(tag);
Install();
}
public virtual void Uninstall()
{
throw new NotImplementedException();
}
public virtual void Update()
{
throw new NotImplementedException();
}
public virtual void SetEnabled(bool isEnabled = true)
{
throw new NotImplementedException();
}
public virtual bool GetEnabled()
{
throw new NotImplementedException();
}
}
}