Skip to content

Commit

Permalink
add identicon avatars and render urls
Browse files Browse the repository at this point in the history
  • Loading branch information
NikkyAI committed Jan 21, 2021
1 parent 47de412 commit 2738b3e
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 43 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/PUBLISH_SNAPSHOT.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ jobs:
wget https://cdn.vintagestory.at/gamefiles/stable/vs_server_1.14.5.tar.gz --quiet -O bin/vs_server.tar.gz
tar -xf bin/vs_server.tar.gz -C bin/vs_server/
echo "VINTAGE_STORY=bin/vs_server" >> $GITHUB_ENV
- run: dotnet build -target:GenerateResource -c Release
- run: dotnet build -c Release
- name: Set enviroment for github-release
run: |
echo "BRANCH=${GITHUB_REF##*/}" >> $GITHUB_ENV
echo "VERSION=$(cat .generated/modinfo.json | jq -r .version)" >> $GITHUB_ENV
echo "VERSION=$(cat resources/modinfo.json | jq -r .version)" >> $GITHUB_ENV
- name: Set enviroment RELEASE_TAG
run: |
echo "RELEASE_TAG=snapshot/${{ env.VERSION }}-${{ env.BRANCH }}-$GITHUB_RUN_NUMBER" >> $GITHUB_ENV
Expand Down
11 changes: 2 additions & 9 deletions Matterbridge.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Nullable>enable</Nullable>

<AssemblyTitle>Matterbridge API Connector</AssemblyTitle>
<Version>0.0.5</Version>
<Version>0.0.6</Version>

<Description>A matterbridge api connector for VS server</Description>
<Authors>NikkyAI</Authors>
Expand Down Expand Up @@ -52,16 +52,9 @@
</None>
</ItemGroup>

<ItemGroup>
<None Include=".generated\**\*.*">
<Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

<Target Name="GenerateResource" BeforeTargets="BeforeBuild">
<Delete Files=".generated\**\*.*" />
<GenerateModinfo InputFilename="modinfo.json" OutputFilename=".generated/modinfo.json" Modid="$(AssemblyName)" Version="$(Version)" Description="$(Description)" Name="$(AssemblyTitle)" Author="$(Authors)" Website="$(WebPage)" />
<GenerateModinfo InputFilename="modinfo.json" OutputFilename="resources/modinfo.json" Modid="$(AssemblyName)" Version="$(Version)" Description="$(Description)" Name="$(AssemblyTitle)" Author="$(Authors)" Website="$(WebPage)" />
<Message Importance="High" Text="generated .generated/modinfo.json" />
</Target>

Expand Down
18 changes: 18 additions & 0 deletions resources/modinfo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"type": "code",
"name": "Matterbridge API Connector",
"modid": "matterbridge",
"version": "0.0.6",

"description" : "A matterbridge api connector for VS server",
"website": "https://github.com/NikkyAI/vs-matterbridge",
"authors": [ "NikkyAI" ],

"side": "Server",
"requiredOnClient": false,

"dependencies": {
"game": "1.8.0",
"survival": ""
}
}
5 changes: 5 additions & 0 deletions sample/example2/matterbridge.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
"groupName": "twitch lunarlight",
"gateway": "twitch_lunarlight",
"isPrivate": false
},
{
"groupName": "twitch kainei",
"gateway": "twitch_kainei",
"isPrivate": false
}
],
"TEXT_StormEarlyWarning": "It appears a {strength} storm is coming...",
Expand Down
10 changes: 10 additions & 0 deletions sample/example2/matterbridge.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,14 @@ in = [
out = [
{ account="api.vintagestory", channel="api" }
]

[[gateway]]
name="twitch_kainei"
enable=true
in = [
{ account="irc.twitch", channel="#kainei" }
]
out = [
{ account="api.vintagestory", channel="api" }
]

29 changes: 29 additions & 0 deletions src/Identicon.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Security.Cryptography;
using System.Text;

namespace Matterbridge
{
public class Identicon
{
public static string GenerateUrl(string username)
{
string usernameHash = GetHashString(username);
return $"https://identicon-api.herokuapp.com/{usernameHash}/256?format=png";
}
private static byte[] GetHash(string inputString)
{
using (HashAlgorithm algorithm = SHA256.Create())
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

private static string GetHashString(string inputString)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
sb.Append(b.ToString("X2"));

return sb.ToString();
}
}

}
42 changes: 21 additions & 21 deletions src/MatterbridgeMod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,12 @@ private void ActionCommandHandler(IServerPlayer player, int groupid, CmdArgs arg
gateway = entry.gateway;
}

WebsocketHandler.SendMessage(player.PlayerName, message, gateway, ApiMessage.EventUserAction);
WebsocketHandler.SendUserMessage(
player: player,
text: message,
gateway: gateway,
@event: ApiMessage.EventUserAction
);
}

