forked from Pryaxis/TSAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerHooks.cs
More file actions
81 lines (69 loc) · 2.16 KB
/
ServerHooks.cs
File metadata and controls
81 lines (69 loc) · 2.16 KB
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
using OTAPI;
using System;
using System.Linq;
using Terraria;
namespace TerrariaApi.Server.Hooking;
internal static class ServerHooks
{
private static HookManager _hookManager;
/// <summary>
/// Attaches any of the OTAPI Server hooks to the existing <see cref="HookManager"/> implementation
/// </summary>
/// <param name="hookManager">HookManager instance which will receive the events</param>
public static void AttachTo(HookManager hookManager)
{
_hookManager = hookManager;
HookEvents.Terraria.Main.startDedInput += Main_startDedInput;
HookEvents.Terraria.Main.ReadLineInput += Main_ReadLineInput;
HookEvents.Terraria.RemoteClient.Reset += RemoteClient_Reset;
Hooks.Main.CommandProcess += OnProcess;
}
static void Main_startDedInput(object? sender, HookEvents.Terraria.Main.startDedInputEventArgs args)
{
if (!args.ContinueExecution) return;
args.ContinueExecution = false;
if (Environment.GetCommandLineArgs().Any(x => x.Equals("-disable-commands")))
{
Console.WriteLine("Command thread has been disabled.");
return;
}
args.OriginalMethod();
}
#nullable enable
/// <summary>
/// Hooks the default ReadLineInput method to add a small delay when Console.ReadLine() returns null.
/// For example, some docker instances may experience a 100% CPU usage due to this vanilla thread implementation.
/// </summary>
static void Main_ReadLineInput(object? sender, HookEvents.Terraria.Main.ReadLineInputEventArgs args)
{
args.ContinueExecution = false;
string? text;
while ((text = Console.ReadLine()) is null)
System.Threading.Thread.Sleep(100);
args.HookReturnValue = text;
}
#nullable disable
static void OnProcess(object sender, Hooks.Main.CommandProcessEventArgs e)
{
if (e.Result == HookResult.Cancel)
{
return;
}
if (_hookManager.InvokeServerCommand(e.Command))
{
e.Result = HookResult.Cancel;
}
}
static void RemoteClient_Reset(RemoteClient client, HookEvents.Terraria.RemoteClient.ResetEventArgs args)
{
if (!args.ContinueExecution) return;
if (!Netplay.Disconnect)
{
if (client.IsActive)
{
_hookManager.InvokeServerLeave(client.Id);
}
_hookManager.InvokeServerSocketReset(client);
}
}
}