Skip to content

Commit

Permalink
Updated to work with mod framework updates and fixed version update c…
Browse files Browse the repository at this point in the history
…hecking!
  • Loading branch information
iamwyza committed Nov 30, 2017
1 parent 2ec92fb commit 8771090
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 155 deletions.
63 changes: 24 additions & 39 deletions PlayerDataDump/PlayerDataDump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Linq;
using Modding;
using WebSocketSharp.Server;
using System.Net;
using System.Reflection;

namespace PlayerDataDump
Expand All @@ -15,69 +14,55 @@ namespace PlayerDataDump
/// </summary>
public class PlayerDataDump : Mod
{
public WebSocketServer Wss = new WebSocketServer(11420);

public static string Version = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(PlayerDataDump)).Location).FileVersion;
public static string Current;
private readonly WebSocketServer _wss = new WebSocketServer(11420);
internal static PlayerDataDump Instance;

/// <summary>
/// Fetches the list of the current mods installed.
/// </summary>
public static string GetCurrentMods()
{
List<string> mods = ModHooks.Instance.loadedMods;
List<string> mods = ModHooks.Instance.LoadedMods;
string output = mods.Aggregate("[", (current, mod) => current + $"\"{mod}\",");
output = output.TrimEnd(',') + "]";
return output;
}

/// <summary>
/// Fetches current version from the site
/// Fetches and compares the compiled version with the version from the site.
/// </summary>
/// <returns>Version #</returns>
public string GetCurrentVersion()
/// <returns>Returns the current version. Includes additional text if the current version doesn't match the version of the site.</returns>
public override string GetVersion() => FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(PlayerDataDump)).Location).FileVersion;

public override bool IsCurrent()
{
try
{
WebClient web = new WebClient
{
Headers =
{
[HttpRequestHeader.UserAgent] =
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"
},

};
GithubVersionHelper helper = new GithubVersionHelper("iamwyza/HollowKnightRandomizerTracker");
Version currentVersion = new Version(GetVersion());

return web.DownloadString("https://iamwyza.github.io/HollowKnightRandomizerTracker/version.txt");
} catch(Exception e) {
ModHooks.ModLog(e.ToString());
return Version;
Version newVersion = new Version(helper.GetVersion());
LogDebug($"Comparing Versions: {newVersion} > {currentVersion}");
return newVersion.CompareTo(currentVersion) < 0;
}
catch (Exception ex)
{
LogError("Couldn't check version" + ex);
}
}

/// <summary>
/// Fetches and compares the compiled version with the version from the site.
/// </summary>
/// <returns>Returns the current version. Includes additional text if the current version doesn't match the version of the site.</returns>
public override string GetVersion()
{
if (Current == null)
Current = GetCurrentVersion();
if ( Current == Version )
return Version;
return Version + " | UPDATE REQUIRED";
return true;
}

