~ruther/NosSmooth.Local

ref: d5b3c3ffb40aa86f582a0f26fc0376caa245f220 NosSmooth.Local/src/Core/NosSmooth.LocalClient/NostaleLocalClient.cs -rw-r--r-- 10.1 KiB
d5b3c3ff — Rutherther Merge pull request #18 from Rutherther/feat/optional-binding 2 years ago
                                                                                
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
//
//  NostaleLocalClient.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NosSmooth.Core.Client;
using NosSmooth.Core.Commands;
using NosSmooth.Core.Commands.Control;
using NosSmooth.Core.Extensions;
using NosSmooth.Core.Packets;
using NosSmooth.LocalBinding;
using NosSmooth.LocalBinding.Errors;
using NosSmooth.LocalBinding.EventArgs;
using NosSmooth.LocalBinding.Hooks;
using NosSmooth.LocalBinding.Objects;
using NosSmooth.LocalBinding.Structs;
using NosSmooth.Packets;
using NosSmooth.PacketSerializer;
using NosSmooth.PacketSerializer.Abstractions.Attributes;
using NosSmooth.PacketSerializer.Errors;
using Remora.Results;
using PacketEventArgs = NosSmooth.LocalBinding.EventArgs.PacketEventArgs;

namespace NosSmooth.LocalClient;

/// <summary>
/// The local nostale client.
/// </summary>
/// <remarks>
/// Client used for living in the same process as NostaleClientX.exe.
/// It hooks the send and receive packet methods.
/// </remarks>
public class NostaleLocalClient : BaseNostaleClient
{
    private readonly NosThreadSynchronizer _synchronizer;
    private readonly IHookManager _hookManager;
    private readonly ControlCommands _controlCommands;
    private readonly IPacketHandler _packetHandler;
    private readonly UserActionDetector _userActionDetector;
    private readonly ILogger _logger;
    private readonly IServiceProvider _provider;
    private readonly LocalClientOptions _options;
    private CancellationToken? _stopRequested;
    private IPacketInterceptor? _interceptor;

    /// <summary>
    /// Initializes a new instance of the <see cref="NostaleLocalClient"/> class.
    /// </summary>
    /// <param name="synchronizer">The thread synchronizer.</param>
    /// <param name="hookManager">The hook manager.</param>
    /// <param name="controlCommands">The control commands.</param>
    /// <param name="commandProcessor">The command processor.</param>
    /// <param name="packetHandler">The packet handler.</param>
    /// <param name="userActionDetector">The user action detector.</param>
    /// <param name="logger">The logger.</param>
    /// <param name="options">The options for the client.</param>
    /// <param name="provider">The dependency injection provider.</param>
    public NostaleLocalClient
    (
        NosThreadSynchronizer synchronizer,
        IHookManager hookManager,
        ControlCommands controlCommands,
        CommandProcessor commandProcessor,
        IPacketHandler packetHandler,
        UserActionDetector userActionDetector,
        ILogger<NostaleLocalClient> logger,
        IOptions<LocalClientOptions> options,
        IServiceProvider provider
    )
        : base(commandProcessor)
    {
        _options = options.Value;
        _synchronizer = synchronizer;
        _hookManager = hookManager;
        _controlCommands = controlCommands;
        _packetHandler = packetHandler;
        _userActionDetector = userActionDetector;
        _logger = logger;
        _provider = provider;
    }

    /// <inheritdoc />
    public override async Task<Result> RunAsync(CancellationToken stopRequested = default)
    {
        if (!_hookManager.IsHookLoaded<IPacketSendHook>() || !_hookManager.IsHookLoaded<IPacketReceiveHook>())
        {
            return new NeededModulesNotInitializedError
                ("Client cannot run", IHookManager.PacketSendName, IHookManager.PacketReceiveName);
        }

        _stopRequested = stopRequested;
        _logger.LogInformation("Starting local client");
        var synchronizerResult = _synchronizer.StartSynchronizer();
        if (!synchronizerResult.IsSuccess)
        {
            return synchronizerResult;
        }

        _hookManager.PacketSend.Get().Called += SendCallCallback;
        _hookManager.PacketReceive.Get().Called += ReceiveCallCallback;

        _hookManager.EntityFollow.TryDo(follow => follow.Called += FollowEntity);
        _hookManager.PlayerWalk.TryDo(walk => walk.Called += Walk);
        _hookManager.PetWalk.TryDo(walk => walk.Called += PetWalk);

        try
        {
            await Task.Delay(-1, stopRequested);
        }
        catch
        {
            // ignored
        }

        _hookManager.PacketSend.Get().Called -= SendCallCallback;
        _hookManager.PacketReceive.Get().Called -= ReceiveCallCallback;

        _hookManager.EntityFollow.TryDo(follow => follow.Called -= FollowEntity);
        _hookManager.PlayerWalk.TryDo(walk => walk.Called -= Walk);
        _hookManager.PetWalk.TryDo(walk => walk.Called -= PetWalk);

        // the hooks are not needed anymore.
        _hookManager.DisableAll();

        return Result.FromSuccess();
    }

