-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
194 lines (170 loc) · 7.34 KB
/
Program.cs
File metadata and controls
194 lines (170 loc) · 7.34 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
using DD_Screen.Attributes;
using DD_Screen.DDBOT;
using DD_Screen.Middleware;
using DD_Screen.Timer;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.FileProviders;
using Microsoft.OpenApi;
using Serilog;
using Serilog.Events;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
namespace DD_Screen
{
public class Program
{
public static void Main(string[] args)
{
var baseDir = AppContext.BaseDirectory;
Directory.SetCurrentDirectory(baseDir);
var logDir = Path.Combine(baseDir, "logs");
var screenshotDir = Path.Combine(baseDir, "ScreenShotImg");
var chromeRootDir = Path.Combine(baseDir, "Chrome");
Directory.CreateDirectory(logDir);
Directory.CreateDirectory(screenshotDir);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}"
)
.WriteTo.File(
path: Path.Combine(logDir, "dd-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}"
)
.CreateLogger();
try
{
Log.Information("DD_Screen 启动中");
Log.Information("BaseDirectory: {BaseDirectory}", baseDir);
Log.Information("CurrentDirectory: {CurrentDirectory}", Directory.GetCurrentDirectory());
TimerManager.StartJob();
var options = new WebApplicationOptions
{
Args = args,
ContentRootPath = baseDir
};
var builder = WebApplication.CreateBuilder(options);
builder.Host.UseSerilog();
Config.ChromePath = builder.Configuration["ChromePath"];
Config.Headless = Convert.ToBoolean(builder.Configuration["Headless"]);
Config.Debug = builder.Configuration.GetValue("Debug", false);
if (string.IsNullOrWhiteSpace(Config.ChromePath))
{
if (Directory.Exists(chromeRootDir))
{
string chromeExecutable;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
chromeExecutable = "chrome.exe";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
chromeExecutable = "chrome";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
chromeExecutable = Path.Combine("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
}
else
{
throw new Exception("不支持的操作系统!");
}
Config.ChromePath = Path.Combine(chromeRootDir, chromeExecutable);
Log.Information("Chrome 路径: {ChromePath}", Config.ChromePath);
}
else
{
throw new Exception($"ChromePath 未配置, 且程序目录下未找到 Chrome 文件夹: {chromeRootDir}");
}
}
builder.Services.Configure<ForwardedHeadersOptions>(fho =>
{
fho.ForwardedHeaders = ForwardedHeaders.XForwardedFor
| ForwardedHeaders.XForwardedProto
| ForwardedHeaders.XForwardedHost;
fho.ForwardLimit = null;
fho.KnownNetworks.Clear();
fho.KnownProxies.Clear();
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSwaggerGen(c =>
{
c.OperationFilter<DisableableOperationFilter>();
c.DocumentFilter<DisableableDocumentFilter>();
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "DDBOT Rendering Service",
Version = "v1",
Description =
"一枝独秀不是春,万紫千红春满园。\n\n" +
"**搭配 DDBOT 使用**\n\n" +
"DDBOT 交流群:**980848391**"
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(baseDir, xmlFile);
c.IncludeXmlComments(xmlPath, false);
});
var app = builder.Build();
app.UseForwardedHeaders();
app.UseSwagger();
app.UseSwaggerUI(u =>
{
u.SwaggerEndpoint("/swagger/v1/swagger.json", "DD_Screen");
});
app.Lifetime.ApplicationStopping.Register(() =>
{
Log.Information("正在关闭浏览器...");
try
{
PupperManager.DisposeAsync().GetAwaiter().GetResult();
Log.Information("浏览器已关闭");
}
catch (Exception ex)
{
Log.Error(ex, "关闭浏览器失败");
}
});
app.UseRequestLogging();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Response.Redirect("/swagger/index.html");
}
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(screenshotDir),
RequestPath = "/ScreenShotImg"
});
app.UseRouting();
app.UseAuthorization();
app.UseDisableable();
app.MapControllers();
Log.Information("ScreenShotImg 目录: {ScreenShotDir}", screenshotDir);
Log.Information("DD_Screen 启动成功");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "DD_Screen 启动失败");
throw;
}
finally
{
Log.Information("DD_Screen 关闭中");
Log.CloseAndFlush();
}
}
}
}