/// <summary>
/// Creates and starts the WebSocket Server instances.
/// </summary>
public override void Initialize()
{
ModHooks.ModLog("Initializing PlayerDataDump");
Instance = this;
Log("Initializing PlayerDataDump");

//Setup websockets server
Wss.AddWebSocketService<SocketServer>("/playerData", ss =>
_wss.AddWebSocketService<SocketServer>("/playerData", ss =>
{
ModHooks.Instance.NewGameHook += ss.NewGame;
ModHooks.Instance.SavegameLoadHook += ss.LoadSave;
Expand All @@ -88,11 +73,11 @@ public override void Initialize()
});

//Setup ProfileStorage Server
Wss.AddWebSocketService<ProfileStorageServer>("/ProfileStorage", ss => { });
_wss.AddWebSocketService<ProfileStorageServer>("/ProfileStorage", ss => { });

Wss.Start();
_wss.Start();

ModHooks.ModLog("Initialized PlayerDataDump");
Log("Initialized PlayerDataDump");
}
}
}
98 changes: 1 addition & 97 deletions PlayerDataDump/PlayerDataDump.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
<ItemGroup>
<Reference Include="Assembly-CSharp, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\Steam\steamapps\common\Hollow Knight\hollow_knight_Data\Managed\Assembly-CSharp.dll</HintPath>
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Hollow Knight\hollow_knight_Data\Managed\Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="PlayMaker, Version=1.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
Expand Down Expand Up @@ -76,100 +76,4 @@
<_PostBuildHookTimestamp>@(IntermediateAssembly->'%(FullPath).timestamp')</_PostBuildHookTimestamp>
<_PostBuildHookHostPlatform>$(Platform)</_PostBuildHookHostPlatform>
</PropertyGroup>
<PropertyGroup>
<CompileDependsOn>
CommonBuildDefineModifiedAssemblyVersion;
$(CompileDependsOn);
</CompileDependsOn>
</PropertyGroup>
<Target Name="PostBuildHooks" Inputs="@(IntermediateAssembly);@(ReferencePath)" Outputs="@(IntermediateAssembly);$(_PostBuildHookTimestamp)" AfterTargets="CoreCompile" BeforeTargets="AfterCompile">
<Touch Files="$(_PostBuildHookTimestamp)" AlwaysCreate="True" />
</Target>
<!-- Using this approach vs Community Build Tasks to avoid having more requirements -->
<!-- http://www.lionhack.com/2014/02/13/msbuild-override-assembly-version/ -->
<!--
Creates modified version of AssemblyInfo.cs, replaces [AssemblyFileVersion] attribute with the one specifying actual build version (from MSBuild properties), and includes that file instead of the original AssemblyInfo.cs in the compilation.
Works with both, .cs and .vb version of the AssemblyInfo file, meaning it supports C# and VB.Net projects simultaneously.
-->
<Target Name="CommonBuildDefineModifiedAssemblyVersion">
<!-- Find AssemblyInfo.cs or AssemblyInfo.vb in the "Compile" Items. Remove it from "Compile" Items because we will use a modified version instead. -->
<ItemGroup>
<OriginalAssemblyInfo Include="@(Compile)" Condition="%(Filename) == 'AssemblyInfo' And (%(Extension) == '.vb' Or %(Extension) == '.cs')" />
<Compile Remove="**/AssemblyInfo.vb" />
<Compile Remove="**/AssemblyInfo.cs" />
</ItemGroup>
<!-- Copy the original AssemblyInfo.cs/.vb to obj\ folder, i.e. $(IntermediateOutputPath). The copied filepath is saved into @(ModifiedAssemblyInfo) Item. -->
<Copy SourceFiles="@(OriginalAssemblyInfo)"
DestinationFiles="@(OriginalAssemblyInfo->'$(IntermediateOutputPath)%(Identity)')">
<Output TaskParameter="DestinationFiles" ItemName="ModifiedAssemblyInfo"/>
</Copy>
<GetVersion>
<Output ItemName="FileVersionAssembly" TaskParameter="Result" />
</GetVersion>
<!-- Replace the version bit (in AssemblyVersion and AssemblyFileVersion attributes) using regular expression. Use the defined property: $(VersionAssembly). -->
<Message Text="Setting AssemblyFileVersion to @(FileVersionAssembly)" Importance="high"/>
<RegexUpdateFile Files="@(ModifiedAssemblyInfo)"
Regex="AssemblyFileVersion\(&quot;.*&quot;\)"
ReplacementText="AssemblyFileVersion(&quot;@(FileVersionAssembly)&quot;)"
/>
<!-- Include the modified AssemblyInfo.cs/.vb file in "Compile" items (instead of the original). -->
<ItemGroup>
<Compile Include="@(ModifiedAssemblyInfo)" />
</ItemGroup>
</Target>

<UsingTask TaskName="RegexUpdateFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
<Regex ParameterType="System.String" Required="true" />
<ReplacementText ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Text.RegularExpressions" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
var rx = new System.Text.RegularExpressions.Regex(this.Regex);
for (int i = 0; i < Files.Length; ++i)
{
var path = Files[i].GetMetadata("FullPath");
if (!File.Exists(path)) continue;
var txt = File.ReadAllText(path);
txt = rx.Replace(txt, this.ReplacementText);
File.WriteAllText(path, txt);
}
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
<UsingTask TaskName="GetVersion" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
<ParameterGroup>
<Result ParameterType="System.String" Output="true" />
</ParameterGroup>
<Task>
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
// Log.LogMessage(MessageImportance.High, File.ReadAllText("../version.txt"));
Result = File.ReadAllText("../version.txt");
]]>
</Code>
</Task>
</UsingTask>

</Project>
15 changes: 7 additions & 8 deletions PlayerDataDump/ProfileStorageServer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Modding;
using System;
using System;
using System.IO;
using System.Text;
using UnityEngine;
Expand All @@ -21,7 +20,7 @@ public void Broadcast(string s)

