-
Notifications
You must be signed in to change notification settings - Fork 2
/
Matterbridge.cs
334 lines (301 loc) · 10 KB
/
Matterbridge.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.IO;
using Refit;
using Server.Engines.Chat;
namespace Server.Custom
{
public interface IMatterbridgeClient
{
[Get("/api/messages")]
Task<List<MatterbridgeMessage>> GetNextMessages([Authorize("Bearer")] string token);
[Post("/api/message")]
Task PostMessage([Authorize("Bearer")] string token, [Refit.Body] MatterbridgePostMessage message);
}
public class MatterbridgeMessage : MatterbridgePostMessage
{
[JsonPropertyName("channel")]
public string Channel { get; set; }
[JsonPropertyName("userid")]
public string UserId { get; set; }
[JsonPropertyName("account")]
public string Account { get; set; }
[JsonPropertyName("protocol")]
public string Protocol { get; set; }
[JsonPropertyName("parent_id")]
public string ParentId { get; set; }
[JsonPropertyName("timestamp")]
public string Timestamp { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("extra")]
public object Extra { get; set; }
public MatterbridgeMessage(string gateway, string username, string text) : base(gateway, username, text)
{
}
public override string ToString()
{
return Username + Text;
}
}
public class MatterbridgePostMessage
{
[JsonPropertyName("text")]
public string Text { get; set; }
[JsonPropertyName("username")]
public string Username { get; set; }
[JsonPropertyName("avatar")]
public string Avatar { get; set; }
[JsonPropertyName("event")]
public string Event { get; set; }
[JsonPropertyName("gateway")]
public string Gateway { get; set; }
public MatterbridgePostMessage(string gateway, string username, string text)
{
Gateway = gateway;
Username = username;
Text = text;
}
public override string ToString()
{
return Gateway + " | " + Event + " | " + Username + " | " + Text;
}
}
public class MatterbridgeConfig
{
public string TargetToken => m_Vars["TargetToken"];
public string TargetGateway => m_Vars["TargetGateway"];
public string TargetAddress => m_Vars["TargetAddress"];
public int TargetPort => Int32.Parse(m_Vars["TargetPort"]);
public string TargetUri => "http://" + m_Vars["TargetAddress"] + ":" + m_Vars["TargetPort"];
public List<string> Gateways => m_Gateways;
public string ChatChannel => m_Vars["ChatChannel"];
public string CustomFormat => m_Vars["MessageFormat"];
public bool AutoJoinChatChannel => IsBooleanKeyEnabled("AutoJoinChatChannel");
public bool IncludeWorldChat => IsBooleanKeyEnabled("IncludeWorldChat");
private Dictionary<string, string> m_Vars;
private List<string> m_Gateways;
public MatterbridgeConfig(string filename)
{
m_Vars = new Dictionary<string, string>();
m_Gateways = new List<string>();
var path = Path.Combine("Scripts/Custom", filename);
FileInfo cfg = new FileInfo(path);
if (cfg.Exists)
{
using (StreamReader stream = new StreamReader(cfg.FullName))
{
String line;
while ((line = stream.ReadLine()) != null)
{
if (!line.StartsWith("#"))
{
var parts = line.Split('=');
if (parts.Length == 2)
{
var key = parts[0];
var value = parts[1];
m_Vars.Add(key, value);
}
}
}
}
}
else
{
throw new Exception("MatterbridgeConfig.cfg file is missing.");
}
if(m_Vars.ContainsKey("TargetGateway"))
{
foreach (var gateway in m_Vars["TargetGateway"].Split(','))
{
m_Gateways.Add(gateway);
}
}
}
private bool IsBooleanKeyEnabled(string key)
{
if (m_Vars.ContainsKey(key) && m_Vars[key].ToLower() == "true")
return true;
return false;
}
public string GetMessageFormat(string gateway = null)
{
if (gateway != null && m_Vars.ContainsKey(gateway))
return m_Vars[gateway];
return CustomFormat;
}
}
public static class Matterbridge
{
private static IMatterbridgeClient matterbridgeClient;
private static MatterbridgeConfig matterbridgeConfig;
// private static Dictionary<string, string> m_Tags;
public static void Configure()
{
matterbridgeConfig = new MatterbridgeConfig("MatterbridgeConfig.cfg");
var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
};
matterbridgeClient = RestService.For<IMatterbridgeClient>(matterbridgeConfig.TargetUri, new RefitSettings { ContentSerializer = new SystemTextJsonContentSerializer(options) });
if (matterbridgeConfig.IncludeWorldChat)
{
EventSink.Speech += EventSink_Speech;
}
if (!IsRconPacketHandlersEnabled())
{
if (matterbridgeConfig.ChatChannel != "*")
{
Channel.AddStaticChannel(matterbridgeConfig.ChatChannel);
if (matterbridgeConfig.AutoJoinChatChannel)
{
EventSink.Login += EventSink_JoinDefaultChannelAtLogin;
// quietly ignore General channel join attempt on player login for 5 seconds
// ClassicUO client sends a join request when entering the game, but we want players in our channel
ChatActionHandlers.Register(0x62, false, new OnChatAction(BlockGeneralAtLogin));
}
}
}
ChatActionHandlers.Register(0x61, true, new OnChatAction(OnServUOChatReceived));
Listen();
}
private static void Listen()
{
Task.Run(async () =>
{
while (true)
{
try
{
var nextmessages = await matterbridgeClient.GetNextMessages(matterbridgeConfig.TargetToken);
foreach (var x in nextmessages)
{
OnMatterbridgeMessageReceived(x);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Task.Delay(200).Wait();
}
});
}
private static void EventSink_Speech(SpeechEventArgs e)
{
Mobile from = e.Mobile;
if (from is Mobiles.PlayerMobile)
{
foreach (var gateway in matterbridgeConfig.Gateways)
{
matterbridgeClient.PostMessage(matterbridgeConfig.TargetToken, FormatMatterbridgeMessage(null, from, e.Speech, gateway: gateway));
}
}
}
private static void EventSink_JoinDefaultChannelAtLogin(LoginEventArgs e)
{
var from = e.Mobile;
var defaultChannel = Channel.FindChannelByName(matterbridgeConfig.ChatChannel);
var chatUser = ChatUser.AddChatUser(from);
defaultChannel.AddUser(chatUser);
}
public static void BlockGeneralAtLogin(ChatUser from, Channel channel, string param)
{
if (param.Contains("General") && from.Mobile.NetState.ConnectedFor.TotalSeconds < 5)
return;
ChatActionHandlers.JoinChannel(from, channel, param);
}
public static void OnMatterbridgeMessageReceived(MatterbridgeMessage message)
{
if (matterbridgeConfig.ChatChannel != "*")
{
Channel c = Channel.FindChannelByName(matterbridgeConfig.ChatChannel);
if (c != null)
{
foreach (ChatUser user in c.Users)
{
user.Mobile.SendMessage(0, message.Username + message.Text);
}
}
}
else
{
World.Broadcast(0, false, message.ToString());
}
}
private static void OnServUOChatReceived(ChatUser from, Channel channel, string param)
{
if (IsRconPacketHandlersEnabled())
{
RconPacketHandlersRelayChatPacket(from, channel, param);
}
else
{
ChatActionHandlers.ChannelMessage(from, channel, param);
}
if (channel.Name == matterbridgeConfig.ChatChannel || matterbridgeConfig.ChatChannel == "*")
{
foreach (var gateway in matterbridgeConfig.Gateways)
{
matterbridgeClient.PostMessage(matterbridgeConfig.TargetToken, FormatMatterbridgeMessage(null, from.Mobile, param, channel, gateway: gateway));
}
}
}
private static bool IsRconPacketHandlersEnabled()
{
var rconPacketHandlersClass = Type.GetType("Server.RemoteAdmin.RconPacketHandlers");
if (rconPacketHandlersClass != null)
return true;
return false;
}
private static void RconPacketHandlersRelayChatPacket(ChatUser from, Channel channel, string param)
{
var rconPacketHandlersClass = Type.GetType("Server.RemoteAdmin.RconPacketHandlers");
var m = rconPacketHandlersClass.GetMethod("RelayChatPacket");
object[] parameters = {from, channel, param};
m.Invoke(rconPacketHandlersClass, parameters);
}
public static MatterbridgePostMessage FormatMatterbridgeMessage(string type, Mobile from, string message = null, Channel channel = null, string gateway = null)
{
var t = matterbridgeConfig.CustomFormat;
if (gateway != null)
t = matterbridgeConfig.GetMessageFormat(gateway);
if (message != null)
{
t = t.Replace("{name}", from.Name).Replace("{message}", message).Replace("{account}", from.Account.Username).Replace("{serial}", from.Serial.Value.ToString()).Replace("{region}", from.Region.Name).Replace("{coords.x}", from.X.ToString()).Replace("{coords.y}", from.Y.ToString()).Replace("{coords.z}", from.Z.ToString()).Replace("{ip}", from.NetState.Address.ToString());
if (from.Guild != null)
t = t.Replace("{guild}", " (" + from.Guild.Name + ")");
else
t = t.Replace("{guild}", string.Empty);
if (!from.Alive)
t = t.Replace("{dead}", " <Dead>");
else
t = t.Replace("{dead}", string.Empty);
if (from.Account.Young)
t = t.Replace("{young}", " <Young>");
else
t = t.Replace("{young}", string.Empty);
if (from.Criminal)
t = t.Replace("{criminal}", " <Criminal>");
else
t = t.Replace("{criminal}", string.Empty);
if (from.Murderer)
t = t.Replace("{murderer}", " <Murderer>");
else
t = t.Replace("{murderer}", string.Empty);
if (channel == null)
t = t.Replace("{channel}", "World");
else
t = t.Replace("{channel}", channel.Name);
if (t.Contains("{coords}"))
t = t.Replace("{coords}", from.X + "," + from.Y + "," + from.Z);
}
return new MatterbridgePostMessage(gateway, from.Name, t);
}
}
}