-
Notifications
You must be signed in to change notification settings - Fork 803
Expand file tree
/
Copy pathProfileManager.cs
More file actions
1350 lines (1099 loc) · 50.7 KB
/
ProfileManager.cs
File metadata and controls
1350 lines (1099 loc) · 50.7 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using log4net;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml.Serialization;
namespace NETworkManager.Profiles;
public static class ProfileManager
{
#region Variables
private static readonly ILog Log = LogManager.GetLogger(typeof(ProfileManager));
/// <summary>
/// Profiles directory name.
/// </summary>
private const string ProfilesFolderName = "Profiles";
/// <summary>
/// Profiles backups directory name.
/// </summary>
private static string BackupFolderName => "Backups";
/// <summary>
/// Default profile name.
/// </summary>
private const string ProfilesDefaultFileName = "Default";
/// <summary>
/// Profile file extension.
/// </summary>
private const string ProfileFileExtension = ".json";
/// <summary>
/// Legacy XML profile file extension.
/// </summary>
[Obsolete("Legacy XML profiles are no longer used, but the extension is kept for migration purposes.")]
private static string LegacyProfileFileExtension => ".xml";
/// <summary>
/// Profile file extension for encrypted files.
/// </summary>
private const string ProfileFileExtensionEncrypted = ".encrypted";
/// <summary>
/// JSON serializer options for consistent serialization/deserialization.
/// </summary>
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
Converters = { new JsonStringEnumConverter() }
};
/// <summary>
/// Maximum number of bytes to check for XML content detection.
/// </summary>
private const int XmlDetectionBufferSize = 200;
/// <summary>
/// ObservableCollection of all profile files.
/// </summary>
public static ObservableCollection<ProfileFileInfo> ProfileFiles { get; set; } = [];
/// <summary>
/// Currently loaded profile file.
/// </summary>
private static ProfileFileInfo _loadedProfileFile;
/// <summary>
/// Currently loaded profile file.
/// </summary>
public static ProfileFileInfo LoadedProfileFile
{
get => _loadedProfileFile;
private set
{
if (Equals(value, _loadedProfileFile))
return;
_loadedProfileFile = value;
}
}
/// <summary>
/// Currently loaded profile file data (wrapper containing groups and metadata).
/// This is updated during load/save operations.
/// </summary>
private static ProfileFileData _loadedProfileFileData = new();
/// <summary>
/// Currently loaded profile file data (wrapper containing groups and metadata).
/// This is updated during load/save operations.
/// </summary>
public static ProfileFileData LoadedProfileFileData
{
get => _loadedProfileFileData;
private set
{
if (Equals(value, _loadedProfileFileData))
return;
_loadedProfileFileData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Static constructor. Load all profile files on startup.
/// </summary>
static ProfileManager()
{
LoadProfileFiles();
}
#endregion
#region Events
/// <summary>
/// Event is fired if the currently loaded <see cref="ProfileFileInfo" /> is changed.
/// The <see cref="ProfileFileInfo" /> with the current loaded profile file is passed
/// as argument.
/// </summary>
public static event EventHandler<ProfileFileInfoArgs> OnLoadedProfileFileChangedEvent;
/// <summary>
/// Method to fire the <see cref="OnLoadedProfileFileChangedEvent" />.
/// </summary>
/// <param name="profileFileInfo">Loaded <see cref="ProfileFileInfo" />.</param>
/// <param name="profileFileUpdating">Indicates if the profile file is updating.</param>
private static void LoadedProfileFileChanged(ProfileFileInfo profileFileInfo, bool profileFileUpdating = false)
{
OnLoadedProfileFileChangedEvent?.Invoke(null, new ProfileFileInfoArgs(profileFileInfo, profileFileUpdating));
}
/// <summary>
/// Occurs when the profile migration process begins.
/// </summary>
[Obsolete("Will be removed after some time, as profile migration from legacy XML files is a one-time process.")]
public static event EventHandler OnProfileMigrationStarted;
/// <summary>
/// Raises the event indicating that the profile migration process from legacy XML files has started.
/// </summary>
[Obsolete("Will be removed after some time, as profile migration from legacy XML files is a one-time process.")]
private static void ProfileMigrationStarted()
{
OnProfileMigrationStarted?.Invoke(null, EventArgs.Empty);
}
/// <summary>
/// Occurs when the profile migration from legacy XML files has completed.
/// </summary>
[Obsolete("Will be removed after some time, as profile migration from legacy XML files is a one-time process.")]
public static event EventHandler OnProfileMigrationCompleted;
/// <summary>
/// Raises the event indicating that the profile migration from legacy XML files has completed.
/// </summary>
[Obsolete("Will be removed after some time, as profile migration from legacy XML files is a one-time process.")]
private static void ProfileMigrationCompleted()
{
OnProfileMigrationCompleted?.Invoke(null, EventArgs.Empty);
}
/// <summary>
/// Event is fired if the profiles have changed.
/// </summary>
public static event EventHandler OnProfilesUpdated;
/// <summary>
/// Method to fire the <see cref="OnProfilesUpdated" />.
/// </summary>
private static void ProfilesUpdated(bool profilesChanged = true)
{
LoadedProfileFileData?.ProfilesChanged = profilesChanged;
OnProfilesUpdated?.Invoke(null, EventArgs.Empty);
}
#endregion
#region Profiles locations, default paths and file names
/// <summary>
/// Method to get the path of the profiles folder.
/// </summary>
/// <returns>Path to the profiles folder.</returns>
public static string GetProfilesFolderLocation()
{
return ConfigurationManager.Current.IsPortable
? Path.Combine(AssemblyManager.Current.Location, ProfilesFolderName)
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
AssemblyManager.Current.Name, ProfilesFolderName);
}
/// <summary>
/// Method to get the path of the profiles backup folder.
/// </summary>
/// <returns>Path to the profiles backup folder.</returns>
public static string GetProfilesBackupFolderLocation()
{
return Path.Combine(GetProfilesFolderLocation(), BackupFolderName);
}
/// <summary>
/// Method to get the default profile file name.
/// </summary>
/// <returns>Default profile file name.</returns>
private static string GetProfilesDefaultFileName()
{
return $"{ProfilesDefaultFileName}{ProfileFileExtension}";
}
/// <summary>
/// Method to get the default profile file path.
/// </summary>
/// <returns>Default profile file path.</returns>
private static string GetProfilesDefaultFilePath()
{
return Path.Combine(GetProfilesFolderLocation(), GetProfilesDefaultFileName());
}
#endregion
#region Get and load 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 ||
Path.GetExtension(x) == LegacyProfileFileExtension);
}
/// <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 = GetProfilesFolderLocation();
// 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 no profile file exists.
if (ProfileFiles.Count == 0)
ProfileFiles.Add(new ProfileFileInfo(ProfilesDefaultFileName, GetProfilesDefaultFilePath()));
}
#endregion
#region Create, rename and delete profile file
/// <summary>
/// Method to create a profile file.
/// </summary>
/// <param name="profileName">Name of the profile file to create.</param>
/// <exception cref="ArgumentException">Thrown when profileName is null or empty.</exception>
public static void CreateEmptyProfileFile(string profileName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(profileName);
ProfileFileInfo profileFileInfo = new(profileName,
Path.Combine(GetProfilesFolderLocation(), $"{profileName}{ProfileFileExtension}"));
Directory.CreateDirectory(GetProfilesFolderLocation());
// Create and serialize empty ProfileFileData to new file (without loading it)
var emptyProfileFileData = new ProfileFileData();
var jsonString = JsonSerializer.Serialize(emptyProfileFileData, JsonOptions);
File.WriteAllText(profileFileInfo.Path, jsonString);
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>
/// <exception cref="ArgumentNullException">Thrown when profileFileInfo is null.</exception>
/// <exception cref="ArgumentException">Thrown when newProfileName is null or empty.</exception>
public static void RenameProfileFile(ProfileFileInfo profileFileInfo, string newProfileName)
{
ArgumentNullException.ThrowIfNull(profileFileInfo);
ArgumentException.ThrowIfNullOrWhiteSpace(newProfileName);
// Check if the profile is currently in use
var switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create backup
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// Create new profile info with the new name
ProfileFileInfo newProfileFileInfo = new(newProfileName,
Path.Combine(GetProfilesFolderLocation(), $"{newProfileName}{Path.GetExtension(profileFileInfo.Path)}"),
profileFileInfo.IsEncrypted)
{
Password = profileFileInfo.Password,
IsPasswordValid = profileFileInfo.IsPasswordValid
};
// Copy the profile file to the new location
File.Copy(profileFileInfo.Path, newProfileFileInfo.Path);
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
Switch(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile, true);
}
// Remove the old profile file
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
/// <summary>
/// Method to delete a profile file.
/// </summary>
/// <param name="profileFileInfo"><see cref="ProfileFileInfo" /> to delete.</param>
/// <exception cref="ArgumentNullException">Thrown when profileFileInfo is null.</exception>
public static void DeleteProfileFile(ProfileFileInfo profileFileInfo)
{
ArgumentNullException.ThrowIfNull(profileFileInfo);
// Trigger switch via UI (to get the password if the file is encrypted), if the selected profile file is deleted
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
LoadedProfileFileChanged(ProfileFiles.FirstOrDefault(x => !x.Equals(profileFileInfo)));
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
}
#endregion
#region Enable, disable encryption and 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>
/// <exception cref="ArgumentNullException">Thrown when profileFileInfo or password is null.</exception>
public static void EnableEncryption(ProfileFileInfo profileFileInfo, SecureString password)
{
ArgumentNullException.ThrowIfNull(profileFileInfo);
ArgumentNullException.ThrowIfNull(password);
// Check if the profile is currently in use
var switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create backup
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// 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
};
// Save current state to prevent corruption
var previousLoadedProfileFileData = LoadedProfileFileData;
try
{
// Load the existing profile data (temporarily overwrites LoadedProfileFileData)
if (Path.GetExtension(profileFileInfo.Path) == LegacyProfileFileExtension)
DeserializeFromXmlFile(profileFileInfo.Path);
else
DeserializeFromFile(profileFileInfo.Path);
// Save the encrypted file
var decryptedBytes = SerializeToByteArray();
var encryptedBytes = CryptoHelper.Encrypt(decryptedBytes,
SecureStringHelper.ConvertToString(newProfileFileInfo.Password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(newProfileFileInfo.Path, encryptedBytes);
}
finally
{
// Restore previous state if this wasn't the currently loaded profile
if (!switchProfile)
LoadedProfileFileData = previousLoadedProfileFileData;
}
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
Switch(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile, true);
}
// Remove the old profile file
if (profileFileInfo.Path != null)
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>
/// <exception cref="ArgumentNullException">Thrown when profileFileInfo, password, or newPassword is null.</exception>
public static void ChangeMasterPassword(ProfileFileInfo profileFileInfo, SecureString password,
SecureString newPassword)
{
ArgumentNullException.ThrowIfNull(profileFileInfo);
ArgumentNullException.ThrowIfNull(password);
ArgumentNullException.ThrowIfNull(newPassword);
// Check if the profile is currently in use
var switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create backup
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// Create new profile info with the encryption infos
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name,
Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtensionEncrypted), true)
{
Password = newPassword,
IsPasswordValid = true
};
// Save current state to prevent corruption
var previousLoadedProfileFileData = LoadedProfileFileData;
try
{
// Load and decrypt the profiles from the profile file (temporarily overwrites LoadedProfileFileData)
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes, SecureStringHelper.ConvertToString(password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
if (IsXmlContent(decryptedBytes))
DeserializeFromXmlByteArray(decryptedBytes);
else
DeserializeFromByteArray(decryptedBytes);
// Save the encrypted file with new password
decryptedBytes = SerializeToByteArray();
encryptedBytes = CryptoHelper.Encrypt(decryptedBytes,
SecureStringHelper.ConvertToString(newProfileFileInfo.Password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(newProfileFileInfo.Path, encryptedBytes);
}
finally
{
// Restore previous state if this wasn't the currently loaded profile
if (!switchProfile)
LoadedProfileFileData = previousLoadedProfileFileData;
}
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
Switch(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile, true);
}
// 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>
/// <exception cref="ArgumentNullException">Thrown when profileFileInfo or password is null.</exception>
public static void DisableEncryption(ProfileFileInfo profileFileInfo, SecureString password)
{
ArgumentNullException.ThrowIfNull(profileFileInfo);
ArgumentNullException.ThrowIfNull(password);
// Check if the profile is currently in use
var switchProfile = false;
if (LoadedProfileFile != null && LoadedProfileFile.Equals(profileFileInfo))
{
Save();
switchProfile = true;
}
// Create backup
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// Create new profile info
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name,
Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtension));
// Save current state to prevent corruption
var previousLoadedProfileFileData = LoadedProfileFileData;
try
{
// Load and decrypt the profiles from the profile file (temporarily overwrites LoadedProfileFileData)
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes, SecureStringHelper.ConvertToString(password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
if (IsXmlContent(decryptedBytes))
DeserializeFromXmlByteArray(decryptedBytes);
else
DeserializeFromByteArray(decryptedBytes);
// Save the decrypted profiles to the profile file
SerializeToFile(newProfileFileInfo.Path);
}
finally
{
// Restore previous state if this wasn't the currently loaded profile
if (!switchProfile)
LoadedProfileFileData = previousLoadedProfileFileData;
}
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile, if it was previously loaded
if (switchProfile)
{
Switch(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile, true);
}
// 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)
{
var loadedProfileUpdated = false;
if (File.Exists(profileFileInfo.Path))
{
Log.Info($"Loading profile file from: {profileFileInfo.Path}");
// Encrypted profile file
if (profileFileInfo.IsEncrypted)
{
var encryptedBytes = File.ReadAllBytes(profileFileInfo.Path);
var decryptedBytes = CryptoHelper.Decrypt(encryptedBytes,
SecureStringHelper.ConvertToString(profileFileInfo.Password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
if (IsXmlContent(decryptedBytes))
{
//
// MIGRATION FROM LEGACY XML PROFILE FILE
//
Log.Info($"Legacy XML profile file detected inside encrypted profile: {profileFileInfo.Path}. Migration in progress...");
// Load from legacy XML byte array
DeserializeFromXmlByteArray(decryptedBytes);
// Create a backup of the legacy XML file
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// Save encrypted profile file with new JSON format
var newDecryptedBytes = SerializeToByteArray();
var newEncryptedBytes = CryptoHelper.Encrypt(newDecryptedBytes,
SecureStringHelper.ConvertToString(profileFileInfo.Password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(profileFileInfo.Path, newEncryptedBytes);
Log.Info($"Legacy XML profile file migration completed inside encrypted profile: {profileFileInfo.Path}.");
}
else
{
DeserializeFromByteArray(decryptedBytes);
}
// Password is valid
ProfileFiles.FirstOrDefault(x => x.Equals(profileFileInfo))!.IsPasswordValid = true;
profileFileInfo.IsPasswordValid = true;
loadedProfileUpdated = true;
}
// Unencrypted profile file
else
{
if (Path.GetExtension(profileFileInfo.Path) == LegacyProfileFileExtension)
{
//
// MIGRATION FROM LEGACY XML PROFILE FILE
//
Log.Info($"Legacy XML profile file detected: {profileFileInfo.Path}. Migration in progress...");
// Load from legacy XML file
DeserializeFromXmlFile(profileFileInfo.Path);
LoadedProfileFile = profileFileInfo;
// Create a backup of the legacy XML file and delete the original
Backup(profileFileInfo.Path,
GetProfilesBackupFolderLocation(),
TimestampHelper.GetTimestampFilename(Path.GetFileName(profileFileInfo.Path)));
// Create new profile file info with JSON extension
var newProfileFileInfo = new ProfileFileInfo(profileFileInfo.Name,
Path.ChangeExtension(profileFileInfo.Path, ProfileFileExtension));
// Save new JSON file
SerializeToFile(newProfileFileInfo.Path);
// Notify migration started
ProfileMigrationStarted();
// Add the new profile
ProfileFiles.Add(newProfileFileInfo);
// Switch profile
Log.Info($"Switching to migrated profile file: {newProfileFileInfo.Path}.");
Switch(newProfileFileInfo, false);
LoadedProfileFileChanged(LoadedProfileFile, true);
// Remove the old profile file
File.Delete(profileFileInfo.Path);
ProfileFiles.Remove(profileFileInfo);
// Notify migration completed
ProfileMigrationCompleted();
Log.Info($"Legacy XML profile file migration completed: {profileFileInfo.Path}.");
return;
}
else
{
DeserializeFromFile(profileFileInfo.Path);
}
}
}
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!");
}
LoadedProfileFile = profileFileInfo;
if (loadedProfileUpdated)
LoadedProfileFileChanged(LoadedProfileFile, true);
// Notify subscribers that profiles have been loaded/updated
ProfilesUpdated(false);
Log.Info("Profile file loaded successfully.");
}
/// <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)
{
Log.Warn("Cannot save profiles because no profile file is loaded or the profile file is encrypted and not yet unlocked.");
return;
}
// Ensure the profiles directory exists.
Directory.CreateDirectory(GetProfilesFolderLocation());
// Create backup before modifying
CreateDailyBackupIfNeeded();
// Write profiles to the profile file (JSON, optionally encrypted).
if (LoadedProfileFile.IsEncrypted)
{
// Only if the password provided earlier was valid...
if (LoadedProfileFile.IsPasswordValid)
{
var decryptedBytes = SerializeToByteArray();
var encryptedBytes = CryptoHelper.Encrypt(decryptedBytes,
SecureStringHelper.ConvertToString(LoadedProfileFile.Password),
GlobalStaticConfiguration.Profile_EncryptionKeySize,
GlobalStaticConfiguration.Profile_EncryptionIterations);
File.WriteAllBytes(LoadedProfileFile.Path, encryptedBytes);
}
}
else
{
SerializeToFile(LoadedProfileFile.Path);
}
LoadedProfileFileData?.ProfilesChanged = false;
}
/// <summary>
/// Method to unload the currently loaded profile file.
/// </summary>
/// <param name="saveLoadedProfiles">Save loaded profile file (default is true)</param>
public static void Unload(bool saveLoadedProfiles = true)
{
if (saveLoadedProfiles && LoadedProfileFile != null && LoadedProfileFileData?.ProfilesChanged == true)
Save();
LoadedProfileFile = null;
LoadedProfileFileData = new ProfileFileData();
// Don't mark as changed since we just unloaded
ProfilesUpdated(false);
}
/// <summary>
/// Method to switch to another profile file.
/// </summary>
/// <param name="info">New <see cref="ProfileFileInfo" /> to load.</param>
/// <param name="saveLoadedProfiles">Save loaded profile file (default is true)</param>
public static void Switch(ProfileFileInfo info, bool saveLoadedProfiles = true)
{
Unload(saveLoadedProfiles);
Load(info);
}
#endregion
#region Serialize and deserialize
/// <summary>
/// Method to serialize profile data to a JSON file.
/// </summary>
/// <param name="filePath">Path to a JSON file.</param>
private static void SerializeToFile(string filePath)
{
// Ensure LoadedProfileFileData exists
LoadedProfileFileData ??= new ProfileFileData();
var jsonString = JsonSerializer.Serialize(LoadedProfileFileData, JsonOptions);
File.WriteAllText(filePath, jsonString);
}
/// <summary>
/// Method to serialize profile data to a byte array.
/// </summary>
/// <returns>Serialized profile data as byte array.</returns>
private static byte[] SerializeToByteArray()
{
// Ensure LoadedProfileFileData exists
LoadedProfileFileData ??= new ProfileFileData();
var jsonString = JsonSerializer.Serialize(LoadedProfileFileData, JsonOptions);
return Encoding.UTF8.GetBytes(jsonString);
}
/// <summary>
/// Method to deserialize profile data from a JSON file.
/// </summary>
/// <param name="filePath">Path to a JSON file.</param>
private static void DeserializeFromFile(string filePath)
{
var jsonString = File.ReadAllText(filePath);
DeserializeFromJson(jsonString);
}
/// <summary>
/// Method to deserialize a list of groups as <see cref="GroupInfo" /> from a legacy XML file.
/// </summary>
/// <param name="filePath">Path to an XML file.</param>
[Obsolete("Legacy XML profile files are no longer used, but the method is kept for migration purposes.")]
private static void DeserializeFromXmlFile(string filePath)
{
using FileStream fileStream = new(filePath, FileMode.Open);
DeserializeFromXmlStream(fileStream);
}
/// <summary>
/// Method to deserialize profile data from a byte array.
/// </summary>
/// <param name="data">Serialized profile data as byte array.</param>
private static void DeserializeFromByteArray(byte[] data)
{
var jsonString = Encoding.UTF8.GetString(data);
DeserializeFromJson(jsonString);
}
/// <summary>
/// Method to deserialize a list of groups as <see cref="GroupInfo" /> from a legacy XML byte array.
/// </summary>
/// <param name="xml">Serialized list of groups as <see cref="GroupInfo" /> as XML byte array.</param>
[Obsolete("Legacy XML profile files are no longer used, but the method is kept for migration purposes.")]
private static void DeserializeFromXmlByteArray(byte[] xml)
{
using MemoryStream memoryStream = new(xml);
DeserializeFromXmlStream(memoryStream);
}
/// <summary>
/// Method to deserialize profile data from JSON string.
/// </summary>
/// <param name="jsonString">JSON string to deserialize.</param>
private static void DeserializeFromJson(string jsonString)
{
try
{
var profileFileData = JsonSerializer.Deserialize<ProfileFileData>(jsonString, JsonOptions);
if (profileFileData != null)
{
LoadedProfileFileData = profileFileData;
return;
}
}
catch (JsonException)
{
Log.Info("Failed to deserialize as ProfileFileData, trying legacy format (direct Groups array)...");
}
// Fallback: Try to deserialize as legacy format (direct array of GroupInfoSerializable)
var groupsSerializable = JsonSerializer.Deserialize<List<GroupInfoSerializable>>(jsonString, JsonOptions);
if (groupsSerializable == null)
throw new InvalidOperationException("Failed to deserialize JSON profile file.");
// Create ProfileFileData wrapper for legacy format
LoadedProfileFileData = new ProfileFileData
{
GroupsSerializable = groupsSerializable
};
Log.Info("Successfully loaded profile file in legacy format. It will be migrated to new format on next save.");
}
/// <summary>
/// Method to deserialize a list of groups as <see cref="GroupInfo" /> from an XML stream.
/// </summary>
/// <param name="stream">Stream to deserialize.</param>
[Obsolete("Legacy XML profile files are no longer used, but the method is kept for migration purposes.")]
private static void DeserializeFromXmlStream(Stream stream)
{
XmlSerializer xmlSerializer = new(typeof(List<GroupInfoSerializable>));
var groupsSerializable = xmlSerializer.Deserialize(stream) as List<GroupInfoSerializable>;
if (groupsSerializable == null)
throw new InvalidOperationException("Failed to deserialize XML profile file.");
LoadedProfileFileData = new ProfileFileData
{
GroupsSerializable = groupsSerializable
};
}
/// <summary>
/// Method to check if the byte array content is XML.
/// </summary>
/// <param name="data">Byte array to check.</param>
/// <returns>True if the content is XML.</returns>
[Obsolete("Legacy XML profile files are no longer used, but the method is kept for migration purposes.")]
private static bool IsXmlContent(byte[] data)
{
if (data == null || data.Length == 0)
return false;
try
{
// Only check the first few bytes for performance
var bytesToCheck = Math.Min(XmlDetectionBufferSize, data.Length);
var text = Encoding.UTF8.GetString(data, 0, bytesToCheck).TrimStart();
// Check for XML declaration or root element that matches profile structure
return text.StartsWith("<?xml") || text.StartsWith("<ArrayOfGroupInfoSerializable");
}
catch
{
return false;
}
}
#endregion
#region Add, remove, replace group(s) and more.
/// <summary>
/// Method to add a list of <see cref="GroupInfo" /> to the loaded profile data.
/// </summary>
/// <param name="groups">List of groups as <see cref="GroupInfo" /> to add.</param>
/// <exception cref="ArgumentNullException">Thrown when groups collection is null.</exception>
private static void AddGroups(List<GroupInfo> groups, bool profilesChanged = true)
{
ArgumentNullException.ThrowIfNull(groups);
var skippedCount = 0;
foreach (var group in groups)
{
if (group is null)
{
skippedCount++;
continue;
}
LoadedProfileFileData.Groups.Add(group);
}
if (skippedCount > 0)
Log.Warn($"AddGroups skipped {skippedCount} null group(s) in collection.");
ProfilesUpdated(profilesChanged);
}
/// <summary>