~ruther/NosTale-PacketLogger

ref: c61f45970d133d6973bfa51d03c9ff4ff5b4e19b NosTale-PacketLogger/src/PacketLogger/ViewModels/MainWindowViewModel.cs -rw-r--r-- 9.3 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
//
//  MainWindowViewModel.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;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reflection;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Dock.Model.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NosSmooth.Comms.Local.Extensions;
using NosSmooth.Core.Extensions;
using NosSmooth.PacketSerializer.Abstractions.Attributes;
using NosSmooth.PacketSerializer.Extensions;
using NosSmooth.PacketSerializer.Packets;
using NosSmooth.Pcap;
using PacketLogger.Models;
using PacketLogger.Models.Filters;
using PacketLogger.Models.Packets;
using PacketLogger.ViewModels.Log;
using ReactiveUI;

namespace PacketLogger.ViewModels;

/// <inheritdoc />
public class MainWindowViewModel : ViewModelBase
{
    private readonly DockFactory _factory;
    private readonly NostaleProcesses _processes;

    /// <summary>
    /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
    /// </summary>
    public MainWindowViewModel()
    {
        var filterProfiles = new FilterProfiles();
        if (Path.Exists("settings.json"))
        {
            using var file = File.OpenRead("settings.json");
            var deserialized = JsonSerializer.Deserialize<FilterProfiles>(file);

            if (deserialized is not null)
            {
                filterProfiles = deserialized;
            }
        }

        var services = new ServiceCollection()
            .AddLogging(b => b.ClearProviders().AddConsole())
            .AddSingleton<FilterProfiles>(_ => filterProfiles)
            .AddSingleton<DockFactory>()
            .AddSingleton<NostaleProcesses>()
            .AddSingleton<ObservableCollection<IPacketProvider>>(_ => Providers)
            .AddSingleton<ProcessTcpManager>()
            .AddSingleton<PcapNostaleManager>()
            .AddNostaleCore()
            .AddStatefulInjector()
            .AddStatefulEntity<ClientPacketProvider>()
            .AddLocalComms()
            .AddPacketResponder(typeof(PacketResponder))
            .BuildServiceProvider();

        _processes = services.GetRequiredService<NostaleProcesses>();

        _factory = services.GetRequiredService<DockFactory>();
        Layout = _factory.CreateLayout();
        if (Layout is { })
        {
            _factory.InitLayout(Layout);
            if (Layout is { } root)
            {
                root.Navigate.Execute("Home");
            }
        }

        _factory.DocumentLoaded += doc =>
        {
            if (doc.Provider is not null)
            {
                RxApp.MainThreadScheduler.Schedule(() => Providers.Add(doc.Provider));
            }
        };

        _factory.DocumentClosed += doc =>
        {
            if (doc.Provider is not null)
            {
                RxApp.MainThreadScheduler.Schedule(() => Providers.Remove(doc.Provider));
            }
        };

        SaveAll = ReactiveCommand.CreateFromTask
        (
            async () =>
            {
                if (Layout?.FocusedDockable is DocumentViewModel activeDocument && activeDocument.Loaded
                    && activeDocument.NestedViewModel is not null)
                {
                    var mainWindow = (App.Current!.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
                        ?.MainWindow;
                    var result = await new SaveFileDialog()
                    {
                        DefaultExtension = ".log",
                        InitialFileName = Assembly.GetEntryAssembly()?.GetModules().FirstOrDefault()?.FullyQualifiedName
                    }.ShowAsync(mainWindow!);

                    if (result is null)
                    {
                        return;
                    }

                    if (activeDocument.Provider is null)
                    {
                        return;
                    }

                    using var file = File.OpenWrite(result);
                    using var streamWriter = new StreamWriter(file);

                    foreach (var packet in activeDocument.Provider.Packets.Items)
                    {
                        await streamWriter.WriteLineAsync
                        (
                            $"[{packet.Date:HH:mm:ss}]\t[{(packet.Source == PacketSource.Server ? "Recv" : "Send")}]\t{packet.PacketString.Trim()}"
                        );
                    }
                }
            }
        );

        SaveFiltered = ReactiveCommand.CreateFromTask
        (
            async () =>
            {
                if (Layout?.FocusedDockable is DocumentViewModel activeDocument && activeDocument.Loaded
                    && activeDocument.NestedViewModel is not null)
                {
                    var mainWindow = (App.Current!.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
                        ?.MainWindow;
                    var result = await new SaveFileDialog()
                    {
                        DefaultExtension = ".log",
                    }.ShowAsync(mainWindow!);

                    if (result is null)
                    {
                        return;
                    }

                    if (activeDocument.NestedViewModel is not PacketLogViewModel packetLogVM)
                    {
                        return;
                    }

                    using var file = File.OpenWrite(result);
                    using var streamWriter = new StreamWriter(file);
                    foreach (var packet in packetLogVM.FilteredPackets)
                    {
                        await streamWriter.WriteLineAsync
                        (
                            $"[{packet.Date:HH:mm:ss}]\t[{(packet.Source == PacketSource.Server ? "Recv" : "Send")}]\t{packet.PacketString.Trim()}"
                        );
                    }
                }
            }
        );

        SaveSettings = ReactiveCommand.CreateFromTask
        (
            async () =>
            {
                using var file = File.Open("settings.json", FileMode.Create);
                await JsonSerializer.SerializeAsync(file, filterProfiles);
            }
        );

        OpenFile = ReactiveCommand.Create
            (() => _factory.CreateLoadedDocument(doc => doc.OpenFile.Execute(Unit.Default)));

        OpenEmpty = ReactiveCommand.Create
            (() => _factory.CreateLoadedDocument(doc => doc.OpenDummy.Execute(Unit.Default)));

        OpenSettings = ReactiveCommand.Create
            (() => _factory.CreateLoadedDocument(doc => doc.OpenSettings.Execute(Unit.Default)));

        Connect = ReactiveCommand.Create<IList>
            (process => _factory.CreateLoadedDocument(doc => doc.OpenProcess.Execute((NostaleProcess)process[0]!)));

        OpenSender = ReactiveCommand.Create<IList>
            (provider => _factory.CreateLoadedDocument(doc => doc.OpenSender.Execute((IPacketProvider)provider[0]!)));

        NewTab = ReactiveCommand.Create
            (() => _factory.DocumentDock.CreateDocument?.Execute(null));

        QuitApplication = ReactiveCommand.Create
            (() => (Application.Current?.ApplicationLifetime as IControlledApplicationLifetime)?.Shutdown());
    }

    /// <summary>
    /// Gets the nostale processes.
    /// </summary>
    public ObservableCollection<NostaleProcess> Processes => _processes.Processes;

    /// <summary>
    /// Gets the packet provider.
    /// </summary>
    public ObservableCollection<IPacketProvider> Providers { get; } = new ObservableCollection<IPacketProvider>();

    /// <summary>
    /// Gets or sets the layout.
    /// </summary>
    public IRootDock? Layout { get; set; }

    /// <summary>
    /// Gets a command that quits the application.
    /// </summary>
    public ReactiveCommand<Unit, Unit> QuitApplication { get; }

    /// <summary>
    /// Gets a command that saves all packets.
    /// </summary>
    public ReactiveCommand<Unit, Unit> SaveAll { get; }

    /// <summary>
    /// Gets a command that saves filtered packets.
    /// </summary>
    public ReactiveCommand<Unit, Unit> SaveFiltered { get; }

    /// <summary>
    /// Gets the comamnd that opens a file.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenFile { get; }

    /// <summary>
    /// Gets the command that opens empty logger.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenEmpty { get; }

    /// <summary>
    /// Gets the command that opens empty logger.
    /// </summary>
    public ReactiveCommand<IList, Unit> OpenSender { get; }

    /// <summary>
    /// Gets the command that opens empty logger.
    /// </summary>
    public ReactiveCommand<IList, Unit> Connect { get; }

    /// <summary>
    /// Gets the command that opens a new tab.
    /// </summary>
    public ReactiveCommand<Unit, Unit> NewTab { get; }

    /// <summary>
    /// Gets the command used for opening settings.
    /// </summary>
    public ReactiveCommand<Unit, Unit> OpenSettings { get; }

    /// <summary>
    /// Gets the command used for saving settings.
    /// </summary>
    public ReactiveCommand<Unit, Unit> SaveSettings { get; }
}
Do not follow this link