Program.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. using Microsoft.AspNetCore.DataProtection;
  2. using Microsoft.AspNetCore.Http.Connections;
  3. using Microsoft.AspNetCore.Http.Features;
  4. using Microsoft.AspNetCore.ResponseCompression;
  5. using Microsoft.AspNetCore.Server.Kestrel.Core;
  6. using Microsoft.Extensions.DependencyInjection.Extensions;
  7. using NPOI.POIFS.Crypt;
  8. using OASystem.API.Middlewares;
  9. using OASystem.API.OAMethodLib;
  10. using OASystem.API.OAMethodLib.AMapApi;
  11. using OASystem.API.OAMethodLib.APNs;
  12. using OASystem.API.OAMethodLib.DeepSeekAPI;
  13. using OASystem.API.OAMethodLib.GenericSearch;
  14. using OASystem.API.OAMethodLib.Hotmail;
  15. using OASystem.API.OAMethodLib.Hub.Hubs;
  16. using OASystem.API.OAMethodLib.HunYuanAPI;
  17. using OASystem.API.OAMethodLib.JuHeAPI;
  18. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  19. using OASystem.API.OAMethodLib.Quartz.Jobs;
  20. using OASystem.API.OAMethodLib.SignalR.HubService;
  21. using OASystem.Infrastructure.Logging;
  22. using Quartz;
  23. using Quartz.Impl;
  24. using Quartz.Spi;
  25. using QuzrtzJob.Factory;
  26. using Serilog.Events;
  27. using System.IO.Compression;
  28. using TencentCloud.Common;
  29. using TencentCloud.Common.Profile;
  30. using TencentCloud.Hunyuan.V20230901;
  31. using static OASystem.API.Middlewares.RateLimitMiddleware;
  32. using OASystem.API.OAMethodLib.MicrosoftGraphMailbox;
  33. Console.Title = $"FMGJ OASystem Server";
  34. var builder = WebApplication.CreateBuilder(args);
  35. var basePath = AppContext.BaseDirectory;
  36. //寮曞叆閰嶇疆鏂囦欢
  37. var _config = new ConfigurationBuilder()
  38. .SetBasePath(basePath)
  39. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  40. .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
  41. .AddEnvironmentVariables()
  42. .Build();
  43. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  44. //璁剧疆璇锋眰鍙傛暟鍙�涓嶅~
  45. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  46. //璁剧疆璇锋眰鍙傛暟閿欒��榛樿�よ繑鍥炴牸寮�
  47. builder.Services.AddControllers()
  48. .ConfigureApiBehaviorOptions(options =>
  49. {
  50. options.InvalidModelStateResponseFactory = context =>
  51. {
  52. var errors = context.ModelState
  53. .Where(e => e.Value.Errors.Count > 0)
  54. .ToDictionary(
  55. kvp => kvp.Key,
  56. kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
  57. );
  58. var result = new JsonView
  59. {
  60. Code = 400,
  61. Msg = errors.FirstOrDefault().Value.FirstOrDefault() ?? "",
  62. Data = errors
  63. };
  64. return new BadRequestObjectResult(result);
  65. };
  66. });
  67. // Add services to the container.
  68. builder.Services.AddControllersWithViews();
  69. builder.Services.AddControllers()
  70. .AddJsonOptions(options =>
  71. {
  72. //绌哄瓧娈典笉鍝嶅簲Response
  73. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  74. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  75. //鏃堕棿鏍煎紡鍖栧搷搴�
  76. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  77. //decimal 鍥涗綅灏忔暟
  78. //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces)); // 灏嗕繚鐣欏皬鏁颁綅鏁板弬鏁颁紶閫掔粰鑷�瀹氫箟搴忓垪鍖栧櫒
  79. });
  80. builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  81. #region 娣诲姞闄愭祦涓�闂翠欢鏈嶅姟娉ㄥ唽
  82. // 娣诲姞鍐呭瓨缂撳瓨锛堥檺娴侀渶瑕侊級
  83. builder.Services.AddMemoryCache();
  84. // 閰嶇疆闄愭祦璁剧疆
  85. builder.Services.Configure<RateLimitConfig>(
  86. builder.Configuration.GetSection("RateLimiting"));
  87. #endregion
  88. #region Gzip
  89. builder.Services.AddResponseCompression(options =>
  90. {
  91. options.EnableForHttps = true;
  92. options.Providers.Add<GzipCompressionProvider>();
  93. });
  94. builder.Services.Configure<GzipCompressionProviderOptions>(options =>
  95. {
  96. options.Level = CompressionLevel.Optimal;
  97. });
  98. #endregion
  99. #region Cors
  100. builder.Services.AddCors(options =>
  101. {
  102. //policy.AddPolicy("Cors", opt => opt
  103. // //.SetIsOriginAllowed(origin =>
  104. // //{
  105. // // // 瀹氫箟鍏佽�哥殑鏉ユ簮鍒楄〃
  106. // // var allowedOrigins = new List<string>
  107. // // {
  108. // // "http://132.232.92.186:9002",
  109. // // "http://oa.pan-american-intl.com:4399"
  110. // // };
  111. // // // 妫€鏌ヨ�锋眰鐨勬潵婧愭槸鍚﹀湪鍏佽�哥殑鍒楄〃涓�
  112. // // return allowedOrigins.Contains(origin);
  113. // //})
  114. // //.AllowAnyOrigin()
  115. // //.AllowAnyHeader()
  116. // //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
  117. // //.AllowCredentials());
  118. // .AllowAnyHeader()
  119. // .AllowAnyMethod()
  120. // .AllowCredentials());
  121. options.AddPolicy("Cors", policy =>
  122. {
  123. policy.AllowAnyOrigin()
  124. .AllowAnyHeader()
  125. .AllowAnyMethod();
  126. });
  127. });
  128. #endregion
  129. #region 涓婁紶鏂囦欢
  130. builder.Services.AddCors(policy =>
  131. {
  132. policy.AddPolicy("Cors", opt => opt
  133. .AllowAnyOrigin()
  134. .AllowAnyHeader()
  135. .AllowAnyMethod()
  136. .WithExposedHeaders("X-Pagination"));
  137. });
  138. builder.Services.Configure<FormOptions>(options =>
  139. {
  140. options.KeyLengthLimit = int.MaxValue;
  141. options.ValueLengthLimit = int.MaxValue;
  142. options.MultipartBodyLengthLimit = int.MaxValue;
  143. options.MultipartHeadersLengthLimit = int.MaxValue;
  144. });
  145. builder.Services.Configure<KestrelServerOptions>(options =>
  146. {
  147. options.Limits.MaxRequestBodySize = int.MaxValue;
  148. options.Limits.MaxRequestBufferSize = int.MaxValue;
  149. });
  150. #endregion
  151. #region 鎺ュ彛鍒嗙粍
  152. var groups = new List<Tuple<string, string>>
  153. {
  154. //new Tuple<string, string>("Group1","鍒嗙粍涓€"),
  155. //new Tuple<string, string>("Group2","鍒嗙粍浜�")
  156. };
  157. #endregion
  158. #region 娉ㄥ叆鏁版嵁搴�
  159. #region old
  160. builder.Services.AddScoped(options =>
  161. {
  162. return new SqlSugarClient(new List<ConnectionConfig>()
  163. {
  164. new() {
  165. ConfigId = DBEnum.OA2023DB,
  166. ConnectionString = _config.GetConnectionString("OA2023DB"),
  167. DbType = DbType.SqlServer,
  168. IsAutoCloseConnection = true,
  169. },
  170. new()
  171. {
  172. ConfigId = DBEnum.OA2014DB,
  173. ConnectionString = _config.GetConnectionString("OA2014DB"),
  174. DbType = DbType.SqlServer,
  175. IsAutoCloseConnection = true },
  176. }
  177. , db =>
  178. {
  179. // SQL鎵ц�屽畬
  180. db.Aop.OnLogExecuted = (sql, pars) =>
  181. {
  182. // 瓒呰繃1绉�
  183. if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  184. {
  185. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  186. //鎵ц�屽畬浜嗗彲浠ヨ緭鍑篠QL鎵ц�屾椂闂� (OnLogExecutedDelegate)
  187. Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
  188. Console.WriteLine("MethodName:" + FirstMethodName);
  189. Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
  190. Console.WriteLine("ExecuteSQL:" + sql);
  191. }
  192. };
  193. //SQL鎵ц�屽墠
  194. db.Aop.OnLogExecuting = (sql, pars) =>
  195. {
  196. };
  197. //SQL鎶ラ敊
  198. db.Aop.OnError = (exp) =>
  199. {
  200. //鑾峰彇鍘熺敓SQL鎺ㄨ崘 5.1.4.63 鎬ц兘OK
  201. //UtilMethods.GetNativeSql(exp.Sql, exp.Parametres);
  202. //鑾峰彇鏃犲弬鏁癝QL瀵规€ц兘鏈夊奖鍝嶏紝鐗瑰埆澶х殑SQL鍙傛暟澶氱殑锛岃皟璇曚娇鐢�
  203. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  204. };
  205. //淇�鏀筍QL鍜屽弬鏁扮殑鍊�
  206. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  207. {
  208. //sql=newsql
  209. //foreach(var p in pars) //淇�鏀�
  210. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  211. };
  212. }
  213. );
  214. });
  215. #endregion
  216. #endregion
  217. //#region Identity 閰嶇疆
  218. //builder.Services.AddDataProtection();
  219. ////涓嶈�佺敤 AddIdentity 锛� AddIdentity 鏄�浜嶮VC妗嗘灦涓�鐨�
  220. //builder.Services.AddIdentityCore<User>(opt =>
  221. //{
  222. // opt.Password.RequireDigit = false; //鏁板瓧
  223. // opt.Password.RequireLowercase = false;//灏忓啓瀛楁瘝
  224. // opt.Password.RequireNonAlphanumeric = false;//鐗规畩绗﹀彿 渚嬪�� 锟�#@锛�
  225. // opt.Password.RequireUppercase = false; //澶у啓瀛楁瘝
  226. // opt.Password.RequiredLength = 6;//瀵嗙爜闀垮害 6
  227. // opt.Password.RequiredUniqueChars = 1;//鐩稿悓瀛楃�﹀彲浠ュ嚭鐜板嚑娆�
  228. // opt.Lockout.MaxFailedAccessAttempts = 5; //鍏佽�告渶澶氳緭鍏ヤ簲娆$敤鎴峰悕/瀵嗙爜閿欒��
  229. // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//閿佸畾浜斿垎閽�
  230. // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 淇�鏀瑰瘑鐮佷娇鐢ㄩ偖浠躲€愰獙璇佺爜妯″紡銆�
  231. // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
  232. //});
  233. //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
  234. //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
  235. //#endregion
  236. #region 娉ㄥ叆Swagger娉ㄩ噴(鍚�鐢�)
  237. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  238. {
  239. builder.Services.AddSwaggerGen(a =>
  240. {
  241. a.SwaggerDoc("v1", new OpenApiInfo
  242. {
  243. Version = "v1",
  244. Title = "Api",
  245. Description = "Api鎺ュ彛鏂囨。"
  246. });
  247. foreach (var item in groups)
  248. {
  249. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}鎺ュ彛鏂囨。" });
  250. }
  251. a.DocumentFilter<SwaggerApi>();
  252. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  253. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  254. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  255. {
  256. Description = "Value: Bearer {token}",
  257. Name = "Authorization",
  258. In = ParameterLocation.Header,
  259. Type = SecuritySchemeType.ApiKey,
  260. Scheme = "Bearer"
  261. });
  262. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  263. {{
  264. new OpenApiSecurityScheme
  265. {
  266. Reference = new OpenApiReference
  267. {
  268. Type = ReferenceType.SecurityScheme,
  269. Id = "Bearer"
  270. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  271. }
  272. });
  273. });
  274. }
  275. #endregion
  276. #region 娣诲姞鏍¢獙
  277. builder.Services.AddTransient<OASystemAuthentication>();
  278. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  279. .AddJwtBearer(options =>
  280. {
  281. options.TokenValidationParameters = new TokenValidationParameters
  282. {
  283. ValidateIssuer = true,
  284. ValidateAudience = true,
  285. ValidateLifetime = true,
  286. ValidateIssuerSigningKey = true,
  287. ValidAudience = "OASystem.com",
  288. ValidIssuer = "OASystem.com",
  289. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  290. ClockSkew = TimeSpan.FromSeconds(30), //杩囨湡鏃堕棿瀹归敊鍊硷紝瑙e喅鏈嶅姟鍣ㄧ��鏃堕棿涓嶅悓姝ラ棶棰橈紙绉掞級
  291. RequireExpirationTime = true,
  292. };
  293. options.Events = new JwtBearerEvents
  294. {
  295. OnMessageReceived = context =>
  296. {
  297. var path = context.HttpContext.Request.Path;
  298. //濡傛灉鏄痵ignalr璇锋眰锛岄渶瑕佸皢token杞�瀛橈紝鍚﹀垯JWT鑾峰彇涓嶅埌token銆侽PTIONS璇锋眰闇€瑕佽繃婊ゅ埌锛屽洜涓篛PTIONS璇锋眰鑾峰彇涓嶅埌Token锛岀敤NGINX杩囨护鎺塐PTION璇锋眰.
  299. if (path.StartsWithSegments("/ChatHub"))
  300. {
  301. string accessToken = context.Request.Query["access_token"].ToString();
  302. if (string.IsNullOrWhiteSpace(accessToken))
  303. {
  304. accessToken = context.Request.Headers["Authorization"].ToString();
  305. }
  306. context.Token = accessToken.Replace("Bearer ", "").Trim();
  307. }
  308. return Task.CompletedTask;
  309. }
  310. };
  311. });
  312. #endregion
  313. #region 鍒濆�嬪寲鏃ュ織
  314. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  315. Log.Logger = new LoggerConfiguration()
  316. //涓嶈�板綍瀹氭椂璁块棶API
  317. .Filter.ByIncludingOnly(logEvent =>
  318. {
  319. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  320. {
  321. var path = pathValue.ToString().Trim('"');
  322. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  323. }
  324. return true;
  325. })
  326. .MinimumLevel.Information()
  327. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  328. .MinimumLevel.Override("System", LogEventLevel.Warning)
  329. .Enrich.FromLogContext()
  330. .WriteTo.Console()
  331. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  332. .CreateLogger();
  333. //
  334. #region 鍑哄叆澧冭垂鐢ㄦ槑缁� 涓撶敤璁板綍鍣�
  335. // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
  336. var logDirectory = @"D:\OASystem\Logs\EnterExitCost";
  337. // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
  338. try
  339. {
  340. Directory.CreateDirectory(logDirectory);
  341. Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {logDirectory}");
  342. }
  343. catch (Exception ex)
  344. {
  345. Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {logDirectory}: {ex.Message}");
  346. throw;
  347. }
  348. var eec_TextLogger = new LoggerConfiguration()
  349. .MinimumLevel.Information()
  350. .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  351. .CreateLogger();
  352. #endregion
  353. #region 鍥㈢粍姝ラ�ゆ搷浣� 涓撶敤璁板綍鍣�
  354. // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
  355. var groupLogDir = @"D:\OASystem\Logs\GroupStepOP";
  356. // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
  357. try
  358. {
  359. Directory.CreateDirectory(groupLogDir);
  360. Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {groupLogDir}");
  361. }
  362. catch (Exception ex)
  363. {
  364. Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {groupLogDir}: {ex.Message}");
  365. throw;
  366. }
  367. var groupStepOP_TextLogger = new LoggerConfiguration()
  368. .MinimumLevel.Information()
  369. .WriteTo.File(Path.Combine(groupLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  370. .CreateLogger();
  371. #endregion
  372. #region 浠诲姟鍒嗛厤鎿嶄綔 涓撶敤璁板綍鍣�
  373. // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
  374. var taskLogDir = @"D:\OASystem\Logs\TaskAllocation";
  375. // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
  376. try
  377. {
  378. Directory.CreateDirectory(taskLogDir);
  379. Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {taskLogDir}");
  380. }
  381. catch (Exception ex)
  382. {
  383. Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {taskLogDir}: {ex.Message}");
  384. throw;
  385. }
  386. var task_TextLogger = new LoggerConfiguration()
  387. .MinimumLevel.Information()
  388. .WriteTo.File(Path.Combine(taskLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
  389. .CreateLogger();
  390. #endregion
  391. // 閰嶇疆Serilog涓篖og;
  392. builder.Host.UseSerilog();
  393. builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
  394. builder.Services.AddSingleton<IGroupTextFileLogger>(new GroupTextFileLogger(groupStepOP_TextLogger));
  395. builder.Services.AddSingleton<ITaskTextFileLogger>(new TaskTextFileLogger(task_TextLogger));
  396. #endregion
  397. #region 寮曞叆娉ㄥ唽Autofac Module
  398. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  399. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  400. {
  401. try
  402. {
  403. builder.RegisterModule(new AutofacRegister());
  404. }
  405. catch (Exception ex)
  406. {
  407. throw new Exception(ex.Message + "\n" + ex.InnerException);
  408. }
  409. });
  410. #endregion
  411. #region AutoMapper
  412. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  413. {
  414. cfg.AddProfile<_baseMappingProfile>();
  415. });
  416. builder.Services.AddSingleton(config);
  417. builder.Services.AddScoped<IMapper, Mapper>();
  418. #endregion
  419. #region DeepSeek AI 鏈嶅姟
  420. // 閰嶇疆HTTP瀹㈡埛绔�锛圖eepSeek 闀胯€楁椂璋冪敤锛岄粯璁� 10 鍒嗛挓锛�
  421. builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
  422. client.Timeout = TimeSpan.FromMinutes(10));
  423. #endregion
  424. #region Doubao API 鏈嶅姟
  425. var doubaoSetting = builder.Configuration.GetSection("DouBao").Get<OASystem.API.OAMethodLib.DoubaoAPI.DoubaoSetting>();
  426. builder.Services.AddSingleton(doubaoSetting);
  427. builder.Services.AddHttpClient("Doubao", c => c.BaseAddress = new Uri(doubaoSetting.BaseAddress));
  428. builder.Services.AddScoped<OASystem.API.OAMethodLib.DoubaoAPI.IDoubaoService, OASystem.API.OAMethodLib.DoubaoAPI.DoubaoService>();
  429. #endregion
  430. #region 鑱氬悎API 鏈嶅姟
  431. builder.Services.AddControllersWithViews();
  432. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  433. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  434. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  435. #endregion
  436. #region 浼佷笟寰�淇�API 鏈嶅姟
  437. builder.Services.AddControllersWithViews();
  438. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  439. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  440. #endregion
  441. #region 娣峰厓API
  442. // 浠庨厤缃�涓�璇诲彇鑵捐��浜戝瘑閽ヤ俊鎭�锛堣�风‘淇漚ppsettings.json涓�鏈夊�瑰簲閰嶇疆锛�
  443. var secretId = builder.Configuration["TencentCloud:SecretId"];
  444. var secretKey = builder.Configuration["TencentCloud:SecretKey"];
  445. var region = builder.Configuration["TencentCloud:Region"] ?? "ap-guangzhou";
  446. // 閰嶇疆HttpClientFactory锛圫DK鍐呴儴浼氱敤鍒帮級
  447. builder.Services.AddHttpClient();
  448. // 娉ㄥ唽鑵捐��浜慔unyuan Client涓篠ingleton锛堟帹鑽愶級
  449. builder.Services.AddSingleton(provider =>
  450. {
  451. Credential cred = new Credential
  452. {
  453. SecretId = secretId,
  454. SecretKey = secretKey
  455. };
  456. ClientProfile clientProfile = new ClientProfile();
  457. HttpProfile httpProfile = new HttpProfile
  458. {
  459. Endpoint = "hunyuan.tencentcloudapi.com",
  460. Timeout = 60 * 10, // 鍗曚綅绉�
  461. };
  462. clientProfile.HttpProfile = httpProfile;
  463. return new HunyuanClient(cred, region, clientProfile);
  464. });
  465. // 娉ㄥ唽鑷�瀹氫箟鏈嶅姟鎺ュ彛鍙婂叾瀹炵幇涓篠coped鐢熷懡鍛ㄦ湡
  466. builder.Services.AddScoped<IHunyuanService, HunyuanService>();
  467. // 娉ㄥ唽娣峰厓鏈嶅姟
  468. //builder.Services.AddHttpClient<IHunyuanService, HunyuanService>(client =>
  469. //{
  470. // client.BaseAddress = new Uri("https://hunyuan.ap-chengdu.tencentcloudapi.com/");
  471. // client.Timeout = TimeSpan.FromSeconds(60);
  472. //});
  473. //builder.Services.Configure<HunyuanApiSettings>(builder.Configuration.GetSection("HunyuanApiSettings"));
  474. #endregion
  475. #region 鏈夐亾API 鏈嶅姟
  476. //builder.Services.AddControllersWithViews();
  477. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  478. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  479. #endregion
  480. #region 楂樺痉鍦板浘API 鏈嶅姟
  481. builder.Services.AddHttpClient<GeocodeService>();
  482. #endregion
  483. #region 閫氱敤鎼滅储鏈嶅姟
  484. builder.Services.AddScoped(typeof(DynamicSearchService<>));
  485. #endregion
  486. #region Quartz
  487. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  488. builder.Services.AddSingleton<QuartzFactory>();
  489. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  490. builder.Services.AddSingleton<TaskJob>();
  491. builder.Services.AddSingleton<TaskNewsFeedJob>();
  492. builder.Services.AddSingleton<PerformanceJob>();
  493. builder.Services.AddSingleton<GroupProcessNodeJob>();
  494. builder.Services.AddSingleton<WeeklyFridayJob>();
  495. builder.Services.AddSingleton<ProcessAndNotifySummaryJob>();
  496. //# new business
  497. builder.Services.AddControllersWithViews();
  498. builder.Services.AddSingleton<IAPNsService, APNsService>();
  499. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  500. #endregion
  501. #region SignalR
  502. builder.Services.AddSignalR()
  503. .AddJsonProtocol(options =>
  504. {
  505. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  506. });
  507. builder.Services.TryAddSingleton(typeof(CommonService));
  508. #endregion
  509. #region hotmail
  510. builder.Services.AddScoped<HotmailService>();
  511. #endregion
  512. #region Microsoft Graph 閭�绠辨湇鍔�
  513. builder.Services.Configure<MicrosoftGraphMailboxOptions>(
  514. builder.Configuration.GetSection(MicrosoftGraphMailboxOptions.SectionName));
  515. builder.Services.AddHttpClient("MicrosoftGraph", c =>
  516. {
  517. c.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
  518. c.Timeout = TimeSpan.FromMinutes(2);
  519. });
  520. builder.Services.AddSingleton<IMicrosoftGraphMailboxService, MicrosoftGraphMailboxService>();
  521. #endregion
  522. var app = builder.Build();
  523. //// 1. 寮傚父澶勭悊鍣ㄥ簲璇ュ湪鏈€鏃╃殑浣嶇疆锛堥櫎浜嗘棩蹇楃瓑锛�
  524. //app.UseExceptionHandler(new ExceptionHandlerOptions
  525. //{
  526. // ExceptionHandlingPath = "/Home/Error",
  527. // AllowStatusCode404Response = true
  528. //});
  529. //鑷�瀹氫箟寮傚父涓�闂翠欢
  530. //app.UseMiddleware<ExceptionHandlingMiddleware>();
  531. //serilog鏃ュ織 璇锋眰涓�闂寸�¢亾
  532. app.UseSerilogRequestLogging(options =>
  533. {
  534. //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
  535. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  536. // 鑷�瀹氫箟鏃ュ織绾у埆
  537. options.GetLevel = (httpContext, elapsed, ex) =>
  538. {
  539. if (ex != null) return LogEventLevel.Error;
  540. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  541. // 瀵瑰仴搴锋�€鏌ョ瓑绔�鐐逛娇鐢ㄦ洿浣庣骇鍒�
  542. if (httpContext.Request.Path.StartsWithSegments("/health"))
  543. return LogEventLevel.Debug;
  544. return LogEventLevel.Information;
  545. };
  546. // 涓板瘜鏃ュ織涓婁笅鏂�
  547. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  548. {
  549. // 鑾峰彇瀹㈡埛绔疘P锛堝�勭悊浠g悊鎯呭喌锛�
  550. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  551. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  552. // 娣诲姞IP鍜屽叾浠栨湁鐢ㄤ俊鎭�鍒版棩蹇椾笂涓嬫枃
  553. diagnosticContext.Set("ClientIP", ipAddress);
  554. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  555. diagnosticContext.Set("UserAgent", userAgent);
  556. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  557. // 瀵逛簬API璇锋眰娣诲姞棰濆�栦俊鎭�
  558. if (httpContext.Request.Path.StartsWithSegments("/api"))
  559. {
  560. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  561. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  562. }
  563. };
  564. });
  565. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  566. // Configure the HTTP request pipeline.
  567. if (!app.Environment.IsDevelopment())
  568. {
  569. app.UseExceptionHandler("/Home/Error");
  570. }
  571. app.UseStaticFiles();
  572. app.UseRouting();
  573. app.UseCors("Cors"); //Cors
  574. //app.UseMiddleware<FixedPromptMiddleware>();
  575. // 瀹氫箟鍏佽�窤PI鐨勮�块棶鏃堕棿娈�
  576. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  577. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  578. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  579. //鎸囧畾API鎿嶄綔璁板綍淇℃伅
  580. app.UseMiddleware<RecordAPIOperationMiddleware>();
  581. app.UseAuthentication(); // 璁よ瘉
  582. app.UseMiddleware<RateLimitMiddleware>();
  583. app.UseAuthorization(); // 鎺堟潈
  584. app.UseWhen(context =>
  585. context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
  586. branch => branch.UseResponseCompression());
  587. // 鎺堟潈璺�寰�
  588. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  589. #region 鍚�鐢╯waggerUI
  590. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  591. {
  592. app.UseSwagger();
  593. app.UseSwaggerUI(c =>
  594. {
  595. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  596. foreach (var item in groups)
  597. {
  598. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  599. }
  600. c.RoutePrefix = string.Empty;
  601. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  602. c.DefaultModelsExpandDepth(-1);
  603. //c.EnableFilter();// 娣诲姞鎼滅储鍔熻兘
  604. //c.EnableDeepLinking(); // 鍚�鐢ㄦ繁搴﹂摼鎺�
  605. });
  606. }
  607. #endregion
  608. #region Quartz
  609. //鑾峰彇瀹瑰櫒涓�鐨凲uartzFactory
  610. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  611. app.Lifetime.ApplicationStarted.Register(async () =>
  612. {
  613. await quartz.Start();
  614. });
  615. app.Lifetime.ApplicationStopped.Register(() =>
  616. {
  617. //Quzrtz鍏抽棴鏂规硶
  618. //quartz.Stop();
  619. });
  620. #endregion
  621. #region SignalR
  622. app.MapHub<ChatHub>("/ChatHub", options =>
  623. {
  624. options.Transports =
  625. HttpTransportType.WebSockets |
  626. HttpTransportType.LongPolling;
  627. });
  628. #endregion
  629. app.MapControllerRoute(
  630. name: "default",
  631. pattern: "{controller=Home}/{action=Index}/{id?}");
  632. app.Run();