Repository navigation
Expand file tree
/
Copy pathAppConfig.cs
More file actions
359 lines (318 loc) · 13.4 KB
/
Copy pathAppConfig.cs
File metadata and controls
359 lines (318 loc) · 13.4 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace WpfApp1
{
public enum ConfigLoadStatus
{
Missing,
Loaded,
Corrupt
}
/// <summary>
/// 应用程序配置类
/// </summary>
public class AppConfig
{
/// <summary>
/// 广播项目列表
/// </summary>
public List<BroadcastItem> BroadcastItems { get; set; } = new List<BroadcastItem>();
/// <summary>
/// 选中的音频设备
/// </summary>
public string SelectedAudioDevice { get; set; } = string.Empty;
/// <summary>
/// 选中的 WASAPI 模式音频设备ID
/// </summary>
public string SelectedAudioDeviceId { get; set; } = string.Empty;
/// <summary>
/// 音频输出模式
/// </summary>
public AudioOutputMode OutputMode { get; set; } = AudioOutputMode.Compatible;
/// <summary>
/// 广播方案列表
/// </summary>
public List<BroadcastProfile> Profiles { get; set; } = new List<BroadcastProfile>();
/// <summary>
/// 当前激活的方案名称
/// </summary>
public string ActiveProfileName { get; set; } = string.Empty;
/// <summary>
/// 独占广播模式:持续静音本程序以外所有程序的声音
/// </summary>
public bool MuteOtherSounds { get; set; }
/// <summary>
/// 值守锁定:防止误触修改广播项、方案和输出设置
/// </summary>
public bool IsAttendantLocked { get; set; }
/// <summary>
/// 创建默认配置
/// </summary>
/// <returns>默认配置实例</returns>
public static AppConfig CreateDefault()
{
// 创建默认方案
var defaultProfile = BroadcastProfile.CreateDefault();
defaultProfile.IsActive = true;
return new AppConfig
{
BroadcastItems = new List<BroadcastItem>(),
SelectedAudioDevice = string.Empty,
SelectedAudioDeviceId = string.Empty,
OutputMode = AudioOutputMode.Compatible,
Profiles = new List<BroadcastProfile> { defaultProfile },
ActiveProfileName = defaultProfile.Name,
MuteOtherSounds = false,
IsAttendantLocked = false
};
}
}
/// <summary>
/// 配置管理器
/// </summary>
public class ConfigManager
{
private const string ConfigFileName = "broadcast_config.json";
internal static string ConfigFilePath { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFileName);
public static ConfigLoadStatus LastLoadStatus { get; private set; } = ConfigLoadStatus.Missing;
public static string? LastBackupPath { get; private set; }
/// <summary>
/// 保存配置到文件
/// </summary>
/// <param name="config">要保存的配置对象</param>
public static void SaveConfig(AppConfig config)
{
try
{
string json = JsonConvert.SerializeObject(config, Formatting.Indented);
File.WriteAllText(ConfigFilePath, json);
}
catch (Exception ex)
{
// 在实际应用中可能需要记录日志或通知用户
System.Diagnostics.Debug.WriteLine($"保存配置时出错: {ex.Message}");
}
}
/// <summary>
/// 从文件加载配置
/// </summary>
/// <returns>加载的配置对象,如果加载失败则返回默认配置</returns>
public static AppConfig LoadConfig()
{
LastLoadStatus = ConfigLoadStatus.Missing;
LastBackupPath = null;
if (!File.Exists(ConfigFilePath))
{
return AppConfig.CreateDefault();
}
AppConfig? config;
try
{
string json = File.ReadAllText(ConfigFilePath);
config = JsonConvert.DeserializeObject<AppConfig>(json);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"加载配置时出错: {ex.Message}");
return HandleCorruptConfig();
}
if (config == null)
{
return HandleCorruptConfig();
}
try
{
NormalizeLoadedConfig(config);
}
catch (Exception ex)
{
// 规范化异常同样按损坏处理:宁可只读运行,也不能带着半规范化数据保存回原文件
System.Diagnostics.Debug.WriteLine($"规范化配置时出错: {ex.Message}");
return HandleCorruptConfig();
}
LastLoadStatus = ConfigLoadStatus.Loaded;
return config;
}
private static AppConfig HandleCorruptConfig()
{
LastLoadStatus = ConfigLoadStatus.Corrupt;
BackupCorruptConfig();
return AppConfig.CreateDefault();
}
private static void NormalizeLoadedConfig(AppConfig config)
{
// 手工编辑过的 JSON 可能带 null 列表元素,先滤掉再走后续规范化
config.BroadcastItems = config.BroadcastItems?.Where(item => item != null).ToList() ?? new List<BroadcastItem>();
config.Profiles = config.Profiles?.Where(profile => profile != null).ToList() ?? new List<BroadcastProfile>();
config.SelectedAudioDevice = config.SelectedAudioDevice ?? string.Empty;
config.SelectedAudioDeviceId = config.SelectedAudioDeviceId ?? string.Empty;
if (!Enum.IsDefined(typeof(AudioOutputMode), config.OutputMode))
{
config.OutputMode = AudioOutputMode.Compatible;
}
// 确保配置中包含方案
if (config.Profiles.Count == 0)
{
// 如果没有方案但有广播项,则创建一个包含现有广播项的默认方案
var defaultProfile = BroadcastProfile.CreateDefault();
defaultProfile.BroadcastItems = config.BroadcastItems;
defaultProfile.SelectedAudioDevice = config.SelectedAudioDevice;
defaultProfile.SelectedAudioDeviceId = config.SelectedAudioDeviceId;
defaultProfile.IsActive = true;
config.Profiles = new List<BroadcastProfile> { defaultProfile };
config.ActiveProfileName = defaultProfile.Name;
}
else
{
// 确保激活的方案标记正确
bool hasActiveProfile = false;
foreach (var profile in config.Profiles)
{
profile.BroadcastItems = profile.BroadcastItems?.Where(item => item != null).ToList() ?? new List<BroadcastItem>();
profile.SelectedAudioDevice = profile.SelectedAudioDevice ?? string.Empty;
profile.SelectedAudioDeviceId = profile.SelectedAudioDeviceId ?? string.Empty;
if (profile.Name == config.ActiveProfileName)
{
profile.IsActive = true;
hasActiveProfile = true;
}
else
{
profile.IsActive = false;
}
}
// 如果没有激活的方案,默认激活第一个
if (!hasActiveProfile && config.Profiles.Count > 0)
{
config.Profiles[0].IsActive = true;
config.ActiveProfileName = config.Profiles[0].Name;
}
// 确保BroadcastItems和SelectedAudioDevice与当前激活的方案同步
var activeProfile = config.Profiles.FirstOrDefault(p => p.IsActive);
if (activeProfile != null)
{
config.BroadcastItems = activeProfile.BroadcastItems;
config.SelectedAudioDevice = activeProfile.SelectedAudioDevice;
if (string.IsNullOrEmpty(activeProfile.SelectedAudioDeviceId) && !string.IsNullOrEmpty(config.SelectedAudioDeviceId))
{
activeProfile.SelectedAudioDeviceId = config.SelectedAudioDeviceId;
}
config.SelectedAudioDeviceId = activeProfile.SelectedAudioDeviceId;
}
}
}
private static void BackupCorruptConfig()
{
try
{
if (!File.Exists(ConfigFilePath))
{
return;
}
string directory = Path.GetDirectoryName(ConfigFilePath) ?? AppDomain.CurrentDomain.BaseDirectory;
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
string backupPath = Path.Combine(directory, $"{ConfigFileName}.corrupt-{timestamp}.bak");
int duplicateIndex = 2;
while (File.Exists(backupPath))
{
backupPath = Path.Combine(directory, $"{ConfigFileName}.corrupt-{timestamp}-{duplicateIndex}.bak");
duplicateIndex++;
}
File.Copy(ConfigFilePath, backupPath, overwrite: false);
LastBackupPath = backupPath;
TryPruneCorruptBackups(directory);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"备份损坏配置时出错: {ex.Message}");
}
}
private static void TryPruneCorruptBackups(string directory)
{
// 配置持续损坏 + 开机自启会每次启动落一份备份,只保最近几份防止无限堆积
const int maxBackups = 5;
try
{
var backups = Directory.GetFiles(directory, $"{ConfigFileName}.corrupt-*.bak")
.OrderByDescending(File.GetLastWriteTime)
.Skip(maxBackups);
foreach (var file in backups)
{
File.Delete(file);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"清理损坏配置备份时出错: {ex.Message}");
}
}
/// <summary>
/// 将ObservableCollection转换为List用于保存
/// </summary>
public static AppConfig PrepareConfigForSave(ObservableCollection<BroadcastItem> broadcastItems, string selectedAudioDevice, string selectedAudioDeviceId, AudioOutputMode outputMode, ObservableCollection<BroadcastProfile> profiles, string activeProfileName, bool isAttendantLocked)
{
var normalizedDeviceId = selectedAudioDeviceId ?? string.Empty;
var normalizedOutputMode = Enum.IsDefined(typeof(AudioOutputMode), outputMode) ? outputMode : AudioOutputMode.Compatible;
// 更新当前激活方案的数据
foreach (var profile in profiles)
{
if (profile.Name == activeProfileName)
{
profile.BroadcastItems = broadcastItems.ToList();
profile.SelectedAudioDevice = selectedAudioDevice;
profile.SelectedAudioDeviceId = normalizedDeviceId;
profile.IsActive = true;
}
else
{
profile.IsActive = false;
}
}
return new AppConfig
{
BroadcastItems = broadcastItems.ToList(),
SelectedAudioDevice = selectedAudioDevice,
SelectedAudioDeviceId = normalizedDeviceId,
OutputMode = normalizedOutputMode,
Profiles = profiles.ToList(),
ActiveProfileName = activeProfileName,
IsAttendantLocked = isAttendantLocked
};
}
/// <summary>
/// 将加载的配置转换为ObservableCollection
/// </summary>
public static ObservableCollection<BroadcastItem> ConvertToObservableCollection(AppConfig config)
{
if (config.BroadcastItems == null)
{
return new ObservableCollection<BroadcastItem>();
}
return new ObservableCollection<BroadcastItem>(config.BroadcastItems);
}
/// <summary>
/// 将方案列表转换为ObservableCollection
/// </summary>
public static ObservableCollection<BroadcastProfile> ConvertProfilesToObservableCollection(AppConfig config)
{
if (config.Profiles == null)
{
var defaultProfile = BroadcastProfile.CreateDefault();
defaultProfile.IsActive = true;
return new ObservableCollection<BroadcastProfile> { defaultProfile };
}
return new ObservableCollection<BroadcastProfile>(config.Profiles);
}
/// <summary>
/// 获取当前激活的方案
/// </summary>
public static BroadcastProfile? GetActiveProfile(ObservableCollection<BroadcastProfile> profiles)
{
return profiles.FirstOrDefault(p => p.IsActive) ?? profiles.FirstOrDefault();
}
}
}