Repository navigation
Expand file tree
/
Copy pathUpdateService.cs
More file actions
160 lines (135 loc) · 5.78 KB
/
Copy pathUpdateService.cs
File metadata and controls
160 lines (135 loc) · 5.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
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
namespace WindowsPrivacyTools
{
public class UpdateInfo
{
public string Version { get; set; } = "";
public string DownloadUrl { get; set; } = "";
public string Changelog { get; set; } = "";
public DateTime ReleaseDate { get; set; }
}
public static class UpdateService
{
private const string GitHubOwner = "JusteSEB";
private const string GitHubRepo = "WindowsPrivacyTools";
private static readonly string CurrentVersion = GetAppVersion();
private static string GetAppVersion()
{
var asm = Assembly.GetExecutingAssembly();
var attr = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (attr != null)
{
var ver = attr.InformationalVersion.Split('+')[0].Trim();
if (Version.TryParse(ver, out _)) return ver;
}
return asm.GetName().Version?.ToString() ?? "1.0.0";
}
private static readonly string AppDir = AppDomain.CurrentDomain.BaseDirectory;
public static string GetCurrentVersion() => CurrentVersion;
public static async Task<UpdateInfo?> CheckForUpdateAsync()
{
try
{
using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("WindowsPrivacyTools");
var releasesUrl = $"https://api.github.com/repos/{GitHubOwner}/{GitHubRepo}/releases/latest";
var response = await client.GetAsync(releasesUrl);
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var tagName = root.GetProperty("tag_name").GetString() ?? "";
var body = root.GetProperty("body").GetString() ?? "";
var published = root.GetProperty("published_at").GetString() ?? "";
string latestVersion = tagName.TrimStart('v', 'V');
if (!Version.TryParse(latestVersion, out var latest) || !Version.TryParse(CurrentVersion, out var current))
return null;
if (latest <= current) return null;
string downloadUrl = "";
if (root.TryGetProperty("assets", out var assets) && assets.GetArrayLength() > 0)
{
downloadUrl = assets[0].GetProperty("browser_download_url").GetString() ?? "";
}
if (string.IsNullOrEmpty(downloadUrl)) return null;
DateTime.TryParse(published, out var releaseDate);
return new UpdateInfo
{
Version = latestVersion,
DownloadUrl = downloadUrl,
Changelog = body,
ReleaseDate = releaseDate
};
}
catch
{
return null;
}
}
public static async Task<bool> DownloadAndInstallAsync(UpdateInfo update, Action<double>? progressCallback = null)
{
try
{
string tempDir = Path.Combine(Path.GetTempPath(), "WPT_Update");
if (Directory.Exists(tempDir))
Directory.Delete(tempDir, true);
Directory.CreateDirectory(tempDir);
string zipPath = Path.Combine(tempDir, "update.zip");
string extractDir = Path.Combine(tempDir, "extracted");
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.UserAgent.ParseAdd("WindowsPrivacyTools");
var response = await client.GetAsync(update.DownloadUrl);
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength ?? -1;
var stream = await response.Content.ReadAsStreamAsync();
using var fileStream = File.Create(zipPath);
var buffer = new byte[8192];
long totalRead = 0;
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fileStream.WriteAsync(buffer, 0, bytesRead);
totalRead += bytesRead;
if (totalBytes > 0)
progressCallback?.Invoke((double)totalRead / totalBytes * 100);
}
}
ZipFile.ExtractToDirectory(zipPath, extractDir);
string batchPath = Path.Combine(tempDir, "update.bat");
string currentExe = Process.GetCurrentProcess().MainModule?.FileName ?? "";
string exeName = Path.GetFileName(currentExe);
string batchContent = $@"
@echo off
timeout /t 2 /nobreak >nul
taskkill /F /IM ""{exeName}"" 2>nul
timeout /t 1 /nobreak >nul
xcopy /E /Y /I ""{extractDir}\*"" ""{AppDir}""
del ""{zipPath}""
rmdir /S /Q ""{tempDir}"" 2>nul
start """" ""{currentExe}""
";
File.WriteAllText(batchPath, batchContent);
Process.Start(new ProcessStartInfo
{
FileName = batchPath,
UseShellExecute = true,
Verb = "runas",
CreateNoWindow = true
});
return true;
}
catch
{
return false;
}
}
}
}