-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppEntry.cs
More file actions
470 lines (401 loc) · 17.7 KB
/
Copy pathAppEntry.cs
File metadata and controls
470 lines (401 loc) · 17.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
using LMP.Core.Data;
using LMP.Core.Data.Repositories;
using LMP.UI.Features.Home;
using LMP.UI.Features.Library;
using LMP.UI.Features.Player;
using LMP.UI.Features.Playlist;
using LMP.UI.Features.Search;
using LMP.UI.Features.Settings;
using LMP.UI.Features.Shell;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Avalonia;
using AsyncImageLoader;
using LMP.UI.Dialogs;
using LMP.Core.Audio.Cache;
using LMP.Core.Youtube.Bridge.NToken;
using LMP.Core.Audio.Http;
using LMP.Core.Youtube.Bridge.SigCipher;
using LMP.Core.Youtube.Bridge.Common;
using LMP.UI.Features.Notifications;
using ReactiveUI.Avalonia;
using LMP.UI.Features.Queue;
using LMP.Core.Data.Entities;
using LMP.Core.Diagnostics;
namespace LMP;
/// <summary>
/// Точка входа в приложение Lite Music Player.
/// </summary>
public sealed class AppEntry
{
/// <summary>
/// Глобальный провайдер служб внедрения зависимостей.
/// </summary>
public static IServiceProvider Services { get; private set; } = null!;
/// <summary>
/// Флаг, указывающий, была ли выполнена инкрементальная миграция схемы с версии ниже v3 на старте этого запуска.
/// </summary>
public static bool WasMigratedFromLegacy { get; private set; }
[STAThread]
public static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.InputEncoding = System.Text.Encoding.UTF8;
SetupGlobalExceptionHandlers();
try
{
G.Folder.Create();
Log.Initialize();
Log.Info($"{G.AppId} starting...");
BootstrapSettings.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
Services = services.BuildServiceProvider();
LifecycleRegistry.Instance = Services.GetRequiredService<LifecycleRegistry>();
LifecycleRegistry.ActiveUiPageResolver = () =>
Services.GetService<MainWindowViewModel>()?.CurrentPage;
// Безопасная инициализация и автоматическая миграция БД
MigrateDatabaseSync();
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
catch (Exception ex)
{
Log.Fatal($"Global crash: {ex.Message}\n{ex.StackTrace}");
}
finally
{
Log.Shutdown();
}
}
/// <summary>
/// Выполняет инициализацию базы данных с поддержкой инкрементных миграций.
/// <para><b>Алгоритм:</b></para>
/// <list type="number">
/// <item>БД отсутствует → создать с нуля</item>
/// <item>Версия устарела → выполнить инкрементную миграцию</item>
/// <item>Миграция упала → backup + recreate как аварийный fallback</item>
/// <item>Версия актуальна → только оптимизация и проверка FTS</item>
/// </list>
/// </summary>
private static void MigrateDatabaseSync()
{
var dbPath = G.FilePath.Database;
if (!File.Exists(dbPath))
{
CreateFreshDatabase();
return;
}
int dbVersion = 0;
try
{
var dbFactory = Services.GetRequiredService<IDbContextFactory<LibraryDbContext>>();
using var ctx = dbFactory.CreateDbContext();
dbVersion = ctx.GetDatabaseVersionAsync(CancellationToken.None).GetAwaiter().GetResult();
if (dbVersion < DatabaseExtensions.CurrentDbVersion)
{
// Если старая версия базы данных была меньше v3 (в которой произошла крупная миграция плейлистов)
if (dbVersion < 3)
{
WasMigratedFromLegacy = true;
}
Log.Info($"[DB] Upgrading schema: v{dbVersion} -> v{DatabaseExtensions.CurrentDbVersion}");
ctx.Database.EnsureCreated();
ctx.MigrateSchemaAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.OptimizeAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.EnsureFtsTablesAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.SetDatabaseVersionAsync(DatabaseExtensions.CurrentDbVersion, CancellationToken.None).GetAwaiter().GetResult();
Log.Info($"[DB] Schema upgrade complete (Version: {DatabaseExtensions.CurrentDbVersion})");
}
else
{
ctx.Database.EnsureCreated();
ctx.OptimizeAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.EnsureFtsTablesAsync(CancellationToken.None).GetAwaiter().GetResult();
Log.Info($"[DB] Database schema is current (Version: {dbVersion})");
}
}
catch (Exception ex)
{
Log.Error($"[DB] Incremental migration from v{dbVersion} failed: {ex.Message}");
BackupAndRecreateDatabase(dbPath);
}
}
/// <summary>
/// Создаёт новую пустую базу данных.
/// Используется при первом запуске и после аварийного fallback-recreate.
/// </summary>
private static void CreateFreshDatabase()
{
try
{
var dbFactory = Services.GetRequiredService<IDbContextFactory<LibraryDbContext>>();
using var ctx = dbFactory.CreateDbContext();
ctx.Database.EnsureCreated();
ctx.MigrateSchemaAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.OptimizeAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.EnsureFtsTablesAsync(CancellationToken.None).GetAwaiter().GetResult();
ctx.SetDatabaseVersionAsync(DatabaseExtensions.CurrentDbVersion, CancellationToken.None).GetAwaiter().GetResult();
Log.Info($"[DB] Fresh database created (Version: {DatabaseExtensions.CurrentDbVersion})");
}
catch (Exception ex)
{
Log.Fatal($"[DB] Failed to create fresh database: {ex.Message}");
throw;
}
}
/// <summary>
/// Выполняет backup текущей БД и пересоздаёт её с нуля.
/// Вызывается только при неустранимой ошибке инкрементной миграции.
/// </summary>
private static void BackupAndRecreateDatabase(string dbPath)
{
try
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
GC.Collect();
GC.WaitForPendingFinalizers();
if (File.Exists(dbPath))
{
var backupPath = dbPath + $".backup.{DateTime.Now:yyyyMMddHHmmss}";
File.Move(dbPath, backupPath, overwrite: true);
Log.Info($"[DB] Incompatible database backed up to: {backupPath}");
}
var auth = Services.GetRequiredService<CookieAuthService>();
auth.Logout();
Log.Info("[DB] Authorization cleared after database recreation.");
}
catch (Exception backupEx)
{
Log.Error($"[DB] Failed to backup database before recreation: {backupEx.Message}");
}
try
{
CreateFreshDatabase();
SaveEmergencyNotification();
}
catch (Exception ex)
{
Log.Fatal($"[DB] Failed to recover database with a clean slate: {ex.Message}");
throw;
}
}
/// <summary>
/// Записывает локализованное уведомление о сбросе базы данных с использованием JSON-ключей
/// </summary>
private static void SaveEmergencyNotification()
{
try
{
var dbFactory = Services.GetRequiredService<IDbContextFactory<LibraryDbContext>>();
using var ctx = dbFactory.CreateDbContext();
var notification = new NotificationEntity
{
Id = Guid.NewGuid().ToString(),
TitleKey = "Dialog_Warning_Title", // "Предупреждение" / "Warning"
MessageKey = "Auth_ProfileLoadError_Message", // Сообщение об ошибке профиля/БД
RecommendationKey = "Recommendation_ContactDev", // "Обратитесь к разработчику"
Severity = (int)NotificationSeverity.Warning,
IsRead = false,
CreatedAt = DateTime.UtcNow
};
ctx.Notifications.Add(notification);
ctx.SaveChanges();
Log.Info("[DB] Emergency recovery notification saved to database using localization keys");
}
catch (Exception ex)
{
Log.Warn($"[DB] Failed to save emergency notification: {ex.Message}");
}
}
private static void SetupGlobalExceptionHandlers()
{
TaskScheduler.UnobservedTaskException += (_, e) =>
{
e.SetObserved();
try
{
var msg = e.Exception?.InnerException?.Message
?? e.Exception?.Message
?? "unknown";
Log.Debug($"[UnobservedTask] Suppressed: {msg}");
}
catch { }
};
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
try
{
if (e.ExceptionObject is Exception ex)
{
if (IsSslRelatedException(ex))
{
Log.Warn($"[AppDomain] SSL/TLS exception suppressed: {ex.Message}");
return;
}
Log.Error($"[AppDomain] Unhandled: {ex.Message}", ex);
}
else
{
Log.Error($"[AppDomain] Unhandled non-exception: {e.ExceptionObject}");
}
}
catch { }
};
}
private static bool IsSslRelatedException(Exception ex)
{
var current = ex;
while (current != null)
{
var typeName = current.GetType().FullName ?? "";
var msg = current.Message ?? "";
if (typeName.Contains("SslStream", StringComparison.Ordinal) ||
typeName.Contains("Ssl", StringComparison.OrdinalIgnoreCase) ||
typeName.Contains("Tls", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("SSL", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("TLS", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("secure channel", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("authentication", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("EnsureFullTlsFrame", StringComparison.Ordinal))
{
return true;
}
current = current.InnerException;
}
if (ex is AggregateException agg)
{
foreach (var inner in agg.InnerExceptions)
{
if (IsSslRelatedException(inner))
return true;
}
}
return false;
}
/// <summary>
/// Настраивает конфигурацию сборщика приложения Avalonia.
/// Выполняет условную настройку графического стека в зависимости от версии ОС.
/// </summary>
public static AppBuilder BuildAvaloniaApp()
{
BootstrapSettings.Initialize();
var gpuCacheBytes = BootstrapSettings.Current.GpuTextureCacheMb * 1024L * 1024L;
var builder = AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithInterFont()
.With(new SkiaOptions
{
MaxGpuResourceSizeBytes = gpuCacheBytes
});
// Windows 11 начинается со сборки 22000.
// Если это Windows, но версия сборки ниже 22000 — значит это Windows 10 или старше.
if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000))
{
Log.Info("[AppEntry] Windows 10 detected. Using RedirectionSurface to prevent dcomp.dll compositor crashes.");
builder.With(new Win32PlatformOptions
{
// Исключаем DirectComposition на Windows 10.
// RedirectionSurface рендерит окно через стандартный GDI-backbuffer, что обходит баги нативных аниматоров ОС.
CompositionMode =
[
Win32CompositionMode.RedirectionSurface
]
});
}
#if DEBUG
// Инициализируем наш Sink после создания приложения
builder.AfterSetup(_ =>
{
Avalonia.Logging.Logger.Sink = new AvaloniaCustomLogSink(Avalonia.Logging.LogEventLevel.Debug);
});
#endif
return builder.UseReactiveUI(_ => { });
}
private static void ConfigureServices(IServiceCollection services)
{
Log.Info("Configuring services...");
services.AddSingleton(_ => BootstrapSettings.Current);
var dbPath = G.FilePath.Database;
services.AddDbContextFactory<LibraryDbContext>(options =>
{
options.UseSqlite($"Data Source={dbPath};Cache=Shared");
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
#if DEBUG
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
#endif
});
services.AddSingleton<ITrackRepository, TrackRepository>();
services.AddSingleton<IPlaylistRepository, PlaylistRepository>();
services.AddSingleton<ISettingsRepository, SettingsRepository>();
services.AddSingleton<INotificationRepository, NotificationRepository>();
services.AddSingleton(sp =>
{
var trackRepo = sp.GetRequiredService<ITrackRepository>();
var playlistRepo = sp.GetRequiredService<IPlaylistRepository>();
var auth = sp.GetRequiredService<CookieAuthService>();
return new TrackRegistry(trackRepo, playlistRepo, auth);
});
services.AddSingleton<IAsyncImageLoader>(sp =>
new CachedImageLoader(sp.GetRequiredService<ImageCacheService>(), ImageQuality.Low));
services.AddSingleton<LibraryService>();
services.AddSingleton<ThemeManagerService>();
services.AddSingleton<CookieAuthService>();
services.AddSingleton<LocalAuthServer>();
services.AddSingleton<YoutubeProvider>();
services.AddTransient(sp => new Lazy<YoutubeProvider>(sp.GetRequiredService<YoutubeProvider>));
services.AddSingleton<YoutubeUserDataService>();
services.AddSingleton<MusicLibraryManager>();
services.AddSingleton<DialogHostViewModel>();
services.AddSingleton(sp =>
{
var auth = sp.GetRequiredService<CookieAuthService>();
var userData = sp.GetRequiredService<YoutubeUserDataService>();
var localServer = sp.GetRequiredService<LocalAuthServer>();
DialogHostViewModel GetDialogHost()
{
var mainWindow = sp.GetRequiredService<MainWindowViewModel>();
return mainWindow.DialogHost;
}
return new DialogService(auth, userData, localServer, GetDialogHost);
});
services.AddSingleton(_ => new PlayerContextManager(SharedHttpClient.Instance));
services.AddSingleton<JsDecryptionService>();
services.AddSingleton(sp =>
{
var jsService = sp.GetRequiredService<JsDecryptionService>();
return new NTokenDecryptor(jsService, G.FilePath.NTokenCache);
});
services.AddSingleton(sp =>
{
var jsService = sp.GetRequiredService<JsDecryptionService>();
return new SigCipherDecryptor(jsService, G.FilePath.SigCipherCache);
});
services.AddSingleton<PlaylistSyncService>();
services.AddSingleton<PlaylistEditService>();
services.AddSingleton<SearchCacheService>();
services.AddSingleton<ImageCacheService>();
services.AddSingleton<AudioCacheManager>();
services.AddSingleton<AudioEngine>();
services.AddSingleton<DownloadService>();
services.AddSingleton<NotificationService>();
services.AddTransient<NotificationButtonViewModel>();
services.AddTransient<NotificationPanelViewModel>();
services.AddTransient<ToastOverlayViewModel>();
services.AddSingleton<PlaybackErrorOrchestrator>();
services.AddSingleton<DominantColorService>();
services.AddSingleton<PlayerControlService>();
services.AddTransient<HomeViewModel>();
services.AddTransient<SearchViewModel>();
services.AddTransient<LibraryViewModel>();
services.AddTransient<QueueViewModel>();
services.AddTransient<SettingsViewModel>();
services.AddTransient<PlaylistViewModel>();
services.AddTransient<SyncSelectionViewModel>();
services.AddSingleton<LifecycleRegistry>();
services.AddSingleton<TrackViewModelFactory>();
services.AddSingleton<MainWindowViewModel>();
services.AddSingleton<PlayerBarViewModel>();
Log.Info("Services registered.");
}
}