    /// <inheritdoc />
    public override async Task<Result> ReceivePacketAsync(string packetString, CancellationToken ct = default)
    {
        var result = _hookManager.PacketReceive.MapResult
        (
            receive => receive.WrapperFunction.MapResult
            (
                wrapperFunction =>
                {
                    _synchronizer.EnqueueOperation(() => wrapperFunction(packetString));
                    return Result.FromSuccess();
                }
            )
        );

        if (result.IsSuccess)
        {
            _logger.LogDebug($"Receiving client packet {packetString}");
            await ProcessPacketAsync(PacketSource.Server, packetString);
        }
        else
        {
            _logger.LogError("Could not receive packet");
            _logger.LogResultError(result);
        }

        return result;
    }

    /// <inheritdoc />
    public override async Task<Result> SendPacketAsync(string packetString, CancellationToken ct = default)
    {
        var result = _hookManager.PacketSend.MapResult
        (
            send => send.WrapperFunction.MapResult
            (
                wrapperFunction =>
                {
                    _synchronizer.EnqueueOperation(() => wrapperFunction(packetString));
                    return Result.FromSuccess();
                }
            )
        );

        if (result.IsSuccess)
        {
            _logger.LogDebug($"Sending client packet {packetString}");
            await ProcessPacketAsync(PacketSource.Server, packetString);
        }
        else
        {
            _logger.LogError("Could not send packet");
            _logger.LogResultError(result);
        }

        return result;
    }

    private void ReceiveCallCallback(object? owner, PacketEventArgs packetArgs)
    {
        bool accepted = true;
        var packet = packetArgs.Packet;
        if (_options.AllowIntercept)
        {
            if (_interceptor is null)
            {
                _interceptor = _provider.GetRequiredService<IPacketInterceptor>();
            }

            accepted = _interceptor.InterceptReceive(ref packet);
        }

        Task.Run(async () => await ProcessPacketAsync(PacketSource.Server, packet));

        if (!accepted)
        {
            packetArgs.Cancel = true;
        }
    }

    private void SendCallCallback(object? owner, PacketEventArgs packetArgs)
    {
        bool accepted = true;
        var packet = packetArgs.Packet;
        if (_options.AllowIntercept)
        {
            if (_interceptor is null)
            {
                _interceptor = _provider.GetRequiredService<IPacketInterceptor>();
            }

            accepted = _interceptor.InterceptSend(ref packet);
        }

        Task.Run(async () => await ProcessPacketAsync(PacketSource.Client, packet));

        if (!accepted)
        {
            packetArgs.Cancel = true;
        }
    }

    private void SendPacket(string packetString)
    {
        _synchronizer.EnqueueOperation
        (
            () => _hookManager.PacketSend.Get().WrapperFunction.Get()(packetString)
        );
        _logger.LogDebug($"Sending client packet {packetString}");
    }

    private async Task ProcessPacketAsync(PacketSource type, string packetString)
    {
        try
        {
            var result = await _packetHandler.HandlePacketAsync(this, type, packetString);

            if (!result.IsSuccess)
            {
                _logger.LogError("There was an error whilst handling packet {packetString}", packetString);
                _logger.LogResultError(result);
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e, "The process packet threw an exception");
        }
    }

    private void FollowEntity(object? owner, EntityEventArgs entityEventArgs)
    {
        if (entityEventArgs.Entity is not null)
        {
            Task.Run
            (
                async () => await _controlCommands.CancelAsync
                    (ControlCommandsFilter.UserCancellable, false, (CancellationToken)_stopRequested!)
            );
        }
    }

    private void PetWalk(object? owner, PetWalkEventArgs petWalkEventArgs)
    {
        if (!_userActionDetector.IsPetWalkUserOperation
            (petWalkEventArgs.PetManager, petWalkEventArgs.X, petWalkEventArgs.Y))
        { // do not cancel operations made by NosTale or bot
            return;
        }

        if (_controlCommands.AllowUserActions)
        {
            Task.Run
            (
                async () => await _controlCommands.CancelAsync
                    (ControlCommandsFilter.UserCancellable, false, (CancellationToken)_stopRequested!)
            );
        }
        else
        {
            petWalkEventArgs.Cancel = true;
        }
    }

    private void Walk(object? owner, WalkEventArgs walkEventArgs)
    {
        if (!_userActionDetector.IsWalkUserAction(walkEventArgs.X, walkEventArgs.Y))
        { // do not cancel operations made by NosTale or bot
            return;
        }

        if (_controlCommands.AllowUserActions)
        {
            Task.Run
            (
                async () => await _controlCommands.CancelAsync
                    (ControlCommandsFilter.UserCancellable, false, (CancellationToken)_stopRequested!)
            );
        }
        else
        {
            walkEventArgs.Cancel = true;
        }
    }
}
Do not follow this link