CDN browser in Admin Portal

This commit is contained in:
dingo
2026-03-03 11:26:59 -05:00
parent 18aeaf093b
commit 8bf7da1092
3 changed files with 485 additions and 0 deletions
@@ -0,0 +1,464 @@
@page "/content/cdn"
@attribute [Authorize(Roles = "Admin,SuperAdmin")]
@using Amazon.S3
@using Amazon.S3.Model
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.Extensions.Options
@using SOR.Cdn
@inject IAmazonS3 S3
@inject IOptions<CdnOptions> CdnOptionsAccessor
@inject IJSRuntime Js
<PageTitle>CDN Browser - SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="mb-0">CDN Browser</h1>
<div class="text-muted small">@_bucketLabel</div>
</div>
<button class="btn btn-outline-secondary btn-sm" @onclick="RefreshAsync" disabled="@_loading">
@if (_loading)
{
<span class="spinner-border spinner-border-sm me-1"></span>
}
else
{
<i class="bi bi-arrow-clockwise me-1"></i>
}
Refresh
</button>
</div>
@if (_message != null)
{
<div class="alert @(_isError ? "alert-danger" : "alert-success")">@_message</div>
}
<div class="row g-4">
<div class="col-lg-4">
<div class="card shadow-sm mb-4">
<div class="card-header fw-medium">Browse Prefix</div>
<div class="card-body">
<label class="form-label small">Folder Prefix</label>
<div class="input-group input-group-sm mb-2">
<input @bind="_prefixInput" class="form-control font-monospace"
placeholder="e.g. cards/art or cosmetics" />
<button class="btn btn-outline-secondary" @onclick="ApplyPrefixAsync" disabled="@_loading">
Open
</button>
</div>
<div class="form-text">
Leave blank to browse the bucket root.
</div>
</div>
</div>
<div class="card shadow-sm mb-4">
<div class="card-header fw-medium">Upload New File</div>
<div class="card-body">
<div class="small text-muted mb-2">
Upload destination:
<span class="font-monospace">@(_activePrefixDisplay)</span>
</div>
<label class="btn btn-sm btn-primary @(_uploading ? "disabled" : "")">
@if (_uploading)
{
<span class="spinner-border spinner-border-sm me-1"></span>
}
else
{
<i class="bi bi-upload me-1"></i>
}
Upload File
<InputFile style="display:none" OnChange="UploadNewAsync" />
</label>
</div>
</div>
<div class="card shadow-sm">
<div class="card-header fw-medium">Replace File</div>
<div class="card-body">
@if (_replaceTarget is null)
{
<div class="text-muted small">
Select a file from the list, then choose a replacement upload.
</div>
}
else
{
<div class="small mb-2">
<div class="text-muted">Target Key</div>
<div class="font-monospace text-break">@_replaceTarget.Key</div>
</div>
<div class="d-flex gap-2">
<label class="btn btn-sm btn-warning @(_replacing ? "disabled" : "")">
@if (_replacing)
{
<span class="spinner-border spinner-border-sm me-1"></span>
}
else
{
<i class="bi bi-arrow-repeat me-1"></i>
}
Replace
<InputFile style="display:none" OnChange="ReplaceAsync" />
</label>
<button class="btn btn-sm btn-outline-secondary" @onclick="ClearReplaceTarget">
Clear
</button>
</div>
<div class="form-text mt-2">
Replaces the selected object at the same CDN path.
</div>
}
</div>
</div>
</div>
<div class="col-lg-8">
<div class="card shadow-sm">
<div class="card-header fw-medium d-flex justify-content-between align-items-center">
<span>Objects <span class="badge bg-secondary ms-1">@_items.Count</span></span>
<small class="text-muted font-monospace">@_activePrefixDisplay</small>
</div>
<div class="card-body p-0">
@if (_loading && _items.Count == 0)
{
<div class="p-3 text-muted">Loading...</div>
}
else if (_items.Count == 0)
{
<div class="p-3 text-muted">No objects found for this prefix.</div>
}
else
{
<div style="max-height:65vh;overflow:auto;">
<table class="table table-sm table-hover mb-0">
<thead class="sticky-top bg-body">
<tr>
<th>Key</th>
<th style="width:110px">Size</th>
<th style="width:180px">Modified</th>
<th style="width:270px">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var item in _items)
{
var row = item;
<tr class="@(_replaceTarget?.Key == row.Key ? "table-warning" : "")">
<td class="font-monospace small text-break align-middle">@row.Key</td>
<td class="align-middle">@FormatBytes(row.Size)</td>
<td class="align-middle text-muted small">@row.LastModified.ToString("yyyy-MM-dd HH:mm UTC")</td>
<td class="align-middle">
<div class="d-flex flex-wrap gap-1">
<a class="btn btn-sm btn-outline-primary"
href="@row.PublicUrl"
target="_blank"
rel="noopener noreferrer">
<i class="bi bi-eye me-1"></i>View
</a>
<button class="btn btn-sm btn-outline-secondary"
@onclick="() => CopyUrlAsync(row.PublicUrl)">
<i class="bi bi-clipboard me-1"></i>Copy URL
</button>
<button class="btn btn-sm btn-outline-warning"
@onclick="() => SelectReplaceTarget(row)">
<i class="bi bi-arrow-repeat me-1"></i>Replace
</button>
<button class="btn btn-sm btn-outline-danger"
disabled="@(_deletingKey == row.Key)"
@onclick="() => DeleteAsync(row)">
@if (_deletingKey == row.Key)
{
<span class="spinner-border spinner-border-sm me-1"></span>
}
else
{
<i class="bi bi-trash me-1"></i>
}
Delete
</button>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
@if (_hasMore)
{
<div class="card-footer">
<button class="btn btn-sm btn-outline-secondary" @onclick="LoadMoreAsync" disabled="@_loading">
Load More
</button>
</div>
}
</div>
</div>
</div>
@code {
private readonly List<CdnObjectRow> _items = new();
private string _prefixInput = "";
private string _activePrefix = "";
private string _bucketLabel = "";
private string _continuationToken = "";
private string _deletingKey = "";
private string? _message;
private bool _isError;
private bool _loading;
private bool _uploading;
private bool _replacing;
private bool _hasMore;
private CdnObjectRow? _replaceTarget;
private string _activePrefixDisplay => string.IsNullOrEmpty(_activePrefix) ? "/" : $"/{_activePrefix}";
protected override async Task OnInitializedAsync()
{
var options = CdnOptionsAccessor.Value;
_bucketLabel = $"{options.BucketName} @ {options.EndpointUrl}";
await LoadAsync(reset: true);
}
private async Task ApplyPrefixAsync()
{
_activePrefix = NormalizePrefix(_prefixInput);
_replaceTarget = null;
await LoadAsync(reset: true);
}
private async Task RefreshAsync()
{
await LoadAsync(reset: true);
}
private async Task LoadMoreAsync()
{
if (_loading || !_hasMore)
return;
await LoadAsync(reset: false);
}
private async Task LoadAsync(bool reset)
{
if (_loading)
return;
_loading = true;
_message = null;
try
{
if (reset)
{
_items.Clear();
_continuationToken = "";
_hasMore = false;
}
var options = CdnOptionsAccessor.Value;
var request = new ListObjectsV2Request
{
BucketName = options.BucketName,
Prefix = _activePrefix,
MaxKeys = 200,
ContinuationToken = string.IsNullOrWhiteSpace(_continuationToken) ? null : _continuationToken,
};
var response = await S3.ListObjectsV2Async(request);
foreach (var obj in response.S3Objects)
{
if (string.IsNullOrWhiteSpace(obj.Key) || obj.Key.EndsWith('/'))
continue;
_items.Add(new CdnObjectRow
{
Key = obj.Key,
Size = obj.Size,
LastModified = obj.LastModified.ToUniversalTime(),
PublicUrl = BuildPublicUrl(obj.Key),
});
}
_continuationToken = response.NextContinuationToken ?? "";
_hasMore = response.IsTruncated;
}
catch (Exception ex)
{
_message = $"CDN list failed: {ex.Message}";
_isError = true;
}
finally
{
_loading = false;
}
}
private async Task UploadNewAsync(InputFileChangeEventArgs e)
{
var file = e.File;
if (file is null)
return;
_uploading = true;
_message = null;
try
{
var key = $"{_activePrefix}{file.Name}";
await UploadFileToKeyAsync(key, file);
_message = $"Uploaded {file.Name}.";
_isError = false;
await LoadAsync(reset: true);
}
catch (Exception ex)
{
_message = $"Upload failed: {ex.Message}";
_isError = true;
}
finally
{
_uploading = false;
}
}
private async Task ReplaceAsync(InputFileChangeEventArgs e)
{
var file = e.File;
if (file is null || _replaceTarget is null)
return;
_replacing = true;
_message = null;
try
{
await UploadFileToKeyAsync(_replaceTarget.Key, file);
_message = $"Replaced {_replaceTarget.Key}.";
_isError = false;
await LoadAsync(reset: true);
}
catch (Exception ex)
{
_message = $"Replace failed: {ex.Message}";
_isError = true;
}
finally
{
_replacing = false;
}
}
private async Task DeleteAsync(CdnObjectRow item)
{
_deletingKey = item.Key;
_message = null;
try
{
var options = CdnOptionsAccessor.Value;
await S3.DeleteObjectAsync(options.BucketName, item.Key);
_items.Remove(item);
if (_replaceTarget?.Key == item.Key)
_replaceTarget = null;
_message = $"Deleted {item.Key}.";
_isError = false;
}
catch (Exception ex)
{
_message = $"Delete failed: {ex.Message}";
_isError = true;
}
finally
{
_deletingKey = "";
}
}
private async Task CopyUrlAsync(string url)
{
try
{
await Js.InvokeVoidAsync("sorAdmin.copyText", url);
_message = "CDN URL copied to clipboard.";
_isError = false;
}
catch (Exception ex)
{
_message = $"Copy failed: {ex.Message}";
_isError = true;
}
}
private void SelectReplaceTarget(CdnObjectRow item)
{
_replaceTarget = item;
_message = null;
}
private void ClearReplaceTarget()
{
_replaceTarget = null;
}
private async Task UploadFileToKeyAsync(string key, IBrowserFile file)
{
const long maxUploadBytes = 100 * 1024 * 1024;
var options = CdnOptionsAccessor.Value;
await using var stream = file.OpenReadStream(maxUploadBytes);
var request = new PutObjectRequest
{
BucketName = options.BucketName,
Key = key,
InputStream = stream,
ContentType = string.IsNullOrWhiteSpace(file.ContentType)
? "application/octet-stream"
: file.ContentType,
CannedACL = S3CannedACL.PublicRead,
DisableDefaultChecksumValidation = true,
};
await S3.PutObjectAsync(request);
}
private string NormalizePrefix(string raw)
{
var prefix = raw.Trim().Trim('/');
if (string.IsNullOrWhiteSpace(prefix))
return string.Empty;
return prefix + "/";
}
private string BuildPublicUrl(string key)
{
return $"{CdnOptionsAccessor.Value.PublicBaseUrl.TrimEnd('/')}/{key}";
}
private string FormatBytes(long bytes)
{
if (bytes < 1024)
return $"{bytes} B";
if (bytes < 1024 * 1024)
return $"{bytes / 1024.0:F1} KB";
if (bytes < 1024 * 1024 * 1024)
return $"{bytes / 1024.0 / 1024.0:F1} MB";
return $"{bytes / 1024.0 / 1024.0 / 1024.0:F1} GB";
}
private sealed class CdnObjectRow
{
public string Key { get; set; } = string.Empty;
public long Size { get; set; }
public DateTime LastModified { get; set; }
public string PublicUrl { get; set; } = string.Empty;
}
}