Skip to content

Commit

Permalink
Rename "Chromium" to "Browser" in config and code
Browse files Browse the repository at this point in the history
* Updated AppSettings.json to rename "Chromium" section to "Browser" for PDF generation.
* Reflected this change across multiple files including ReportSheetCacheTests.cs, UnitTestHelpers.cs, and ReportSheetCache.cs.
* Updated comments in ReportSheet.cshtml accordingly.
* Simplified AppSettings.json by removing comments about `AllowedUserNameCharacters` and `DefaultLockoutTimeSpan` settings.
  • Loading branch information
axunonb committed Sep 28, 2024
1 parent 65f19e7 commit 8884848
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 27 deletions.
6 changes: 3 additions & 3 deletions League.Demo/Configuration/AppSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"User": {
"RequireUniqueEmail": true,
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789öäüÖÄÜß#-._" /* no @; if set to "", all characters are allowed! */
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789öäüÖÄÜß#-._"
},
"Password": {
"RequireDigit": false,
Expand All @@ -26,14 +26,14 @@
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpan": "0.00:05:00.0000", /* TimeSpan of 5 minutes */
"DefaultLockoutTimeSpan": "0.00:05:00.0000",
"MaxFailedAccessAttempts": 5
}
},
"LeagueUserValidatorOptions": {
"RequiredUsernameLength": 2
},
"Chromium": {
"Browser": {
"ExecutablePath": "Chromium-Win\\chrome.exe"
}
}
8 changes: 4 additions & 4 deletions League.Tests/Caching/ReportSheetCacheTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ReportSheetCacheTests()
{
_webHostEnvironment = new HostingEnvironment {
WebRootPath = Path.GetTempPath(), ContentRootPath
// Because we use the Chromium installation in the demo web app
// Because we use a Browser installation in the demo web app
= DirectoryLocator.GetTargetProjectPath(typeof(League.WebApp.WebAppStartup))
};

Expand All @@ -34,10 +34,10 @@ public ReportSheetCacheTests()
Identifier = "testorg"
};

var chromiumPath = new List<KeyValuePair<string, string?>>
{ new("Chromium:ExecutablePath", "Chromium-Win\\chrome.exe") };
var browserPath = new List<KeyValuePair<string, string?>>
{ new("Browser:ExecutablePath", "Chromium-Win\\chrome.exe") };

IServiceProvider services = UnitTestHelpers.GetReportSheetCacheServiceProvider(_tenantContext, _webHostEnvironment, chromiumPath);
IServiceProvider services = UnitTestHelpers.GetReportSheetCacheServiceProvider(_tenantContext, _webHostEnvironment, browserPath);
_cache = services.GetRequiredService<ReportSheetCache>();
}

Expand Down
4 changes: 2 additions & 2 deletions League.Tests/TestComponents/UnitTestHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public static ServiceProvider GetTextTemplatingServiceProvider(ITenantContext te
.BuildServiceProvider();
}

