ItemDB+API

This commit is contained in:
dingo
2025-12-04 09:30:32 -05:00
parent 841b241ef2
commit d66ff2af40
10 changed files with 2183 additions and 1 deletions
+300
View File
@@ -0,0 +1,300 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
using VoidScavengers.Game;
namespace VoidScavengers.Api;
/// <summary>
/// API endpoints for game items and recipes
/// </summary>
[ApiController]
[Route("api/items")]
public class ItemsController : ControllerBase
{
private readonly GameDbContext _db;
private readonly IItemService _itemService;
public ItemsController(GameDbContext db, IItemService itemService)
{
_db = db;
_itemService = itemService;
}
/// <summary>
/// Get all items (from cache)
/// </summary>
[HttpGet]
public IActionResult GetAllItems([FromQuery] ItemCategory? category = null)
{
var items = category.HasValue
? _itemService.GetItemsByCategory(category.Value)
: _itemService.GetAllItems();
return Ok(items);
}
/// <summary>
/// Get a specific item
/// </summary>
[HttpGet("{id}")]
public IActionResult GetItem(int id)
{
var item = _itemService.GetItem(id);
if (item == null)
return NotFound(new { error = "Item not found" });
return Ok(item);
}
/// <summary>
/// Get all recipes (from cache)
/// </summary>
[HttpGet("recipes")]
public IActionResult GetAllRecipes()
{
var recipes = _itemService.GetAllRecipes();
// Enrich with item names
var enriched = recipes.Select(r => new
{
r.Id,
r.ResultItemId,
ResultItemName = _itemService.GetItem(r.ResultItemId)?.Name ?? "Unknown",
r.ScrapCost,
r.EnergyCost,
r.RareCost
});
return Ok(enriched);
}
/// <summary>
/// Force reload the item cache (admin only)
/// </summary>
[HttpPost("reload")]
public async Task<IActionResult> ReloadCache([FromHeader(Name = "X-Admin-Key")] string? adminKey)
{
// Simple admin key check - in production use proper auth
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
await _itemService.ReloadCacheAsync();
return Ok(new { message = "Cache reloaded", itemCount = _itemService.GetAllItems().Count });
}
/// <summary>
/// Create or update an item (admin only)
/// </summary>
[HttpPost]
public async Task<IActionResult> UpsertItem(
[FromHeader(Name = "X-Admin-Key")] string? adminKey,
[FromBody] GameItemDto dto)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existing = await _db.GameItems.FindAsync(dto.Id);
if (existing == null)
{
var item = new GameItem
{
Id = dto.Id,
Name = dto.Name,
Category = dto.Category,
CraftCost = dto.CraftCost,
Description = dto.Description,
LootValue = dto.LootValue,
Stackable = dto.Stackable,
IsEnabled = dto.IsEnabled,
Damage = dto.Damage,
FireRate = dto.FireRate,
ProjectileSpeed = dto.ProjectileSpeed,
Range = dto.Range,
AmmoType = dto.AmmoType,
PelletCount = dto.PelletCount,
Spread = dto.Spread,
ExplosionRadius = dto.ExplosionRadius,
HarvestMultiplier = dto.HarvestMultiplier,
ScanRadius = dto.ScanRadius,
ScanCooldown = dto.ScanCooldown,
ShieldHealth = dto.ShieldHealth,
ShieldDuration = dto.ShieldDuration,
HealAmount = dto.HealAmount,
ShieldBoostDuration = dto.ShieldBoostDuration,
DamageReduction = dto.DamageReduction,
SpeedBoostDuration = dto.SpeedBoostDuration,
SpeedMultiplier = dto.SpeedMultiplier,
HealthBonus = dto.HealthBonus,
SpeedPenalty = dto.SpeedPenalty,
DashDistance = dto.DashDistance,
DashCooldown = dto.DashCooldown,
CreatedAt = DateTime.UtcNow
};
_db.GameItems.Add(item);
}
else
{
existing.Name = dto.Name;
existing.Category = dto.Category;
existing.CraftCost = dto.CraftCost;
existing.Description = dto.Description;
existing.LootValue = dto.LootValue;
existing.Stackable = dto.Stackable;
existing.IsEnabled = dto.IsEnabled;
existing.Damage = dto.Damage;
existing.FireRate = dto.FireRate;
existing.ProjectileSpeed = dto.ProjectileSpeed;
existing.Range = dto.Range;
existing.AmmoType = dto.AmmoType;
existing.PelletCount = dto.PelletCount;
existing.Spread = dto.Spread;
existing.ExplosionRadius = dto.ExplosionRadius;
existing.HarvestMultiplier = dto.HarvestMultiplier;
existing.ScanRadius = dto.ScanRadius;
existing.ScanCooldown = dto.ScanCooldown;
existing.ShieldHealth = dto.ShieldHealth;
existing.ShieldDuration = dto.ShieldDuration;
existing.HealAmount = dto.HealAmount;
existing.ShieldBoostDuration = dto.ShieldBoostDuration;
existing.DamageReduction = dto.DamageReduction;
existing.SpeedBoostDuration = dto.SpeedBoostDuration;
existing.SpeedMultiplier = dto.SpeedMultiplier;
existing.HealthBonus = dto.HealthBonus;
existing.SpeedPenalty = dto.SpeedPenalty;
existing.DashDistance = dto.DashDistance;
existing.DashCooldown = dto.DashCooldown;
}
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new { message = existing == null ? "Item created" : "Item updated", id = dto.Id });
}
/// <summary>
/// Create or update a recipe (admin only)
/// </summary>
[HttpPost("recipes")]
public async Task<IActionResult> UpsertRecipe(
[FromHeader(Name = "X-Admin-Key")] string? adminKey,
[FromBody] GameRecipeDto dto)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existing = await _db.GameRecipes.FindAsync(dto.Id);
if (existing == null)
{
var recipe = new GameRecipe
{
Id = dto.Id,
ResultItemId = dto.ResultItemId,
ScrapCost = dto.ScrapCost,
EnergyCost = dto.EnergyCost,
RareCost = dto.RareCost,
IsEnabled = dto.IsEnabled,
CreatedAt = DateTime.UtcNow
};
_db.GameRecipes.Add(recipe);
}
else
{
existing.ResultItemId = dto.ResultItemId;
existing.ScrapCost = dto.ScrapCost;
existing.EnergyCost = dto.EnergyCost;
existing.RareCost = dto.RareCost;
existing.IsEnabled = dto.IsEnabled;
}
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new { message = existing == null ? "Recipe created" : "Recipe updated", id = dto.Id });
}
/// <summary>
/// Seed default items if database is empty (admin only)
/// </summary>
[HttpPost("seed")]
public async Task<IActionResult> SeedDefaults([FromHeader(Name = "X-Admin-Key")] string? adminKey)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existingItemCount = await _db.GameItems.CountAsync();
var existingRecipeCount = await _db.GameRecipes.CountAsync();
if (existingItemCount > 0 || existingRecipeCount > 0)
return BadRequest(new { error = "Database already has items/recipes. Clear first or use upsert." });
var defaultItems = DefaultItemData.GetDefaultItems();
var defaultRecipes = DefaultItemData.GetDefaultRecipes();
_db.GameItems.AddRange(defaultItems);
_db.GameRecipes.AddRange(defaultRecipes);
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new {
message = "Default items seeded",
itemsAdded = defaultItems.Count,
recipesAdded = defaultRecipes.Count
});
}
}
public class GameItemDto
{
public int Id { get; set; }
public string Name { get; set; } = "";
public ItemCategory Category { get; set; }
public int CraftCost { get; set; }
public string Description { get; set; } = "";
public int LootValue { get; set; }
public bool Stackable { get; set; }
public bool IsEnabled { get; set; } = true;
public int Damage { get; set; }
public float FireRate { get; set; }
public float ProjectileSpeed { get; set; }
public float Range { get; set; }
public int AmmoType { get; set; }
public int PelletCount { get; set; } = 1;
public float Spread { get; set; }
public float ExplosionRadius { get; set; }
public float HarvestMultiplier { get; set; } = 1f;
public float ScanRadius { get; set; }
public float ScanCooldown { get; set; }
public int ShieldHealth { get; set; }
public float ShieldDuration { get; set; }
public int HealAmount { get; set; }
public float ShieldBoostDuration { get; set; }
public float DamageReduction { get; set; }
public float SpeedBoostDuration { get; set; }
public float SpeedMultiplier { get; set; } = 1f;
public int HealthBonus { get; set; }
public float SpeedPenalty { get; set; }
public float DashDistance { get; set; }
public float DashCooldown { get; set; }
}
public class GameRecipeDto
{
public int Id { get; set; }
public int ResultItemId { get; set; }
public int ScrapCost { get; set; }
public int EnergyCost { get; set; }
public int RareCost { get; set; }
public bool IsEnabled { get; set; } = true;
}
+343
View File
@@ -0,0 +1,343 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
namespace VoidScavengers.Api;
/// <summary>
/// API endpoints for player statistics and leaderboards
/// </summary>
[ApiController]
[Route("api/stats")]
public class StatsController : ControllerBase
{
private readonly GameDbContext _db;
public StatsController(GameDbContext db)
{
_db = db;
}
/// <summary>
/// Get stats for a specific player by account ID
/// </summary>
[HttpGet("player/{accountId}")]
public async Task<IActionResult> GetPlayerStats(ulong accountId)
{
var stats = await _db.PlayerStats
.Where(s => s.AccountId == accountId)
.Select(s => new PlayerStatsDto
{
AccountId = s.AccountId,
Username = s.Account.Username,
MatchesPlayed = s.MatchesPlayed,
Wins = s.Wins,
Losses = s.Losses,
Extractions = s.Extractions,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
TotalDamageDealt = s.TotalDamageDealt,
TotalDamageTaken = s.TotalDamageTaken,
TotalScrapCollected = s.TotalScrapCollected,
TotalEnergyCollected = s.TotalEnergyCollected,
TotalRareCollected = s.TotalRareCollected,
ItemsCrafted = s.ItemsCrafted,
TotalPlayTimeSeconds = s.TotalPlayTimeSeconds,
LongestSurvivalSeconds = s.LongestSurvivalSeconds,
Elo = s.Elo
})
.FirstOrDefaultAsync();
if (stats == null)
return NotFound(new { error = "Player stats not found" });
return Ok(stats);
}
/// <summary>
/// Get stats for a player by username
/// </summary>
[HttpGet("player/name/{username}")]
public async Task<IActionResult> GetPlayerStatsByName(string username)
{
var stats = await _db.PlayerStats
.Where(s => s.Account.Username == username)
.Select(s => new PlayerStatsDto
{
AccountId = s.AccountId,
Username = s.Account.Username,
MatchesPlayed = s.MatchesPlayed,
Wins = s.Wins,
Losses = s.Losses,
Extractions = s.Extractions,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
TotalDamageDealt = s.TotalDamageDealt,
TotalDamageTaken = s.TotalDamageTaken,
TotalScrapCollected = s.TotalScrapCollected,
TotalEnergyCollected = s.TotalEnergyCollected,
TotalRareCollected = s.TotalRareCollected,
ItemsCrafted = s.ItemsCrafted,
TotalPlayTimeSeconds = s.TotalPlayTimeSeconds,
LongestSurvivalSeconds = s.LongestSurvivalSeconds,
Elo = s.Elo
})
.FirstOrDefaultAsync();
if (stats == null)
return NotFound(new { error = "Player not found" });
return Ok(stats);
}
/// <summary>
/// Get leaderboard by Elo rating
/// </summary>
[HttpGet("leaderboard")]
public async Task<IActionResult> GetLeaderboard(
[FromQuery] string sort = "elo",
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
pageSize = Math.Clamp(pageSize, 1, 100);
page = Math.Max(1, page);
var query = _db.PlayerStats
.Where(s => s.MatchesPlayed >= 5); // Minimum games to appear on leaderboard
query = sort.ToLower() switch
{
"wins" => query.OrderByDescending(s => s.Wins),
"kills" => query.OrderByDescending(s => s.Kills),
"winrate" => query.OrderByDescending(s => s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed : 0),
"kd" => query.OrderByDescending(s => s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills),
"extractions" => query.OrderByDescending(s => s.Extractions),
"playtime" => query.OrderByDescending(s => s.TotalPlayTimeSeconds),
_ => query.OrderByDescending(s => s.Elo)
};
var totalCount = await query.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var entries = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(s => new LeaderboardEntryDto
{
Rank = 0, // Calculated below
AccountId = s.AccountId,
Username = s.Account.Username,
Elo = s.Elo,
Wins = s.Wins,
Losses = s.Losses,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
Extractions = s.Extractions,
MatchesPlayed = s.MatchesPlayed
})
.ToListAsync();
// Calculate ranks
int startRank = (page - 1) * pageSize + 1;
for (int i = 0; i < entries.Count; i++)
{
entries[i].Rank = startRank + i;
}
return Ok(new LeaderboardResponse
{
Entries = entries,
Page = page,
PageSize = pageSize,
TotalPages = totalPages,
TotalCount = totalCount,
SortBy = sort
});
}
/// <summary>
/// Get match history for a player
/// </summary>
[HttpGet("player/{accountId}/history")]
public async Task<IActionResult> GetMatchHistory(
ulong accountId,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
pageSize = Math.Clamp(pageSize, 1, 50);
page = Math.Max(1, page);
var query = _db.MatchHistory
.Where(m => m.AccountId == accountId)
.OrderByDescending(m => m.PlayedAt);
var totalCount = await query.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var matches = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(m => new MatchHistoryDto
{
MatchId = m.MatchId,
PlayedAt = m.PlayedAt,
Result = m.Result.ToString(),
Placement = m.Placement,
TotalPlayers = m.TotalPlayers,
Kills = m.Kills,
Deaths = m.Deaths,
DamageDealt = m.DamageDealt,
DamageTaken = m.DamageTaken,
ScrapCollected = m.ScrapCollected,
EnergyCollected = m.EnergyCollected,
RareCollected = m.RareCollected,
ItemsCrafted = m.ItemsCrafted,
SurvivalTimeSeconds = m.SurvivalTimeSeconds,
EloChange = m.EloChange,
EloAfter = m.EloAfter
})
.ToListAsync();
return Ok(new MatchHistoryResponse
{
Matches = matches,
Page = page,
PageSize = pageSize,
TotalPages = totalPages,
TotalCount = totalCount
});
}
/// <summary>
/// Get global statistics
/// </summary>
[HttpGet("global")]
public async Task<IActionResult> GetGlobalStats()
{
var stats = await _db.PlayerStats
.GroupBy(s => 1)
.Select(g => new GlobalStatsDto
{
TotalPlayers = g.Count(),
TotalMatchesPlayed = g.Sum(s => s.MatchesPlayed),
TotalKills = g.Sum(s => s.Kills),
TotalExtractions = g.Sum(s => s.Extractions),
TotalPlayTimeHours = g.Sum(s => s.TotalPlayTimeSeconds) / 3600.0,
AverageElo = g.Average(s => (double)s.Elo),
TopElo = g.Max(s => s.Elo)
})
.FirstOrDefaultAsync();
if (stats == null)
{
return Ok(new GlobalStatsDto());
}
// Get active players (played in last 7 days)
var sevenDaysAgo = DateTime.UtcNow.AddDays(-7);
stats.ActivePlayers = await _db.MatchHistory
.Where(m => m.PlayedAt >= sevenDaysAgo)
.Select(m => m.AccountId)
.Distinct()
.CountAsync();
return Ok(stats);
}
}
// DTOs
public class PlayerStatsDto
{
public ulong AccountId { get; set; }
public string Username { get; set; } = "";
public int MatchesPlayed { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public int Extractions { get; set; }
public float WinRate { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public float KdRatio { get; set; }
public long TotalDamageDealt { get; set; }
public long TotalDamageTaken { get; set; }
public long TotalScrapCollected { get; set; }
public long TotalEnergyCollected { get; set; }
public long TotalRareCollected { get; set; }
public int ItemsCrafted { get; set; }
public long TotalPlayTimeSeconds { get; set; }
public int LongestSurvivalSeconds { get; set; }
public int Elo { get; set; }
}
public class LeaderboardEntryDto
{
public int Rank { get; set; }
public ulong AccountId { get; set; }
public string Username { get; set; } = "";
public int Elo { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public float WinRate { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public float KdRatio { get; set; }
public int Extractions { get; set; }
public int MatchesPlayed { get; set; }
}
public class LeaderboardResponse
{
public List<LeaderboardEntryDto> Entries { get; set; } = new();
public int Page { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalCount { get; set; }
public string SortBy { get; set; } = "";
}
public class MatchHistoryDto
{
public string MatchId { get; set; } = "";
public DateTime PlayedAt { get; set; }
public string Result { get; set; } = "";
public int Placement { get; set; }
public int TotalPlayers { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public int DamageDealt { get; set; }
public int DamageTaken { get; set; }
public int ScrapCollected { get; set; }
public int EnergyCollected { get; set; }
public int RareCollected { get; set; }
public int ItemsCrafted { get; set; }
public int SurvivalTimeSeconds { get; set; }
public int EloChange { get; set; }
public int EloAfter { get; set; }
}
public class MatchHistoryResponse
{
public List<MatchHistoryDto> Matches { get; set; } = new();
public int Page { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalCount { get; set; }
}
public class GlobalStatsDto
{
public int TotalPlayers { get; set; }
public int ActivePlayers { get; set; }
public int TotalMatchesPlayed { get; set; }
public int TotalKills { get; set; }
public int TotalExtractions { get; set; }
public double TotalPlayTimeHours { get; set; }
public double AverageElo { get; set; }
public int TopElo { get; set; }
}