#region Usings using Mapster; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Roadie.Api.Hubs; using Roadie.Api.ModelBinding; using Roadie.Api.Services; using Roadie.Dlna.Services; using Roadie.Library.Caching; using Roadie.Library.Configuration; using Roadie.Library.Data.Context; using Roadie.Library.Data.Context.Implementation; using Roadie.Library.Encoding; using Roadie.Library.Engines; using Roadie.Library.Identity; using Roadie.Library.Imaging; using Roadie.Library.MetaData.Audio; using Roadie.Library.MetaData.FileName; using Roadie.Library.MetaData.ID3Tags; using Roadie.Library.MetaData.LastFm; using Roadie.Library.MetaData.MusicBrainz; using Roadie.Library.Processors; using Roadie.Library.Scrobble; using Roadie.Library.SearchEngines.Imaging; using Roadie.Library.SearchEngines.MetaData.Discogs; using Roadie.Library.SearchEngines.MetaData.Spotify; using Roadie.Library.SearchEngines.MetaData.Wikipedia; using Roadie.Library.Utility; using Serilog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; #endregion Usings namespace Roadie.Api { public class Startup { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; TypeAdapterConfig .NewConfig() .Map(i => i.ArtistId, src => src.Artist == null ? null : (Guid?)src.Artist.RoadieId) .Map(i => i.ReleaseId, src => src.Release == null ? null : (Guid?)src.Release.RoadieId) .Compile(); TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("CORSPolicy"); app.UseAuthorization(); app.UseAuthentication(); //app.UseSwagger(); //app.UseSwaggerUI(c => //{ // c.SwaggerEndpoint("/swagger/swagger.json", "Roadie API"); // c.RoutePrefix = string.Empty; //}); app.UseSerilogRequestLogging(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub("/playActivityHub"); endpoints.MapHub("/scanActivityHub"); endpoints.MapControllers(); }); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(options => { var logger = options.GetService>(); return new MemoryCacheManager(logger, new CachePolicy(TimeSpan.FromHours(4))); }); services.AddDbContextPool( options => options.UseMySql(_configuration.GetConnectionString("RoadieDatabaseConnection"), mySqlOptions => { mySqlOptions.ServerVersion(new Version(5, 5), ServerType.MariaDb); mySqlOptions.EnableRetryOnFailure( 10, TimeSpan.FromSeconds(30), null); } )); services.AddDbContextPool( options => options.UseMySql(_configuration.GetConnectionString("RoadieDatabaseConnection"), mySqlOptions => { mySqlOptions.ServerVersion(new Version(5, 5), ServerType.MariaDb); mySqlOptions.EnableRetryOnFailure( 10, TimeSpan.FromSeconds(30), null); } )); services.AddIdentity() .AddRoles() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); services.AddAuthorization(options => { options.AddPolicy("Admin", policy => policy.RequireRole("Admin")); options.AddPolicy("Editor", policy => policy.RequireRole("Admin", "Editor")); }); services.Configure(_configuration); var corsOrigins = (_configuration["CORSOrigins"] ?? "http://localhost:8080").Split('|'); Trace.WriteLine($"Setting Up CORS Policy [{string.Join(", ", corsOrigins)}]"); services.AddCors(options => options.AddPolicy("CORSPolicy", builder => { builder .WithOrigins(corsOrigins) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); })); services.AddSingleton(ctx => { var settings = new RoadieSettings(); var configuration = ctx.GetService(); configuration.GetSection("RoadieSettings").Bind(settings); var hostingEnvironment = ctx.GetService(); settings.ContentPath = hostingEnvironment.WebRootPath; settings.ConnectionString = _configuration.GetConnectionString("RoadieDatabaseConnection"); // This is so 'User Secrets' can be used in Debugging var integrationKeys = _configuration.GetSection("IntegrationKeys").Get(); if (integrationKeys != null) settings.Integrations.ApiKeys = new List { new ApiKey { ApiName = "LastFMApiKey", Key = integrationKeys.LastFMApiKey, KeySecret = integrationKeys.LastFMSecret }, new ApiKey { ApiName = "DiscogsConsumerKey", Key = integrationKeys.DiscogsConsumerKey, KeySecret = integrationKeys.DiscogsConsumerSecret }, new ApiKey { ApiName = "BingImageSearch", Key = integrationKeys.BingImageSearch } }; return settings; }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddSingleton(); var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(_configuration["Tokens:PrivateKey"])); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(config => { config.RequireHttpsMetadata = false; config.SaveToken = true; config.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = securityKey, ValidateAudience = true, ValidAudience = _configuration["Tokens:Audience"], ValidateIssuer = true, ValidIssuer = _configuration["Tokens:Issuer"], ValidateLifetime = true, ValidateIssuerSigningKey = true }; }); //services.AddSwaggerGen(c => //{ // c.SwaggerDoc("v1", new Info // { // Title = "Roadie API", // Version = "v1" // }); //}); services.AddSignalR(); services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; // false by default options.ModelBinderProviders.Insert(0, new SubsonicRequestBinderProvider()); }) .AddNewtonsoftJson(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }) .AddXmlSerializerFormatters(); services.Configure(options => { options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 1; }); services.AddHttpContextAccessor(); services.AddScoped(factory => { var actionContext = factory.GetService().ActionContext; if (actionContext == null) { return null; } return new HttpContext(factory.GetService(), new UrlHelper(actionContext)); }); var sp = services.BuildServiceProvider(); var adminService = sp.GetService(); adminService.PerformStartUpTasks(); } private class IntegrationKey { public string BingImageSearch { get; set; } public string DiscogsConsumerKey { get; set; } public string DiscogsConsumerSecret { get; set; } public string LastFMApiKey { get; set; } public string LastFMSecret { get; set; } } } }