protected override void OnMessage(MessageEventArgs e)
{
ModHooks.ModLog("[PlayerDataDump.ProfileStorage] data:" + e.Data);
PlayerDataDump.Instance.Log("[ProfileStorage] data:" + e.Data);

if (e.Data.StartsWith("load"))
{
Expand Down Expand Up @@ -59,28 +58,28 @@ private static void SaveProfile(int profileId, string base64EncodedJson)
byte[] data = Convert.FromBase64String(base64EncodedJson);
string decodedString = Encoding.UTF8.GetString(data);

ModHooks.ModLog("[PlayerDataDump.ProfileStorage] Path::" + path);
ModHooks.ModLog("[PlayerDataDump.ProfileStorage] Decoded Data:" + decodedString);
PlayerDataDump.Instance.Log("[ProfileStorage] Path:" + path);
PlayerDataDump.Instance.Log("[ProfileStorage] Decoded Data:" + decodedString);

File.WriteAllText(path, decodedString);

}

protected override void OnError(WebSocketSharp.ErrorEventArgs e)
{
ModHooks.ModLog("[PlayerDataDump.ProfileStorage] ERROR: " + e.Message);
PlayerDataDump.Instance.LogError("[ProfileStorage]:" + e.Message);
}

protected override void OnClose(CloseEventArgs e)
{
base.OnClose(e);

ModHooks.ModLog("[PlayerDataDump.ProfileStorage] CLOSE: Code:" + e.Code + ", Reason:" + e.Reason);
PlayerDataDump.Instance.Log("[ProfileStorage] CLOSE: Code:" + e.Code + ", Reason:" + e.Reason);
}

protected override void OnOpen()
{
ModHooks.ModLog("[PlayerDataDump.ProfileStorage] OPEN");
PlayerDataDump.Instance.Log("[ProfileStorage] OPEN");
}
}
}
4 changes: 2 additions & 2 deletions PlayerDataDump/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
18 changes: 9 additions & 9 deletions PlayerDataDump/SocketServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ protected override void OnMessage(MessageEventArgs e)
Send(PlayerDataDump.GetCurrentMods());
break;
case "version":
Send(string.Format("{{ \"version\":\"{0}\" }}", PlayerDataDump.Version));
Send(string.Format("{{ \"version\":\"{0}\" }}", PlayerDataDump.Instance.GetVersion()));
break;
case "json":
Send(GetJson());
Expand All @@ -55,12 +55,12 @@ protected override void OnMessage(MessageEventArgs e)
{
if (e.Data.Split('|')[0] == "bool")
{
string b = ModHooks.Instance.GetPlayerBool(e.Data.Split('|')[1]).ToString();
string b = PlayerData.instance.GetBool(e.Data.Split('|')[1]).ToString();
SendMessage(e.Data.Split('|')[1], b);
}
if (e.Data.Split('|')[0] == "int")
{
string i = ModHooks.Instance.GetPlayerInt(e.Data.Split('|')[1]).ToString();
string i = PlayerData.instance.GetInt(e.Data.Split('|')[1]).ToString();
SendMessage(e.Data.Split('|')[1], i);
}
}
Expand All @@ -74,7 +74,7 @@ protected override void OnMessage(MessageEventArgs e)

protected override void OnError(WebSocketSharp.ErrorEventArgs e)
{
ModHooks.ModLog("[PlayerDataDump] ERROR: " + e.Message);
PlayerDataDump.Instance.LogError(e.Message);
}

protected override void OnClose(CloseEventArgs e)
Expand All @@ -88,12 +88,12 @@ protected override void OnClose(CloseEventArgs e)

ModHooks.Instance.ApplicationQuitHook -= OnQuit;

ModHooks.ModLog("[PlayerDataDump] CLOSE: Code:" + e.Code + ", Reason:" + e.Reason);
PlayerDataDump.Instance.Log("CLOSE: Code:" + e.Code + ", Reason:" + e.Reason);
}

protected override void OnOpen()
{
ModHooks.ModLog("[PlayerDataDump] OPEN");
PlayerDataDump.Instance.Log("OPEN");
}

public void SendMessage(string var, string value)
Expand Down Expand Up @@ -128,9 +128,9 @@ public static string GetJson()
PlayerData playerData = PlayerData.instance;
string json = JsonUtility.ToJson(playerData);

int randomFireballLevel = ModHooks.Instance.GetPlayerInt("_fireballLevel");
int randomQuakeLevel = ModHooks.Instance.GetPlayerInt("_quakeLevel");
int randomScreamLevel = ModHooks.Instance.GetPlayerInt("_screamLevel");
int randomFireballLevel = PlayerData.instance.GetInt("_fireballLevel");
int randomQuakeLevel = PlayerData.instance.GetInt("_quakeLevel");
int randomScreamLevel = PlayerData.instance.GetInt("_screamLevel");

if (randomFireballLevel >= 0)
{
Expand Down

0 comments on commit 8771090

Please sign in to comment.