using System.IO; using System.Net.Http; using System.Text; using System.Windows; using System.Windows.Threading; using Azaion.Annotator; using Azaion.Common; using Azaion.Common.Database; using Azaion.Common.DTO; using Azaion.Common.DTO.Config; using Azaion.Common.Events; using Azaion.Common.Extensions; using Azaion.Common.Services; using Azaion.Dataset; using CommandLine; using LibVLCSharp.Shared; using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Serilog; using KeyEventArgs = System.Windows.Input.KeyEventArgs; namespace Azaion.Suite; public partial class App { private IMediator _mediator = null!; private FormState _formState = null!; private IHost _host = null!; private static readonly Guid KeyPressTaskId = Guid.NewGuid(); private LoaderClient _loaderClient = null!; private readonly ICache _cache = new MemoryCache(); private readonly CancellationTokenSource _mainCTokenSource = new(); private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { Log.Logger.Error(e.Exception, "Unhandled exception"); e.Handled = true; } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.File( path: "Logs/log.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); Parser.Default.ParseArguments(e.Args) .WithParsed(Start) .WithNotParsed(ErrorHandling); } private void ErrorHandling(IEnumerable obj) { Log.Fatal($"Error happened: {string.Join(",", obj.Select(x => { if (x is MissingRequiredOptionError err) return $"{err.Tag} {err.NameInfo.NameText}"; return x.Tag.ToString(); } ))}"); Current.Shutdown(); } private Stream GetSystemConfig(LoaderClient loaderClient, string apiDir) { try { return loaderClient.LoadFile("config.system.json", apiDir); } catch (Exception e) { Log.Logger.Error(e, e.Message); return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { AnnotationConfig = Constants.DefaultAnnotationConfig, AIRecognitionConfig = Constants.DefaultAIRecognitionConfig, ThumbnailConfig = Constants.DefaultThumbnailConfig, }))); } } private Stream GetSecuredConfig(LoaderClient loaderClient, string apiDir) { try { return loaderClient.LoadFile("config.secured.json", apiDir); } catch (Exception e) { Log.Logger.Error(e, e.Message); throw; } } private void Start(ApiCredentials credentials) { try { new ConfigUpdater().CheckConfig(); var initConfig = SecurityConstants.ReadInitConfig(Log.Logger); var apiDir = initConfig.DirectoriesConfig.ApiResourcesDirectory; _loaderClient = new LoaderClient(initConfig.LoaderClientConfig, Log.Logger, _mainCTokenSource.Token); _loaderClient.StartClient(); _loaderClient.Connect(); _loaderClient.Login(credentials); var azaionApi = new AzaionApi(Log.Logger, new HttpClient { BaseAddress = new Uri(initConfig.InferenceClientConfig.ApiUrl) }, _cache, credentials); _host = Host.CreateDefaultBuilder() .ConfigureAppConfiguration((_, config) => config .AddCommandLine(Environment.GetCommandLineArgs()) .AddJsonFile(SecurityConstants.CONFIG_PATH, optional: true, reloadOnChange: true) .AddJsonStream(GetSystemConfig(_loaderClient, apiDir)) .AddJsonStream(GetSecuredConfig(_loaderClient, apiDir))) .UseSerilog() .ConfigureServices((context, services) => { services.AddSingleton(); services.Configure(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); services.ConfigureSection(context.Configuration); #region External Services services.ConfigureSection(context.Configuration); services.AddSingleton(_loaderClient); services.ConfigureSection(context.Configuration); services.AddSingleton(); services.AddSingleton(); services.ConfigureSection(context.Configuration); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddHttpClient(); services.AddSingleton(azaionApi); #endregion services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddMediatR(c => c.RegisterServicesFromAssemblies( typeof(Annotator.Annotator).Assembly, typeof(DatasetExplorer).Assembly, typeof(AnnotationService).Assembly)); services.AddSingleton(_ => new LibVLC()); services.AddSingleton(); services.AddSingleton(sp => { var libVLC = sp.GetRequiredService(); return new MediaPlayer(libVLC); }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); }) .Build(); Annotation.InitializeDirs(_host.Services.GetRequiredService>().Value); _host.Services.GetRequiredService(); // datasetExplorer.Show(); // datasetExplorer.Hide(); _mediator = _host.Services.GetRequiredService(); _formState = _host.Services.GetRequiredService(); DispatcherUnhandledException += OnDispatcherUnhandledException; _host.Start(); EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewKeyDownEvent, new RoutedEventHandler(GlobalKeyHandler)); _host.Services.GetRequiredService().Show(); } catch (Exception e) { Log.Logger.Error(e, e.Message); throw; } } private void GlobalKeyHandler(object sender, RoutedEventArgs e) { var args = (KeyEventArgs)e; var keyEvent = new KeyEvent(sender, args, _formState.ActiveWindow); ThrottleExt.Throttle(() => _mediator.Publish(keyEvent, _mainCTokenSource.Token), KeyPressTaskId, TimeSpan.FromMilliseconds(50)); //e.Handled = true; } protected override async void OnExit(ExitEventArgs e) { base.OnExit(e); _loaderClient.Stop(); _loaderClient.Dispose(); await _host.StopAsync(); } }