-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
340 lines (291 loc) · 12.1 KB
/
Program.cs
File metadata and controls
340 lines (291 loc) · 12.1 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
using System.Diagnostics;
using MARS.Server.CustomLoggers.DatabaseLogger;
using MARS.Server.CustomLoggers.SignalRLogger;
using MARS.Server.CustomLoggers.TelegramLogger;
using MARS.Server.Services.CinemaQueue;
using MARS.Server.Services.CommandExecutor;
using MARS.Server.Services.Configuration;
using MARS.Server.Services.KeyboardHook_UNUSED;
using MARS.Server.Services.Logs.Interfaces;
using MARS.Server.Services.Logs.Services;
using MARS.Server.Services.MemoryStorageService;
using MARS.Server.Services.Twitch;
using MARS.Server.Services.Twitch.Rewards;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.Swagger;
namespace MARS.Server;
public static class Program
{
public static bool IsUseSoundRequest { get; set; }
public static bool IsUseSwagger { get; set; }
private const string GenerateOpenApiArgument = "--generate-openapi";
public static async Task Main(string[] args)
{
var shouldGenerateOpenApi = args.Any(arg =>
arg.Equals(GenerateOpenApiArgument, StringComparison.OrdinalIgnoreCase)
);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
var services = builder.Services;
var configuration = builder.Configuration;
var directory = AppDomain.CurrentDomain.BaseDirectory;
var isSpa =
!builder.Environment.IsProduction()
&& Convert.ToBoolean(
Environment.GetEnvironmentVariable("ASPNETCORE_SPA_LAUNCH") ?? string.Empty
);
var contextFactory = new AppDbContextFactory(options =>
{
options.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll);
options.EnableThreadSafetyChecks();
if (builder.Environment.IsDevelopment())
{
options.EnableDetailedErrors();
options.EnableSensitiveDataLogging();
options.UseNpgsql(configuration.GetConnectionString("Dev_Path"));
}
else
{
options.UseNpgsql(configuration.GetConnectionString("Prod_Path"));
}
});
StaticDbContextFactory.Factory = contextFactory;
//Twitch
var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
if (builder.Environment.IsDevelopment())
{
//loggingBuilder.SetMinimumLevel(LogLevel.Trace);
loggingBuilder.AddConsole();
loggingBuilder.SetMinimumLevel(LogLevel.Trace);
}
else
{
loggingBuilder.AddConsole();
if (OperatingSystem.IsWindows())
{
loggingBuilder.AddEventLog();
}
loggingBuilder.SetMinimumLevel(LogLevel.Information);
}
var telegramConfiguration = new TelegramConfiguration();
configuration
.GetSection(AppBase.Base)
.GetSection(TelegramConfiguration.TelegramSection)
.Bind(telegramConfiguration);
var botConfiguration = new BotConfiguration();
configuration
.GetSection(AppBase.Base)
.GetSection(TelegramConfiguration.TelegramSection)
.GetSection(BotConfiguration.Configuration)
.Bind(botConfiguration);
loggingBuilder.AddTelegramLogger(options =>
{
options.BotToken = botConfiguration.BotToken;
options.ChatId = telegramConfiguration.AdminIdsArray;
options.SourceName = "BOT";
options.MinimumLevel = LogLevel.Warning;
});
loggingBuilder.AddDbLogger(() =>
{
var options = new DbContextOptionsBuilder<LoggerDbContext>();
return new DbLoggerOptions
{
Factory = new LoggerDbContextFactory(
(contextOptionsBuilder) =>
{
contextOptionsBuilder.UseQueryTrackingBehavior(
QueryTrackingBehavior.NoTracking
);
contextOptionsBuilder.EnableThreadSafetyChecks();
if (builder.Environment.IsDevelopment())
{
contextOptionsBuilder.UseNpgsql(
configuration.GetConnectionString("Dev_Path")
);
contextOptionsBuilder.EnableDetailedErrors();
contextOptionsBuilder.EnableSensitiveDataLogging();
}
else
{
contextOptionsBuilder.UseNpgsql(
configuration.GetConnectionString("Prod_Path")
);
}
}
),
MinimumLogLevel = builder.Environment.IsProduction()
? LogLevel.Warning
: LogLevel.Information,
Environment = builder.Environment,
};
});
// Добавляем SignalR логгер
loggingBuilder.AddSignalRLogger(options =>
{
options.MinimumLogLevel = builder.Environment.IsProduction()
? LogLevel.Warning
: LogLevel.Information;
options.SourceName = "MARS.Server";
options.IncludeExceptions = true;
options.IncludeStackTrace = true;
options.MaxMessageLength = 2000;
// Исключаем некоторые категории для уменьшения шума
options.ExcludedCategories =
[
"Microsoft.AspNetCore.Hosting.Diagnostics",
"Microsoft.AspNetCore.Routing.EndpointMiddleware",
"Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
];
});
});
if (builder.Environment.IsProduction() && OperatingSystem.IsWindows())
{
var curPath = Directory.GetCurrentDirectory();
var servicePath = curPath.Contains("C:")
? Environment.GetEnvironmentVariable(
"ZYZ_SERVICE_PATH",
EnvironmentVariableTarget.Machine
)
: curPath;
if (string.IsNullOrWhiteSpace(servicePath))
{
throw new NullReferenceException();
}
directory = servicePath;
Environment.CurrentDirectory = directory;
}
/////////////////////////////////////////////////////////////////////////////////////////
services
.AddTwitchServices(configuration)
.AddHostedService<TwitchUserSyncService>()
.AddCommandExecutorServices()
.AddTelegramThings(loggerFactory)
.AddConfiguration(configuration)
.AddBaseAspNetMiddlewares(configuration)
.AddSwaggerServices()
.AddCinemaQueueServicesAsSingleton()
.AddGameServices()
.AddExternalApiServices()
.AddSpecializedServices()
.AddSoundRequest();
services.AddSingleton<IDbContextFactory<AppDbContext>>(contextFactory);
services.AddHostedService<ConfigurationKeysBootstrapHostedService>();
services.AddWindowsService(options =>
{
options.ServiceName = "!Zyz";
});
services.AddSingleton<AnswersForTwitchRewards>();
// WTelegramClient registration moved to StartupExtensions.AddTelegramThings()
// Добавляем сервис архивирования потоков
//services.AddSingleton<IFFmpegService, FFmpegService>();
//services.AddSingleton<IStreamArchiveService, StreamArchiveService>();
//services.AddHostedService<StreamArchiveWorker>();
services.AddSingleton(loggerFactory);
// Добавляем сервис перехвата клавиатуры
services.AddKeyboardHookService();
// Добавляем сервис для работы с логами
services.AddScoped<LoggerDbContext>(sp =>
{
var options = new DbContextOptionsBuilder<LoggerDbContext>();
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
options.EnableThreadSafetyChecks();
if (builder.Environment.IsDevelopment())
{
options.UseNpgsql(configuration.GetConnectionString("Dev_Path"));
options.EnableDetailedErrors();
options.EnableSensitiveDataLogging();
}
else
{
options.UseNpgsql(configuration.GetConnectionString("Prod_Path"));
}
return new LoggerDbContext(options.Options);
});
services.AddScoped<ILogsService, LogsService>();
services.AddMvc();
builder.AddStaticFilesBrowserOptions();
var app = builder.Build();
var logger = app.Logger;
if (shouldGenerateOpenApi)
{
await GenerateOpenApiFilesAsync(app);
return;
}
app.AddStaticFilesBrowser();
if (IsUseSwagger)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "ui";
c.SwaggerEndpoint("/swagger/api/swagger.json", "API");
c.SwaggerEndpoint("/swagger/hubs/swagger.json", "Hubs");
c.DocumentTitle = "SWAGGER SCHEMA";
});
}
app.UseCors("CorsPolicy");
app.MapHub<TelegramusHub>("/hubs/telegramus");
app.MapHub<TunaHub>("/hubs/tuna");
//app.MapHub<SoundBarHub>("/hubs/soundbar");
app.MapHub<ScoreboardHub>("/hubs/scoreboard");
app.AddLogerHub();
if (IsUseSoundRequest)
{
app.MapHub<SoundRequestHub>("/hubs/soundrequest");
}
app.UseRouting();
app.MapControllers();
if (isSpa)
{
app.UseSpaYarp();
}
else
{
app.MapFallbackToFile("index.html");
}
try
{
var cp = Process.GetCurrentProcess();
cp.PriorityClass = ProcessPriorityClass.RealTime;
var appLifeTime = app.Services.GetRequiredService<IHostApplicationLifetime>();
appLifeTime.ApplicationStopping.Register(MemoryStorage.ClearStorage);
await app.RunAsync();
}
catch (Exception e)
{
logger.LogException(e);
}
}
private static async Task GenerateOpenApiFilesAsync(WebApplication app)
{
var outputDirectory = Path.GetFullPath(
Path.Combine(app.Environment.ContentRootPath, "..", "mars.client", "api")
);
Directory.CreateDirectory(outputDirectory);
var swaggerProvider = app.Services.GetRequiredService<ISwaggerProvider>();
var apiDocument = swaggerProvider.GetSwagger("api");
var hubsDocument = swaggerProvider.GetSwagger("hubs");
await WriteSwaggerDocumentAsync(
Path.Combine(outputDirectory, "swagger_api.json"),
apiDocument
);
await WriteSwaggerDocumentAsync(
Path.Combine(outputDirectory, "swagger_hubs.json"),
hubsDocument
);
Console.WriteLine(
$"OpenAPI schema generated: {Path.Combine(outputDirectory, "swagger_api.json")}"
);
Console.WriteLine(
$"OpenAPI schema generated: {Path.Combine(outputDirectory, "swagger_hubs.json")}"
);
}
private static async Task WriteSwaggerDocumentAsync(string filePath, OpenApiDocument document)
{
await using var stream = File.Create(filePath);
await using var writer = new StreamWriter(stream, new System.Text.UTF8Encoding(false));
var jsonWriter = new OpenApiJsonWriter(writer);
document.SerializeAsV3(jsonWriter);
await writer.FlushAsync();
}
}