~ruther/NosTale-PacketLogger

ref: 088a47056fb85ff7330ec09dc90241e7016c9cd8 NosTale-PacketLogger/src/PacketLogger/Models/NostaleProcesses.cs -rw-r--r-- 6.2 KiB
088a4705 — Rutherther feat: add client closed indicator 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
//
//  NostaleProcesses.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.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using NosSmooth.Comms.Local;
using NosSmooth.Core.Extensions;
using NosSmooth.LocalBinding;
using NosSmooth.LocalBinding.Errors;
using NosSmooth.LocalBinding.Options;
using NosSmooth.LocalBinding.Structs;
using ReactiveUI;

namespace PacketLogger.Models;

/// <summary>
/// Keeps and refreshes a collection of NosTale processes.
/// </summary>
public class NostaleProcesses : IDisposable
{
    private readonly IDisposable? _cleanUp;
    private readonly SemaphoreSlim _semaphore;
    private readonly ManagementEventWatcher? _processStartWatcher;
    private readonly ManagementEventWatcher? _processStopWatcher;

    /// <summary>
    /// Initializes a new instance of the <see cref="NostaleProcesses"/> class.
    /// </summary>
    public NostaleProcesses()
    {
        _semaphore = new SemaphoreSlim(1, 1);
        Processes = new ObservableCollection<NostaleProcess>();

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                _cleanUp = Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(1))
                    .Subscribe(_ => UpdateNames());

                Supported = true;
                _processStartWatcher = new ManagementEventWatcher
                    (new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
                _processStartWatcher.EventArrived += HandleProcessOpenedEvent;
                _processStartWatcher.Start();

                _processStopWatcher = new ManagementEventWatcher
                    (new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
                _processStopWatcher.EventArrived += HandleProcessClosedEvent;
                _processStopWatcher.Start();

                // initial nostale processes
                // rest is handled by events
                foreach (var process in CommsInjector.FindNosTaleProcesses())
                {
                    HandleProcessOpened(process.Id);
                }
            }
        }
    }

    private void HandleProcessOpenedEvent(object sender, EventArrivedEventArgs e)
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            HandleProcessOpened(Convert.ToInt32(e.NewEvent.Properties["ProcessId"].Value));
        }
    }

    private void HandleProcessClosedEvent(object sender, EventArrivedEventArgs e)
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            HandleProcessClosed(Convert.ToInt32(e.NewEvent.Properties["ProcessId"].Value));
        }
    }

    private void HandleProcessOpened(int processId)
    {
        Process process;
        try
        {
            process = Process.GetProcessById(processId);
        }
        catch (Exception)
        {
            return;
        }

        if (!NosBrowserManager.IsProcessNostaleProcess(process))
        {
            return;
        }

        NosBrowserManager nosBrowserManager = new NosBrowserManager
        (
            process,
            new PlayerManagerOptions(),
            new SceneManagerOptions(),
            new PetManagerOptions(),
            new NetworkManagerOptions(),
            new UnitManagerOptions()
        );
        var result = nosBrowserManager.Initialize();
        if (!result.IsSuccess)
        {
            Console.WriteLine
                ($"Got an error when trying to initialize nos browser manager for {process.ProcessName}");
            Console.WriteLine(result.ToFullString());
        }

        if (nosBrowserManager.IsModuleLoaded<PlayerManager>())
        {
            RxApp.MainThreadScheduler.Schedule
                (() =>
                    {
                        _semaphore.Wait();
                        Processes.Add(new NostaleProcess(process, nosBrowserManager));
                        _semaphore.Release();
                    }
                );
        }
        else
        {
            Console.WriteLine
            (
                $"Cannot add {process.ProcessName} to nostale processes as player manager was not found in memory."
            );
        }
    }

    private void HandleProcessClosed(int processId)
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            var process = Processes.FirstOrDefault(x => x.Process.Id == processId);

            if (process is not null)
            {
                RxApp.MainThreadScheduler.Schedule
                    (() =>
                        {
                            process.ObserveChanges();
                            _semaphore.Wait();
                            Processes.Remove(process);
                            _semaphore.Release();
                        }
                    );
            }
        }
    }

    /// <summary>
    /// Gets whether tracking and attaching to processes is supported for this run.
    /// </summary>
    /// <remarks>
    /// Supported only on Windows run as elevated.
    /// </remarks>
    public bool Supported { get; }

    /// <summary>
    /// Gets NosTale processes.
    /// </summary>
    public ObservableCollection<NostaleProcess> Processes { get; }

    /// <inheritdoc />
    public void Dispose()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            _processStartWatcher?.Stop();
            _processStartWatcher?.Dispose();
            _processStopWatcher?.Stop();
            _processStopWatcher?.Dispose();
        }
    }

    private void UpdateNames()
    {
        _semaphore.Wait();
        foreach (var process in Processes)
        {
            process.ObserveChanges();
        }
        _semaphore.Release();
    }
}
Do not follow this link