using System.IO.Compression; using LANCommander.Server.Data; using LANCommander.Server.Data.Models; using LANCommander.Server.Services.Extensions; using LANCommander.Server.Services.Mappers; using LANCommander.SDK; using LANCommander.SDK.Enums; using System.Linq.Expressions; using ZiggyCreatures.Caching.Fusion; using LANCommander.Server.Services.Models; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; namespace LANCommander.Server.Services { public class GameService( ILogger logger, SettingsProvider settingsProvider, IFusionCache cache, SdkMapper sdkMapper, ManifestMapper manifestMapper, IHttpContextAccessor httpContextAccessor, IDbContextFactory contextFactory, ArchiveService archiveService, GameVersionService gameVersionService, MediaService mediaService, StorageLocationService storageLocationService, SDK.Services.ScriptClient scriptClient) : BaseDatabaseService(logger, settingsProvider, cache, httpContextAccessor, contextFactory) { public override async Task AddAsync(Game entity) { await cache.ExpireGameCacheAsync(entity.Id); return await base.AddAsync(entity, async context => { await context.UpdateRelationshipAsync(g => g.Actions); await context.UpdateRelationshipAsync(g => g.Archives); await context.UpdateRelationshipAsync(g => g.BaseGame); await context.UpdateRelationshipAsync(g => g.Categories); await context.UpdateRelationshipAsync(g => g.Collections); await context.UpdateRelationshipAsync(g => g.CustomFields); await context.UpdateRelationshipAsync(g => g.Developers); await context.UpdateRelationshipAsync(g => g.Engine); await context.UpdateRelationshipAsync(g => g.Genres); await context.UpdateRelationshipAsync(g => g.Keys); await context.UpdateRelationshipAsync(g => g.Libraries); await context.UpdateRelationshipAsync(g => g.Media); await context.UpdateRelationshipAsync(g => g.MultiplayerModes); await context.UpdateRelationshipAsync(g => g.Pages); await context.UpdateRelationshipAsync(g => g.Platforms); await context.UpdateRelationshipAsync(g => g.Publishers); await context.UpdateRelationshipAsync(g => g.Redistributables); await context.UpdateRelationshipAsync(g => g.SavePaths); await context.UpdateRelationshipAsync(g => g.Scripts); await context.UpdateRelationshipAsync(g => g.Tags); await context.UpdateRelationshipAsync(g => g.ExternalIds); }); } public override async Task> AddMissingAsync(Expression> predicate, Game entity) { await cache.ExpireGameCacheAsync(entity.Id); return await base.AddMissingAsync(predicate, entity); } public override async Task UpdateAsync(Game entity) { await cache.ExpireGameCacheAsync(entity.Id); if (entity.Media != null) foreach (var media in entity.Media.Where(m => m.Id == Guid.Empty && String.IsNullOrWhiteSpace(m.Crc32)).ToList()) entity.Media.Remove(media); var update = await base.UpdateAsync(entity, async context => { await context.UpdateRelationshipAsync(g => g.Actions); await context.UpdateRelationshipAsync(g => g.Archives); await context.UpdateRelationshipAsync(g => g.BaseGame); await context.UpdateRelationshipAsync(g => g.Categories); await context.UpdateRelationshipAsync(g => g.Collections); await context.UpdateRelationshipAsync(g => g.CustomFields); await context.UpdateRelationshipAsync(g => g.Developers); await context.UpdateRelationshipAsync(g => g.Engine); await context.UpdateRelationshipAsync(g => g.Genres); await context.UpdateRelationshipAsync(g => g.Keys); await context.UpdateRelationshipAsync(g => g.Libraries); await context.UpdateRelationshipAsync(g => g.Media); await context.UpdateRelationshipAsync(g => g.MultiplayerModes); await context.UpdateRelationshipAsync(g => g.Pages); await context.UpdateRelationshipAsync(g => g.Platforms); await context.UpdateRelationshipAsync(g => g.Publishers); await context.UpdateRelationshipAsync(g => g.Redistributables); await context.UpdateRelationshipAsync(g => g.SavePaths); await context.UpdateRelationshipAsync(g => g.Scripts); await context.UpdateRelationshipAsync(g => g.Tags); await context.UpdateRelationshipAsync(g => g.ExternalIds); }); return update; } public override async Task DeleteAsync(Game game) { game = await Include( g => g.Archives, g => g.Media) .GetAsync(game.Id); if (game.Archives != null) foreach (var archive in game.Archives.ToList()) await archiveService.DeleteAsync(archive); if (game.Media != null) foreach (var media in game.Media.ToList()) await mediaService.DeleteAsync(media); await cache.ExpireGameCacheAsync(game.Id); await base.DeleteAsync(game); } public async Task> GetAddonsAsync(Game game) { return await GetAsync(g => g.AddonTypes.Contains(g.Type)); } public async Task GetManifestAsync(Guid id) { var game = await LoadGameForManifestAsync(id); return await GetManifestAsync(game); } /// /// Builds a manifest scoped to a specific game version, so an installed (potentially older) /// version resolves its own Version string and Scripts/Actions/SavePaths snapshot instead of /// the current latest version's config. /// public async Task GetManifestAsync(Guid id, Guid versionId) { var game = await LoadGameForManifestAsync(id); if (game == null) return null; var version = await gameVersionService.GetWithConfigAsync(versionId); return await BuildManifestAsync(game, version); } private async Task LoadGameForManifestAsync(Guid id) { return await Query(q => { return q .AsNoTracking() .AsSplitQuery() .Include(g => g.Actions) .Include(g => g.Archives) .Include(g => g.BaseGame) .Include(g => g.Categories) .Include(g => g.Collections) .Include(g => g.CustomFields) .Include(g => g.DependentGames) .Include(g => g.Developers) .Include(g => g.Engine) .Include(g => g.Genres) .Include(g => g.Media) .Include(g => g.MultiplayerModes) .Include(g => g.Platforms) .Include(g => g.Publishers) .Include(g => g.Redistributables) .Include(g => g.Tools) .Include(g => g.SavePaths) .Include(g => g.Scripts) .Include(g => g.Tags) .Include(g => g.ExternalIds); }).GetAsync(id); } public async Task GetManifestAsync(Game game) { if (game == null) return null; // Resolve version-scoped config (Version, Scripts, Actions, SavePaths) from the // newest GameVersion so the manifest reflects that version's config snapshot rather // than the union of all historical (dual-written) config rows hanging off the game. var latestVersion = await gameVersionService.GetLatestAsync(game.Id); return await BuildManifestAsync(game, latestVersion); } private async Task BuildManifestAsync(Game game, GameVersion version) { if (game == null) return null; var manifest = manifestMapper.ToManifest(game); if (version != null) { if (!String.IsNullOrWhiteSpace(version.Version)) manifest.Version = version.Version; manifest.Scripts = version.Scripts != null ? version.Scripts.Where(s => s.Type != ScriptType.Package).Select(manifestMapper.ToManifest).ToList() : new List(); manifest.Actions = version.Actions != null ? version.Actions.Select(manifestMapper.ToManifest).ToList() : new List(); manifest.SavePaths = version.SavePaths != null ? version.SavePaths.Select(manifestMapper.ToManifest).ToList() : new List(); } if (game.Redistributables != null && game.Redistributables.Any()) { using var context = await contextFactory.CreateDbContextAsync(); foreach (var redistributable in manifest.Redistributables) { var joinEntry = await context.Set>("GameRedistributable") .FirstOrDefaultAsync(e => EF.Property(e, "GameId") == game.Id && EF.Property(e, "RedistributableId") == redistributable.Id); if (joinEntry != null && joinEntry.TryGetValue("Options", out var options) && options is string optionsJson && !string.IsNullOrWhiteSpace(optionsJson)) { redistributable.Options = System.Text.Json.JsonSerializer.Deserialize>(optionsJson); } } } return manifest; } public async Task GetRedistributableOptionsAsync(Guid gameId, Guid redistributableId) { using var context = await contextFactory.CreateDbContextAsync(); var joinEntry = await context.Set>("GameRedistributable") .FirstOrDefaultAsync(e => EF.Property(e, "GameId") == gameId && EF.Property(e, "RedistributableId") == redistributableId); if (joinEntry != null && joinEntry.TryGetValue("Options", out var options) && options is string optionsJson) return optionsJson; return null; } public async Task SetRedistributableOptionsAsync(Guid gameId, Guid redistributableId, string optionsJson) { using var context = await contextFactory.CreateDbContextAsync(); var joinEntry = await context.Set>("GameRedistributable") .FirstOrDefaultAsync(e => EF.Property(e, "GameId") == gameId && EF.Property(e, "RedistributableId") == redistributableId); if (joinEntry != null) { joinEntry["Options"] = optionsJson; await context.SaveChangesAsync(); } } public async Task GetCustomFieldAsync(Guid id, string name) { var game = await AsNoTracking() .AsSplitQuery() .Include(g => g.CustomFields) .GetAsync(id); return game.CustomFields.FirstOrDefault(c => c.Name == name); } public async Task SetCustomFieldAsync(Guid id, string name, string value) { var game = await AsNoTracking() .AsSplitQuery() .Include(g => g.CustomFields) .GetAsync(id); if (game.CustomFields.Any(c => c.Name == name)) foreach (var customField in game.CustomFields.Where(c => c.Name == name)) customField.Value = value; else { game.CustomFields.Add(new GameCustomField()); } return await GetCustomFieldAsync(id, name); } public async Task GetLatestArchiveAsync(Guid id) { var latestVersion = await gameVersionService.GetLatestAsync(id); if (latestVersion?.Archive != null) return latestVersion.Archive; // Fallback for games not yet backfilled into the versioning model. var game = await AsNoTracking() .AsSplitQuery() .Include(g => g.Archives) .GetAsync(id); return game.Archives.OrderByDescending(a => a.CreatedOn).FirstOrDefault(); } public async Task GetVersionAsync(Guid id) { var latestVersion = await gameVersionService.GetLatestAsync(id); if (latestVersion != null && !String.IsNullOrWhiteSpace(latestVersion.Version)) return latestVersion.Version; var latestArchive = await GetLatestArchiveAsync(id); return latestArchive?.Version ?? String.Empty; } public async Task> GetUpdatesAsync(Guid gameId, string version) { var newerVersions = await gameVersionService.GetNewerThanAsync(gameId, version); return newerVersions .Where(v => v.Archive != null) .Select(v => v.Archive) .ToList(); } public async Task PackageAsync(Guid id) { var game = await AsNoTracking() .AsSplitQuery() .Include(g => g.Archives) .Include(g => g.CustomFields) .Include(g => g.Scripts) .GetAsync(id); logger?.LogInformation("Packaging game {GameTitle}", game.Title); var latestArchive = game.Archives?.OrderByDescending(a => a.CreatedOn).FirstOrDefault(); var storageLocation = await storageLocationService.GetOrDefaultAsync(latestArchive?.StorageLocationId, StorageLocationType.Archive); string latestArchivePath = null; if (latestArchive != null) latestArchivePath = await archiveService.GetArchiveFileLocationAsync(latestArchive); if (game.Scripts?.Any(s => s.Type == ScriptType.Package) ?? false) { foreach (var script in game.Scripts.Where(s => s.Type == ScriptType.Package)) { var package = await scriptClient.Game_RunPackageScriptAsync(sdkMapper.ToSdk(script), sdkMapper.ToSdk(game), latestArchivePath); if (package == null) { var message = $"Could not package game {game.Title}, the package script did not return a result"; logger?.LogError(message); throw new Exception(message); } if (String.IsNullOrWhiteSpace(package.Path) || !Directory.Exists(package.Path)) { var message = $"Could not package game {game.Title}, the path {package.Path} could not be found"; logger?.LogError(message); throw new Exception(message); } var archive = new Archive { Version = package.Version, GameId = game.Id, ObjectKey = Guid.NewGuid().ToString(), LastVersion = latestArchive, StorageLocationId = storageLocation.Id, }; archive = await archiveService.AddAsync(archive); var destination = await archiveService.GetArchiveFileLocationAsync(archive); ZipFile.CreateFromDirectory(package.Path, destination); await archiveService.RecalculateFileSizeArchiveAsync(archive); logger?.LogInformation("Successfully packaged {GameTitle} and created new archive with version number {GameVersion}", game.Title, archive.Version); } } else { var message = $"Could not package game {game.Title}, no packaging scripts are defined"; logger?.LogWarning(message); throw new Exception(message); } } } }