-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
298 lines (259 loc) · 11.3 KB
/
Program.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
/* unified/ban - Management and protection systems
© fabricators SRL, https://fabricators.ltd , https://unifiedban.solutions
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License with our addition
to Section 7 as published in unified/ban's the GitHub repository.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License and the
additional terms along with this program.
If not, see <https://docs.fabricators.ltd/docs/licenses/unifiedban>.
For more information, see Licensing FAQ:
https://docs.fabricators.ltd/docs/licenses/faq */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Telegram.Bot;
using Telegram.Bot.Types;
using Unifiedban.Next.Common;
using Unifiedban.Next.Common.Telegram;
using Unifiedban.Next.Models;
using Unifiedban.Next.Models.Telegram;
using Unifiedban.Next.Service.Telegram.Commands;
namespace Unifiedban.Next.Service.Telegram;
internal static class Program
{
private static bool _manualShutdown;
private static IModel _channel;
private static IConnection? _conn;
private static IBasicProperties _properties;
private static Dictionary<string, Type> commands = new();
private static Dictionary<string, Dictionary<string, UBCustomCommand>> _customCommands = new();
internal static Dictionary<long, List<TGChatMember>> ubTelegramUsers = new();
private static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
Common.Utils.WriteLine($"== {AppDomain.CurrentDomain.FriendlyName} Startup ==");
var builder = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", false, false);
CacheData.Configuration = builder.Build();
_ = new UBContext(CacheData.Configuration["Database"]);
Common.Utils.WriteLine("Registering instance");
Utils.RegisterInstance();
Common.Utils.WriteLine("***************************************");
LoadViaAbstract();
Common.Utils.WriteLine("***************************************");
LoadCustomCommands();
Common.Utils.WriteLine("***************************************");
LoadRabbitMQManager();
Common.Utils.WriteLine("***************************************");
Utils.SetInstanceStatus(Enums.States.Operational);
Common.Utils.WriteLine("Startup completed.\n");
Console.ReadLine();
Common.Utils.WriteLine("Manual shutdown started.\n");
_manualShutdown = true;
DoShutdown();
}
private static void LoadRabbitMQManager()
{
Common.Utils.WriteLine("Creating RabbitMQ instance...");
var factory = new ConnectionFactory();
factory.UserName = CacheData.Configuration?["RabbitMQ:UserName"];
factory.Password = CacheData.Configuration?["RabbitMQ:Password"];
factory.VirtualHost = CacheData.Configuration?["RabbitMQ:VirtualHost"];
factory.HostName = CacheData.Configuration?["RabbitMQ:HostName"];
factory.Port = int.Parse(CacheData.Configuration?["RabbitMQ:Port"] ?? "0");
factory.DispatchConsumersAsync = true;
Common.Utils.WriteLine("Connecting to RabbitMQ server...");
_conn = factory.CreateConnection();
_channel = _conn.CreateModel();
_properties = _channel.CreateBasicProperties();
var tgConsumer = new AsyncEventingBasicConsumer(_channel);
tgConsumer.Received += ConsumerOnTgMessage;
Common.Utils.WriteLine("Start consuming tg.commands queue...");
_channel.BasicConsume("tg.commands", false, tgConsumer);
}
private static async Task ConsumerOnTgMessage(object sender, BasicDeliverEventArgs ea)
{
var body = ea.Body.ToArray();
var str = Encoding.Default.GetString(body);
var qMessage = JsonConvert
.DeserializeObject<QueueMessage<TGChat, UserPrivileges, UserPrivileges, Message>>(str);
var skipChecks = false;
var isCustom = false;
if (qMessage.Payload.Text.StartsWith(qMessage.UBChat.CommandPrefix))
{
var commandStr = qMessage.Payload.Text.Split(" ")[0];
commandStr = commandStr.Remove(0, qMessage.UBChat.CommandPrefix.Length);
if (commandStr.Split(' ')[0].Contains('@'))
{
commandStr = commandStr.Split(' ')[0].Split('@')[0];
}
Common.Utils.WriteLine($"Received command: {qMessage.Payload.Text}");
if (_customCommands.ContainsKey(qMessage.UBChat.ChatId))
{
if (_customCommands[qMessage.UBChat.ChatId].ContainsKey(commandStr) &&
_customCommands[qMessage.UBChat.ChatId][commandStr].Enabled)
{
isCustom = true;
var customCommand = _customCommands[qMessage.UBChat.ChatId][commandStr];
new CustomCommandHandler(customCommand, qMessage);
}
}
if (!isCustom)
{
var isValidCommand = commands.TryGetValue(commandStr, out var command);
if (isValidCommand)
try
{
var cmdInstance = Activator.CreateInstance(command, commandStr, qMessage) as Command;
skipChecks = cmdInstance!.SkipChecks;
}
catch (Exception ex)
{
Common.Utils.WriteLine($"Error executing command: {command.Name}", 3);
Common.Utils.WriteLine($"Exception: {ex.Message}", 3);
}
else
Common.Utils.WriteLine($"Received message (starting with command token): {qMessage.Payload.Text}");
}
}
else
{
Common.Utils.WriteLine($"Received message: {qMessage.Payload.Text}");
}
if (!skipChecks)
_channel.BasicPublish(CacheData.NextQueue.Exchange, CacheData.NextQueue.RoutingKey, _properties, body);
_channel.BasicAck(ea.DeliveryTag, false);
}
private static void LoadViaAbstract()
{
Common.Utils.WriteLine("Loading internal commands...");
var type = typeof(Command);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsAbstract);
var foundCommands = types as Type[] ?? types.ToArray();
Common.Utils.WriteLine($"Found {foundCommands.Count()} command(s)");
foreach (var command in foundCommands)
{
var constructor = command.GetConstructor(
new[] { typeof(string), typeof(QueueMessage<TGChat, UserPrivileges, UserPrivileges, Message>) });
if (constructor == null)
{
Common.Utils.WriteLine($"No valid constructor found for command command: {command.Name}", 3);
continue;
}
try
{
QueueMessage<TGChat, UserPrivileges, UserPrivileges, Message> activate = new();
activate.UBChat = new TGChat();
if (Activator
.CreateInstance(command, "", activate) is Command commandInstance)
{
commands.TryAdd(commandInstance.Name, command);
foreach (var alias in commandInstance.Aliases) commands.TryAdd(alias, command);
}
else
{
Common.Utils.WriteLine($"Error creating instance for command command: {command.Name}", 3);
}
}
catch (Exception ex)
{
Common.Utils.WriteLine($"Error loading command: {command.Name}", 3);
Common.Utils.WriteLine($"Exception: {ex.Message}", 3);
}
}
}
private static void LoadCustomCommands()
{
Common.Utils.WriteLine("Loading custom commands...");
// get custom commands from db
var customCommands = new List<UBCustomCommand>();
customCommands.Add(new UBCustomCommand
{
UBCustomCommandId = "ciao",
ChatId = "0",
Enabled = true,
Platforms = new string[]{"Telegram"},
AnswerType = UBCommand.AnswerTypes.Text,
Command = "ciao",
Content = "Ciao un cazzo."
});
customCommands.Add(new UBCustomCommand
{
UBCustomCommandId = "ciao2",
ChatId = "0",
Platforms = new string[]{"Telegram"},
AnswerType = UBCommand.AnswerTypes.Text,
Command = "ciao2",
Content = "Ciao un cazzo x2.",
TgUserLevel = Enums.UserLevels.Mod
});
customCommands.Add(new UBCustomCommand
{
UBCustomCommandId = "ciao3",
ChatId = "1",
Platforms = new string[]{"Telegram"},
AnswerType = UBCommand.AnswerTypes.Text,
Command = "ciao2",
Content = "Ciao un cazzo x3."
});
foreach(var c in customCommands)
{
if (_customCommands.ContainsKey(c.ChatId))
{
Common.Utils.WriteLine($"Found command {c.Command}");
_customCommands[c.ChatId].Add(c.Command, c);
}
else
{
Common.Utils.WriteLine($"Adding commands for chat {c.ChatId}");
Common.Utils.WriteLine($"Found command {c.Command}");
var d = new Dictionary<string, UBCustomCommand>();
d.Add(c.Command, c);
_customCommands.Add(c.ChatId, d);
}
}
}
private static void DoShutdown()
{
Common.Utils.WriteLine("Closing RabbitMQ connection");
_channel?.Close();
_conn?.Close();
Common.Utils.WriteLine("Deregistering instance");
Utils.DeregisterInstance();
Common.Utils.WriteLine("***************************************");
Common.Utils.WriteLine("Shutdown completed.");
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = (e.ExceptionObject as Exception);
Common.Utils.WriteLine(ex?.Message);
}
private static void CurrentDomainOnProcessExit(object? sender, EventArgs e)
{
if (_manualShutdown) return;
Common.Utils.WriteLine("SIGTERM shutdown started.\n");
DoShutdown();
}
internal static void PublishMessage(ActionRequest actionRequest)
{
if (_channel is { IsClosed: true }) return;
var json = JsonConvert.SerializeObject(actionRequest);
var body = Encoding.UTF8.GetBytes(json);
_channel.BasicPublish("telegram", "result", _properties, body);
}
}