using System.Text; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; using SharepointToolbox.Web.Services.Audit; using SharepointToolbox.Web.Services.Session; namespace SharepointToolbox.Web.Services.Export; /// /// Triggers browser file downloads from Blazor Server components. /// Converts string export outputs to bytes and invokes JS download. /// Every download is audit-logged as a report-export action. /// public class WebExportService { private readonly IJSRuntime _js; private readonly IAuditService _audit; private readonly IUserSessionService _session; public WebExportService(IJSRuntime js, IAuditService audit, IUserSessionService session) { _js = js; _audit = audit; _session = session; } public async Task DownloadCsvAsync(string content, string fileName) { var bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true).GetBytes(content); await _js.InvokeVoidAsync("sptb.downloadFile", fileName, "text/csv;charset=utf-8", Convert.ToBase64String(bytes)); await LogExportAsync(fileName, bytes.Length); } public async Task DownloadHtmlAsync(string content, string fileName) { var bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(content); await _js.InvokeVoidAsync("sptb.downloadFile", fileName, "text/html;charset=utf-8", Convert.ToBase64String(bytes)); await LogExportAsync(fileName, bytes.Length); } /// /// Downloads pre-encoded bytes (e.g. a ZIP or a merged report produced by /// ) with an explicit MIME type. /// public async Task DownloadBytesAsync(byte[] content, string fileName, string mime) { await _js.InvokeVoidAsync("sptb.downloadFile", fileName, mime, Convert.ToBase64String(content)); await LogExportAsync(fileName, content.Length); } /// /// Records the download as a "ReportExport" audit entry. The file name encodes /// the report kind (search_, permissions_, storage_, …) and timestamp. /// private Task LogExportAsync(string fileName, int byteCount) { var client = _session.CurrentProfile?.Name ?? string.Empty; var sizeKb = (byteCount / 1024.0).ToString("F1"); return _audit.LogAsync("ReportExport", client, Array.Empty(), $"{fileName} ({sizeKb} KB)"); } }