Skip to content

Commit

Permalink
Merge pull request #2 from blaxxun-boop/master
Browse files Browse the repository at this point in the history
change server config to yaml
  • Loading branch information
AzumattDev committed May 7, 2022
2 parents a334c0b + 24ed244 commit bfcf290
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 96 deletions.
25 changes: 25 additions & 0 deletions Definition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.Serialization;

namespace FastLink;

public class Definition
{
public string serverName = null!;

public ushort port { get; set; }

public string address { get; set; } = null!;

public string password { get; set; } = "";

public static IEnumerable<Definition> Parse(string yaml) => new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, Definition>>(yaml).Select(kv =>
{
Definition def = kv.Value;
def.serverName = kv.Key;
return def;
});

public override string ToString() => $"Server(name={serverName},address={address},port={port})";
}
18 changes: 18 additions & 0 deletions FastLink.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@
<Reference Include="assembly_valheim, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>$(GamePath)\valheim_Data\Managed\publicized_assemblies\assembly_valheim_publicized.dll</HintPath>
</Reference>
<Reference Include="assembly_steamworks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>$(GamePath)\valheim_Data\Managed\publicized_assemblies\assembly_steamworks_publicized.dll</HintPath>
</Reference>
<Reference Include="BepInEx, Version=5.4.19.0, Culture=neutral, PublicKeyToken=null">
<HintPath>$(GamePath)\BepInEx\core\BepInEx.dll</HintPath>
</Reference>
Expand All @@ -90,8 +93,12 @@
<Reference Include="UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>$(GamePath)\unstripped_corlib\UnityEngine.UI.dll</HintPath>
</Reference>
<Reference Include="YamlDotNet, Version=11.0.0.0, Culture=neutral, PublicKeyToken=ec19458f3c15af5e, processorArchitecture=MSIL">
<HintPath>packages\YamlDotNet.11.2.1\lib\net45\YamlDotNet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Definition.cs" />
<Compile Include="FastLink.cs" />
<Compile Include="Patches\Patches.cs" />
<Compile Include="Patches\SetupGui.cs" />
Expand All @@ -102,8 +109,19 @@
</ItemGroup>
<ItemGroup>
<Content Include=".gitignore" />
<Content Include="ILRepack.targets" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="packages\ILRepack.Lib.MSBuild.Task.2.0.18.2\build\ILRepack.Lib.MSBuild.Task.targets" Condition="Exists('packages\ILRepack.Lib.MSBuild.Task.2.0.18.2\build\ILRepack.Lib.MSBuild.Task.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\ILRepack.Lib.MSBuild.Task.2.0.18.2\build\ILRepack.Lib.MSBuild.Task.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\ILRepack.Lib.MSBuild.Task.2.0.18.2\build\ILRepack.Lib.MSBuild.Task.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
10 changes: 10 additions & 0 deletions ILRepack.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="ILRepacker" AfterTargets="Build">
<ItemGroup>
<InputAssemblies Include="$(TargetPath)"/>
<InputAssemblies Include="$(OutputPath)YamlDotNet.dll"/>
</ItemGroup>
<ILRepack Parallel="true" DebugInfo="true" Internalize="true" InputAssemblies="@(InputAssemblies)" OutputFile="$(TargetPath)" TargetKind="SameAsPrimaryAssembly" LibraryPath="$(OutputPath)"/>
</Target>
</Project>
75 changes: 20 additions & 55 deletions Patches/Servers.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BepInEx;

namespace FastLink.Patches;

