-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBrowserCleanupService.cs
More file actions
256 lines (217 loc) · 7.72 KB
/
BrowserCleanupService.cs
File metadata and controls
256 lines (217 loc) · 7.72 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Threading;
using Microsoft.Web.WebView2.Core;
namespace TidyWindow.App.Services;
public enum BrowserCleanupResultStatus
{
Success,
Skipped,
Failed
}
public sealed record BrowserCleanupResult(BrowserCleanupResultStatus Status, string Message, Exception? Exception = null)
{
public bool IsSuccess => Status == BrowserCleanupResultStatus.Success;
}
public enum BrowserKind
{
Edge,
Chrome
}
public readonly record struct BrowserProfile(BrowserKind Kind, string ProfileDirectory);
public interface IBrowserCleanupService : IDisposable
{
Task<BrowserCleanupResult> ClearHistoryAsync(BrowserProfile profile, IReadOnlyList<string> targetPaths, CancellationToken cancellationToken);
}
public sealed class BrowserCleanupService : IBrowserCleanupService
{
private readonly Dispatcher _dispatcher;
private readonly object _hostLock = new();
private HwndSource? _hostSource;
private bool _disposed;
public BrowserCleanupService()
{
_dispatcher = System.Windows.Application.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher;
}
public Task<BrowserCleanupResult> ClearHistoryAsync(BrowserProfile profile, IReadOnlyList<string> targetPaths, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(profile.ProfileDirectory))
{
return Task.FromResult(new BrowserCleanupResult(BrowserCleanupResultStatus.Skipped, "Browser profile directory is empty."));
}
if (!Directory.Exists(profile.ProfileDirectory))
{
return Task.FromResult(new BrowserCleanupResult(BrowserCleanupResultStatus.Skipped, $"Browser profile directory not found: {profile.ProfileDirectory}"));
}
return InvokeOnDispatcherAsync(() => profile.Kind switch
{
BrowserKind.Edge => ClearEdgeHistoryInternalAsync(profile.ProfileDirectory, cancellationToken),
BrowserKind.Chrome => Task.FromResult(ClearChromiumHistoryFiles(profile.ProfileDirectory, targetPaths)),
_ => Task.FromResult(new BrowserCleanupResult(BrowserCleanupResultStatus.Skipped, "Unsupported browser profile."))
});
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_dispatcher.InvokeAsync(() =>
{
lock (_hostLock)
{
_hostSource?.Dispose();
_hostSource = null;
}
});
}
private async Task<BrowserCleanupResult> ClearEdgeHistoryInternalAsync(string profileDirectory, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
CoreWebView2Environment? environment = null;
CoreWebView2Controller? controller = null;
try
{
environment = await CoreWebView2Environment.CreateAsync(userDataFolder: profileDirectory).ConfigureAwait(true);
controller = await environment.CreateCoreWebView2ControllerAsync(EnsureHostWindowHandle()).ConfigureAwait(true);
controller.IsVisible = false;
cancellationToken.ThrowIfCancellationRequested();
var profile = controller.CoreWebView2.Profile;
await profile.ClearBrowsingDataAsync(CoreWebView2BrowsingDataKinds.BrowsingHistory | CoreWebView2BrowsingDataKinds.DownloadHistory).ConfigureAwait(true);
var profileLabel = string.IsNullOrWhiteSpace(profile.ProfileName)
? Path.GetFileName(profileDirectory)
: profile.ProfileName;
return new BrowserCleanupResult(BrowserCleanupResultStatus.Success, $"Cleared Microsoft Edge browsing history for profile '{profileLabel}'.");
}
catch (Exception ex)
{
return new BrowserCleanupResult(BrowserCleanupResultStatus.Failed, ex.Message, ex);
}
finally
{
controller?.Close();
}
}
private Task<BrowserCleanupResult> InvokeOnDispatcherAsync(Func<Task<BrowserCleanupResult>> work)
{
if (_dispatcher.CheckAccess())
{
return work();
}
var tcs = new TaskCompletionSource<BrowserCleanupResult>(TaskCreationOptions.RunContinuationsAsynchronously);
_dispatcher.BeginInvoke(async () =>
{
try
{
var result = await work().ConfigureAwait(true);
tcs.SetResult(result);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return tcs.Task;
}
private IntPtr EnsureHostWindowHandle()
{
lock (_hostLock)
{
if (_hostSource is { IsDisposed: false })
{
return _hostSource.Handle;
}
var parameters = new HwndSourceParameters("BrowserCleanupHost")
{
Width = 1,
Height = 1,
PositionX = -10000,
PositionY = -10000,
WindowStyle = unchecked((int)(WindowStyles.WS_DISABLED | WindowStyles.WS_POPUP)),
UsesPerPixelOpacity = false
};
_hostSource = new HwndSource(parameters);
return _hostSource.Handle;
}
}
private static BrowserCleanupResult ClearChromiumHistoryFiles(string profileDirectory, IReadOnlyList<string> targetPaths)
{
if (targetPaths is null || targetPaths.Count == 0)
{
return new BrowserCleanupResult(BrowserCleanupResultStatus.Skipped, "No history entries selected for this profile.");
}
var successes = 0;
var failures = new List<string>();
foreach (var path in targetPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (string.IsNullOrWhiteSpace(path))
{
continue;
}
if (!path.StartsWith(profileDirectory, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (!File.Exists(path))
{
continue;
}
if (TryDeleteFileWithRetry(path))
{
successes++;
}
else
{
failures.Add(path);
}
}
if (successes == 0 && failures.Count == 0)
{
return new BrowserCleanupResult(BrowserCleanupResultStatus.Skipped, "History files already removed.");
}
if (failures.Count > 0)
{
var message = $"Failed to clear some history files ({failures.Count} item(s)). Close the browser and try again.";
return new BrowserCleanupResult(BrowserCleanupResultStatus.Failed, message);
}
return new BrowserCleanupResult(BrowserCleanupResultStatus.Success, "Cleared browser history files.");
}
private static bool TryDeleteFileWithRetry(string path)
{
const int maxAttempts = 2;
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
try
{
File.SetAttributes(path, FileAttributes.Normal);
}
catch
{
}
try
{
File.Delete(path);
return true;
}
catch
{
if (attempt == maxAttempts - 1)
{
return false;
}
}
}
return false;
}
private static class WindowStyles
{
public const uint WS_DISABLED = 0x08000000;
public const uint WS_POPUP = 0x80000000;
}
}