Skip to content

Commit

Permalink
Cleanup of all the Classes, Methods, Variables to follow C#.Net (ReSh…
Browse files Browse the repository at this point in the history
…arper) standards. Removed Depreciated method of creating socket server in lieu of the newer correct method. Updated Build events to now grab version.txt from $(SolutionDir)/../version.txt and put that into the AssemblyFileVersion. AssemblyFileVersion is now used for the Version variable. Removed unused "using" statements.
  • Loading branch information
iamwyza committed Oct 28, 2017
1 parent 7eaf9c9 commit 2ec92fb
Show file tree
Hide file tree
Showing 14 changed files with 382 additions and 202 deletions.
103 changes: 55 additions & 48 deletions PlayerDataDump/PlayerDataDump.cs
Original file line number Diff line number Diff line change
@@ -1,89 +1,96 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using Modding;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using HutongGames.PlayMaker;
using System.Reflection;
using WebSocketSharp.Server;
using System.Net;
using System.Reflection;

namespace PlayerDataDump
{

/// <summary>
/// Main mod class for PlayerDataDump. Provides the server and version handling.
/// </summary>
public class PlayerDataDump : Mod
{
public WebSocketServer wss = new WebSocketServer(11420);
public static String version = "27/10/17.a (TGT)";
public static String current;
public WebSocketServer Wss = new WebSocketServer(11420);

public static string Version = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(PlayerDataDump)).Location).FileVersion;
public static string Current;

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

/// <summary>
/// Fetches current version from the site
/// </summary>
/// <returns>Version #</returns>
public string GetCurrentVersion()
{
try
{
WebClient web = new WebClient();
web.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";
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"
},

};

return web.DownloadString("https://iamwyza.github.io/HollowKnightRandomizerTracker/version.txt");
} catch {
return version;
} catch(Exception e) {
ModHooks.ModLog(e.ToString());
return Version;
}
}

/// <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";
if (Current == null)
Current = GetCurrentVersion();
if ( Current == Version )
return Version;
return Version + " | UPDATE REQUIRED";
}

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

//Setup websockets server
wss.AddWebSocketService<SocketServer>(
"/playerData",
() =>{
SocketServer ss = new SocketServer()
{
IgnoreExtensions = true
};
ModHooks.Instance.NewGameHook += ss.NewGame;
ModHooks.Instance.SavegameLoadHook += ss.LoadSave;
ModHooks.Instance.SetPlayerBoolHook += ss.EchoBool;
ModHooks.Instance.SetPlayerIntHook += ss.EchoInt;
Wss.AddWebSocketService<SocketServer>("/playerData", ss =>
{
ModHooks.Instance.NewGameHook += ss.NewGame;
ModHooks.Instance.SavegameLoadHook += ss.LoadSave;
ModHooks.Instance.SetPlayerBoolHook += ss.EchoBool;
ModHooks.Instance.SetPlayerIntHook += ss.EchoInt;
ModHooks.Instance.ApplicationQuitHook += ss.OnQuit;
return ss;
}
);
wss.AddWebSocketService<ProfileStorageServer>("/ProfileStorage", () => {
ProfileStorageServer ss = new ProfileStorageServer() {
IgnoreExtensions = true
};
return ss;
}
);
ModHooks.Instance.ApplicationQuitHook += ss.OnQuit;
});

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

wss.Start();
Wss.Start();

ModHooks.ModLog("Initialized PlayerDataDump");
}
Expand Down
112 changes: 94 additions & 18 deletions PlayerDataDump/PlayerDataDump.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -64,36 +64,112 @@
</ItemGroup>
<ItemGroup>
<Compile Include="ProfileStorageServer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SocketServer.cs" />
<Reference Include="UnityEngine">
<HintPath>UnityEngine.dll</HintPath>
</Reference>
<Compile Include="PlayerDataDump.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<_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>
<ItemGroup />
<!-- 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>
33 changes: 16 additions & 17 deletions PlayerDataDump/ProfileStorageServer.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
using Modding;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace PlayerDataDump
{
class ProfileStorageServer : WebSocketBehavior
internal class ProfileStorageServer : WebSocketBehavior
{
public void Broadcast(String s)
public ProfileStorageServer()
{
IgnoreExtensions = true;
}
public void Broadcast(string s)
{
Sessions.Broadcast(s);
}
Expand All @@ -26,37 +28,34 @@ protected override void OnMessage(MessageEventArgs e)
string[] temp = e.Data.Split('|');
if (int.TryParse(temp[1], out int profileId))
{
Send(profileId + "|" + getProfile(profileId));
Send(profileId + "|" + GetProfile(profileId));
}
}else if (e.Data.StartsWith("save"))
{
string[] temp = e.Data.Split('|');
if (int.TryParse(temp[1], out int profileId))
{
saveProfile(profileId, temp[2]);
Broadcast(profileId + "|" + getProfile(profileId));
SaveProfile(profileId, temp[2]);
Broadcast(profileId + "|" + GetProfile(profileId));
}
}else
{
Send("load|int,save|int|{data}");
}
}

private string getProfile(int i)
private static string GetProfile(int i)
{
String path = Application.persistentDataPath + $"/OverlayProfile.{i}.js";
if (File.Exists(path))
{
string data = File.ReadAllText(path);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
}
string path = Application.persistentDataPath + $"/OverlayProfile.{i}.js";
if (!File.Exists(path)) return "undefined";

return "undefined";
string data = File.ReadAllText(path);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
}

private void saveProfile(int profileId, string base64EncodedJson)
private static void SaveProfile(int profileId, string base64EncodedJson)
{
String path = Application.persistentDataPath + $"/OverlayProfile.{profileId}.js";
string path = Application.persistentDataPath + $"/OverlayProfile.{profileId}.js";
byte[] data = Convert.FromBase64String(base64EncodedJson);
string decodedString = Encoding.UTF8.GetString(data);

Expand Down
32 changes: 32 additions & 0 deletions PlayerDataDump/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hollow Knight - Player Data Dumper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlayerDataDump.Properties")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cc2ef5af-4830-4e83-82bf-b6532469f282")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading

0 comments on commit 2ec92fb

Please sign in to comment.