internal class Servers
{
internal static string ConfigFileName = FastLinkPlugin.Author + "." +
$"{FastLinkPlugin.ModName}_servers.cfg";
$"{FastLinkPlugin.ModName}_servers.yml";

public static string ConfigPath = Paths.ConfigPath +
Path.DirectorySeparatorChar + ConfigFileName;

public static List<Entry> entries = new();
public static List<Definition> entries = new();

public static void Init()
{
Expand All @@ -23,54 +24,28 @@ public static void Init()
if (!File.Exists(ConfigPath))
{
using StreamWriter streamWriter = File.CreateText(ConfigPath);
streamWriter.Write("# Config your servers for Azumatt's FastLink mod in this file. This file is intentionally made the same as QuickConnect's for easier migration." +
Environment.NewLine +
Environment.NewLine +
"# Lines starting with #, // and empty lines are ignored" +
Environment.NewLine +
"# Put one server per line" + Environment.NewLine + Environment.NewLine +
"# Name:Address:Port:Password" + Environment.NewLine +
"# Address can be ether IP or a fully qualified domain name. I have provided some examples below." +
Environment.NewLine +
"# This mod supports IPv4 and IPv6. You may type them the same, I parse the IP/port for you." +
Environment.NewLine + Environment.NewLine +
"Valheim Test:fastlink.us:2496:Uzc5cGee" + Environment.NewLine +
Environment.NewLine +
"# Password is optional, you can skip it if your server doesn't need a password" +
Environment.NewLine +
"# or if you don't want to write it down" + Environment.NewLine +
Environment.NewLine +
"#No Password Server:127.0.0.1:2456:76453");
streamWriter.Write(new StringBuilder()
.AppendLine("# Configure your servers for Azumatt's FastLink mod in this file.")
.AppendLine("")
.AppendLine("Example Server:")
.AppendLine(" address: example.com")
.AppendLine(" port: 1234")
.AppendLine(" password: somepassword")
.AppendLine("")
.AppendLine("Some IPv6 Server:")
.AppendLine(" address: 2606:2800:220:1:248:1893:25c8:1946")
.AppendLine(" port: 4023")
.AppendLine(" password: a password with spaces")
.AppendLine("")
.AppendLine("Passwordless IPv4 Server:")
.AppendLine(" address: 93.184.216.34")
.AppendLine(" port: 9999"));
streamWriter.Close();
}

if (File.Exists(ConfigPath))
{
using StreamReader streamReader = File.OpenText(ConfigPath);
while (streamReader.ReadLine() is { } str1)
{
string str2 = str1.Trim();
if (str2.Length == 0 || str2.StartsWith("#") || str2.StartsWith("//")) continue;
string[] strArray = str2.Split(':');
if (strArray.Length >= 3)
{
string str3 = strArray[0];
string str4 = strArray[1];
int num = int.Parse(strArray[2]);
string str5 = "";
if (strArray.Length >= 4)
str5 = strArray[3];
entries.Add(new Entry
{
MName = str3,
Mip = str4,
MPort = num,
MPass = str5
});
}
else
FastLinkPlugin.FastLinkLogger.LogWarning("Invalid config line: " + str2);
}
entries.AddRange(Definition.Parse(File.ReadAllText(ConfigPath)));

FastLinkPlugin.FastLinkLogger.LogDebug($"Loaded {entries.Count} server entries");
}
Expand All @@ -80,14 +55,4 @@ public static void Init()
FastLinkPlugin.FastLinkLogger.LogError($"Error loading config {ex}");
}
}

public class Entry
{
public string MName = "";
public string Mip = "";
public int MPort;
public string MPass = "";

public override string ToString() => $"Server(name={MName},ip={Mip},port={MPort})";
}
}
10 changes: 5 additions & 5 deletions Patches/SetupGui.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ namespace FastLink.Patches;
[HarmonyPatch(typeof(FejdStartup), nameof(FejdStartup.SetupGui))]
internal class SetupGui
{
public static GameObject Fastlink;
public static GameObject FastlinkRootGo;
public static readonly List<Servers.Entry> MServerList = new();
public static Servers.Entry? MJoinServer = new();
public static GameObject Fastlink = null!;
public static GameObject FastlinkRootGo = null!;
public static readonly List<Definition> MServerList = new();
public static Definition? MJoinServer = new();
public static readonly List<GameObject> MServerListElements = new();
public static Text? MServerCount;
public static GameObject MServerListElement = new();
Expand All @@ -25,7 +25,7 @@ internal class SetupGui
public static float MServerListBaseSize;

public static Task<IPHostEntry>? ResolveTask;
public static Servers.Entry? Connecting;
public static Definition? Connecting;

private static void Postfix(FejdStartup __instance)
{
Expand Down
79 changes: 43 additions & 36 deletions Util/Functions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ internal static void UpdateServerList()
}
else if (Servers.entries.Count > 0)
{
foreach (Servers.Entry entry in Servers.entries)
foreach (Definition Definition in Servers.entries)
{
MServerList.Add(entry);
MServerList.Add(Definition);
}
}
else
Expand All @@ -64,8 +64,8 @@ internal static void UpdateServerList()
FastLinkPlugin.FastLinkLogger.LogError($"Please create this file {Servers.ConfigPath}");
}

