Browse Source

Improve web request reliability and readability

tags/v1.0.0
NGnius (Graham) 3 years ago
parent
commit
1a03950b4a
4 changed files with 58 additions and 37 deletions
  1. +6
    -6
      Leadercraft/LeadercraftPlugin.cs
  2. +16
    -6
      Leadercraft/Scoring/State.cs
  3. +3
    -2
      Leadercraft/Scoring/UploadJob.cs
  4. +33
    -23
      Leadercraft/Server/LeadercraftApi.cs

+ 6
- 6
Leadercraft/LeadercraftPlugin.cs View File

@@ -26,9 +26,9 @@ namespace Leadercraft

private static string criteriaUrl =
#if DEBUG
"http://192.168.122.229:7048/c/criteria";
"http://192.168.122.229:7048/criteria";
#else
"https://leadercraft.exmods.org/criteria";
"https://leadercraft.exmods.org/c/criteria";
#endif
public static void BuildApi()
{
@@ -36,11 +36,11 @@ namespace Leadercraft
{
if (!Tools.IsSteamAvailable)
{
Logging.MetaDebugLog("Steam is unavailable :(");
Logging.MetaLog("Steam is unavailable :(");
return;
}
Api = new LeadercraftApi(Tools.UserId, tokenUrl, criteriaUrl);
GamecraftModdingAPI.Utility.Logging.MetaDebugLog("Leadercraft API initialized");
GamecraftModdingAPI.Utility.Logging.MetaLog("Leadercraft API initialized");
}
}

@@ -66,10 +66,10 @@ namespace Leadercraft
GamecraftModdingAPI.App.Game.Edit += (_, __) => State.StopPlayingGame();
GamecraftModdingAPI.App.Game.Enter += (_, __) => State.EnterGame();
GamecraftModdingAPI.App.Game.Exit += (_, __) => State.ExitGame();
GamecraftModdingAPI.Utility.Logging.LogDebug($"{Name} has started up");
GamecraftModdingAPI.Utility.Logging.MetaLog($"{Name} has started up");

// Debug mode
Debug();
//Debug();
}

// unused methods


+ 16
- 6
Leadercraft/Scoring/State.cs View File

@@ -30,30 +30,32 @@ namespace Leadercraft.Scoring

public static bool IsGameSynced { get; private set; }

private static bool isBadGame = false;

private static Player localPlayer = null;

public static void EnterGame()
{
if (IsInGame) return;
Logging.MetaDebugLog("Entering game");
IsInGame = true;
IsGameSynced = false;
IsGameComplete = false;
GameId = Server.Tools.GameId;
GameEnterTime = DateTime.UtcNow;
Logging.MetaLog($"Entering game {GameId} at {GameEnterTime}");
}

public static void ExitGame()
{
if (!IsInGame) return;
Logging.MetaDebugLog("Exiting game");
Logging.MetaLog($"Exiting game {GameId}");
IsInGame = false;
}

