using DiwanRazor.Utils; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Net.Http.Headers; using System; using System.IO; using System.IO.Compression; using System.Text.Encodings.Web; using System.Text.Unicode; namespace DiwanRazor { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); services.AddMemoryCache(); services.AddScoped(); // Compresses the HTML/JSON responses themselves (independent of the output cache // below - this runs on every response, cached or not). Persian poem text compresses // very well, so this cuts outbound bandwidth with no effect on freshness at all. services.AddResponseCompression(options => { options.EnableForHttps = true; options.Providers.Add(); options.Providers.Add(); }); services.Configure(options => { options.Level = CompressionLevel.Fastest; }); services.Configure(options => { options.Level = CompressionLevel.Fastest; }); // Server-side output cache for the public content pages. Only ever serves a cached // response to requests that carry none of the personalization cookies - see // AnonymousPageOutputCachePolicy for why that's the safe boundary. This is what // actually avoids re-hitting the Diwan API on every repeat/bot visit to the same // poem/poet/category URL. // // Registered via the (string, IOutputCachePolicy) overload directly - the // OutputCachePolicyBuilder.AddPolicy(IOutputCachePolicy) overload used to attach a // custom policy from inside a builder lambda is internal to ASP.NET Core, not public // (see dotnet/aspnetcore#55809), so it can't be called from application code. services.AddOutputCache(options => { options.AddPolicy("DiwanPublicPage", AnonymousPageOutputCachePolicy.Instance); }); services.AddSingleton( HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin, UnicodeRanges.Arabic })); services.AddRazorPages(options => { options.Conventions.AddPageRoute("/DiwanPage", "{*url}"); // Pages/ reorganization: these pages moved into subfolders (Auth/, SongRecommendation/, // ImageRecommendation/, Recitations/, CommentReports/, Misc/) for readability, but each // one used a bare `@page` (no explicit route), so without these overrides their public // URL would change from the flat form (e.g. "/Login") to the new nested form // (e.g. "/Auth/Login"). None of these pages are referenced via asp-page/RedirectToPage // anywhere in the app (checked), only via plain hrefs and JS-embedded URLs, so // preserving the URL here is sufficient - no other code needed to change. options.Conventions.AddPageRoute("/Auth/Login", "/Login"); options.Conventions.AddPageRoute("/Auth/SignUp", "/SignUp"); options.Conventions.AddPageRoute("/Auth/ResetPassword", "/ResetPassword"); options.Conventions.AddPageRoute("/Recitations/AudioClip", "/AudioClip"); options.Conventions.AddPageRoute("/Recitations/RecitationsOrder", "/RecitationsOrder"); options.Conventions.AddPageRoute("/Recitations/ReportRecitation", "/ReportRecitation"); options.Conventions.AddPageRoute("/CommentReports/ReportComment", "/ReportComment"); options.Conventions.AddPageRoute("/Misc/Photos", "/Photos"); options.Conventions.AddPageRoute("/Misc/t6e", "/t6e"); }); // The antiforgery token bk.js's $.ajax POST/PUT/DELETE calls carry, as a request // header rather than a form field (there's no
around most of these calls). // The token value itself is rendered into each page as a // tag (see _Layout.cshtml / _UserPanelLayout.cshtml / _AdminLayout.cshtml), and // bk.js reads it once and attaches it to every AJAX request via $.ajaxSetup. services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN"; }); services.AddCors(options => { options.AddPolicy(name: "DiwanCorsPolicy", policy => { policy.WithOrigins("https://museum.ganjoor.net", "https://naskban.ir", "http://localhost:5173" ); }); }); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Configuration["DataProtectionPersistPath"])) .SetApplicationName("DiwanRazor"); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Must run before anything writes to the response body. app.UseResponseCompression(); app.UseCors("DiwanCorsPolicy"); app.UseExceptionHandler("/Error"); app.UseStatusCodePagesWithReExecute("/errors/{0}"); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { var path = ctx.Context.Request.Path.Value ?? ""; var isExplicitlyVersioned = ctx.Context.Request.Query.ContainsKey("version") || ctx.Context.Request.Query.ContainsKey("v"); // /lib and /dist are third-party vendor code (jQuery, Bootstrap, TinyMCE, diff.js, // the jPlayer skin) that isn't hand-edited, so it's safe to treat the same as // explicitly-versioned assets even without a query string. var isVendorPath = path.StartsWith("/lib/", StringComparison.OrdinalIgnoreCase) || path.StartsWith("/dist/", StringComparison.OrdinalIgnoreCase); // Web font files (.woff/.woff2/.ttf/.otf/.eot) are effectively immutable in // practice: swapping a live font's glyphs without renaming the file is rare // enough (and disruptive enough to layout if it did happen) that treating every // font as long-cacheable regardless of which folder it happens to sit in // (/fonts, /css, wherever) is safe - this is what was missing for // IranNastaliq-Web.woff2, the Vazirmatn set, and Material-Icons.woff2, which // were stuck on the 6-hour tier purely because they live outside /lib and /dist. var isFont = path.EndsWith(".woff2", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".woff", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".otf", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".eot", StringComparison.OrdinalIgnoreCase); // A handful of specific third-party libraries that ended up directly under /js // instead of /lib (so the path-prefix rule above doesn't catch them) but are // just as static as anything that did. Add future drop-in vendor files here, or // better, put them under /lib or /dist so they're covered automatically. var isKnownVendorFile = path.Equals("/js/chart.js", StringComparison.OrdinalIgnoreCase) || path.Equals("/js/jquery.mark.min.js", StringComparison.OrdinalIgnoreCase); var headers = ctx.Context.Response.GetTypedHeaders(); headers.CacheControl = new CacheControlHeaderValue { Public = true, // Versioned (?version=N / ?v=N), vendor, font, and known-vendor-in-the- // wrong-folder assets: safe for a year-long cache. Everything else (the // app's own hand-edited CSS/JS without a version query) stays on the // conservative 6-hour cache so an un-versioned edit doesn't stay stale long. MaxAge = (isExplicitlyVersioned || isVendorPath || isFont || isKnownVendorFile) ? TimeSpan.FromDays(365) : TimeSpan.FromHours(6) }; } }); app.UseRouting(); app.UseAuthorization(); // Must run after routing/authorization (so it knows which endpoint/policy applies) // and before endpoint execution (so a cache hit can short-circuit it). app.UseOutputCache(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }