-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathProgram.cs
More file actions
253 lines (205 loc) · 8.64 KB
/
Program.cs
File metadata and controls
253 lines (205 loc) · 8.64 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
using Helldivers.API.Configuration;
using Helldivers.API.Controllers;
using Helldivers.API.Controllers.V1;
using Helldivers.API.Middlewares;
using Helldivers.Core.Extensions;
using Helldivers.Models;
using Helldivers.Models.Domain.Localization;
using Helldivers.Sync.Configuration;
using Helldivers.Sync.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Timeouts;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Localization;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System.Globalization;
using System.Net;
using System.Text.Json.Serialization;
using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
#if DEBUG
// When generating an OpenAPI document, get-document runs with the "--applicationName" flag.
// While detecting it this way isn't the 'prettiest' way, we *need* this information for following reasons:
// We don't want to start background services for sync etc when this flag is active
// And we *only* want to include OpenAPI generation stuff when this flag is active.
var isRunningAsTool = args.FirstOrDefault(arg => arg.StartsWith("--applicationName")) is not null;
#endif
var builder = WebApplication.CreateSlimBuilder(args);
// Registers the core services in the container.
builder.Services.AddHelldivers();
// Have ASP.NET Core generate problemdetails for failed requests.
builder.Services.AddProblemDetails();
// Register the rate limiting middleware.
builder.Services.AddTransient<RateLimitMiddleware>();
// Register the memory cache, used in the rate limiting middleware.
builder.Services.AddMemoryCache();
// Add services for response compression.
builder.Services.AddResponseCompression();
// Automatically set the CultureInfo based on the incoming request.
builder.Services.AddRequestLocalization(options =>
{
var defaultLanguage = builder
.Configuration
.GetSection("Helldivers:Synchronization:DefaultLanguage")
.Get<string>();
var languages = builder
.Configuration
.GetSection("Helldivers:Synchronization:Languages")
.Get<List<string>>()!;
// Set the configured default language to be used by the LocalizedMessage class.
LocalizedMessage.FallbackCulture = new CultureInfo(defaultLanguage ?? "en-US");
options.ApplyCurrentCultureToResponseHeaders = true;
options.DefaultRequestCulture = new RequestCulture(LocalizedMessage.FallbackCulture);
options.SupportedCultures = languages.Select(iso => new CultureInfo(iso)).ToList();
options.SupportedCultures.Add(LocalizedMessage.InvariantCulture);
options.SupportedUICultures = options.SupportedCultures;
});
// Set CORS headers for websites directly accessing the API.
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy => policy
.AllowAnyOrigin()
.AllowAnyMethod()
);
});
// Add and configure forwarded headers middleware
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardLimit = 999;
options.OriginalForHeaderName = "Fly-Client-IP";
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor;
options.KnownNetworks.Add(new IPNetwork(IPAddress.Any, 0));
options.KnownNetworks.Add(new IPNetwork(IPAddress.IPv6Any, 0));
});
// This configuration is bound here so that source generators kick in.
builder.Services.Configure<ApiConfiguration>(builder.Configuration.GetSection("Helldivers:API"));
builder.Services.Configure<HelldiversSyncConfiguration>(builder.Configuration.GetSection("Helldivers:Synchronization"));
// If a request takes over 10s to complete, abort it.
builder.Services.AddRequestTimeouts(options =>
{
options.DefaultPolicy = new RequestTimeoutPolicy
{
Timeout = TimeSpan.FromSeconds(10),
TimeoutStatusCode = StatusCodes.Status408RequestTimeout,
};
});
// Setup source generated JSON type information so the API knows how to serialize models.
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Add(ArrowHeadSerializerContext.Default);
options.SerializerOptions.TypeInfoResolverChain.Add(SteamSerializerContext.Default);
options.SerializerOptions.TypeInfoResolverChain.Add(V1SerializerContext.Default);
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
#if DEBUG
IdentityModelEventSource.ShowPII = true;
#endif
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
var config = new AuthenticationConfiguration();
builder.Configuration.GetSection("Helldivers:API:Authentication").Bind(config);
options.TokenValidationParameters = new()
{
ValidIssuers = config.ValidIssuers,
ValidAudiences = config.ValidAudiences,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(config.SigningKey)),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
builder.Services.AddAuthorization();
// Swagger is generated at compile time, so we don't include Swagger dependencies in Release builds.
#if DEBUG
// Only add OpenApi dependencies when generating
if (isRunningAsTool)
{
builder.Services.AddOpenApiDocument(document =>
{
document.Title = "Helldivers 2";
document.Description = "Helldivers 2 Unofficial API";
var languages = builder
.Configuration
.GetSection("Helldivers:Synchronization:Languages")
.Get<List<string>>()!;
document.SchemaSettings.TypeMappers.Add(
new Helldivers.API.OpenApi.TypeMappers.LocalizedMessageTypeMapper(languages)
);
document.DocumentProcessors.Add(new Helldivers.API.OpenApi.DocumentProcessors.HelldiversDocumentProcessor());
});
builder.Services.AddOpenApiDocument(document =>
{
document.Title = "ArrowHead API";
document.Description = "An OpenAPI mapping of the official Helldivers API";
document.DocumentName = "arrowhead";
document.ApiGroupNames = ["arrowhead"];
document.DocumentProcessors.Add(new Helldivers.API.OpenApi.DocumentProcessors.ArrowHeadDocumentProcessor());
});
builder.Services.AddEndpointsApiExplorer();
}
else
{
builder.Services.AddHelldiversSync();
}
#else
// in Release builds we *always* run the sync services
builder.Services.AddHelldiversSync();
#endif
var app = builder.Build();
// Use response compression for smaller payload sizes
app.UseResponseCompression();
// Enable static file host in case the application was built with OpenAPI specifications publicly available (Docker)
if (Directory.Exists(app.Environment.WebRootPath))
app.UseStaticFiles();
// select the correct culture for incoming requests
app.UseRequestLocalization();
// Ensure web applications can access the API by setting CORS headers.
app.UseCors();
// Make sure ASP.NET Core uses the correct addresses internally rather than Fly's proxy
app.UseForwardedHeaders();
// Handles rate limiting so everyone plays nice
app.UseMiddleware<RateLimitMiddleware>();
// Add middleware to timeout requests if they take too long.
app.UseRequestTimeouts();
#region API dev
#if DEBUG
var dev = app
.MapGroup("/dev")
.WithGroupName("development")
.WithTags("dev")
.ExcludeFromDescription();
dev.MapGet("/token", DevelopmentController.CreateToken);
#endif
#endregion
#region ArrowHead API endpoints ('raw' API)
var raw = app
.MapGroup("/raw")
.WithGroupName("arrowhead")
.WithTags("raw");
raw.MapGet("/api/WarSeason/current/WarID", ArrowHeadController.WarId);
raw.MapGet("/api/WarSeason/801/Status", ArrowHeadController.Status);
raw.MapGet("/api/WarSeason/801/WarInfo", ArrowHeadController.WarInfo);
raw.MapGet("/api/Stats/war/801/summary", ArrowHeadController.Summary);
raw.MapGet("/api/NewsFeed/801", ArrowHeadController.NewsFeed);
raw.MapGet("/api/v2/Assignment/War/801", ArrowHeadController.Assignments);
#endregion
#region API v1
var v1 = app
.MapGroup("/api/v1")
.WithGroupName("community")
.WithTags("v1");
v1.MapGet("/war", WarController.Show);
v1.MapGet("/assignments", AssignmentsController.Index);
v1.MapGet("/assignments/{index:long}", AssignmentsController.Show);
v1.MapGet("/campaigns", CampaignsController.Index);
v1.MapGet("/campaigns/{index:int}", CampaignsController.Show);
v1.MapGet("/dispatches", DispatchController.Index);
v1.MapGet("/dispatches/{index:int}", DispatchController.Show);
v1.MapGet("/planets", PlanetController.Index);
v1.MapGet("/planets/{index:int}", PlanetController.Show);
v1.MapGet("/planet-events", PlanetController.WithEvents);
v1.MapGet("/steam", SteamController.Index);
v1.MapGet("/steam/{gid}", SteamController.Show);
#endregion
await app.RunAsync();