~ruther/NosTale-PacketLogger

ref: c61f45970d133d6973bfa51d03c9ff4ff5b4e19b NosTale-PacketLogger/src/PacketLogger/ViewModels/DocumentViewModel.cs -rw-r--r-- 16.0 KiB
c61f4597 — Rutherther fix: make sender title change correctly 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//
//  DocumentViewModel.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 System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Dock.Model.Mvvm.Controls;
using DynamicData.Binding;
using Microsoft.Extensions.DependencyInjection;
using NosSmooth.Comms.Data.Messages;
using NosSmooth.Comms.Inject.Messages;
using NosSmooth.Comms.Local;
using NosSmooth.Comms.Local.Extensions;
using NosSmooth.Core.Contracts;
using NosSmooth.Core.Extensions;
using NosSmooth.Core.Stateful;
using NosSmooth.Pcap;
using PacketLogger.Models;
using PacketLogger.Models.Filters;
using PacketLogger.Models.Packets;
using PacketLogger.Models.Titles;
using PacketLogger.ViewModels.Log;
using PacketLogger.ViewModels.Sender;
using PacketLogger.ViewModels.Settings;
using ReactiveUI;
using Remora.Results;

namespace PacketLogger.ViewModels;

/// <inheritdoc />
public class DocumentViewModel : Document, INotifyPropertyChanged, IDisposable
{
    private readonly ObservableCollection<IPacketProvider> _providers;
    private readonly NostaleProcesses _processes;
    private readonly Action<DocumentViewModel> _onDocumentUnloaded;
    private CancellationTokenSource _ctSource;
    private IPacketProvider? _packetProvider;
    private IDisposable? _cleanUp;
    private NumberedTitleGenerator.TitleHandle _titleHandle;