private void BridgeCommandHandler(IServerPlayer player, int groupid, CmdArgs args)
Expand Down Expand Up @@ -266,8 +271,8 @@ private void BridgeReloadCommandHandler(IServerPlayer player, int groupid, CmdAr

private void Event_PlayerDeath(IServerPlayer byPlayer, DamageSource? damageSource)
{
var deathMessage = (byPlayer?.PlayerName ?? "Unknown player") + " ";
// var deathMessage = "";
// var deathMessage = (byPlayer?.PlayerName ?? "Unknown player") + " ";
var deathMessage = "";
if (damageSource == null)
deathMessage += "was killed by the unknown.";
else
Expand Down Expand Up @@ -312,7 +317,7 @@ private void Event_PlayerDeath(IServerPlayer byPlayer, DamageSource? damageSourc
"locust" => "by a locust.",
"drifter" => "by a drifter.",
"beemob" => "by a swarm of bees.",
_ => "by a monster."
_ => $"by a monster. ({damageSource.SourceEntity.Code.Path})" // TODO: add section to config
},
EnumDamageSource.Explosion => "when they stood by a bomb.",
EnumDamageSource.Machine => "when they got their hands stuck in a machine.",
Expand All @@ -324,8 +329,8 @@ private void Event_PlayerDeath(IServerPlayer byPlayer, DamageSource? damageSourc

if (Config.SendPlayerDeathEvents)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendUserMessage(
player: byPlayer,
text: deathMessage,
@event: ApiMessage.EventUserAction,
// account: byPlayer.PlayerUID,
Expand Down Expand Up @@ -380,8 +385,7 @@ private void Event_PlayerDisconnect(IServerPlayer byPlayer)

if (Config.SendPlayerJoinLeaveEvents)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendSystemMessage(
text: $"{byPlayer.PlayerName} has disconnected from the server! " +
// $"played for {timePlayed} " +
$"({Api.Server.Players.Count(x => x.PlayerUID != byPlayer.PlayerUID && x.ConnectionState == EnumClientState.Playing)}/{Api.Server.Config.MaxClients})",
Expand Down Expand Up @@ -409,13 +413,13 @@ private void Event_PlayerJoin(IServerPlayer byPlayer)

if (Config.SendPlayerJoinLeaveEvents)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendSystemMessage(
// username: "system",
text: $"{byPlayer.PlayerName} has connected to the server! " +
$"({Api.Server.Players.Count(x => x.ConnectionState != EnumClientState.Offline)}/{Api.Server.Config.MaxClients})",
gateway: Config.generalGateway,
@event: ApiMessage.EventJoinLeave,
account: byPlayer.PlayerUID
@event: ApiMessage.EventJoinLeave
// account: byPlayer.PlayerUID
);
}
}
Expand All @@ -441,8 +445,7 @@ private void OnTempStormTick(float t1)

if (_lastData?.stormDayNotify > 1 && data.stormDayNotify == 1 && Config.SendStormEarlyNotification)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendSystemMessage(
text: Config.TEXT_StormEarlyWarning.Replace("{strength}",
data.nextStormStrength.ToString().ToLower()),
gateway: Config.generalGateway
Expand All @@ -451,8 +454,7 @@ private void OnTempStormTick(float t1)

if (_lastData?.stormDayNotify == 1 && data.stormDayNotify == 0)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendSystemMessage(
text: Config.TEXT_StormBegin.Replace("{strength}", data.nextStormStrength.ToString().ToLower()),
gateway: Config.generalGateway
);
Expand All @@ -461,8 +463,7 @@ private void OnTempStormTick(float t1)
//double activeDaysLeft = data.stormActiveTotalDays - api.World.Calendar.TotalDays;
if (_lastData?.stormDayNotify == 0 && data.stormDayNotify != 0)
{
WebsocketHandler.SendMessage(
username: "system",
WebsocketHandler.SendSystemMessage(
text: Config.TEXT_StormEnd.Replace("{strength}", data.nextStormStrength.ToString().ToLower()),
gateway: Config.generalGateway
);
Expand Down Expand Up @@ -499,10 +500,9 @@ private void Event_PlayerChat(IServerPlayer byPlayer, int channelId, ref string
Mod.Logger.Debug($"data: {data}");
Mod.Logger.Chat($"**{byPlayer.PlayerName}**: {foundText.Groups[1].Value}");

WebsocketHandler.SendMessage(
username: byPlayer.PlayerName,
WebsocketHandler.SendUserMessage(
player: byPlayer,
text: foundText.Groups[1].Value,
account: byPlayer.PlayerUID,
gateway: gateway
);
}
Expand Down
4 changes: 3 additions & 1 deletion src/ModConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ internal class ModConfig
public bool SendPlayerDeathEvents = true;
public bool SendStormNotification = true;
public bool SendStormEarlyNotification = true;
// public string Gateway = "";

public string systemUsername = "system";
public string systemAvatar = "";

public string generalGateway = "general";
public List<ChannelMappingEntry> ChannelMapping = new List<ChannelMappingEntry>();
Expand Down
57 changes: 47 additions & 10 deletions src/WebsocketHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
using System.Linq;
using System.Threading;
using Newtonsoft.Json;
using SuperSocket.ClientEngine;
using Vintagestory.API.Common;
using Vintagestory.API.Config;
using Vintagestory.API.Server;
using WebSocket4Net;
using ErrorEventArgs = SuperSocket.ClientEngine.ErrorEventArgs;
using WebSocket = WebSocket4Net.WebSocket;

namespace Matterbridge
{
Expand All @@ -20,9 +21,10 @@ internal class WebsocketHandler : IDisposable
// ReSharper disable ConvertToAutoProperty
private ICoreServerAPI Api => _api;
private Mod Mod => _mod;

private ModConfig Config => _config!;
// ReSharper restore ConvertToAutoProperty

private WebSocket? _websocket;
private bool _reconnectWebsocket = true;
private int _connectErrrors = 0;
Expand All @@ -49,7 +51,8 @@ public void Connect()
_websocket = new WebSocket(
uri: Config.Uri,
customHeaderItems: customHeaderItems
) {
)
{
EnableAutoSendPing = true,
AutoSendPingInterval = 100
};
Expand All @@ -71,8 +74,7 @@ public void Close(bool skipMessage = false)
{
if (Config.SendApiConnectEvents && !skipMessage)
{
SendMessage(
username: "system",
SendSystemMessage(
text: Config.TEXT_ServerStop,
@event: ApiMessage.EventJoinLeave,
gateway: Config.generalGateway
Expand All @@ -83,7 +85,32 @@ public void Close(bool skipMessage = false)
_websocket?.Close();
}

public void SendMessage(string username, string text, string gateway, string @event = "", string account = "")
public void SendSystemMessage(string text, string gateway, string @event = "")
{
SendMessage(
username: _config.systemUsername,
text: text,
gateway: gateway,
@event: @event,
account: "",
avatar: _config.systemAvatar
);
}

public void SendUserMessage(IServerPlayer player, string text, string gateway, string @event = "")
{
SendMessage(
username: player.PlayerName,
text: text,
gateway: gateway,
@event: @event,
account: player.PlayerUID,
avatar: Identicon.GenerateUrl(player.PlayerUID)
);
}

private void SendMessage(string username, string text, string gateway, string @event, string account,
string avatar)
{
if (_websocket == null)
{
Expand All @@ -96,8 +123,7 @@ public void SendMessage(string username, string text, string gateway, string @ev
gateway: gateway,
channel: "api",
username: username,
// TODO: render face and get url to it
avatar: "",
avatar: avatar,
@event: @event,
account: account,
protocol: "api"
Expand Down Expand Up @@ -166,8 +192,7 @@ private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e

if (Config.SendApiConnectEvents)
{
SendMessage(
username: "system",
SendSystemMessage(
text: Config.TEXT_ServerStart,
gateway: Config.generalGateway,
@event: ""
Expand Down Expand Up @@ -200,6 +225,18 @@ private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e

var cleanedMessageText = message.Text.Replace(">", "&gt;").Replace("<", "&lt;");

cleanedMessageText = string.Join(
" ",
cleanedMessageText
.Split(new[] {' '}, StringSplitOptions.None)
.Select(
word => Uri.IsWellFormedUriString(word, UriKind.Absolute)
? $"<a href=\"{word}\">{word}</a>"
: word
)
.ToArray()
);

switch (message.Event)
{
case ApiMessage.EventJoinLeave:
Expand Down

0 comments on commit 2738b3e

Please sign in to comment.