-
Notifications
You must be signed in to change notification settings - Fork 2
/
Startup.cs
199 lines (177 loc) · 7.78 KB
/
Startup.cs
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
namespace Hst.Imager.GuiApp
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using ElectronNET.API;
using ElectronNET.API.Entities;
using Helpers;
using Core;
using Hst.Imager.Core.Helpers;
using Hst.Imager.Core.Models;
using Hubs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Middlewares;
using Models;
using Services;
using OperatingSystem = Hst.Core.OperatingSystem;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#if BACKEND
services.AddCors(options =>
{
options.AddPolicy("AllowLocalhost", builder =>
{
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();;
});
});
#endif
services.AddSignalR(o =>
{
o.EnableDetailedErrors = ApplicationDataHelper.HasDebugEnabled(Core.Models.Constants.AppName);
o.MaximumReceiveMessageSize = 1024 * 1024;
}).AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.Converters
.Add(new JsonStringEnumConverter());
});
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue>(new BackgroundTaskQueue(100));
services.AddHostedService<BackgroundTaskService>();
services.AddSingleton<IActiveBackgroundTaskList>(new ActiveBackgroundTaskList());
services.AddSingleton(new AppState
{
AppPath = AppContext.BaseDirectory,
LogsPath = Path.Combine(ApplicationDataHelper.GetApplicationDataDir(Core.Models.Constants.AppName), "logs"),
ExecutingFile = WorkerHelper.GetExecutingFile(),
IsLicenseAgreed = ApplicationDataHelper.IsLicenseAgreed(Core.Models.Constants.AppName),
IsAdministrator = OperatingSystem.IsAdministrator(),
IsElectronActive = HybridSupport.IsElectronActive,
UseFake = Debugger.IsAttached,
IsWindows = OperatingSystem.IsWindows(),
IsMacOs = OperatingSystem.IsMacOs(),
IsLinux = OperatingSystem.IsLinux()
});
services.AddSingleton<PhysicalDriveManagerFactory>();
services.AddSingleton<WorkerService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AppState appState, ILogger<Startup> logger)
{
var addresses = app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.ToList();
logger.LogDebug($"Addresses = '{string.Join(",", addresses)}'");
appState.BaseUrl = addresses.FirstOrDefault(x => x.StartsWith("https")) ?? addresses.FirstOrDefault();
logger.LogDebug($"Base url = '{appState.BaseUrl}'");
logger.LogDebug($"AppPath = '{appState.AppPath}'");
#if BACKEND
app.UseCors("AllowLocalhost");
#endif
app.UseMiddleware<ExceptionMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
#if (BACKEND == false)
app.UseSpaStaticFiles();
#endif
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ErrorHub>("/hubs/error");
endpoints.MapHub<ProgressHub>("/hubs/progress");
endpoints.MapHub<ShowDialogResultHub>("/hubs/show-dialog-result");
endpoints.MapHub<WorkerHub>("/hubs/worker");
endpoints.MapHub<ResultHub>("/hubs/result");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
#if (BACKEND == false)
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
Task.Run(() => ElectronBootstrap(appState.AppPath));
#endif
}
private async Task ElectronBootstrap(string appPath)
{
if (!HybridSupport.IsElectronActive)
{
return;
}
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Width = 1280,
Height = 720,
Center = true,
BackgroundColor = "#1A2933",
Frame = false,
WebPreferences = new WebPreferences
{
NodeIntegration = true,
},
Show = false,
Icon = Path.Combine(appPath, "ClientApp", "build", "icon.ico")
});
browserWindow.RemoveMenu();
await browserWindow.WebContents.Session.ClearCacheAsync();
browserWindow.OnClosed += () => Electron.App.Quit();
browserWindow.OnReadyToShow += () => browserWindow.Show();
browserWindow.OnMaximize += () => Electron.IpcMain.Send(browserWindow, "window-maximized");
browserWindow.OnUnmaximize += () => Electron.IpcMain.Send(browserWindow, "window-unmaximized");
var debugMode = (await ApplicationDataHelper.ReadSettings<Settings>(Core.Models.Constants.AppName))?.DebugMode ?? false;
if (ApplicationDataHelper.HasDebugEnabled(Core.Models.Constants.AppName) || debugMode)
{
browserWindow.WebContents.OpenDevTools();
}
await Electron.IpcMain.On("minimize-window", _ => browserWindow.Minimize());
await Electron.IpcMain.On("maximize-window", _ => browserWindow.Maximize());
await Electron.IpcMain.On("unmaximize-window", _ => browserWindow.Unmaximize());
await Electron.IpcMain.On("close-window", _ => browserWindow.Close());
}
}
}