public static ServiceProvider GetReportSheetCacheServiceProvider(ITenantContext tenantContext, IWebHostEnvironment webHostEnvironment, IEnumerable<KeyValuePair<string,string?>> chromiumPath)
public static ServiceProvider GetReportSheetCacheServiceProvider(ITenantContext tenantContext, IWebHostEnvironment webHostEnvironment, IEnumerable<KeyValuePair<string,string?>> browserPath)
{
return new ServiceCollection()
.AddLogging(builder =>
Expand All @@ -151,7 +151,7 @@ public static ServiceProvider GetReportSheetCacheServiceProvider(ITenantContext
.AddTransient<IConfiguration>(sp =>
{
var c = new ConfigurationManager();
c.AddInMemoryCollection(chromiumPath);
c.AddInMemoryCollection(browserPath);
return c;
})
.AddTransient<ITenantContext>(sp => tenantContext)
Expand Down
28 changes: 14 additions & 14 deletions League/Caching/ReportSheetCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class ReportSheetCache
{
private readonly ITenantContext _tenantContext;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly string _pathToChromium;
private readonly string _pathToBrowser;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<ReportSheetCache> _logger;

Expand All @@ -44,15 +44,15 @@ public ReportSheetCache(ITenantContext tenantContext, IConfiguration configurati
{
_tenantContext = tenantContext;
_webHostEnvironment = webHostEnvironment;
_pathToChromium = Path.Combine(webHostEnvironment.ContentRootPath, configuration["Chromium:ExecutablePath"] ?? string.Empty);
_pathToBrowser = Path.Combine(webHostEnvironment.ContentRootPath, configuration["Browser:ExecutablePath"] ?? string.Empty);
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<ReportSheetCache>();
UsePuppeteer = false;
}

/// <summary>
/// Gets or sets a value indicating whether to use Puppeteer for generating the report sheet,
/// instead of Chromium command line.
/// instead of Browser command line.
/// </summary>
public bool UsePuppeteer { get; set; }

Expand Down Expand Up @@ -85,7 +85,7 @@ public async Task<Stream> GetOrCreatePdf(MatchReportSheetRow data, string html,

cacheFile = UsePuppeteer
? await GetReportSheetPuppeteer(data.Id, html, cancellationToken)
: await GetReportSheetChromium(data.Id, html, cancellationToken);
: await GetReportSheetBrowser(data.Id, html, cancellationToken);

if (cacheFile == null) return Stream.Null;
}
Expand All @@ -101,15 +101,15 @@ private static bool IsOutdated(string cacheFile, DateTime dataModifiedOn)
return !fi.Exists || fi.LastWriteTimeUtc < dataModifiedOn; // Database dates are in UTC
}

private async Task<string?> GetReportSheetChromium(long matchId, string html, CancellationToken cancellationToken)
private async Task<string?> GetReportSheetBrowser(long matchId, string html, CancellationToken cancellationToken)
{
// Create folder in TempPath
var tempFolder = CreateTempPathFolder();

// Temporary file with HTML content - extension must be ".html"!
var htmlUri = await CreateHtmlFile(html, tempFolder, cancellationToken);

var pdfFile = await CreateReportSheetPdfChromium(tempFolder, htmlUri, cancellationToken);
var pdfFile = await CreateReportSheetPdfBrowser(tempFolder, htmlUri, cancellationToken);

var cacheFile = MovePdfToCache(pdfFile, matchId);

Expand Down Expand Up @@ -151,9 +151,9 @@ private string GetPathToCacheFile(long matchId)
Headless = true,
Browser = PuppeteerSharp.SupportedBrowser.Chromium,
// Alternative: --use-cmd-decoder=validating
Args = new[] // Chromium requires using a sandboxed browser for PDF generation, unless sandbox is disabled
Args = new[] // Chromium-based browsers requires using a sandboxed browser for PDF generation, unless sandbox is disabled
{ "--no-sandbox", "--disable-gpu", "--disable-extensions", "--use-cmd-decoder=passthrough" },
ExecutablePath = _pathToChromium,
ExecutablePath = _pathToBrowser,
Timeout = 5000,
ProtocolTimeout = 10000 // default is 180,000 - used for page.PdfDataAsync
};
Expand Down Expand Up @@ -183,23 +183,23 @@ private string GetPathToCacheFile(long matchId)
return fullPath;
}

private async Task<string> CreateReportSheetPdfChromium(string tempFolder, string htmlUri, CancellationToken cancellationToken)
private async Task<string> CreateReportSheetPdfBrowser(string tempFolder, string htmlUri, CancellationToken cancellationToken)
{
// Temporary file for the PDF stream from Chromium
// Temporary file for the PDF stream from the Browser
// Note: non-existing file is handled in MovePdfToCache
var pdfFile = Path.Combine(tempFolder, Path.GetRandomFileName() + ".pdf");

// Run Chromium
// Run the Browser
// Command line switches overview: https://kapeli.com/cheat_sheets/Chromium_Command_Line_Switches.docset/Contents/Resources/Documents/index
// or better https://peter.sh/experiments/chromium-command-line-switches/
var startInfo = new System.Diagnostics.ProcessStartInfo(_pathToChromium,
var startInfo = new System.Diagnostics.ProcessStartInfo(_pathToBrowser,
$"--allow-pre-commit-input --disable-background-networking --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-component-update --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --enable-automation --enable-blink-features=IdleDetection --enable-features=NetworkServiceInProcess2 --export-tagged-pdf --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain --headless --hide-scrollbars --mute-audio --no-sandbox --disable-gpu --use-cmd-decoder=passthrough --no-margins --user-data-dir={tempFolder} --no-pdf-header-footer --print-to-pdf={pdfFile} {htmlUri}")
{ CreateNoWindow = true, UseShellExecute = false };
var proc = System.Diagnostics.Process.Start(startInfo);

if (proc == null)
{
_logger.LogError("Process '{PathToChromium}' could not be started.", _pathToChromium);
_logger.LogError("Process '{PathToBrowser}' could not be started.", _pathToBrowser);
return pdfFile;
}

Expand All @@ -211,7 +211,7 @@ private async Task<string> CreateReportSheetPdfChromium(string tempFolder, strin
if (processTask.IsCompleted) return pdfFile;

proc.Kill(true);
throw new OperationCanceledException($"Chromium timed out after {timeout.TotalMilliseconds}ms.");
throw new OperationCanceledException($"Browser timed out after {timeout.TotalMilliseconds}ms.");
}

private static async Task<string> CreateHtmlFile(string html, string tempFolder, CancellationToken cancellationToken)
Expand Down
6 changes: 3 additions & 3 deletions League/Configuration/AppSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
},
"User": {
"RequireUniqueEmail": true,
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789öäüÖÄÜß#-._" /* no @; if set to "", all characters are allowed! */
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789öäüÖÄÜß#-._"
},
"Password": {
"RequireDigit": false,
Expand All @@ -34,14 +34,14 @@
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpan": "0.00:05:00.0000", /* TimeSpan of 5 minutes */
"DefaultLockoutTimeSpan": "0.00:05:00.0000",
"MaxFailedAccessAttempts": 5
}
},
"LeagueUserValidatorOptions": {
"RequiredUsernameLength": 2
},
"Chromium": {
"Browser": {
"ExecutablePath": "Chromium-Win\\chrome.exe"
}
}
2 changes: 1 addition & 1 deletion League/Views/Match/ReportSheet.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
@@media print {
@@page {
size: 210mm 297mm;
margin: 0; /* removes header and footer when printing with browsers, for automatic pdf generation --no-pdf-header-footer is required for Chromium browsers */
margin: 0; /* removes header and footer when printing with browsers, for automatic pdf generation --no-pdf-header-footer is required for browser PDF generation */
}
div.container {
Expand Down

0 comments on commit 8884848

Please sign in to comment.