/
Startup.cs
259 lines (222 loc) · 9.25 KB
/
Startup.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
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
using System;
using System.IO;
using AutoMapper;
using AutoMapper.EquivalencyExpression;
using Hangfire;
using Hangfire.Dashboard;
using Hangfire.SQLite;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ombi.Core.Authentication;
using Ombi.Core.Settings;
using Ombi.DependencyInjection;
using Ombi.Helpers;
using Ombi.Mapping;
using Ombi.Schedule;
using Ombi.Settings.Settings.Models;
using Ombi.Store.Context;
using Ombi.Store.Entities;
using Ombi.Store.Repository;
using Serilog;
namespace Ombi
{
public class Startup
{
public static StoragePathSingleton StoragePath => StoragePathSingleton.Instance;
public Startup(IHostingEnvironment env)
{
Console.WriteLine(env.ContentRootPath);
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
//if (env.IsDevelopment())
//{
Serilog.ILogger config;
if (string.IsNullOrEmpty(StoragePath.StoragePath))
{
config = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "Logs", "log-{Date}.txt"))
.CreateLogger();
}
else
{
config = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(StoragePath.StoragePath, "Logs", "log-{Date}.txt"))
.CreateLogger();
}
Log.Logger = config;
//}
//if (env.IsProduction())
//{
// Log.Logger = new LoggerConfiguration()
// .MinimumLevel.Debug()
// .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "Logs", "log-{Date}.txt"))
// .WriteTo.SQLite("Ombi.db", "Logs", LogEventLevel.Debug)
// .CreateLogger();
//}
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<OmbiContext>();
services.AddIdentity<OmbiUser, IdentityRole>()
.AddEntityFrameworkStores<OmbiContext>()
.AddDefaultTokenProviders()
.AddUserManager<OmbiUserManager>();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 1;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.User.AllowedUserNameCharacters = string.Empty;
});
services.AddMemoryCache();
services.AddJwtAuthentication(Configuration);
services.AddMvc()
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddOmbiMappingProfile();
services.AddAutoMapper(expression =>
{
expression.AddCollectionMappers();
});
services.RegisterApplicationDependencies(); // Ioc and EF
services.AddSwagger();
services.AddAppSettingsValues(Configuration);
var i = StoragePathSingleton.Instance;
if (string.IsNullOrEmpty(i.StoragePath))
{
i.StoragePath = string.Empty;
}
var sqliteStorage = $"Data Source={Path.Combine(i.StoragePath, "Schedules.db")};";
services.AddHangfire(x =>
{
x.UseSQLiteStorage(sqliteStorage);
x.UseActivator(new IoCJobActivator(services.BuildServiceProvider()));
//x.UseConsole();
});
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// Build the intermediate service provider
return services.BuildServiceProvider();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
IMemoryCache cache, IServiceProvider serviceProvider)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
var ctx = serviceProvider.GetService<IOmbiContext>();
loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ConfigFile = "webpack.config.ts",
//EnvParam = new
//{
// aot = true // can't use AOT with HMR currently https://github.com/angular/angular-cli/issues/6347
//}
});
}
var ombiService =
app.ApplicationServices.GetService<ISettingsService<OmbiSettings>>();
var settings = ombiService.GetSettings();
if (settings.ApiKey.IsNullOrEmpty())
{
// Generate a API Key
settings.ApiKey = Guid.NewGuid().ToString("N");
ombiService.SaveSettings(settings);
}
// Check if it's in the startup args
var appConfig = serviceProvider.GetService<IApplicationConfigRepository>();
var baseUrl = appConfig.Get(ConfigurationTypes.BaseUrl);
if (baseUrl != null)
{
if (baseUrl.Value.HasValue())
{
settings.BaseUrl = baseUrl.Value;
ombiService.SaveSettings(settings);
}
}
if (settings.BaseUrl.HasValue())
{
app.UsePathBase(settings.BaseUrl);
}
app.UseHangfireServer(new BackgroundJobServerOptions { WorkerCount = 1, ServerTimeout = TimeSpan.FromDays(1), ShutdownTimeout = TimeSpan.FromDays(1)});
if (env.IsDevelopment())
{
app.UseHangfireDashboard(settings.BaseUrl.HasValue() ? $"{settings.BaseUrl}/hangfire" : "/hangfire",
new DashboardOptions
{
Authorization = new[] {new HangfireAuthorizationFilter()}
});
}
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 3 });
// Setup the scheduler
var jobSetup = app.ApplicationServices.GetService<IJobSetup>();
jobSetup.Setup();
ctx.Seed();
var settingsctx = serviceProvider.GetService<ISettingsContext>();
var externalctx = serviceProvider.GetService<IExternalContext>();
settingsctx.Seed();
externalctx.Seed();
var provider = new FileExtensionContentTypeProvider { Mappings = { [".map"] = "application/octet-stream" } };
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = provider,
});
app.UseAuthentication();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseMiddleware<ApiKeyMiddlewear>();
app.UseCors("MyPolicy");
//app.ApiKeyMiddlewear(app.ApplicationServices);
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
ombiService.Dispose();
}
}
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
return true;
}
}
}