Skip to content

Commit

Permalink
Boiler plate for replay upload at end of game
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEadie committed Jul 19, 2023
1 parent 91badf8 commit ac83bc7
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Worms.Cli.Resources.Remote;
using Worms.Cli.Resources.Remote.Auth;
using Worms.Cli.Resources.Remote.Games;
using Worms.Cli.Resources.Remote.Replays;

namespace Worms.Cli.Resources.Modules
{
Expand Down Expand Up @@ -37,6 +38,7 @@ protected override void Load(ContainerBuilder builder)
builder.RegisterType<LocalReplayRetriever>().As<IResourceRetriever<LocalReplay>>();
builder.RegisterType<LocalReplayDeleter>().As<IResourceDeleter<LocalReplay>>();
builder.RegisterType<LocalReplayViewer>().As<IResourceViewer<LocalReplay, LocalReplayViewParameters>>();
builder.RegisterType<RemoteReplayCreator>().As<IResourceCreator<RemoteReplay, string>>();

// Gifs
builder.RegisterType<LocalGifCreator>().As<IResourceCreator<LocalGif, LocalGifCreateParameters>>();
Expand Down Expand Up @@ -67,4 +69,4 @@ private static void RegisterOsModules(ContainerBuilder builder)
}
}
}
}
}
2 changes: 2 additions & 0 deletions src/cli/src/Worms.Cli.Resources/Remote/IWormsServerApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ internal interface IWormsServerApi

Task<WormsServerApi.GamesDtoV1> CreateGame(WormsServerApi.CreateGameDtoV1 hostMachineName);
Task UpdateGame(WormsServerApi.GamesDtoV1 newGameDetails);

Task<WormsServerApi.ReplayDtoV1> CreateReplay(string replayFilePath);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Worms.Cli.Resources.Remote.Replays;

public record RemoteReplay(string Id);
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Serilog;

namespace Worms.Cli.Resources.Remote.Replays;

internal class RemoteReplayCreator : IResourceCreator<RemoteReplay, string>
{
private readonly IWormsServerApi _api;

public RemoteReplayCreator(IWormsServerApi api)
{
_api = api;
}

public async Task<RemoteReplay> Create(string parameters, ILogger logger, CancellationToken cancellationToken)
{
try
{
var apiReplay = await _api.CreateReplay(parameters);
return new RemoteReplay(apiReplay.Id);
}
catch (HttpRequestException e)
{
switch (e.StatusCode)
{
case HttpStatusCode.Unauthorized:
logger.Warning(
"You don't have access to the Worms Hub. Please run worms auth or contact an admin");
break;
default:
logger.Error(e, "An error occured calling the Worms Hub API");
break;
}

return new RemoteReplay("");
}
}
}
38 changes: 29 additions & 9 deletions src/cli/src/Worms.Cli.Resources/Remote/WormsServerApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
Expand All @@ -15,12 +16,15 @@ internal class WormsServerApi : IWormsServerApi
{
private readonly IAccessTokenRefreshService _accessTokenRefreshService;
private readonly ITokenStore _tokenStore;
private readonly IFileSystem _fileSystem;
private readonly HttpClient _httpClient;

public WormsServerApi(IAccessTokenRefreshService accessTokenRefreshService, ITokenStore tokenStore)
public WormsServerApi(IAccessTokenRefreshService accessTokenRefreshService, ITokenStore tokenStore,
IFileSystem fileSystem)
{
_accessTokenRefreshService = accessTokenRefreshService;
_tokenStore = tokenStore;
_fileSystem = fileSystem;
_httpClient = new HttpClient();
#if DEBUG
_httpClient.BaseAddress = new Uri("https://localhost:5001/");
Expand All @@ -29,6 +33,16 @@ public WormsServerApi(IAccessTokenRefreshService accessTokenRefreshService, ITok
#endif
}

public record GamesDtoV1(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("hostMachine")]
string HostMachine);

public record CreateGameDtoV1(
[property: JsonPropertyName("hostMachine")]
string HostMachine);

public async Task<IReadOnlyCollection<GamesDtoV1>> GetGames()
{
var path = new Uri("api/v1/games", UriKind.Relative);
Expand All @@ -50,15 +64,21 @@ await CallApiRefreshAccessTokenIfInvalid(async () =>
await _httpClient.PutAsJsonAsync(path, newGameDetails));
}

public record GamesDtoV1(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("hostMachine")]
string HostMachine);
public record ReplayDtoV1([property: JsonPropertyName("id")] string Id);