MServerList.Sort((Comparison<Servers.Entry>)((a, b) =>
string.Compare(a?.MName, b?.MName, StringComparison.Ordinal)));
MServerList.Sort((Comparison<Definition>)((a, b) =>
string.Compare(a?.serverName, b?.serverName, StringComparison.Ordinal)));
if (MJoinServer != null && !MServerList.Contains(MJoinServer))
{
FastLinkPlugin.FastLinkLogger.LogDebug(
Expand Down Expand Up @@ -110,54 +110,49 @@ private static void UpdateServerListGui(bool centerSelection)
FastLinkPlugin.FastLinkLogger.LogDebug($"ServerList count: {MServerList.Count}");
for (int index = 0; index < MServerList.Count; ++index)
{
Servers.Entry server = MServerList[index];
Definition server = MServerList[index];
GameObject? serverListElement = MServerListElements?[index];
if (serverListElement == null) continue;
serverListElement.GetComponentInChildren<Text>().text =
index + 1 + ". " + server.MName;
index + 1 + ". " + server.serverName;
serverListElement.GetComponentInChildren<UITooltip>().m_text = server.ToString();
serverListElement.transform.Find("version").GetComponent<Text>().text = server.Mip;
serverListElement.transform.Find("players").GetComponent<Text>().text = server.MPort.ToString();
serverListElement.transform.Find("version").GetComponent<Text>().text = server.address;
serverListElement.transform.Find("players").GetComponent<Text>().text = server.port.ToString();
serverListElement.transform.Find("Private").gameObject
.SetActive(server.MPass.Length > 1);
.SetActive(server.password.Length > 1);
Transform target = serverListElement.transform.Find("selected");

bool flag = MJoinServer != null && MJoinServer.Equals(server);
target.gameObject.SetActive(flag);
}
}

private static void Connect(Servers.Entry server)
private static void Connect(Definition server)
{
FastLinkPlugin.FastLinkLogger.LogDebug("DO CONNECT");
Connecting = server;
try
{
IPAddress.Parse(server.Mip);
FastLinkPlugin.FastLinkLogger.LogDebug(
$"Server and Port passed into Connect: {server.Mip}:{server.MPort}");
try
{
ZSteamMatchmaking.instance.QueueServerJoin($"{server.Mip}:{server.MPort}");
}
catch (Exception e)
IPAddress address = IPAddress.Parse(server.address);
if (!JoinServer(address, server.port))
{
FastLinkPlugin.FastLinkLogger.LogDebug($"Error queueServerJoin: {e}");
Connecting = null;
FastLinkPlugin.FastLinkLogger.LogError("Server address was not valid");
}
}
catch (FormatException)
{
FastLinkPlugin.FastLinkLogger.LogDebug("Resolving: " + server.Mip);
FastLinkPlugin.FastLinkLogger.LogDebug("Resolving: " + server.address);
try
{
ResolveTask = Dns.GetHostEntryAsync(server.Mip);
ResolveTask = Dns.GetHostEntryAsync(server.address);
FastLinkPlugin.FastLinkLogger.LogDebug("Resolving after task: " +
ResolveTask.Result.AddressList[0]);
}
catch (Exception)
{
FastLinkPlugin.FastLinkLogger.LogError(
$"You are trying to resolve the IP : {server.Mip}, but something is happening causing it to not work properly.");
$"You are trying to resolve the IP : {server.address}, but something is happening causing it to not work properly.");
}

if (ResolveTask == null)
Expand All @@ -183,23 +178,17 @@ private static void Connect(Servers.Entry server)
}
else if (ResolveTask.IsCompleted)
{
FastLinkPlugin.FastLinkLogger.LogDebug("COMPLETE: " + server.Mip);
FastLinkPlugin.FastLinkLogger.LogDebug("COMPLETE: " + server.address);
foreach (IPAddress address in ResolveTask.Result.AddressList)
{
if (address.AddressFamily is not AddressFamily.InterNetwork and not AddressFamily.InterNetworkV6)
return;
FastLinkPlugin.FastLinkLogger.LogDebug($"Resolved Completed: {address}");
ResolveTask = null;
try
{
ZSteamMatchmaking.instance.QueueServerJoin(
$"{(address.AddressFamily is AddressFamily.InterNetworkV6 ? $"[{address}]" : $"{address}")}:{Connecting.MPort}");
}
catch (Exception e)
if (!JoinServer(address, server.port))
{
FastLinkPlugin.FastLinkLogger.LogDebug($"ERROR: {e}");
return;
Connecting = null;
FastLinkPlugin.FastLinkLogger.LogError("Server DNS resolved to invalid address");
}
return;
}
}
else
Expand All @@ -211,7 +200,25 @@ private static void Connect(Servers.Entry server)
}
}

public static string? CurrentPass() => Connecting?.MPass;
private static bool JoinServer(IPAddress address, ushort port)
{
string target = (address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{address}]" : $"{address}") + $":{port}";
FastLinkPlugin.FastLinkLogger.LogDebug($"Server and Port passed into JoinServer: {target}");

if (address.AddressFamily == AddressFamily.InterNetwork)
{
address = address.MapToIPv6();
}
if (address.AddressFamily != AddressFamily.InterNetworkV6)
{
return false;
}
ZSteamMatchmaking.instance.m_joinAddr.SetIPv6(address.GetAddressBytes(), port);
ZSteamMatchmaking.instance.m_haveJoinAddr = true;
return true;
}

public static string? CurrentPass() => Connecting?.password;

public static void AbortConnect()
{
Expand All @@ -224,9 +231,9 @@ private static void OnSelectedServer()
{
FastLinkPlugin.FastLinkLogger.LogDebug("SELECTED SERVER");
MJoinServer = MServerList[FindSelectedServer(EventSystem.current.currentSelectedGameObject)];
Connect(new Servers.Entry
Connect(new Definition
{
MName = MJoinServer.MName, Mip = MJoinServer.Mip, MPort = MJoinServer.MPort, MPass = MJoinServer.MPass
serverName = MJoinServer.serverName, address = MJoinServer.address, port = MJoinServer.port, password = MJoinServer.password
});
UpdateServerListGui(false);
}
Expand Down
5 changes: 5 additions & 0 deletions packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ILRepack.Lib.MSBuild.Task" version="2.0.18.2" targetFramework="net462" />
<package id="YamlDotNet" version="11.2.1" targetFramework="net462" />
</packages>

0 comments on commit bfcf290

Please sign in to comment.