LANCommander/LANCommander.Server/Controllers/Api/SavesController.cs

182 lines
6 KiB
C#
Raw Permalink Normal View History

using AutoMapper;
2024-08-04 18:44:33 -05:00
using LANCommander.Server.Data.Models;
using LANCommander.Server.Extensions;
using LANCommander.Server.Services;
2023-03-28 21:30:29 -05:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
2024-08-04 18:44:33 -05:00
namespace LANCommander.Server.Controllers.Api
2023-03-28 21:30:29 -05:00
{
[Authorize(AuthenticationSchemes = "Bearer")]
[Route("api/[controller]")]
[ApiController]
public class SavesController : BaseApiController
2023-03-28 21:30:29 -05:00
{
private readonly IMapper Mapper;
2023-03-28 21:30:29 -05:00
private readonly GameService GameService;
private readonly GameSaveService GameSaveService;
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
private readonly UserService UserService;
2023-03-28 21:30:29 -05:00
public SavesController(
ILogger<SavesController> logger,
IMapper mapper,
GameService gameService,
GameSaveService gameSaveService,
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
UserService userService) : base(logger)
2023-03-28 21:30:29 -05:00
{
Mapper = mapper;
2023-03-28 21:30:29 -05:00
GameService = gameService;
GameSaveService = gameSaveService;
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
UserService = userService;
2023-03-28 21:30:29 -05:00
}
[HttpGet]
2024-11-12 23:22:01 -06:00
public async Task<ActionResult<IEnumerable<SDK.Models.GameSave>>> GetAsync()
2023-03-28 21:30:29 -05:00
{
return Ok(Mapper.Map<IEnumerable<SDK.Models.GameSave>>(await GameSaveService.GetAsync()));
2023-03-28 21:30:29 -05:00
}
[HttpGet("{id}")]
2024-11-12 23:22:01 -06:00
public async Task<ActionResult<SDK.Models.GameSave>> GetAsync(Guid id)
2023-03-28 21:30:29 -05:00
{
var gameSave = await GameSaveService.GetAsync(id);
if (gameSave == null)
return NotFound();
return Ok(Mapper.Map<SDK.Models.GameSave>(gameSave));
2023-03-28 21:30:29 -05:00
}
2024-02-17 17:30:14 -06:00
[HttpGet("Game/{gameId}")]
2024-11-12 23:22:01 -06:00
public async Task<ActionResult<IEnumerable<SDK.Models.GameSave>>> GetGameSavesAsync(Guid gameId)
2024-02-17 17:30:14 -06:00
{
var user = await UserService.GetAsync(User?.Identity?.Name);
2024-02-17 17:30:14 -06:00
if (user == null)
return Unauthorized();
2024-02-17 17:30:14 -06:00
var userSaves = await GameSaveService.GetAsync(gs => gs.UserId == user.Id && gs.GameId == gameId);
return Ok(Mapper.Map<IEnumerable<SDK.Models.GameSave>>(userSaves));
2024-02-17 17:30:14 -06:00
}
[HttpGet("Latest/{gameId}")]
2024-11-12 23:22:01 -06:00
public async Task<ActionResult<SDK.Models.GameSave>> LatestAsync(Guid gameId)
{
var user = await UserService.GetAsync(User?.Identity?.Name);
if (user == null)
return Unauthorized();
var latestSave = await GameSaveService.Query(q =>
{
return q.OrderByDescending(s => s.CreatedOn);
}).FirstOrDefaultAsync(gs => gs.UserId == user.Id && gs.GameId == gameId);
// Should probably return 404 if no latest save exists
// Not sure if this will affect launcher stability
return Ok(Mapper.Map<SDK.Models.GameSave>(latestSave));
}
2023-03-28 21:30:29 -05:00
[HttpGet("DownloadLatest/{gameId}")]
2024-11-12 23:22:01 -06:00
public async Task<IActionResult> DownloadLatestAsync(Guid gameId)
2023-03-28 21:30:29 -05:00
{
var user = await UserService.GetAsync(User?.Identity?.Name);
2023-03-28 21:30:29 -05:00
if (user == null)
return NotFound();
var save = await GameSaveService.Query(q =>
{
return q.OrderByDescending(s => s.CreatedOn);
}).FirstOrDefaultAsync(gs => gs.UserId == user.Id && gs.GameId == gameId);
2023-03-28 21:30:29 -05:00
if (save == null)
return NotFound();
var filename = save.GetUploadPath();
if (!System.IO.File.Exists(filename))
return NotFound();
return File(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), "application/octet-stream", $"{save.Id.ToString().SanitizeFilename()}.zip");
}
[HttpGet("Download/{id}")]
2024-11-12 23:22:01 -06:00
public async Task<IActionResult> DownloadAsync(Guid id)
2023-03-28 21:30:29 -05:00
{
var save = await GameSaveService.GetAsync(id);
2023-03-28 21:30:29 -05:00
if (save == null)
return NotFound();
var filename = save.GetUploadPath();
if (!System.IO.File.Exists(filename))
return NotFound();
return File(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), "application/octet-stream", $"{save.Id.ToString().SanitizeFilename()}.zip");
}
[HttpPost("Upload/{id}")]
2024-11-12 23:22:01 -06:00
public async Task<IActionResult> UploadAsync(Guid id)
2023-03-28 21:30:29 -05:00
{
var file = Request.Form.Files.First();
var user = await UserService.GetAsync(User?.Identity?.Name);
var game = await GameService.GetAsync(id);
2023-03-28 21:30:29 -05:00
if (game == null)
return NotFound();
var save = new GameSave()
{
GameId = id,
2024-10-23 22:33:28 -05:00
UserId = user.Id,
Size = file.Length,
2023-03-28 21:30:29 -05:00
};
save = await GameSaveService.AddAsync(save);
2023-03-28 21:30:29 -05:00
var saveUploadPath = Path.GetDirectoryName(save.GetUploadPath());
if (!Directory.Exists(saveUploadPath))
Directory.CreateDirectory(saveUploadPath);
using (var stream = System.IO.File.Create(save.GetUploadPath()))
{
await file.CopyToAsync(stream);
}
if (Settings.UserSaves.MaxSaves > 0)
{
var saves = (await GameSaveService.GetAsync(gs => gs.UserId == user.Id && gs.GameId == game.Id)).OrderByDescending(gs => gs.CreatedOn).Skip(Settings.UserSaves.MaxSaves).ToList();
foreach (var extraSave in saves)
await GameSaveService.DeleteAsync(extraSave);
}
return Ok(Mapper.Map<SDK.Models.GameSave>(save));
2023-03-28 21:30:29 -05:00
}
2024-02-17 17:30:14 -06:00
2024-11-12 23:28:05 -06:00
[HttpDelete("Delete/{id}")]
2024-11-12 23:22:01 -06:00
public async Task<IActionResult> DeleteAsync(Guid id)
2024-02-17 17:30:14 -06:00
{
try
{
var save = await GameSaveService.GetAsync(id);
2024-02-17 17:30:14 -06:00
await GameSaveService.DeleteAsync(save);
2024-02-17 17:30:14 -06:00
return Ok();
2024-02-17 17:30:14 -06:00
}
catch (Exception ex)
2024-02-17 17:30:14 -06:00
{
Logger.LogError(ex, "An unknown error occurred while trying to delete a game save with the ID {GameSaveId}", id);
return BadRequest();
2024-02-17 17:30:14 -06:00
}
}
2023-03-28 21:30:29 -05:00
}
}