-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAutoUpdate.cs
More file actions
182 lines (166 loc) · 7.29 KB
/
Copy pathAutoUpdate.cs
File metadata and controls
182 lines (166 loc) · 7.29 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
using System.Diagnostics;
using System.IO.Compression;
using System.Text.Json;
using HarmonyLib;
using UnityEngine;
namespace PolyMod.Managers;
/// <summary>
/// Manages the automatic update process for PolyMod.
/// </summary>
internal static class AutoUpdate
{
/// <summary>
/// Checks for updates when the start screen is shown.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))]
private static void StartScreen_UI2_OnShow()
{
if (!Plugin.config.autoUpdate) return;
if (Environment.GetEnvironmentVariable("WINEPREFIX") != null)
{
Plugin.logger.LogError("Autoupdate is not supported on Wine!");
return;
}
HttpClient client = new();
client.DefaultRequestHeaders.Add("User-Agent", "PolyMod");
try
{
// Fetch release information from GitHub API
var json = JsonDocument.Parse(
client.GetAsync("https://api.github.com/repos/PolyModdingTeam/PolyMod/releases").UnwrapAsync()
.Content.ReadAsStringAsync().UnwrapAsync()
);
JsonElement? latest = null;
for (int i = 0; i < json.RootElement.GetArrayLength(); i++)
{
var release = json.RootElement[i];
if (release.GetProperty("prerelease").GetBoolean() && !Plugin.config.updatePrerelease) continue;
latest = release;
break;
}
string newVersion = latest?.GetProperty("tag_name").GetString()!.TrimStart('v')!;
if (newVersion.IsVersionOlderOrEqual(Plugin.VERSION)) return;
// Determine the correct BepInEx URL for the current OS
string os = Application.platform switch
{
RuntimePlatform.WindowsPlayer => "win",
RuntimePlatform.LinuxPlayer => "linux",
RuntimePlatform.OSXPlayer => "macos",
_ => "unknown",
};
if (os == "unknown")
{
Plugin.logger.LogError("Unsupported platform for autoupdate!");
return;
}
string bepinex_url = client
.GetAsync("https://polymod.dev/data/bepinex.txt").UnwrapAsync()
.Content.ReadAsStringAsync().UnwrapAsync()
.Replace("{os}", os);
// The actual update logic
void Update()
{
Time.timeScale = 0;
// Download new PolyMod DLL and BepInEx files
File.WriteAllBytes(
Path.Combine(Plugin.BASE_PATH, "PolyMod.new.dll"),
client.GetAsync(latest?.GetProperty("assets")[0].GetProperty("browser_download_url").GetString()!).UnwrapAsync()
.Content.ReadAsByteArrayAsync().UnwrapAsync()
);
using ZipArchive bepinex = new(client.GetAsync(bepinex_url).UnwrapAsync().Content.ReadAsStream());
bepinex.ExtractToDirectory(Path.Combine(Plugin.BASE_PATH, "New"), overwriteFiles: true);
// Create and run the appropriate update script for the OS
ProcessStartInfo info = new()
{
WorkingDirectory = Path.Combine(Plugin.BASE_PATH),
CreateNoWindow = true,
};
if (Application.platform == RuntimePlatform.WindowsPlayer)
{
string batchPath = Path.Combine(Plugin.BASE_PATH, "update.bat");
File.WriteAllText(batchPath, $@"
@echo off
echo Waiting for Polytopia.exe to exit...
:waitloop
tasklist | findstr /I ""Polytopia.exe"" >nul
if not errorlevel 1 (
timeout /T 1 >nul
goto waitloop
)
echo Updating...
robocopy ""New"" . /E /MOVE /NFL /NDL /NJH /NJS /NP >nul
rmdir /S /Q ""New""
del /F /Q ""BepInEx\plugins\PolyMod.dll""
move /Y ""PolyMod.new.dll"" ""BepInEx\plugins\PolyMod.dll""
echo Launching game...
start steam://rungameid/874390
timeout /T 3 /NOBREAK >nul
exit
");
info.FileName = "cmd.exe";
info.Arguments = $"/C start \"\" \"{batchPath}\"";
info.WorkingDirectory = Plugin.BASE_PATH;
info.CreateNoWindow = true;
info.UseShellExecute = false;
}
if (Application.platform == RuntimePlatform.LinuxPlayer || Application.platform == RuntimePlatform.OSXPlayer)
{
string bashPath = Path.Combine(Plugin.BASE_PATH, "update.sh");
File.WriteAllText(bashPath, $@"
#!/bin/bash
echo ""Waiting for Polytopia to exit...""
while pgrep -x ""Polytopia"" > /dev/null; do
sleep 1
done
echo ""Updating...""
mv New/* . && rm -rf New
rm -f BepInEx/plugins/PolyMod.dll
mv -f PolyMod.new.dll BepInEx/plugins/PolyMod.dll
echo ""Launching game...""
xdg-open steam://rungameid/874390 &
sleep 3
exit 0
");
System.Diagnostics.Process chmod = new System.Diagnostics.Process();
chmod.StartInfo.FileName = "chmod";
chmod.StartInfo.Arguments = $"+x \"{bashPath}\"";
chmod.StartInfo.UseShellExecute = false;
chmod.StartInfo.CreateNoWindow = true;
chmod.Start();
chmod.WaitForExit();
info.FileName = "/bin/bash";
info.Arguments = $"\"{bashPath}\"";
info.WorkingDirectory = Plugin.BASE_PATH;
info.CreateNoWindow = true;
info.UseShellExecute = false;
}
Process.Start(info);
Application.Quit();
}
// Show a popup to the user asking if they want to update
PopupManager.GetBasicPopupWithData(new(
Localization.Get("polymod.autoupdate"),
Localization.Get("polymod.autoupdate.description"),
new(new PopupBase.PopupButtonData[] {
new(
"polymod.autoupdate.update",
PopupBase.PopupButtonData.States.None,
(Il2CppSystem.Action)Update
)
}))
).Show();
}
catch (Exception e)
{
Plugin.logger.LogError($"Failed to check updates: {e.Message}");
}
}
/// <summary>
/// Initializes the AutoUpdate manager by patching the necessary methods.
/// </summary>
internal static void Init()
{
Harmony.CreateAndPatchAll(typeof(AutoUpdate));
}
}