LANCommander/LANCommander.Server.Services/PlaySessionService.cs

77 lines
2.6 KiB
C#
Raw Permalink Normal View History

2024-08-04 18:44:33 -05:00
using LANCommander.Server.Data;
using LANCommander.Server.Data.Models;
2023-11-17 02:28:46 -06:00
using LANCommander.Helpers;
2024-08-04 18:44:33 -05:00
using LANCommander.Server.Models;
2023-12-11 17:29:06 -06:00
using Microsoft.EntityFrameworkCore;
2024-08-12 00:15:16 -05:00
using LANCommander.SDK.Enums;
using Microsoft.Extensions.Logging;
using ZiggyCreatures.Caching.Fusion;
2023-11-17 02:28:46 -06:00
2024-08-04 18:44:33 -05:00
namespace LANCommander.Server.Services
2023-11-17 02:28:46 -06:00
{
public class PlaySessionService : BaseDatabaseService<PlaySession>
{
2023-12-11 17:29:06 -06:00
private ServerService ServerService { get; set; }
private ServerProcessService ServerProcessService;
public PlaySessionService(
ILogger<PlaySessionService> logger,
IFusionCache cache,
RepositoryFactory repositoryFactory,
ServerService serverService,
ServerProcessService serverProcessService) : base(logger, cache, repositoryFactory)
{
2023-12-11 19:39:46 -06:00
ServerService = serverService;
2023-12-11 17:29:06 -06:00
ServerProcessService = serverProcessService;
}
2023-11-17 02:28:46 -06:00
public async Task StartSessionAsync(Guid gameId, Guid userId)
2023-11-17 02:28:46 -06:00
{
var existingSession = await FirstOrDefaultAsync(ps => ps.GameId == gameId && ps.UserId == userId && ps.End == null);
2023-11-17 02:28:46 -06:00
if (existingSession != null)
await DeleteAsync(existingSession);
2023-11-17 02:28:46 -06:00
var session = new PlaySession()
{
GameId = gameId,
UserId = userId,
Start = DateTime.UtcNow
};
await AddAsync(session);
2023-12-11 17:29:06 -06:00
var servers = await ServerService.GetAsync(s => s.GameId == gameId && s.Autostart && s.AutostartMethod == ServerAutostartMethod.OnPlayerActivity);
2023-12-11 17:29:06 -06:00
foreach (var server in servers)
{
ServerProcessService.StartServerAsync(server.Id);
2023-12-11 17:29:06 -06:00
}
2023-11-17 02:28:46 -06:00
}
public async Task EndSessionAsync(Guid gameId, Guid userId)
2023-11-17 02:28:46 -06:00
{
var existingSession = await FirstOrDefaultAsync(ps => ps.GameId == gameId && ps.UserId == userId && ps.End == null);
2023-11-17 02:28:46 -06:00
if (existingSession != null)
{
existingSession.End = DateTime.UtcNow;
await UpdateAsync(existingSession);
2023-11-17 02:28:46 -06:00
}
2023-12-11 17:29:06 -06:00
var activeSessions = (await GetAsync(ps => ps.GameId == gameId && ps.End == null)).Any();
2023-12-11 17:29:06 -06:00
if (!activeSessions)
{
var servers = await ServerService.GetAsync(s => s.GameId == gameId && s.Autostart && s.AutostartMethod == ServerAutostartMethod.OnPlayerActivity);
2023-12-11 17:29:06 -06:00
foreach (var server in servers)
{
ServerProcessService.StopServerAsync(server.Id);
2023-12-11 17:29:06 -06:00
}
}
2023-11-17 02:28:46 -06:00
}
}
}