LANCommander/LANCommander.Server.Services/PlaySessionService.cs

69 lines
2.3 KiB
C#
Raw Permalink Normal View History

using AutoMapper;
using LANCommander.Server.Data;
2024-08-04 18:44:33 -05:00
using LANCommander.Server.Data.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.AspNetCore.Http;
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 sealed class PlaySessionService(
ILogger<PlaySessionService> logger,
SettingsProvider<Settings.Settings> settingsProvider,
IFusionCache cache,
IMapper mapper,
IHttpContextAccessor httpContextAccessor,
IDbContextFactory<DatabaseContext> contextFactory,
ServerService serverService) : BaseDatabaseService<PlaySession>(logger, settingsProvider, cache, mapper, httpContextAccessor, contextFactory)
2023-11-17 02:28:46 -06:00
{
2025-02-23 08:49:43 -06:00
public override async Task<PlaySession> AddAsync(PlaySession entity)
{
return await base.AddAsync(entity, async context =>
{
await context.UpdateRelationshipAsync(ps => ps.Game);
await context.UpdateRelationshipAsync(ps => ps.User);
});
}
2025-02-02 14:58:07 -06:00
public override async Task<PlaySession> UpdateAsync(PlaySession entity)
{
2025-02-02 14:58:07 -06:00
return await base.UpdateAsync(entity, async context =>
{
await context.UpdateRelationshipAsync(ps => ps.Game);
await context.UpdateRelationshipAsync(ps => ps.User);
});
2023-12-11 17:29:06 -06:00
}
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-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
}
}
}
}