public async Task<ReplayDtoV1> CreateReplay(string replayFilePath)
{
using var form = new MultipartFormDataContent();
using var fileContent = new ByteArrayContent(await _fileSystem.File.ReadAllBytesAsync(replayFilePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

form.Add(fileContent, "replayFile", _fileSystem.Path.GetFileName(replayFilePath));

var path = new Uri("api/v1/replays", UriKind.Relative);
return await CallApiRefreshAccessTokenIfInvalid<ReplayDtoV1>(async () =>
await _httpClient.PostAsync(path, form));
}

public record CreateGameDtoV1(
[property: JsonPropertyName("hostMachine")]
string HostMachine);

private async Task<T> CallApiRefreshAccessTokenIfInvalid<T>(Func<Task<HttpResponseMessage>> apiCall)
{
Expand Down
15 changes: 12 additions & 3 deletions src/cli/src/Worms/Commands/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Worms.Armageddon.Game;
using Worms.Cli.Resources;
using Worms.Cli.Resources.Remote.Games;
using Worms.Cli.Resources.Remote.Replays;
using Worms.Configuration;
using Worms.League;
using Worms.Slack;
Expand All @@ -18,12 +19,13 @@ namespace Worms.Commands
internal class Host : Command
{
public static readonly Option<bool> DryRun = new(
new[] { "--dry-run", "-dr" },
new[] {"--dry-run", "-dr"},
"When set the CLI will print what will happen rather than running the commands");

public static readonly Option<bool> LocalMode = new(
new[] { "--local-mode" },
new[] {"--local-mode"},
"Use legacy local mode to announce to Slack");

public Host() : base("host", "Host a game of worms using the latest options")
{
AddOption(DryRun);
Expand All @@ -41,6 +43,7 @@ internal class HostHandler : ICommandHandler
private readonly LeagueUpdater _leagueUpdater;
private readonly IResourceCreator<RemoteGame, string> _remoteGameCreator;
private readonly IRemoteGameUpdater _gameUpdater;
private readonly IResourceCreator<RemoteReplay, string> _remoteReplayCreator;
private readonly ILogger _logger;

public HostHandler(
Expand All @@ -51,6 +54,7 @@ public HostHandler(
LeagueUpdater leagueUpdater,
IResourceCreator<RemoteGame, string> remoteGameCreator,
IRemoteGameUpdater gameUpdater,
IResourceCreator<RemoteReplay, string> remoteReplayCreator,
ILogger logger)
{
_wormsRunner = wormsRunner;
Expand All @@ -60,6 +64,7 @@ public HostHandler(
_leagueUpdater = leagueUpdater;
_remoteGameCreator = remoteGameCreator;
_gameUpdater = gameUpdater;
_remoteReplayCreator = remoteReplayCreator;
_logger = logger;
}

Expand Down Expand Up @@ -102,7 +107,7 @@ public async Task<int> InvokeAsync(InvocationContext context)
}

_logger.Information("Starting Worms Armageddon");
var runGame = !dryRun ? _wormsRunner.RunWorms("wa://") : Task.CompletedTask;
var runGame = !dryRun ? _wormsRunner.RunWorms("wa://") : Task.Delay(5000, cancellationToken);

if (localMode)
{
Expand Down Expand Up @@ -136,6 +141,10 @@ await _slackAnnouncer.AnnounceGameStarting(hostIp, config.SlackWebHook, _logger)
await _gameUpdater.SetGameComplete(game, _logger, cancellationToken);
}

_logger.Information("Uploading replay to hub");
await _remoteReplayCreator.Create("test.txt", _logger, cancellationToken);


return 0;
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/hub/src/Worms.Gateway/Controllers/ReplaysController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Worms.Gateway.Dtos;

namespace Worms.Gateway.Controllers;

public class ReplaysController : V1ApiController
{
[HttpPost]
public ActionResult<ReplayDto> Post(IFormFile replayFile)
{
Console.WriteLine(replayFile.FileName);
return new ReplayDto("0");
}
}
3 changes: 3 additions & 0 deletions src/hub/src/Worms.Gateway/Dtos/ReplayDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Worms.Gateway.Dtos;

public record ReplayDto(string Id);

0 comments on commit ac83bc7

Please sign in to comment.