public static void StartPlayingGame()
{
if (IsPlayingGame) return;
Logging.MetaDebugLog("Starting to play game");
Logging.MetaLog($"Starting to play game {GameId}");
Score = 0;
IsPlayingGame = true;
GameStartTime = DateTime.UtcNow;
@@ -67,7 +69,7 @@ namespace Leadercraft.Scoring
{
if (!IsPlayingGame) return;
GamePlayTime = DateTime.UtcNow - GameStartTime;
Logging.MetaDebugLog("Stopping game");
Logging.MetaLog($"Stopping game {GameId} after {GamePlayTime.TotalSeconds}s");
IsPlayingGame = false;
}

@@ -98,9 +100,17 @@ namespace Leadercraft.Scoring
private static void loopPass()
{
if (!State.IsPlayingGame) return;
if (localPlayer == null && Player.Exists(PlayerType.Local)) localPlayer = new Player(PlayerType.Local);
if (localPlayer == null && Player.Exists(PlayerType.Local))
{
localPlayer = new Player(PlayerType.Local);
isBadGame = localPlayer.GameOver;
if (isBadGame)
{
GamecraftModdingAPI.Utility.Logging.MetaLog($"Ignoring game {GameId} since it does not seem to have a GameOver state.");
}
}
if (localPlayer == null) return;
if (localPlayer.GameOver && !localPlayer.Dead)
if (localPlayer.GameOver && !localPlayer.Dead && !isBadGame)
{
State.StopPlayingGame();
//State.GamePlayTime.TotalSeconds


+ 3
- 2
Leadercraft/Scoring/UploadJob.cs View File

@@ -1,6 +1,6 @@
using System;
using System.Threading;
using GamecraftModdingAPI.App;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
@@ -32,7 +32,7 @@ namespace Leadercraft.Scoring
this.location = new float[3] { position.x, position.y, position.z};
this.player = playerId;
this.playerName = playerName;
this.game = 2;//gameId;
this.game = gameId;
LeadercraftPlugin.BuildApi();
}

@@ -44,6 +44,7 @@ namespace Leadercraft.Scoring

private void Execute()
{
if (Game.CurrentGame().Name == "Leadercraft's sucky game") game = 2;
if (player < 1000 || game == 0) return; // offline game
LeadercraftResult<KeyStruct> tokenResult = LeadercraftPlugin.Api.RequestPOSTToken(playerName);
if (tokenResult.IsError)


+ 33
- 23
Leadercraft/Server/LeadercraftApi.cs View File

@@ -23,22 +23,25 @@ namespace Leadercraft.Server
public LeadercraftResult<KeyStruct> RequestPOSTToken(string playerName = "???")
{
NewKeyStruct reqBodyObj = new NewKeyStruct{ PlayerID = _userId, PlayerName = playerName };
byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(reqBodyObj));
// Request
string reqBodyStr = JsonConvert.SerializeObject(reqBodyObj);
// Request
WebRequest request = WebRequest.Create(_tokenUrl);
request.Method = "POST";
request.ContentLength = reqBodyBytes.Length;
request.ContentLength = reqBodyStr.Length;
request.ContentType = "application/json";
Stream body;
StreamWriter body;
try
{
body = request.GetRequestStream();
body.Write(reqBodyBytes, 0, reqBodyBytes.Length);
body = new StreamWriter(request.GetRequestStream());
body.Write(reqBodyStr);
body.Close();
}
catch (WebException e)
{
return new LeadercraftResult<KeyStruct>(new byte[] { }, (int)e.Status);
int status = (int) e.Status;
if (e.Response != null && e.Response is HttpWebResponse webResponse)
status = (int)webResponse.StatusCode;
return new LeadercraftResult<KeyStruct>(new byte[] { }, status);
}
// Response
HttpWebResponse response = null;
@@ -48,35 +51,40 @@ namespace Leadercraft.Server
}
catch (WebException e)
{
return new LeadercraftResult<KeyStruct>(new byte[] { }, (int)e.Status);
int status = (int) e.Status;
if (e.Response != null && e.Response is HttpWebResponse webResponse)
status = (int)webResponse.StatusCode;
return new LeadercraftResult<KeyStruct>(new byte[] { }, status);
}
body = response.GetResponseStream();
byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))];
body.Read(respBodyBytes, 0, respBodyBytes.Length);
StreamReader respBody = new StreamReader(response.GetResponseStream());
string respBodyStr = respBody.ReadToEnd();
response.Close();
return new LeadercraftResult<KeyStruct>(respBodyBytes, (int)response.StatusCode);
return new LeadercraftResult<KeyStruct>(respBodyStr, (int)response.StatusCode);
}

public LeadercraftResult<string> RequestPOSTCriteria(CriteriaStruct criteria, string token)
{
criteria.PlayerID = _userId;
byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(criteria));
string reqBodyStr = JsonConvert.SerializeObject(criteria);
// Request
WebRequest request = WebRequest.Create(_criteriaUrl);
request.Method = "POST";
request.ContentLength = reqBodyBytes.Length;
request.ContentLength = reqBodyStr.Length;
request.ContentType = "application/json";
request.Headers.Add(HttpRequestHeader.Authorization, "leadercraft "+token);
Stream body;
StreamWriter body;
try
{
body = request.GetRequestStream();
body.Write(reqBodyBytes, 0, reqBodyBytes.Length);
body = new StreamWriter(request.GetRequestStream());
body.Write(reqBodyStr);
body.Close();
}
catch (WebException e)
{
return new LeadercraftResult<string>(new byte[] { }, (int)e.Status);
int status = (int) e.Status;
if (e.Response != null && e.Response is HttpWebResponse webResponse)
status = (int)webResponse.StatusCode;
return new LeadercraftResult<string>(new byte[] { }, status);
}
// Response
HttpWebResponse response = null;
@@ -86,13 +94,15 @@ namespace Leadercraft.Server
}
catch (WebException e)
{
return new LeadercraftResult<string>(new byte[] { }, (int)e.Status);
int status = (int) e.Status;
if (e.Response != null && e.Response is HttpWebResponse webResponse)
status = (int)webResponse.StatusCode;
return new LeadercraftResult<string>(new byte[] { }, status);
}
body = response.GetResponseStream();
byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))];
body.Read(respBodyBytes, 0, respBodyBytes.Length);
StreamReader respBody = new StreamReader(response.GetResponseStream());
string respBodyStr = respBody.ReadToEnd();
response.Close();
return new LeadercraftResult<string>(respBodyBytes, (int)response.StatusCode);
return new LeadercraftResult<string>(respBodyStr, (int)response.StatusCode);
}
}
}