62 lines
2.4 KiB
C#
62 lines
2.4 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Downloads pre-encoded bytes (e.g. a ZIP or a merged report produced by
|
|
/// <see cref="ReportMergeHelper"/>) with an explicit MIME type.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Records the download as a "ReportExport" audit entry. The file name encodes
|
|
/// the report kind (search_, permissions_, storage_, …) and timestamp.
|
|
/// </summary>
|
|
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<string>(), $"{fileName} ({sizeKb} KB)");
|
|
}
|
|
}
|