426 lines
14 KiB
C#
426 lines
14 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using DataServer.Data;
|
|
using DataServer.Data.Entities;
|
|
using GameServices;
|
|
using System.Net.Http;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace GameServices.Admin.Pages.Assets;
|
|
|
|
public class IndexModel : AdminPageModel
|
|
{
|
|
private readonly GameDbContext _db;
|
|
private readonly ICdnBrowserService _cdnService;
|
|
private readonly IHttpClientFactory? _httpClientFactory;
|
|
|
|
public IndexModel(GameDbContext db, ICdnBrowserService cdnService, IHttpClientFactory? httpClientFactory = null)
|
|
{
|
|
_db = db;
|
|
_cdnService = cdnService;
|
|
_httpClientFactory = httpClientFactory;
|
|
}
|
|
|
|
// Tab state
|
|
[FromQuery(Name = "tab")]
|
|
public string Tab { get; set; } = "browse";
|
|
|
|
// Browse tab
|
|
[FromQuery(Name = "prefix")]
|
|
public string? Prefix { get; set; }
|
|
|
|
[FromQuery(Name = "filter")]
|
|
public string? Filter { get; set; }
|
|
|
|
[FromQuery(Name = "bpage")]
|
|
public int BrowsePage { get; set; } = 1;
|
|
|
|
public int BrowsePageSize { get; set; } = 100;
|
|
public int BrowseTotalPages => (int)Math.Ceiling(FilteredFileCount / (double)BrowsePageSize);
|
|
public int FilteredFileCount => AllFiles.Count;
|
|
|
|
public List<CdnFile> AllFiles { get; set; } = new();
|
|
public List<CdnFile> Files => AllFiles
|
|
.Skip((BrowsePage - 1) * BrowsePageSize)
|
|
.Take(BrowsePageSize)
|
|
.ToList();
|
|
public List<string> Subfolders { get; set; } = new();
|
|
public List<string> AvailableFolders { get; set; } = new()
|
|
{
|
|
"textures/items/",
|
|
"textures/mobs/",
|
|
"textures/objects/",
|
|
"textures/spells/",
|
|
"textures/ui/",
|
|
"scenes/mobs/"
|
|
};
|
|
|
|
public bool CdnConfigured => _cdnService.IsConfigured;
|
|
|
|
// Tracked tab
|
|
[FromQuery(Name = "search")]
|
|
public string? Search { get; set; }
|
|
|
|
[FromQuery(Name = "type")]
|
|
public ClientAssetType? AssetTypeFilter { get; set; }
|
|
|
|
[FromQuery(Name = "tpage")]
|
|
public int TrackedPage { get; set; } = 1;
|
|
|
|
public List<ClientAsset> Assets { get; set; } = new();
|
|
public int TrackedTotalPages { get; set; }
|
|
|
|
public HashSet<string> TrackedPaths { get; set; } = new();
|
|
|
|
// Edit tab
|
|
[FromQuery(Name = "path")]
|
|
public string? EditPath { get; set; }
|
|
|
|
public ClientAsset? EditingAsset { get; set; }
|
|
|
|
// Stats
|
|
public int TrackedCount { get; set; }
|
|
public int TextureCount { get; set; }
|
|
public int SceneCount { get; set; }
|
|
public int ScriptCount { get; set; }
|
|
|
|
public int PageSize { get; set; } = 50;
|
|
|
|
public string CdnBaseUrl { get; set; } = "https://assets.aeternalisgames.com";
|
|
|
|
public string? Message { get; set; }
|
|
public bool IsError { get; set; }
|
|
|
|
public string GetBrowsePageUrl(int page)
|
|
{
|
|
var parts = new List<string> { $"tab=browse", $"bpage={page}" };
|
|
if (!string.IsNullOrEmpty(Prefix)) parts.Add($"prefix={Uri.EscapeDataString(Prefix)}");
|
|
if (!string.IsNullOrEmpty(Filter)) parts.Add($"filter={Uri.EscapeDataString(Filter)}");
|
|
return "/admin/assets?" + string.Join("&", parts);
|
|
}
|
|
|
|
public string GetTrackedPageUrl(int page)
|
|
{
|
|
var parts = new List<string> { $"tab=tracked", $"tpage={page}" };
|
|
if (!string.IsNullOrEmpty(Search)) parts.Add($"search={Uri.EscapeDataString(Search)}");
|
|
if (AssetTypeFilter.HasValue) parts.Add($"type={AssetTypeFilter}");
|
|
return "/admin/assets?" + string.Join("&", parts);
|
|
}
|
|
|
|
public async Task OnGetAsync()
|
|
{
|
|
var cdnUrl = Environment.GetEnvironmentVariable("CDN_BASE_URL");
|
|
if (!string.IsNullOrEmpty(cdnUrl)) CdnBaseUrl = cdnUrl;
|
|
|
|
// Stats
|
|
TrackedCount = await _db.ClientAssets.CountAsync();
|
|
TextureCount = await _db.ClientAssets.CountAsync(a => a.AssetType == ClientAssetType.Texture);
|
|
SceneCount = await _db.ClientAssets.CountAsync(a => a.AssetType == ClientAssetType.Scene);
|
|
ScriptCount = await _db.ClientAssets.CountAsync(a => a.AssetType == ClientAssetType.Script);
|
|
|
|
// Get tracked paths for comparison
|
|
TrackedPaths = (await _db.ClientAssets.Select(a => a.FilePath).ToListAsync()).ToHashSet();
|
|
|
|
if (Tab == "edit" && !string.IsNullOrEmpty(EditPath))
|
|
{
|
|
EditingAsset = await _db.ClientAssets.FirstOrDefaultAsync(a => a.FilePath == EditPath);
|
|
if (EditingAsset == null)
|
|
{
|
|
Tab = "tracked";
|
|
Message = "Asset not found.";
|
|
IsError = true;
|
|
}
|
|
}
|
|
else if (Tab == "browse" && CdnConfigured)
|
|
{
|
|
if (BrowsePage < 1) BrowsePage = 1;
|
|
|
|
// Normalize prefix
|
|
Prefix = Prefix?.TrimEnd('/');
|
|
if (!string.IsNullOrEmpty(Prefix))
|
|
Prefix += "/";
|
|
|
|
// List files from MinIO (high limit for large buckets)
|
|
var allItems = await _cdnService.ListFilesAsync(Prefix ?? "", 100000);
|
|
|
|
// Separate files and folders
|
|
Subfolders = allItems
|
|
.Where(f => f.IsDirectory)
|
|
.Select(f => f.Key)
|
|
.OrderBy(f => f)
|
|
.ToList();
|
|
|
|
// Apply filter
|
|
var files = allItems.Where(f => !f.IsDirectory);
|
|
if (!string.IsNullOrWhiteSpace(Filter))
|
|
{
|
|
var filterLower = Filter.ToLower();
|
|
files = files.Where(f => f.Name.ToLower().Contains(filterLower));
|
|
}
|
|
|
|
AllFiles = files.OrderBy(f => f.Name).ToList();
|
|
}
|
|
else if (Tab == "tracked")
|
|
{
|
|
if (TrackedPage < 1) TrackedPage = 1;
|
|
|
|
var query = _db.ClientAssets.AsQueryable();
|
|
|
|
if (!string.IsNullOrWhiteSpace(Search))
|
|
query = query.Where(a => a.FilePath.Contains(Search));
|
|
|
|
if (AssetTypeFilter.HasValue)
|
|
query = query.Where(a => a.AssetType == AssetTypeFilter.Value);
|
|
|
|
var total = await query.CountAsync();
|
|
TrackedTotalPages = (int)Math.Ceiling(total / (double)PageSize);
|
|
|
|
Assets = await query
|
|
.OrderBy(a => a.FilePath)
|
|
.Skip((TrackedPage - 1) * PageSize)
|
|
.Take(PageSize)
|
|
.ToListAsync();
|
|
}
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostRegisterAssetAsync(
|
|
string filePath,
|
|
ClientAssetType assetType,
|
|
long fileSize,
|
|
string? returnPrefix,
|
|
string? returnFilter,
|
|
int? returnPage)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(filePath))
|
|
{
|
|
Message = "File path is required.";
|
|
IsError = true;
|
|
return RedirectToPage(new { tab = "browse", prefix = returnPrefix, filter = returnFilter, bpage = returnPage });
|
|
}
|
|
|
|
// Normalize path
|
|
filePath = filePath.Trim().Replace("\\", "/");
|
|
if (filePath.StartsWith("/")) filePath = filePath.Substring(1);
|
|
|
|
// Check if already tracked
|
|
var existing = await _db.ClientAssets.FirstOrDefaultAsync(a => a.FilePath == filePath);
|
|
if (existing != null)
|
|
{
|
|
Message = $"Asset already tracked.";
|
|
IsError = true;
|
|
return RedirectToPage(new { tab = "browse", prefix = returnPrefix, filter = returnFilter, bpage = returnPage });
|
|
}
|
|
|
|
// Try to compute actual hash from CDN
|
|
var fileHash = await ComputeFileHashAsync(filePath);
|
|
|
|
// Create new asset tracking entry
|
|
var asset = new ClientAsset
|
|
{
|
|
FilePath = filePath,
|
|
CdnPath = filePath, // Set CdnPath = FilePath
|
|
AssetType = assetType,
|
|
FileHash = fileHash,
|
|
FileSize = fileSize,
|
|
Version = 1,
|
|
IsRequired = false,
|
|
IsEnabled = true,
|
|
MinClientVersion = "1.0.0",
|
|
CreatedAt = DateTime.UtcNow,
|
|
UpdatedAt = DateTime.UtcNow
|
|
};
|
|
|
|
_db.ClientAssets.Add(asset);
|
|
await _db.SaveChangesAsync();
|
|
|
|
Message = $"Asset registered.";
|
|
return RedirectToPage(new { tab = "browse", prefix = returnPrefix, filter = returnFilter, bpage = returnPage });
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostUpdateAssetAsync(
|
|
int assetId,
|
|
ClientAssetType assetType,
|
|
int version,
|
|
string fileHash,
|
|
long fileSize,
|
|
string? minClientVersion,
|
|
bool isRequired,
|
|
bool isEnabled)
|
|
{
|
|
var asset = await _db.ClientAssets.FindAsync(assetId);
|
|
if (asset == null)
|
|
{
|
|
Message = "Asset not found.";
|
|
IsError = true;
|
|
return RedirectToPage(new { tab = "tracked" });
|
|
}
|
|
|
|
asset.AssetType = assetType;
|
|
asset.Version = version;
|
|
asset.FileHash = fileHash;
|
|
asset.FileSize = fileSize;
|
|
asset.MinClientVersion = string.IsNullOrWhiteSpace(minClientVersion) ? null : minClientVersion;
|
|
asset.IsRequired = isRequired;
|
|
asset.IsEnabled = isEnabled;
|
|
asset.UpdatedAt = DateTime.UtcNow;
|
|
|
|
await _db.SaveChangesAsync();
|
|
|
|
Message = "Asset updated.";
|
|
return RedirectToPage(new { tab = "edit", path = asset.FilePath });
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostDeleteAssetAsync(int assetId)
|
|
{
|
|
var asset = await _db.ClientAssets.FindAsync(assetId);
|
|
if (asset != null)
|
|
{
|
|
_db.ClientAssets.Remove(asset);
|
|
await _db.SaveChangesAsync();
|
|
Message = $"Asset deleted.";
|
|
}
|
|
return RedirectToPage(new { tab = "tracked" });
|
|
}
|
|
|
|
public IActionResult OnPostRefreshCache()
|
|
{
|
|
// Signal that asset cache should be refreshed
|
|
// The DungeonHandler queries the database each time, so there's no server-side cache to clear
|
|
// But we can bump a version or signal clients
|
|
Message = "Asset manifest will be refreshed on next client request. (Database is queried directly)";
|
|
return RedirectToPage(new { tab = Tab });
|
|
}
|
|
|
|
private async Task<string> ComputeFileHashAsync(string filePath)
|
|
{
|
|
// Try to download the file and compute actual MD5 hash
|
|
try
|
|
{
|
|
if (_httpClientFactory != null)
|
|
{
|
|
var client = _httpClientFactory.CreateClient();
|
|
var url = $"{CdnBaseUrl}/downloads/{filePath}";
|
|
var response = await client.GetAsync(url);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var bytes = await response.Content.ReadAsByteArrayAsync();
|
|
using var md5c = MD5.Create();
|
|
var hash = md5c.ComputeHash(bytes);
|
|
return Convert.ToHexString(hash).ToLower();
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Fall through to placeholder
|
|
}
|
|
|
|
// Fallback: generate placeholder hash
|
|
using var md5 = MD5.Create();
|
|
var placeholderBytes = System.Text.Encoding.UTF8.GetBytes(filePath + DateTime.UtcNow.Ticks);
|
|
var placeholderHash = md5.ComputeHash(placeholderBytes);
|
|
return Convert.ToHexString(placeholderHash).ToLower();
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostUploadFileAsync(IFormFile file, string? uploadPath)
|
|
{
|
|
if (file == null || file.Length == 0)
|
|
{
|
|
Message = "Please select a file to upload.";
|
|
IsError = true;
|
|
return RedirectToPage(new { tab = "browse", prefix = uploadPath });
|
|
}
|
|
|
|
// Sanitize and build the full path
|
|
var fileName = Path.GetFileName(file.FileName).Replace(" ", "_");
|
|
var fullPath = string.IsNullOrEmpty(uploadPath)
|
|
? fileName
|
|
: $"{uploadPath.TrimEnd('/')}/{fileName}";
|
|
|
|
try
|
|
{
|
|
// Determine content type
|
|
var contentType = file.ContentType;
|
|
if (string.IsNullOrEmpty(contentType))
|
|
{
|
|
var ext = Path.GetExtension(fileName).ToLower();
|
|
contentType = ext switch
|
|
{
|
|
".png" => "image/png",
|
|
".jpg" or ".jpeg" => "image/jpeg",
|
|
".gif" => "image/gif",
|
|
".webp" => "image/webp",
|
|
".tscn" => "text/plain",
|
|
".gd" => "text/plain",
|
|
".json" => "application/json",
|
|
_ => "application/octet-stream"
|
|
};
|
|
}
|
|
|
|
using var stream = file.OpenReadStream();
|
|
var success = await _cdnService.UploadFileAsync(fullPath, stream, contentType);
|
|
|
|
if (success)
|
|
{
|
|
Message = $"Uploaded: {fullPath}";
|
|
}
|
|
else
|
|
{
|
|
Message = "Upload failed. Check server logs.";
|
|
IsError = true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Message = $"Upload error: {ex.Message}";
|
|
IsError = true;
|
|
}
|
|
|
|
return RedirectToPage(new { tab = "browse", prefix = uploadPath });
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostDeleteCdnFileAsync(string filePath, string? returnPrefix)
|
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
|
{
|
|
Message = "File path is required.";
|
|
IsError = true;
|
|
return RedirectToPage(new { tab = "browse", prefix = returnPrefix });
|
|
}
|
|
|
|
try
|
|
{
|
|
var success = await _cdnService.DeleteFileAsync(filePath);
|
|
|
|
if (success)
|
|
{
|
|
// Also remove from tracking if exists
|
|
var tracked = await _db.ClientAssets.FirstOrDefaultAsync(a => a.FilePath == filePath);
|
|
if (tracked != null)
|
|
{
|
|
_db.ClientAssets.Remove(tracked);
|
|
await _db.SaveChangesAsync();
|
|
Message = $"Deleted from CDN and removed tracking: {filePath}";
|
|
}
|
|
else
|
|
{
|
|
Message = $"Deleted from CDN: {filePath}";
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Message = "Delete failed. Check server logs.";
|
|
IsError = true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Message = $"Delete error: {ex.Message}";
|
|
IsError = true;
|
|
}
|
|
|
|
return RedirectToPage(new { tab = "browse", prefix = returnPrefix });
|
|
}
|
|
}
|