-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
546 lines (464 loc) · 20.5 KB
/
Copy pathApp.xaml.cs
File metadata and controls
546 lines (464 loc) · 20.5 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
using System.IO;
using System.Text.Json;
using System.Windows;
namespace WinFolderLock
{
public partial class App : Application
{
private const string WizardInstanceMutexName = @"Global\WinFolderLock.Wizard";
private static readonly string ProgramDataDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "WinFolderLock");
private static readonly string PasswordsFilePath = Path.Combine(ProgramDataDirectoryPath, "passwords.json");
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
WriteIndented = true
};
private Mutex? _wizardMutex;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
bool isWizardLaunch = e.Args.Length == 0;
if (isWizardLaunch)
{
_wizardMutex = new Mutex(initiallyOwned: true, WizardInstanceMutexName, out bool isFirstWizardInstance);
if (!isFirstWizardInstance)
{
_wizardMutex.Dispose();
_ = MessageBox.Show("A wizard is already running.", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Information);
Shutdown();
return;
}
MainWindow = new WizardWindow();
MainWindow.Show();
return;
}
if (e.Args.Length > 0)
{
if (e.Args[0] == "/install")
{
HandleInstall();
Shutdown();
return;
}
if (e.Args[0] == "/uninstall")
{
HandleUninstall();
Shutdown();
return;
}
}
bool isPermanentUnlock = e.Args.Length > 0 && e.Args[0] == "/permunlock";
int fileArgIndex = isPermanentUnlock ? 1 : 0;
if (e.Args.Length <= fileArgIndex)
{
Shutdown();
return;
}
string filePath = e.Args[fileArgIndex];
WindowMode mode = WindowMode.LockFolder;
if (FolderLocker.IsLockedFile(filePath))
{
mode = isPermanentUnlock ? WindowMode.PermanentlyUnlockFolder : WindowMode.UnlockFolder;
}
PasswordInputWindow passwordWindow = new(mode);
while (true)
{
bool isConfirmed = passwordWindow.ShowDialog() == true;
if (!isConfirmed)
{
Shutdown();
return;
}
string password = passwordWindow.Password;
if (string.IsNullOrWhiteSpace(password))
{
_ = MessageBox.Show("Password cannot be empty. Please try again.", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Warning);
passwordWindow = new(mode);
continue;
}
if (mode is WindowMode.UnlockFolder or WindowMode.PermanentlyUnlockFolder)
{
List<PasswordEntry> entries = LoadPasswordEntries();
FileInfo lockedFileInfo = new(filePath);
string folderName = Path.GetFileNameWithoutExtension(filePath);
PasswordEntry? entry = entries.FirstOrDefault(x =>
x.FolderName.Equals(folderName, StringComparison.OrdinalIgnoreCase));
if (entry == null || !entry.Password.Equals(password))
{
_ = MessageBox.Show("Incorrect password. Please try again.", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Error);
passwordWindow = new(mode);
continue;
}
}
try
{
if (mode == WindowMode.LockFolder)
{
SavePasswordEntry(filePath, password);
string normalizedDirectoryPath = Path.GetFullPath(filePath);
string trimmedDirectoryPath = normalizedDirectoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string folderNameForLock = Path.GetFileName(trimmedDirectoryPath);
if (string.IsNullOrWhiteSpace(folderNameForLock))
{
folderNameForLock = trimmedDirectoryPath;
}
string? parentDir = Path.GetDirectoryName(trimmedDirectoryPath);
if (string.IsNullOrWhiteSpace(parentDir))
{
parentDir = Path.GetPathRoot(trimmedDirectoryPath) ?? Environment.CurrentDirectory;
}
string lockedFilePath = Path.Combine(parentDir, folderNameForLock + ".wflck");
if (File.Exists(lockedFilePath))
{
_ = MessageBox.Show($"A locked file already exists: {lockedFilePath}", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
FolderLocker.LockFolder(normalizedDirectoryPath, lockedFilePath);
}
}
else if (mode == WindowMode.UnlockFolder)
{
string sessionFolderPath = FolderLocker.UnlockFolderToTemp(filePath);
try
{
_ = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = "/n,\"" + sessionFolderPath + "\"",
UseShellExecute = true
});
}
catch (Exception ex)
{
Helper.ExceptionHandler(ex);
_ = MessageBox.Show($"Could not open Explorer for the session folder: {ex.Message}", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Error);
}
const int pollMs = 500;
int consecutiveNoWindowMs = 0;
const int requiredNoWindowMs = 1500;
while (true)
{
try
{
if (!IsShellWindowShowingPath(sessionFolderPath))
{
consecutiveNoWindowMs += pollMs;
}
else
{
consecutiveNoWindowMs = 0;
}
if (consecutiveNoWindowMs >= requiredNoWindowMs)
{
int attempts = 0;
const int maxAttempts = 10;
const int attemptDelayMs = 300;
bool relocked = false;
while (attempts < maxAttempts)
{
try
{
FolderLocker.LockFolder(sessionFolderPath, filePath, overwriteExisting: true);
relocked = true;
break;
}
catch (IOException)
{
attempts++;
System.Threading.Thread.Sleep(attemptDelayMs);
}
catch (Exception ex)
{
Helper.ExceptionHandler(ex);
break;
}
}
if (relocked)
{
try { AdminUtils.NotifyShellOfChange(Path.GetDirectoryName(filePath) ?? string.Empty); } catch { }
}
break;
}
}
catch { }
System.Threading.Thread.Sleep(pollMs);
}
try
{
string sessionsRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WinFolderLock", "Sessions");
if (Directory.Exists(sessionsRoot))
{
foreach (string dir in Directory.EnumerateDirectories(sessionsRoot))
{
try { Directory.Delete(dir, recursive: true); } catch { }
}
}
}
catch { }
}
else if (mode == WindowMode.PermanentlyUnlockFolder)
{
string? destinationFolderPath = Path.GetDirectoryName(filePath);
if (string.IsNullOrWhiteSpace(destinationFolderPath))
{
destinationFolderPath = Environment.CurrentDirectory;
}
string folderName = Path.GetFileNameWithoutExtension(filePath);
destinationFolderPath = Path.Combine(destinationFolderPath, folderName);
if (Directory.Exists(destinationFolderPath))
{
_ = MessageBox.Show($"Destination folder already exists: {destinationFolderPath}", "WinFolderLock", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
FolderLocker.UnlockFolder(filePath, destinationFolderPath, deleteLockedFile: true);
AdminUtils.NotifyShellOfChange(destinationFolderPath);
try
{
RemovePasswordEntry(destinationFolderPath);
}
catch (Exception ex)
{
Helper.LogError(ex);
}
}
}
break; // Exit the retry loop on success
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException or System.Text.Json.JsonException or NotSupportedException)
{
Helper.ExceptionHandler(ex);
break;
}
catch (Exception ex)
{
Helper.ExceptionHandler(ex);
break;
}
}
Shutdown();
}
private static void HandleInstall()
{
try
{
AdminUtils.InstallApplicationFiles();
AdminUtils.AddLockFolderContextMenu();
AdminUtils.AddUnlockFolderContextMenu();
AdminUtils.AddPermanentUnlockFolderContextMenu();
}
catch (Exception ex)
{
Helper.ExceptionHandler(ex);
}
}
private static void HandleUninstall()
{
try
{
if (MessageBox.Show(
"Uninstalling WinFolderLock will permanently unlock all currently locked folders.\n\nDo you want to continue?",
"WinFolderLock - Uninstall Confirmation",
MessageBoxButton.YesNo,
MessageBoxImage.Question) != MessageBoxResult.Yes)
{
Environment.Exit(1);
return;
}
UnlockAllFolders();
AdminUtils.RemoveLockFolderContextMenu();
AdminUtils.RemoveUnlockFolderContextMenu();
AdminUtils.RemovePermanentUnlockFolderContextMenu();
AdminUtils.RemoveInstalledApplicationFiles();
Environment.Exit(0);
}
catch (Exception ex)
{
Helper.ExceptionHandler(ex);
// Error occurred - exit with code 2
Environment.Exit(2);
}
}
private static void UnlockAllFolders()
{
List<PasswordEntry> entries = LoadPasswordEntries();
if (entries.Count == 0)
{
return; // No folders to unlock
}
int successCount = 0;
int failureCount = 0;
foreach (PasswordEntry entry in entries)
{
try
{
string lockedFilePath = Path.Combine(
Path.GetDirectoryName(entry.DirectoryLocation) ?? Environment.CurrentDirectory,
entry.FolderName + ".wflck");
if (File.Exists(lockedFilePath))
{
string destinationFolderPath = entry.DirectoryLocation;
if (!Directory.Exists(destinationFolderPath))
{
FolderLocker.UnlockFolder(lockedFilePath, destinationFolderPath, deleteLockedFile: true);
successCount++;
}
}
}
catch (Exception ex)
{
Helper.LogError(ex);
failureCount++;
}
}
// Clear password entries
if (successCount > 0 || failureCount == 0)
{
try
{
File.Delete(PasswordsFilePath);
}
catch (Exception ex)
{
Helper.LogError(ex);
}
}
}
protected override void OnExit(ExitEventArgs e)
{
_wizardMutex?.ReleaseMutex();
_wizardMutex?.Dispose();
base.OnExit(e);
}
private static void SavePasswordEntry(string directoryLocation, string folderPassword)
{
if (string.IsNullOrWhiteSpace(directoryLocation))
{
throw new ArgumentException("Directory location is required.", nameof(directoryLocation));
}
if (string.IsNullOrWhiteSpace(folderPassword))
{
throw new ArgumentException("Password is required.", nameof(folderPassword));
}
string normalizedDirectoryPath = Path.GetFullPath(directoryLocation);
string trimmedDirectoryPath = normalizedDirectoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string folderName = Path.GetFileName(trimmedDirectoryPath);
if (string.IsNullOrWhiteSpace(folderName))
{
folderName = trimmedDirectoryPath;
}
_ = Directory.CreateDirectory(ProgramDataDirectoryPath);
List<PasswordEntry> entries = LoadPasswordEntries();
PasswordEntry entry = new()
{
FolderName = folderName,
DirectoryLocation = normalizedDirectoryPath,
Password = folderPassword
};
int existingIndex = entries.FindIndex(x => string.Equals(x.DirectoryLocation, normalizedDirectoryPath, StringComparison.OrdinalIgnoreCase));
if (existingIndex >= 0)
{
entries[existingIndex] = entry;
}
else
{
entries.Add(entry);
}
string json = JsonSerializer.Serialize(entries, JsonSerializerOptions);
File.WriteAllText(PasswordsFilePath, json);
}
private static List<PasswordEntry> LoadPasswordEntries()
{
if (!File.Exists(PasswordsFilePath))
{
return [];
}
string json = File.ReadAllText(PasswordsFilePath);
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
List<PasswordEntry> entries = JsonSerializer.Deserialize<List<PasswordEntry>>(json) ?? [];
return entries;
}
private static void RemovePasswordEntry(string directoryLocation)
{
if (string.IsNullOrWhiteSpace(directoryLocation))
{
return;
}
string normalizedDirectoryPath = Path.GetFullPath(directoryLocation).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
List<PasswordEntry> entries = LoadPasswordEntries();
int index = entries.FindIndex(x => string.Equals(x.DirectoryLocation, normalizedDirectoryPath, StringComparison.OrdinalIgnoreCase));
if (index >= 0)
{
entries.RemoveAt(index);
try
{
if (entries.Count == 0)
{
File.Delete(PasswordsFilePath);
}
else
{
string json = JsonSerializer.Serialize(entries, JsonSerializerOptions);
File.WriteAllText(PasswordsFilePath, json);
}
}
catch (Exception ex)
{
Helper.LogError(ex);
}
}
}
private static bool IsShellWindowShowingPath(string path)
{
try
{
Type? shellType = Type.GetTypeFromProgID("Shell.Application");
if (shellType == null)
{
return false;
}
object? shell = Activator.CreateInstance(shellType);
if (shell == null)
{
return false;
}
foreach (dynamic window in ((dynamic)shell).Windows())
{
try
{
string? locationUrl = window.LocationURL as string;
if (string.IsNullOrWhiteSpace(locationUrl))
{
continue;
}
string localPath;
try { localPath = new Uri(locationUrl).LocalPath; } catch { localPath = locationUrl; }
if (string.IsNullOrWhiteSpace(localPath))
{
continue;
}
string normalizedLocal = Path.GetFullPath(localPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string normalizedTarget = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (string.Equals(normalizedLocal, normalizedTarget, StringComparison.OrdinalIgnoreCase) ||
normalizedLocal.StartsWith(normalizedTarget + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
catch { }
}
}
catch { }
return false;
}
private sealed class PasswordEntry
{
public string FolderName { get; set; } = string.Empty;
public string DirectoryLocation { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
}
}