~ruther/NosTale-PacketLogger

ref: b1c19518089f0a93fb34cd09bd367e916acc0ffc NosTale-PacketLogger/src/PacketLogger/ViewModels/MainWindowViewModel.cs -rw-r--r-- 7.0 KiB
b1c19518 — Rutherther feat: allow connecting to process from menu 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
//
//  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.Linq;
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Dock.Model.Controls;
using Dock.Model.Core;
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 PacketLogger.Models;
using PacketLogger.Models.Packets;
using PacketLogger.Views;
using ReactiveUI;

namespace PacketLogger.ViewModels;

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

    /// <summary>
    /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
    /// </summary>
    public MainWindowViewModel()
    {
        var services = new ServiceCollection()
            .AddLogging(b => b.ClearProviders().AddConsole())
            .AddSingleton<DockFactory>()
            .AddSingleton<NostaleProcesses>()
            .AddNostaleCore()
            .AddStatefulInjector()
            .AddStatefulEntity<CommsPacketProvider>()
            .AddLocalComms()
            .AddPacketResponder<PacketResponder>()
            .BuildServiceProvider();

        _processes = services.GetRequiredService<NostaleProcesses>();
        var packetTypes = services.GetRequiredService<IPacketTypesRepository>();

        var result = packetTypes.AddDefaultPackets();
        if (!result.IsSuccess)
        {
            Console.WriteLine(result.ToFullString());
        }

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

        SaveAll = ReactiveCommand.CreateFromTask
        (
            async () =>
            {
                if (Layout?.FocusedDockable is PacketLogDocumentViewModel activeDocument && activeDocument.Loaded
                    && activeDocument.LogViewModel 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;
                    }

                    using var file = File.OpenWrite(result);
                    using var streamWriter = new StreamWriter(file);
                    foreach (var packet in activeDocument.LogViewModel.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 PacketLogDocumentViewModel activeDocument && activeDocument.Loaded
                    && activeDocument.LogViewModel 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;
                    }

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

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

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

        Connect = ReactiveCommand.Create<IList>
            (process => _factory.CreateLoadedDocument(doc => doc.OpenProcess.Execute((NostaleProcess)process[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 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> Connect { get; }

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