-
-
Notifications
You must be signed in to change notification settings - Fork 462
/
WebApplicationLauncher.cs
231 lines (202 loc) · 6.97 KB
/
WebApplicationLauncher.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
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
using AssetRipper.GUI.Web.Pages;
using AssetRipper.GUI.Web.Pages.Settings;
using AssetRipper.Import.Logging;
using AssetRipper.Web.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System.CommandLine;
using System.Diagnostics;
namespace AssetRipper.GUI.Web;
public static class WebApplicationLauncher
{
private static class Defaults
{
public const int Port = 0;
public const bool LaunchBrowser = true;
}
public static void Launch(string[] args)
{
RootCommand rootCommand = new() { Description = "AssetRipper" };
Option<int> portOption = new Option<int>(
name: "--port",
description: "If nonzero, the application will attempt to host on this port, instead of finding a random unused port.",
getDefaultValue: () => Defaults.Port);
rootCommand.AddOption(portOption);
Option<bool> launchBrowserOption = new Option<bool>(
name: "--launch-browser",
description: "If true, a browser window will be launched automatically.",
getDefaultValue: () => Defaults.LaunchBrowser);
rootCommand.AddOption(launchBrowserOption);
bool shouldRun = false;
int port = Defaults.Port;
bool launchBrowser = Defaults.LaunchBrowser;
rootCommand.SetHandler((int portParsed, bool launchBrowserParsed) =>
{
shouldRun = true;
port = portParsed;
launchBrowser = launchBrowserParsed;
}, portOption, launchBrowserOption);
rootCommand.Invoke(args);
if (shouldRun)
{
Launch(port, launchBrowser);
}
}
public static void Launch(int port = Defaults.Port, bool launchBrowser = Defaults.LaunchBrowser)
{
WelcomeMessage.Print();
Logger.Add(new FileLogger());
Logger.LogSystemInformation("AssetRipper");
Logger.Add(new ConsoleLogger());
WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions()
{
#if DEBUG
EnvironmentName = Environments.Development,
#else
EnvironmentName = Environments.Production,
#endif
});
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
builder.Services.AddTransient<ErrorHandlingMiddleware>(static (_) => new());
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
builder.Logging.ConfigureLoggingLevel();
WebApplication app = builder.Build();
// Configure the HTTP request pipeline.
#if !DEBUG
app.UseMiddleware<ErrorHandlingMiddleware>();
#endif
if (launchBrowser)
{
app.Lifetime.ApplicationStarted.Register(() =>
{
string? address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();
if (address is not null)
{
OpenUrl(address);
}
});
}
//Static files
app.MapGet("/favicon.ico", async () =>
{
byte[] data = await StaticContentLoader.Load("favicon.ico");
return Results.Bytes(data, "image/x-icon");
});
app.MapGet("/css/site.css", async () =>
{
byte[] data = await StaticContentLoader.Load("css/site.css");
return Results.Bytes(data, "text/css");
});
app.MapGet("/js/site.js", async () =>
{
byte[] data = await StaticContentLoader.Load("js/site.js");
return Results.Bytes(data, "text/javascript");
});
//Normal Pages
app.MapGet("/", (context) =>
{
context.Response.DisableCaching();
return IndexPage.Instance.WriteToResponse(context.Response);
});
app.MapGet("/Commands", () => CommandsPage.Instance.ToResult());
app.MapGet("/Privacy", () => PrivacyPage.Instance.ToResult());
app.MapGet("/Licenses", () => LicensesPage.Instance.ToResult());
app.MapGet("/Settings/Edit", (context) =>
{
context.Response.DisableCaching();
return SettingsPage.Instance.WriteToResponse(context.Response);
});
app.MapPost("/Settings/Update", SettingsPage.HandlePostRequest);
app.MapPost("/Assets/View", Pages.Assets.ViewPage.HandlePostRequest);
app.MapPost("/Bundles/View", Pages.Bundles.ViewPage.HandlePostRequest);
app.MapPost("/Collections/View", Pages.Collections.ViewPage.HandlePostRequest);
app.MapPost("/Resources/View", Pages.Resources.ViewPage.HandlePostRequest);
app.MapPost("/Scenes/View", Pages.Scenes.ViewPage.HandlePostRequest);
app.MapPost("/Localization", (context) =>
{
context.Response.DisableCaching();
if (context.Request.Query.TryGetValue("code", out StringValues code))
{
string? language = code;
if (language is not null && LocalizationLoader.LanguageNameDictionary.ContainsKey(language))
{
Localization.LoadLanguage(language);
}
}
return Results.Redirect("/").ExecuteAsync(context);
});
//Commands
app.MapPost("/Export", Commands.HandleCommand<Commands.Export>);
app.MapPost("/LoadFile", Commands.HandleCommand<Commands.LoadFile>);
app.MapPost("/LoadFolder", Commands.HandleCommand<Commands.LoadFolder>);
app.MapPost("/Reset", Commands.HandleCommand<Commands.Reset>);
//Dialogs
app.MapGet("/Dialogs/SaveFile", Dialogs.SaveFile.HandleGetRequest);
app.MapGet("/Dialogs/OpenFolder", Dialogs.OpenFolder.HandleGetRequest);
app.MapGet("/Dialogs/OpenFile", Dialogs.OpenFile.HandleGetRequest);
app.MapGet("/Dialogs/OpenFiles", Dialogs.OpenFiles.HandleGetRequest);
app.Run();
}
private static ILoggingBuilder ConfigureLoggingLevel(this ILoggingBuilder builder)
{
builder.Services.Add(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(
new LifetimeOrWarnConfigureOptions()));
return builder;
}
private sealed class LifetimeOrWarnConfigureOptions : ConfigureOptions<LoggerFilterOptions>
{
public LifetimeOrWarnConfigureOptions() : base(AddRule)
{
}
private static void AddRule(LoggerFilterOptions options)
{
options.Rules.Add(new LoggerFilterRule(null, null, LogLevel.Information, static (provider, category, logLevel) =>
{
return category is "Microsoft.Hosting.Lifetime" || logLevel >= LogLevel.Warning;
}));
}
}
private static void OpenUrl(string url)
{
if (OperatingSystem.IsWindows())
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (OperatingSystem.IsLinux())
{
Process.Start("xdg-open", url);
}
else if (OperatingSystem.IsMacOS())
{
Process.Start("open", url);
}
}
private static void MapGet(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, Func<IResult> handler)
{
endpoints.MapGet(pattern, (context) =>
{
IResult result = handler.Invoke();
return result.ExecuteAsync(context);
});
}
private static void MapGet(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, Func<Task<IResult>> handler)
{
endpoints.MapGet(pattern, async (context) =>
{
IResult result = await handler.Invoke();
await result.ExecuteAsync(context);
});
}
}