Repository navigation
Expand file tree
/
Copy pathProfileManager.cs
More file actions
640 lines (518 loc) · 24.1 KB
/
Copy pathProfileManager.cs
File metadata and controls
640 lines (518 loc) · 24.1 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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Xml.Serialization;
using NETworkManager.Settings;
using NETworkManager.Utilities;
namespace NETworkManager.Profiles
{
public static class ProfileManager
{
#region Variables
/// <summary>
/// Name of the profiles directory in the %appdata%\NETworkManager or in the portable location.
/// </summary>
private static string ProfilesFolderName => "Profiles";
/// <summary>
/// Default profile name.
/// </summary>
private static string ProfilesDefaultFileName => "Default";
/// <summary>
/// Profile file extension.
/// </summary>
public static string ProfileFileExtension => ".xml";
/// <summary>
/// Profile file extension for encrypted files.
/// </summary>
public static string ProfileFileExtensionEncrypted => ".encrypted";
public static string TagIdentifier => "tag=";
public static ObservableCollection<ProfileFileInfo> ProfileFiles { get; set; } = new ObservableCollection<ProfileFileInfo>();
private static ProfileFileInfo _profileFileInfo;
public static ProfileFileInfo LoadedProfileFile
{
get => _profileFileInfo;
set
{
if (value == _profileFileInfo)
return;
_profileFileInfo = value;
}
}
public static ObservableCollection<ProfileInfo> Profiles { get; set; } = new ObservableCollection<ProfileInfo>();
public static bool ProfilesChanged { get; set; }
#endregion
#region Events
/// <summary>
/// Event is fired if a loaded profile file is changed.
/// </summary>
public static event EventHandler<ProfileFileInfoArgs> OnLoadedProfileFileChangedEvent;
private static void LoadedProfileFileChanged(ProfileFileInfo profileFileInfo)
{
OnLoadedProfileFileChangedEvent?.Invoke(null, new ProfileFileInfoArgs(profileFileInfo));
}
#endregion
static ProfileManager()
{
// Load files
LoadProfileFiles();
Profiles.CollectionChanged += Profiles_CollectionChanged;
}
#region Profiles locations (default, custom, portable)
public static string GetDefaultProfilesLocation()
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), AssemblyManager.Current.Name, ProfilesFolderName);
}
public static string GetCustomProfilesLocation()
{
return SettingsManager.Current.Profiles_CustomProfilesLocation;
}
public static string GetPortableProfilesLocation()
{
return Path.Combine(AssemblyManager.Current.Location ?? throw new InvalidOperationException(), ProfilesFolderName);
}
public static string GetProfilesLocation()
{
return ConfigurationManager.Current.IsPortable ? GetPortableProfilesLocation() : GetProfilesLocationNotPortable();
}
public static string GetProfilesLocationNotPortable()
{
var location = GetCustomProfilesLocation();
if (!string.IsNullOrEmpty(location) && Directory.Exists(location))
return location;
return GetDefaultProfilesLocation();
}
#endregion
#region FileName, FilePath
public static string GetProfilesDefaultFileName()
{
return $"{ProfilesDefaultFileName}{ProfileFileExtension}";
}
public static string GetProfilesDefaultFilePath()
{
var path = Path.Combine(GetProfilesLocation(), GetProfilesDefaultFileName());
return path;
}
#endregion
#region Get profile files, load profile files, refresh profile files
/// <summary>
/// Get all files in the folder with the extension <see cref="ProfileFileExtension" /> or <see cref="ProfileFileExtensionEncrypted"/>.
/// </summary>
/// <param name="location">Path of the profile folder.</param>
/// <returns>List of profile files.</returns>
private static IEnumerable<string> GetProfileFiles(string location)
{
return Directory.GetFiles(location).Where(x => (Path.GetExtension(x) == ProfileFileExtension || Path.GetExtension(x) == ProfileFileExtensionEncrypted));
}
/// <summary>
/// Method to get the list of profile files from file system and detect if the file is encrypted.
/// </summary>
private static void LoadProfileFiles()
{
var location = GetProfilesLocation();
// Folder exists
if (Directory.Exists(location))
{
foreach (var file in GetProfileFiles(location))
{
// Gets the filename, path and if the file is encrypted.
ProfileFiles.Add(new ProfileFileInfo(Path.GetFileNameWithoutExtension(file), file, Path.GetFileName(file).EndsWith(ProfileFileExtensionEncrypted)));
}
}
// Create default profile
if (ProfileFiles.Count == 0)
ProfileFiles.Add(new ProfileFileInfo(ProfilesDefaultFileName, GetProfilesDefaultFilePath()));
}
#endregion
#region Create empty profile file, rename profile file, delete profile file
/// <summary>
/// Method to add a profile file.
/// </summary>
/// <param name="profileName"></param>
public static void CreateEmptyProfileFile(string profileName)
{
ProfileFileInfo profileFileInfo = new ProfileFileInfo(profileName, Path.Combine(GetDefaultProfilesLocation(), $"{profileName}{ProfileFileExtension}"));
CheckAndCreateDirectory();
SerializeToFile(profileFileInfo.Path, new List<ProfileInfo>());
ProfileFiles.Add(profileFileInfo);
}
/// <summary>
/// Method to rename a profile file.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo"/> to rename.</param>
/// <param name="newProfileName">New <see cref="ProfileFileInfo.Name"/> of the profile file.</param>
public static void RenameProfileFile(ProfileFileInfo profileFileInfo, string newProfileName)
{
bool switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
ProfileFileInfo newProfileFileInfo = new ProfileFileInfo(newProfileName, Path.Combine(GetProfilesLocation(), newProfileName, Path.GetExtension(profileFileInfo.Path)), profileFileInfo.IsEncrypted)
{
Password = profileFileInfo.Password,
IsPasswordValid = profileFileInfo.IsPasswordValid
};
File.Copy(profileFileInfo.Path, newProfileFileInfo.Path);
ProfileFiles.Add(newProfileFileInfo);
if (switchProfile)
{
SwitchProfile(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile);
}
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
/// <summary>
/// Method to delete a profile file.
/// </summary>
/// <param name="profileFileInfo"></param>
public static void DeleteProfileFile(ProfileFileInfo profileFileInfo)
{
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
SwitchProfile(ProfileFiles.FirstOrDefault(x => !x.Equals(profileFileInfo)));
LoadedProfileFileChanged(LoadedProfileFile);
}
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
#endregion
#region Enable encryption, disable encryption, change master password
/// <summary>
/// Method to enable encryption for a profile file.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo"/> which should be encrypted.</param>
/// <param name="password">Password to encrypt the profile file.</param>
public static void EnableEncryption(ProfileFileInfo profileFileInfo, SecureString password)
{
// Check if the profile is currently in use
bool switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create a new profile info with the encryption infos
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name, Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtensionEncrypted), true)
{
Password = password,
IsPasswordValid = true
};
// Load the profiles from the profile file
var profiles = DeserializeFromFile(profileFileInfo.Path);
// Save the encrypted file
byte[] decryptedBytes = SerializeToByteArray(profiles);
byte[] encryptedBytes = CryptoHelper.Encrypt(decryptedBytes, SecureStringHelper.ConvertToString(newProfileFileInfo.Password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(newProfileFileInfo.Path, encryptedBytes);
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
SwitchProfile(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile);
}
// Remove the old profile file
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
/// <summary>
/// Method to change the master password of an encrypted profile file.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo"/> which should be changed.</param>
/// <param name="password">Password to decrypt the profile file.</param>
/// <param name="newPassword">Password to encrypt the profile file.</param>
public static void ChangeMasterPassword(ProfileFileInfo profileFileInfo, SecureString password, SecureString newPassword)
{
// Check if the profile is currently in use
bool switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create a new profile info with the encryption infos
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name, Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtensionEncrypted), true)
{
Password = newPassword,
IsPasswordValid = true
};
// Load and decrypt the profiles from the profile file
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes, SecureStringHelper.ConvertToString(password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
var profiles = DeserializeFromByteArray(decryptedBytes);
// Save the encrypted file
decryptedBytes = SerializeToByteArray(profiles);
encryptedBytes = CryptoHelper.Encrypt(decryptedBytes, SecureStringHelper.ConvertToString(newProfileFileInfo.Password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(newProfileFileInfo.Path, encryptedBytes);
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
SwitchProfile(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile);
}
// Remove the old profile file
ProfileFiles.Remove(profileFileInfo);
}
/// <summary>
/// Method to disable encryption for a profile file.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo"/> which should be decrypted.</param>
/// <param name="password">Password to decrypt the profile file.</param>
public static void DisableEncryption(ProfileFileInfo profileFileInfo, SecureString password)
{
// Check if the profile is currently in use
bool switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create a new profile info
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name, Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtension));
// Load and decrypt the profiles from the profile file
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes, SecureStringHelper.ConvertToString(password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
var profiles = DeserializeFromByteArray(decryptedBytes);
// Save the decrypted profiles to the profile file
SerializeToFile(newProfileFileInfo.Path, profiles);
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
SwitchProfile(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile);
}
// Remove the old profile file
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
#endregion
#region Load, save and switch profile
/// <summary>
/// Method to load profiles based on the infos provided in the <see cref="ProfileFileInfo"/>.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo"/> to be loaded.</param>
private static void Load(ProfileFileInfo profileFileInfo)
{
bool loadedProfileUpdated = false;
if (File.Exists(profileFileInfo.Path))
{
if (profileFileInfo.IsEncrypted)
{
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes, SecureStringHelper.ConvertToString(profileFileInfo.Password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
DeserializeFromByteArray(decryptedBytes).ForEach(AddProfile);
// Password is valid
ProfileFiles.FirstOrDefault(x => x.Equals(profileFileInfo)).IsPasswordValid = true;
profileFileInfo.IsPasswordValid = true;
loadedProfileUpdated = true;
}
else
{
DeserializeFromFile(profileFileInfo.Path).ForEach(AddProfile);
}
}
else
{
// Don't throw an error if it's the default file.
if (profileFileInfo.Path != GetProfilesDefaultFilePath())
throw new FileNotFoundException($"{profileFileInfo.Path} could not be found!");
}
ProfilesChanged = false;
LoadedProfileFile = profileFileInfo;
if (loadedProfileUpdated)
LoadedProfileFileChanged(LoadedProfileFile);
}
/// <summary>
/// Method to save the currently loaded profiles based on the infos provided in the <see cref="ProfileFileInfo"/>.
/// </summary>
public static void Save()
{
if (LoadedProfileFile == null)
return;
CheckAndCreateDirectory();
// Write to an xml file.
if (LoadedProfileFile.IsEncrypted)
{
// Only if the password provided earlier was valid...
if (LoadedProfileFile.IsPasswordValid)
{
byte[] decryptedBytes = SerializeToByteArray(new List<ProfileInfo>(Profiles));
byte[] encryptedBytes = CryptoHelper.Encrypt(decryptedBytes, SecureStringHelper.ConvertToString(LoadedProfileFile.Password), GlobalStaticConfiguration.Profile_EncryptionKeySize, GlobalStaticConfiguration.Profile_EncryptionBlockSize, GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(LoadedProfileFile.Path, encryptedBytes);
}
}
else
{
SerializeToFile(LoadedProfileFile.Path, new List<ProfileInfo>(Profiles));
}
ProfilesChanged = false;
}
public static void SwitchProfile(ProfileFileInfo info, bool saveLoadedProfiles = true)
{
if (saveLoadedProfiles && LoadedProfileFile != null && ProfilesChanged)
Save();
ClearProfile();
Load(info);
}
private static void CheckAndCreateDirectory()
{
var location = GetProfilesLocation();
if (!Directory.Exists(location))
Directory.CreateDirectory(location);
}
#endregion
#region Deserialize, serialize to file
private static List<ProfileInfo> DeserializeFromFile(string filePath)
{
var profiles = new List<ProfileInfo>();
var xmlSerializer = new XmlSerializer(typeof(List<ProfileInfo>));
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
((List<ProfileInfo>)xmlSerializer.Deserialize(fileStream)).ForEach(x => profiles.Add(x));
}
return profiles;
}
private static void SerializeToFile(string filePath, List<ProfileInfo> profiles)
{
var xmlSerializer = new XmlSerializer(typeof(List<ProfileInfo>));
using var fileStream = new FileStream(filePath, FileMode.Create);
xmlSerializer.Serialize(fileStream, profiles);
}
#endregion
#region Deserialize, serialize to byte[]
private static List<ProfileInfo> DeserializeFromByteArray(byte[] xml)
{
var profiles = new List<ProfileInfo>();
var xmlSerializer = new XmlSerializer(typeof(List<ProfileInfo>));
using var memoryStream = new MemoryStream(xml);
((List<ProfileInfo>)xmlSerializer.Deserialize(memoryStream)).ForEach(x => profiles.Add(x));
return profiles;
}
private static byte[] SerializeToByteArray(List<ProfileInfo> profiles)
{
var xmlSerializer = new XmlSerializer(typeof(List<ProfileInfo>));
using var memoryStream = new MemoryStream();
using var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);
xmlSerializer.Serialize(streamWriter, profiles);
return memoryStream.ToArray();
}
#endregion
#region Move profiles
public static Task MoveProfilesAsync(string targedLocation, bool overwrite)
{
return Task.Run(() => MoveProfiles(targedLocation, overwrite));
}
private static void MoveProfiles(string targedLocation, bool overwrite)
{
// Save the current profile
Save();
// Create the directory
if (!Directory.Exists(targedLocation))
Directory.CreateDirectory(targedLocation);
// Copy files
foreach (var profileFile in ProfileFiles)
File.Copy(profileFile.Path, Path.Combine(targedLocation, Path.GetFileName(profileFile.Path)), overwrite);
// Remove old profile files
foreach (var profileFile in ProfileFiles)
File.Delete(profileFile.Path);
// Delete folder, if it is empty
var profileLocation = GetProfilesLocation();
if (Directory.GetFiles(profileLocation).Length == 0 && Directory.GetDirectories(profileLocation).Length == 0)
Directory.Delete(profileLocation);
}
#endregion
#region Reset profiles
public static void ResetProfiles()
{
Profiles.Clear();
}
#endregion
#region Add profile, Remove profile, Rename group
/// <summary>
/// Add a profile.
/// </summary>
/// <param name="profile"><see cref="ProfileInfo"/> to add.</param>
public static void AddProfile(ProfileInfo profile)
{
// Possible fix for appcrash --> when icollection view is refreshed...
System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate
{
//lock (Profiles)
Profiles.Add(profile);
}));
}
/// <summary>
/// Remove a profile.
/// </summary>
/// <param name="profile"><see cref="ProfileInfo"/> to remove.</param>
public static void RemoveProfile(ProfileInfo profile)
{
// Possible fix for appcrash --> when icollection view is refreshed...
System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate
{
//lock (Profiles)
Profiles.Remove(profile);
}));
}
public static void ClearProfile()
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate
{
Profiles.Clear();
}));
}
/// <summary>
/// Method to rename a group.
/// </summary>
/// <param name="oldGroup">Old name of the group.</param>
/// <param name="group">New name of the group.</param>
public static void RenameGroup(string oldGroup, string group)
{
// Go through all groups
foreach (var profile in Profiles)
{
// Find specific group
if (profile.Group != oldGroup)
continue;
// Rename the group
profile.Group = @group?.Trim();
ProfilesChanged = true;
}
}
#endregion
#region GetGroups
/// <summary>
/// Method to get a list of all groups.
/// </summary>
/// <returns>List of groups.</returns>
public static List<string> GetGroups()
{
var list = new List<string>();
foreach (var profile in Profiles)
{
if (!list.Contains(profile.Group))
list.Add(profile.Group);
}
return list;
}
#endregion
#region Collection changed
private static void Profiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
ProfilesChanged = true;
}
#endregion
}
}