    /// <summary>
    /// Initializes a new instance of the <see cref="DocumentViewModel"/> class.
    /// </summary>
    /// <param name="services">The services.</param>
    /// <param name="filterProfiles">The filter profiles.</param>
    /// <param name="injector">The injector.</param>
    /// <param name="repository">The repository.</param>
    /// <param name="providers">The providers.</param>
    /// <param name="processes">The NosTale processes collection.</param>
    /// <param name="titleGenerator">The title generator.</param>
    /// <param name="onDocumentLoaded">The action to call on loaded.</param>
    /// <param name="onDocumentUnloaded">The action to call on document unloaded/closed.</param>
    public DocumentViewModel
    (
        IServiceProvider services,
        FilterProfiles filterProfiles,
        CommsInjector injector,
        StatefulRepository repository,
        ObservableCollection<IPacketProvider> providers,
        NostaleProcesses processes,
        NumberedTitleGenerator titleGenerator,
        Action<DocumentViewModel> onDocumentLoaded,
        Action<DocumentViewModel> onDocumentUnloaded
    )
    {
        _titleHandle = titleGenerator.AddTitle
        (
            title => Title = title,
            Observable.Empty<string>(),
            "New tab"
        );

        _cleanUp = this.WhenAnyValue(x => x.Title)
            .Subscribe
            (
                title =>
                {
                    if (_packetProvider is not null)
                    {
                        _packetProvider.DocumentTitle = title;
                    }
                }
            );

        FilterProfiles = filterProfiles;
        _ctSource = new CancellationTokenSource();
        _providers = providers;
        _processes = processes;
        _onDocumentUnloaded = onDocumentUnloaded;
        OpenDummy = ReactiveCommand.CreateFromTask
        (
            () => Task.Run
            (
                () =>
                {
                    Loading = true;
                    _packetProvider = new DummyPacketProvider(Title);
                    _packetProvider.DocumentTitle = Title;
                    NestedViewModel = new PacketLogViewModel(_packetProvider, filterProfiles);
                    Loaded = true;
                    onDocumentLoaded(this);
                }
            )
        );

        OpenFile = ReactiveCommand.CreateFromTask
        (
            async () =>
            {
                var mainWindow = (App.Current!.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
                    ?.MainWindow;
                var result = await new OpenFileDialog
                {
                    AllowMultiple = false,
                    InitialFileName = Assembly.GetEntryAssembly()?.GetModules().FirstOrDefault()?.FullyQualifiedName
                }.ShowAsync(mainWindow!);

                if (result is null || result.Length == 0)
                {
                    return;
                }
                Loading = true;

                var path = result[0];
                var provider = new FilePacketProvider(path);
                _packetProvider = provider;

                var openResult = await provider.Open();
                if (!openResult.IsSuccess)
                {
                    Error = "File could not be opened. " + openResult.ToFullString();
                    Loading = false;
                    return;
                }

                _titleHandle?.Dispose();
                _titleHandle = titleGenerator.AddTitle
                (
                    title => Title = title,
                    Observable.Empty<string>(),
                    Path.GetFileName(path)
                );
                _packetProvider.DocumentTitle = Title;
                NestedViewModel = new PacketLogViewModel(provider, filterProfiles);
                Loaded = true;
                Loading = false;
                onDocumentLoaded(this);
            }
        );

        OpenProcess = ReactiveCommand.CreateFromTask<NostaleProcess>
        (
            async (process, ct) =>
            {
                Loading = true;
                var connectionResult = await injector.EstablishNamedPipesConnectionAsync
                    (process.Process, _ctSource.Token, ct);
                if (!connectionResult.IsDefined(out var connection))
                {
                    Error = "An error has occurred upon establishing a connection: " + connectionResult.ToFullString();
                    Loading = false;
                    return;
                }

                var provider = new CommsPacketProvider(process, connection);
                _packetProvider = provider;
                repository.SetEntity<ClientPacketProvider>(connection.Client, provider);

                var contractResult = await connection.Connection.ContractHanshake
                        (new HandshakeRequest("PacketLogger", true, false))
                    .WaitForAsync(DefaultStates.ResponseObtained, ct: ct);

                if (!contractResult.IsDefined(out var handshakeResponse))
                {
                    repository.Remove(connection.Client);
                    Error = "An error has occurred upon sending handshake: " + contractResult.ToFullString();
                    Loading = false;
                    return;
                }

                var handshakeInitResponse = handshakeResponse.InitializationResult;
                if (handshakeInitResponse is not null && !handshakeInitResponse.Value.IsSuccess)
                {
                    repository.Remove(connection.Client);
                    Error = "An error has occurred during handshaking: " + handshakeInitResponse.ToFullString();
                    Loading = false;
                    return;
                }

                if (handshakeInitResponse is null)
                {
                    var runClientContractResult = await connection.Connection.ContractRunClient(new RunClientRequest())
                        .WaitForAsync(DefaultStates.ResponseObtained, ct: ct);

                    if (!runClientContractResult.IsDefined(out var runClientResponse))
                    {
                        repository.Remove(connection.Client);
                        Error = "An error has occurred upon sending run client: "
                            + runClientContractResult.ToFullString();
                        Loading = false;
                        return;
                    }

                    if (runClientResponse.InitializationResult is null)
                    {
                        repository.Remove(connection.Client);
                        Error = "Unknown error";
                        Loading = false;
                        return;
                    }

                    if (runClientResponse.BindingManagerResult is not null
                        && !runClientResponse.BindingManagerResult.Value.IsSuccess)
                    {
                        Console.WriteLine("There was an error in binding initialization.");
                        Console.WriteLine(runClientResponse.BindingManagerResult.Value.ToFullString());
                    }

                    if (!runClientResponse.InitializationResult.Value.IsSuccess)
                    {
                        repository.Remove(connection.Client);
                        Error = "An error has occurred during starting client: "
                            + runClientResponse.InitializationResult.ToFullString();
                        Loading = false;
                        return;
                    }
                }

                _titleHandle?.Dispose();
                _titleHandle = titleGenerator.AddTitle
                (
                    title => Title = title,
                    provider
                        .WhenAnyValue(x => x.Name, x => x.Closed)
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Select
                        (
                            (x) => (x.Item2 ? "Closed (" : string.Empty) + x.Item1
                                + (x.Item2 ? ")" : string.Empty)
                        ),
                    provider.Name
                );

                _packetProvider.DocumentTitle = Title;
                NestedViewModel = new PacketLogViewModel(provider, filterProfiles);
                Loading = false;
                Loaded = true;
                onDocumentLoaded(this);
            }
        );

        OpenPcap = ReactiveCommand.CreateFromTask<NostaleProcess>
        (
            async process =>
            {
                Loading = true;

                var initialEncryptionKey = 0;
                if (process.BrowserManager.IsInGame.Get())
                {
                    var encryptionKeyOptional = process.BrowserManager.NtClient.Map(client => client.EncryptionKey);
                    encryptionKeyOptional.TryGet(out initialEncryptionKey);
                }

                var client = ActivatorUtilities.CreateInstance<PcapNostaleClient>
                    (services, process.Process, initialEncryptionKey, Encoding.Default);

                var provider = new PcapPacketProvider(process, client);
                _packetProvider = provider;
                repository.SetEntity<ClientPacketProvider>(client, provider);

                _titleHandle?.Dispose();
                _titleHandle = titleGenerator.AddTitle
                (
                    title => Title = title,
                    provider
                        .WhenAnyValue(x => x.Name, x => x.Closed)
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Select
                        (
                            (x) => (x.Item2 ? "Closed (" : string.Empty) + (x.Item1 + " - sniff")
                                + (x.Item2 ? ")" : string.Empty)
                        ),
                    provider.Name
                );
                await provider.Open();

                _packetProvider.DocumentTitle = Title;
                NestedViewModel = new PacketLogViewModel(provider, filterProfiles);
                Loading = false;
                Loaded = true;
                onDocumentLoaded(this);
            }
        );

        OpenSender = ReactiveCommand.Create<IPacketProvider>
        (
            provider =>
            {
                Loading = true;
                NestedViewModel = new PacketSenderViewModel(provider);
                _cleanUp?.Dispose();
                _cleanUp = null;

                _titleHandle?.Dispose();
                _titleHandle = titleGenerator.AddTitle
                (
                    title => Title = title,
                    provider
                        .WhenValueChanged(x => x.DocumentTitle)
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Select(x => "Sender - " + x),
                    provider.Name
                );
                Loaded = true;
                Loading = false;
            }
        );

        ClearError = ReactiveCommand.Create(() => Error = null);

        OpenSettings = ReactiveCommand.Create
        (
            () =>
            {
                _titleHandle?.Dispose();
                _titleHandle = titleGenerator.AddTitle
                (
                    title => Title = title,
                    Observable.Empty<string>(),
                    "Settings"
                );
                NestedViewModel = new SettingsViewModel(filterProfiles);
                Loaded = true;
            }
        );
    }

    /// <summary>
    /// Gets the filter profiles.
    /// </summary>
    public FilterProfiles FilterProfiles { get; }

    /// <summary>
    /// Gets the processes observable.
    /// </summary>
    public NostaleProcesses Processes => _processes;

    /// <summary>
    /// Gets packet provider.
    /// </summary>
    public IPacketProvider? Provider => _packetProvider;

    /// <summary>
    /// Gets the open providers.
    /// </summary>
    public ObservableCollection<IPacketProvider> Providers => _providers;

    /// <summary>
    /// Gets whether the document is currently being loaded.
    /// </summary>
    public bool Loading { get; private set; }

    /// <summary>
    /// Gets whether a document has been loaded.
    /// </summary>
    public bool Loaded { get; private set; }

    /// <summary>
    /// Gets or sets the current error.
    /// </summary>
    public string? Error { get; private set; }

    /// <summary>
    /// Gets or sets whether there is an error.
    /// </summary>
    public bool HasError => Error is not null;

    /// <summary>
    /// Gets the log tab view model.
    /// </summary>
    public ViewModelBase? NestedViewModel { get; private set; }

    /// <summary>
    /// Gets command for opening a dummy.
    /// </summary>
    public ReactiveCommand<IPacketProvider, Unit> OpenSender { get; }

    /// <summary>
    /// Gets command for opening a dummy.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenDummy { get; }

    /// <summary>
    /// Gets command for opening a file.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenFile { get; }

    /// <summary>
    /// Gets the command to clear the error.
    /// </summary>
    public ReactiveCommand<Unit, string?> ClearError { get; }

    /// <summary>
    /// Gets the command for opening a process / connecting to a process.
    /// </summary>
    public ReactiveCommand<NostaleProcess, Unit> OpenProcess { get; }

    /// <summary>
    /// Gets the command for opening a process / connecting to a process.
    /// </summary>
    public ReactiveCommand<NostaleProcess, Unit> OpenPcap { get; }

    /// <summary>
    /// Get open settings command.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenSettings { get; }

    /// <inheritdoc />
    public override bool OnClose()
    {
        _onDocumentUnloaded(this);
        var result = _packetProvider?.Close().GetAwaiter().GetResult();
        Dispose();

        if (!(result?.IsSuccess ?? true))
        {
            Console.WriteLine(result.ToFullString());
        }
        return base.OnClose();
    }

    /// <inheritdoc />
    public void Dispose()
    {
        _titleHandle?.Dispose();
        _cleanUp?.Dispose();
        _ctSource.Cancel();
        _ctSource.Dispose();
        (NestedViewModel as IDisposable)?.Dispose();
        OpenDummy.Dispose();
        OpenFile.Dispose();
        OpenProcess.Dispose();
        OpenSender.Dispose();
    }
}
Do not follow this link