LANCommander/LANCommander.Launcher.Services/PlaySessionService.cs

85 lines
2.9 KiB
C#
Raw Permalink Normal View History

using LANCommander.Launcher.Data;
using LANCommander.Launcher.Data.Models;
2025-10-08 19:51:44 -05:00
using LANCommander.SDK.Extensions;
using Microsoft.EntityFrameworkCore;
2024-09-11 00:24:34 -05:00
using Microsoft.Extensions.Logging;
2024-06-03 19:06:25 -05:00
namespace LANCommander.Launcher.Services
2024-06-03 19:06:25 -05:00
{
public class PlaySessionService(
ILogger<PlaySessionService> logger,
DatabaseContext dbContext,
SDK.Client client) : BaseDatabaseService<PlaySession>(dbContext, logger)
2024-06-03 19:06:25 -05:00
{
public async Task<PlaySession> GetLatestSession(Guid gameId, Guid userId)
{
return await Query(ps => ps.GameId == gameId && ps.UserId == userId).OrderByDescending(ps => ps.End).FirstOrDefaultAsync();
}
2024-06-03 19:06:25 -05:00
public async Task StartSession(Guid gameId, Guid userId)
{
2025-10-08 19:51:44 -05:00
using (var op = Logger.BeginOperation("Starting game session"))
2024-06-03 19:06:25 -05:00
{
2025-10-08 19:51:44 -05:00
op.Enrich("GameId", gameId);
op.Enrich("UserId", userId);
try
{
var existingSession = Query(ps => ps.GameId == gameId && ps.UserId == userId && ps.End == null).FirstOrDefault();
2024-06-03 19:06:25 -05:00
2025-10-08 19:51:44 -05:00
if (existingSession != null)
await DeleteAsync(existingSession);
2025-10-08 19:51:44 -05:00
var session = new PlaySession()
{
GameId = gameId,
UserId = userId,
Start = DateTime.UtcNow
};
2025-10-08 19:51:44 -05:00
await AddAsync(session);
2025-10-08 19:51:44 -05:00
await client.Games.StartedAsync(gameId);
}
catch (Exception ex)
{
Logger?.LogError(ex, "An unknown error occurred while trying to start session recording for game with ID {GameId}", gameId);
}
op.Complete();
}
2024-06-03 19:06:25 -05:00
}
public async Task EndSession(Guid gameId, Guid userId)
{
2025-10-08 19:51:44 -05:00
using (var op = Logger.BeginOperation("Ending game session"))
2024-06-03 19:06:25 -05:00
{
2025-10-08 19:51:44 -05:00
op.Enrich("GameId", gameId);
op.Enrich("UserId", userId);
try
{
2025-10-08 19:51:44 -05:00
var existingSession = Query(ps => ps.GameId == gameId && ps.UserId == userId && ps.End == null).FirstOrDefault();
2025-10-08 19:51:44 -05:00
if (existingSession != null)
{
existingSession.End = DateTime.UtcNow;
await UpdateAsync(existingSession);
}
}
2025-10-08 19:51:44 -05:00
catch (Exception ex)
{
Logger?.LogError(ex, "An unknown error occurred while trying to end session recording for game with ID {GameId}", gameId);
}
finally
{
await client.Games.StoppedAsync(gameId);
}
op.Complete();
}
2024-06-03 19:06:25 -05:00
}
}
}