-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaveLoad.cs
More file actions
292 lines (267 loc) · 10.8 KB
/
Copy pathSaveLoad.cs
File metadata and controls
292 lines (267 loc) · 10.8 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
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
namespace YT_DLP_UI
{
public sealed partial class HomePage
{
private readonly SemaphoreSlim _settingsLock = new(1, 1);
private bool _isSettingsLoaded = false;
public const string ProfilesFileName = "Profiles.json";
public const string SettingsFileName = "Settings.json";
public AppSettings Settings = new();
private static readonly JsonTypeInfo<AppSettings> _appSettingsJsonTypeInfo = AppJsonSerializerContext.Default.AppSettings;
private static readonly JsonTypeInfo<AppSettingsProfile> _oldAppSettingsJsonTypeInfo = OldAppJsonSerializerContext.Default.AppSettingsProfile;
public static readonly JsonSerializerOptions JsonOptions = new()
{
IncludeFields = true,
WriteIndented = true,
};
public struct AppSettingsProfile
{
public AppSettingsProfile()
{
}
public string Name { get; set; } = "Default";
public string Link { get; set; } = string.Empty;
public string LinkActionOnProfileChange { get; set; } = "ClearLink";
public string DownloadFolderPath { get; set; } = string.Empty;
public string AdditionalArguments { get; set; } = string.Empty;
public string Format { get; set; } = "mp4";
public bool EmbedMetadata { get; set; } = true;
public bool Sponsorblock { get; set; } = false;
public bool UseSystemFFMPEG { get; set; }
}
public struct AppSettings
{
public AppSettings()
{
}
public AppSettingsProfile[] Profiles { get; set; } = [new()];
public int ActiveProfileId { get; set; } = 0;
public ref AppSettingsProfile GetActiveProfile()
{
return ref Profiles[Math.Clamp(ActiveProfileId, 0, Profiles.Length - 1)];
}
public void AddAndUseProfile(AppSettingsProfile profile)
{
var profilesList = Profiles.ToList();
profilesList.Add(profile);
Profiles = profilesList.ToArray();
ActiveProfileId = Profiles.Length - 1;
}
public void RemoveProfile(int index)
{
if (index < 0 || index >= Profiles.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), "Invalid profile index");
}
var profilesList = Profiles.ToList();
if (profilesList.Count <= 1)
{
throw new InvalidOperationException("Cannot remove the last profile");
}
profilesList.RemoveAt(index);
Profiles = profilesList.ToArray();
if (ActiveProfileId >= Profiles.Length)
{
ActiveProfileId = Profiles.Length - 1;
}
}
}
public async void SaveSettingsUI(object sender, RoutedEventArgs e)
{
SavingSettingsProgressRing.IsActive = true;
await SaveSettingsAsync();
SavingSettingsProgressRing.IsActive = false;
}
public async void EmbedMetadataToggle_Toggled(object sender, RoutedEventArgs e)
{
if (sender is ToggleSwitch toggle)
{
Settings.GetActiveProfile().EmbedMetadata = toggle.IsOn;
}
SaveSettingsUI(sender, e);
}
public async void SponsorblockToggle_Toggled(object sender, RoutedEventArgs e)
{
if (sender is ToggleSwitch toggle)
{
Settings.GetActiveProfile().Sponsorblock = toggle.IsOn;
}
SaveSettingsUI(sender, e);
}
public async void UseSystemFFMPEGToggle_Toggled(object sender, RoutedEventArgs e)
{
if (sender is ToggleSwitch toggle)
{
Settings.GetActiveProfile().UseSystemFFMPEG = toggle.IsOn;
}
}
public async Task SaveSettingsAsync()
{
if (!_isSettingsLoaded)
{
return;
}
try
{
// Use a semaphore to prevent concurrent access to Settings file
await _settingsLock.WaitAsync();
string json = JsonSerializer.Serialize(Settings, _appSettingsJsonTypeInfo);
if (string.IsNullOrWhiteSpace(json) || json == "{}" || json == "null")
{
Debug.WriteLine("WARNING: Attempted to save empty Settings, operation aborted");
return;
}
var tempFileName = ProfilesFileName + ".temp";
var tempFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
tempFileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(tempFile, json);
string verificationJson = await FileIO.ReadTextAsync(tempFile);
if (string.IsNullOrWhiteSpace(verificationJson))
{
Debug.WriteLine("ERROR: Settings verification failed - temp file is empty");
return;
}
StorageFile actualFile;
try
{
actualFile = await ApplicationData.Current.LocalFolder.GetFileAsync(ProfilesFileName);
}
catch
{
actualFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
ProfilesFileName, CreationCollisionOption.ReplaceExisting);
}
await tempFile.CopyAndReplaceAsync(actualFile);
await tempFile.DeleteAsync();
Debug.WriteLine("Settings saved successfully");
}
catch (Exception ex)
{
Debug.WriteLine($"ERROR saving Settings: {ex.Message}");
}
finally
{
_settingsLock.Release();
}
}
public async Task LoadSettingsAsync()
{
bool shouldSaveMigration = false;
try
{
await _settingsLock.WaitAsync();
var isMigrating = false;
StorageFile? file;
try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(ProfilesFileName);
}
catch (FileNotFoundException)
{
isMigrating = true;
Debug.WriteLine("Profiles file not found, migrating from old settings");
file = await ApplicationData.Current.LocalFolder.GetFileAsync(SettingsFileName);
}
string json = await FileIO.ReadTextAsync(file);
if (string.IsNullOrWhiteSpace(json))
{
Debug.WriteLine("WARNING: Settings file exists but is empty, using defaults");
Settings = new();
return;
}
if (isMigrating)
{
var loadedOldSettings = JsonSerializer.Deserialize(json, _oldAppSettingsJsonTypeInfo);
Settings = new()
{
Profiles = [ new AppSettingsProfile
{
DownloadFolderPath = loadedOldSettings.DownloadFolderPath,
AdditionalArguments = loadedOldSettings.AdditionalArguments,
Format = loadedOldSettings.Format,
EmbedMetadata = loadedOldSettings.EmbedMetadata,
Sponsorblock = loadedOldSettings.Sponsorblock,
UseSystemFFMPEG = loadedOldSettings.UseSystemFFMPEG
} ],
ActiveProfileId = 0
};
Debug.WriteLine("Migration successful, saving new settings format");
shouldSaveMigration = true;
}
else
{
var loadedSettings = JsonSerializer.Deserialize(json, _appSettingsJsonTypeInfo);
Settings = loadedSettings;
}
Debug.WriteLine("Settings loaded successfully");
}
catch (FileNotFoundException)
{
Debug.WriteLine("Settings file not found, using defaults");
Settings = new();
}
catch (Exception ex)
{
Debug.WriteLine($"ERROR loading Settings: {ex.Message}");
Settings = new(); // Use defaults on any error
}
finally
{
if (Settings.Profiles == null || Settings.Profiles.Length == 0)
{
Settings.Profiles = [new AppSettingsProfile()];
Settings.ActiveProfileId = 0;
}
Settings.GetActiveProfile().DownloadFolderPath ??= string.Empty;
Settings.GetActiveProfile().Format ??= "mp4";
Settings.GetActiveProfile().AdditionalArguments ??= string.Empty;
_isSettingsLoaded = true;
_settingsLock.Release();
Debug.WriteLine("Settings are ready for use");
}
if (shouldSaveMigration)
{
await SaveSettingsAsync();
}
}
public static string? GetFormatFromDisplayName(string format)
{
var match = FormatRegex().Match(format);
return match.Success ? match.Groups[1].Value : null;
}
public string? GetDisplayNameFromFormat(string format)
{
foreach (var item in FormatComboBox.Items)
{
if (item.ToString() is string displayName && GetFormatFromDisplayName(displayName) == format)
{
return displayName;
}
}
return null;
}
[GeneratedRegex(@"\((.*)\)$")]
private static partial Regex FormatRegex();
}
[JsonSerializable(typeof(HomePage.AppSettings))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
[JsonSerializable(typeof(HomePage.AppSettingsProfile))]
internal partial class OldAppJsonSerializerContext : JsonSerializerContext
{
}
}