Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc92c80b43 | ||
|
|
724644c8eb | ||
|
|
23768dbe0e | ||
|
|
ace23b954e | ||
|
|
a4fc8c047a | ||
|
|
5a2639f96c | ||
|
|
fbd94ae1e6 | ||
|
|
cf01546b0b | ||
|
|
ec80bea024 | ||
|
|
b88006f02d | ||
|
|
c5ac1681f2 | ||
|
|
06f2ebb1ac | ||
|
|
9912ca8ba4 | ||
|
|
427f16cde0 | ||
|
|
fe8abb589f | ||
|
|
ae787373dc | ||
|
|
4f2fe7b292 | ||
|
|
635a489cc1 | ||
|
|
5b82edb9ee | ||
|
|
84e0fbb959 | ||
|
|
fdebc16b37 | ||
|
|
8467399001 |
+1
-1
@@ -1 +1 @@
|
|||||||
1.0.2
|
1.0.23
|
||||||
|
|||||||
@@ -1 +1,79 @@
|
|||||||
"# monster_monitor_v2"
|
# Monster Monitor v2
|
||||||
|
|
||||||
|
Windows-приложение (WinForms, .NET Framework 4.7.2) для мониторинга процесса `ss.exe`, поддержки SSH-туннеля и контроля состояния сервисов с логированием в UI.
|
||||||
|
|
||||||
|
## Возможности
|
||||||
|
|
||||||
|
- мониторинг и автоподдержка процесса `ss.exe`;
|
||||||
|
- управление SSH-туннелем;
|
||||||
|
- предотвращение засыпания системы во время работы;
|
||||||
|
- логирование событий в консоль приложения;
|
||||||
|
- хранение настроек в локальном профиле пользователя;
|
||||||
|
- автообновление через GitHub Releases (с проверкой раз в час);
|
||||||
|
- поддержка proxy для запросов к GitHub API и скачивания релизов.
|
||||||
|
|
||||||
|
## Требования
|
||||||
|
|
||||||
|
- Windows 10+;
|
||||||
|
- .NET Framework 4.7.2 (target `net472`);
|
||||||
|
- доступ к GitHub (напрямую или через proxy).
|
||||||
|
|
||||||
|
## Сборка и запуск
|
||||||
|
|
||||||
|
Из корня репозитория:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet build .\src\MonsterMonitor\MonsterMonitor.csproj
|
||||||
|
dotnet run --project .\src\MonsterMonitor\MonsterMonitor.csproj
|
||||||
|
```
|
||||||
|
|
||||||
|
Или откройте `src/MonsterMonitor.sln` в Visual Studio и запустите проект `MonsterMonitor`.
|
||||||
|
|
||||||
|
## Настройки
|
||||||
|
|
||||||
|
Настройки сохраняются в:
|
||||||
|
|
||||||
|
`%LOCALAPPDATA%\MonsterMonitor\settings.ini`
|
||||||
|
|
||||||
|
Основные параметры:
|
||||||
|
|
||||||
|
- `SshHost`, `SshPort`, `SshUsername`, `SshPasswordProtected`;
|
||||||
|
- `RemotePort`, `LocalPort`;
|
||||||
|
- `MaxPingFailures`, `ReconnectTimeoutSec`;
|
||||||
|
- `SsProcessPath`, `SsArguments`;
|
||||||
|
- `Proxy` — адрес proxy для GitHub-запросов (пример: `http://host:port`).
|
||||||
|
|
||||||
|
Часть паролей хранится в защищенном виде через DPAPI.
|
||||||
|
|
||||||
|
## Автообновление
|
||||||
|
|
||||||
|
Приложение проверяет новые версии в GitHub репозитории:
|
||||||
|
|
||||||
|
- owner: `monster1025`
|
||||||
|
- repo: `monster_monitor_v2`
|
||||||
|
|
||||||
|
Логика:
|
||||||
|
|
||||||
|
1. Определяется текущая версия приложения.
|
||||||
|
2. Получается последняя версия релиза из GitHub.
|
||||||
|
3. Если версия новее текущей — скачивается `.zip`-ассет релиза.
|
||||||
|
4. Обновление подготавливается в директории приложения:
|
||||||
|
- `.\update\<version>\update.zip`
|
||||||
|
- `.\update\<version>\extracted`
|
||||||
|
- `.\update\<version>\apply_update.bat`
|
||||||
|
5. Пользователю предлагается перезапустить приложение для применения обновления.
|
||||||
|
|
||||||
|
Периодичность проверки: каждые 60 минут (и первичная проверка после старта приложения).
|
||||||
|
|
||||||
|
## Интерфейс
|
||||||
|
|
||||||
|
- Главное окно:
|
||||||
|
- кнопка `Настройки`;
|
||||||
|
- кнопка `Выход`;
|
||||||
|
- консоль логов (уровни: Debug/Info/Warn/Error).
|
||||||
|
- При сворачивании окно уходит в трей.
|
||||||
|
|
||||||
|
## Примечания
|
||||||
|
|
||||||
|
- Для автообновления релиз должен содержать `.zip`-ассет с файлами приложения.
|
||||||
|
- Если `/releases/latest` недоступен, используется fallback на список релизов `/releases`.
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ git tag -m "Version v%VERSION%: %~1" -a v%VERSION%
|
|||||||
git push origin v%VERSION%
|
git push origin v%VERSION%
|
||||||
|
|
||||||
git push --tags
|
git push --tags
|
||||||
|
git push
|
||||||
GOTO End
|
GOTO End
|
||||||
pause
|
pause
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
|||||||
# Visual Studio Version 16
|
# Visual Studio Version 16
|
||||||
VisualStudioVersion = 16.0.32929.386
|
VisualStudioVersion = 16.0.32929.386
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonsterMonitor", "src\MonsterMonitor.csproj", "{7D6104C6-6AEF-4D31-8463-FCEABDF1577A}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonsterMonitor", "MonsterMonitor\MonsterMonitor.csproj", "{7D6104C6-6AEF-4D31-8463-FCEABDF1577A}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -4,7 +4,7 @@ using System.IO;
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Models
|
namespace MonsterMonitor.Models
|
||||||
{
|
{
|
||||||
public sealed class AppSettings
|
public sealed class AppSettings
|
||||||
{
|
{
|
||||||
@@ -21,6 +21,7 @@ namespace SshTunnelMonitor.Models
|
|||||||
public int LocalPort { get; set; } = 7829;
|
public int LocalPort { get; set; } = 7829;
|
||||||
public int MaxPingFailures { get; set; } = 3;
|
public int MaxPingFailures { get; set; } = 3;
|
||||||
public int ReconnectTimeoutSec { get; set; } = 45;
|
public int ReconnectTimeoutSec { get; set; } = 45;
|
||||||
|
public string Proxy { get; set; } = string.Empty;
|
||||||
public string SsProcessPath { get; set; } = Path.Combine("App_Data", "ss", "ss.exe");
|
public string SsProcessPath { get; set; } = Path.Combine("App_Data", "ss", "ss.exe");
|
||||||
public string SsArguments { get; set; } = string.Empty;
|
public string SsArguments { get; set; } = string.Empty;
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ namespace SshTunnelMonitor.Models
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(SystemPasswordProtected))
|
if (string.IsNullOrWhiteSpace(SystemPasswordProtected))
|
||||||
{
|
{
|
||||||
return "STerra";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!SystemPasswordProtected.StartsWith(ProtectedPrefix, StringComparison.Ordinal))
|
if (!SystemPasswordProtected.StartsWith(ProtectedPrefix, StringComparison.Ordinal))
|
||||||
@@ -163,6 +164,7 @@ namespace SshTunnelMonitor.Models
|
|||||||
result.LocalPort = GetInt(map, nameof(LocalPort), result.LocalPort);
|
result.LocalPort = GetInt(map, nameof(LocalPort), result.LocalPort);
|
||||||
result.MaxPingFailures = GetInt(map, nameof(MaxPingFailures), result.MaxPingFailures);
|
result.MaxPingFailures = GetInt(map, nameof(MaxPingFailures), result.MaxPingFailures);
|
||||||
result.ReconnectTimeoutSec = GetInt(map, nameof(ReconnectTimeoutSec), result.ReconnectTimeoutSec);
|
result.ReconnectTimeoutSec = GetInt(map, nameof(ReconnectTimeoutSec), result.ReconnectTimeoutSec);
|
||||||
|
result.Proxy = Get(map, nameof(Proxy), result.Proxy);
|
||||||
result.SsProcessPath = Get(map, nameof(SsProcessPath), result.SsProcessPath);
|
result.SsProcessPath = Get(map, nameof(SsProcessPath), result.SsProcessPath);
|
||||||
result.SsArguments = Get(map, nameof(SsArguments), result.SsArguments);
|
result.SsArguments = Get(map, nameof(SsArguments), result.SsArguments);
|
||||||
|
|
||||||
@@ -191,6 +193,7 @@ namespace SshTunnelMonitor.Models
|
|||||||
$"{nameof(LocalPort)}={LocalPort}",
|
$"{nameof(LocalPort)}={LocalPort}",
|
||||||
$"{nameof(MaxPingFailures)}={MaxPingFailures}",
|
$"{nameof(MaxPingFailures)}={MaxPingFailures}",
|
||||||
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
|
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
|
||||||
|
$"{nameof(Proxy)}={Proxy}",
|
||||||
$"{nameof(SsProcessPath)}={SsProcessPath}",
|
$"{nameof(SsProcessPath)}={SsProcessPath}",
|
||||||
$"{nameof(SsArguments)}={SsArguments}"
|
$"{nameof(SsArguments)}={SsArguments}"
|
||||||
};
|
};
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net472</TargetFramework>
|
<TargetFramework>net472</TargetFramework>
|
||||||
<UseWindowsForms>true</UseWindowsForms>
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
<LangVersion>7.3</LangVersion>
|
<LangVersion>7.3</LangVersion>
|
||||||
<RootNamespace>SshTunnelMonitor</RootNamespace>
|
<RootNamespace>MonsterMonitor</RootNamespace>
|
||||||
<AssemblyName>MonsterMonitor</AssemblyName>
|
<AssemblyName>devenv</AssemblyName>
|
||||||
|
<AssemblyVersion>1.0.23</AssemblyVersion>
|
||||||
|
<Version>1.0.23</Version>
|
||||||
|
<FileVersion>1.0.23</FileVersion>
|
||||||
|
<InformationalVersion>1.0.23</InformationalVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
||||||
@@ -14,7 +18,9 @@
|
|||||||
<PackageReference Include="Fody" Version="6.9.3">
|
<PackageReference Include="Fody" Version="6.9.3">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<Reference Include="System.IO.Compression.FileSystem" />
|
||||||
<Reference Include="System.Security" />
|
<Reference Include="System.Security" />
|
||||||
|
<Reference Include="System.Runtime.Serialization" />
|
||||||
<PackageReference Include="SSH.NET" Version="2025.1.0" />
|
<PackageReference Include="SSH.NET" Version="2025.1.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -28,4 +34,4 @@
|
|||||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
using MonsterMonitor.UI;
|
||||||
|
|
||||||
|
namespace MonsterMonitor
|
||||||
|
{
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private const string SingleInstanceMutexName = @"Global\MonsterMonitor_v2_SingleInstance";
|
||||||
|
private const string ActivateEventName = @"Global\MonsterMonitor_v2_Activate";
|
||||||
|
|
||||||
|
[STAThread]
|
||||||
|
private static void Main()
|
||||||
|
{
|
||||||
|
var createdNew = false;
|
||||||
|
using (var mutex = new Mutex(true, SingleInstanceMutexName, out createdNew))
|
||||||
|
{
|
||||||
|
if (!createdNew)
|
||||||
|
{
|
||||||
|
TrySignalExistingInstance();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Application.ThreadException += (sender, args) =>
|
||||||
|
{
|
||||||
|
MessageBox.Show(
|
||||||
|
args.Exception.ToString(),
|
||||||
|
"Необработанное исключение UI-потока",
|
||||||
|
MessageBoxButtons.OK,
|
||||||
|
MessageBoxIcon.Error);
|
||||||
|
};
|
||||||
|
|
||||||
|
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
|
||||||
|
{
|
||||||
|
MessageBox.Show(
|
||||||
|
args.ExceptionObject.ToString(),
|
||||||
|
"Критическое исключение",
|
||||||
|
MessageBoxButtons.OK,
|
||||||
|
MessageBoxIcon.Error);
|
||||||
|
};
|
||||||
|
|
||||||
|
Application.EnableVisualStyles();
|
||||||
|
Application.SetCompatibleTextRenderingDefault(false);
|
||||||
|
using (var activateEvent = new EventWaitHandle(false, EventResetMode.AutoReset, ActivateEventName))
|
||||||
|
{
|
||||||
|
var form = new MainForm();
|
||||||
|
ThreadPool.RegisterWaitForSingleObject(
|
||||||
|
activateEvent,
|
||||||
|
(state, timedOut) =>
|
||||||
|
{
|
||||||
|
var mainForm = state as MainForm;
|
||||||
|
mainForm?.RestoreAndActivateFromExternalSignal();
|
||||||
|
},
|
||||||
|
form,
|
||||||
|
Timeout.Infinite,
|
||||||
|
false);
|
||||||
|
|
||||||
|
Application.Run(form);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TrySignalExistingInstance()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (var activateEvent = EventWaitHandle.OpenExisting(ActivateEventName))
|
||||||
|
{
|
||||||
|
activateEvent.Set();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Если не удалось отправить сигнал, просто завершаем второй инстанс.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using SshTunnelMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public sealed class AppController : IDisposable
|
public sealed class AppController : IDisposable
|
||||||
{
|
{
|
||||||
@@ -10,6 +10,7 @@ namespace SshTunnelMonitor.Services
|
|||||||
private readonly SsConfigService _ssConfig;
|
private readonly SsConfigService _ssConfig;
|
||||||
private ProcessMonitorService _processMonitor;
|
private ProcessMonitorService _processMonitor;
|
||||||
private SshTunnelService _sshTunnel;
|
private SshTunnelService _sshTunnel;
|
||||||
|
private IAuthMonitor _authMonitor;
|
||||||
|
|
||||||
public AppController(LogService log, PowerManagementService power)
|
public AppController(LogService log, PowerManagementService power)
|
||||||
{
|
{
|
||||||
@@ -25,10 +26,12 @@ namespace SshTunnelMonitor.Services
|
|||||||
_power.PreventSleep();
|
_power.PreventSleep();
|
||||||
_processMonitor = new ProcessMonitorService(_log);
|
_processMonitor = new ProcessMonitorService(_log);
|
||||||
_sshTunnel = new SshTunnelService(_log);
|
_sshTunnel = new SshTunnelService(_log);
|
||||||
|
_authMonitor = new AuthMonitor(settings);
|
||||||
|
|
||||||
_ssConfig.EnsureConfig(settings);
|
_ssConfig.EnsureConfig(settings);
|
||||||
_processMonitor.Start(settings.SsProcessPath, settings.SsArguments);
|
_processMonitor.Start(settings.SsProcessPath, settings.SsArguments);
|
||||||
_sshTunnel.Start(settings);
|
_sshTunnel.Start(settings);
|
||||||
|
_ = _authMonitor.StartMonitor();
|
||||||
|
|
||||||
_log.Info("Сервисы приложения запущены.");
|
_log.Info("Сервисы приложения запущены.");
|
||||||
}
|
}
|
||||||
@@ -38,6 +41,9 @@ namespace SshTunnelMonitor.Services
|
|||||||
_sshTunnel?.Dispose();
|
_sshTunnel?.Dispose();
|
||||||
_sshTunnel = null;
|
_sshTunnel = null;
|
||||||
|
|
||||||
|
_authMonitor?.StopMonitor();
|
||||||
|
_authMonitor = null;
|
||||||
|
|
||||||
_processMonitor?.Dispose();
|
_processMonitor?.Dispose();
|
||||||
_processMonitor = null;
|
_processMonitor = null;
|
||||||
|
|
||||||
@@ -2,11 +2,12 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
using SshTunnelMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public class AuthMonitor: IAuthMonitor
|
public class AuthMonitor: IAuthMonitor
|
||||||
{
|
{
|
||||||
@@ -20,6 +21,8 @@ namespace SshTunnelMonitor.Services
|
|||||||
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
|
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
|
||||||
|
|
||||||
private readonly AppSettings _settings;
|
private readonly AppSettings _settings;
|
||||||
|
private CancellationTokenSource _monitorCancellation;
|
||||||
|
private Task _monitorTask;
|
||||||
|
|
||||||
public AuthMonitor(AppSettings settings)
|
public AuthMonitor(AppSettings settings)
|
||||||
{
|
{
|
||||||
@@ -36,12 +39,39 @@ namespace SshTunnelMonitor.Services
|
|||||||
|
|
||||||
public async Task StartMonitor()
|
public async Task StartMonitor()
|
||||||
{
|
{
|
||||||
_ = Task.Run(async () => await CheckProcess());
|
StopMonitor();
|
||||||
|
_monitorCancellation = new CancellationTokenSource();
|
||||||
|
_monitorTask = Task.Run(async () => await CheckProcess(_monitorCancellation.Token));
|
||||||
|
await Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task CheckProcess()
|
public void StopMonitor()
|
||||||
{
|
{
|
||||||
while (true)
|
if (_monitorCancellation == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_monitorCancellation.Cancel();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_monitorTask?.Wait(TimeSpan.FromSeconds(1));
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Ignore shutdown errors.
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_monitorCancellation.Dispose();
|
||||||
|
_monitorCancellation = null;
|
||||||
|
_monitorTask = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CheckProcess(CancellationToken token)
|
||||||
|
{
|
||||||
|
while (!token.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -57,8 +87,12 @@ namespace SshTunnelMonitor.Services
|
|||||||
var activeWindowTitle = GetActiveWindowTitle();
|
var activeWindowTitle = GetActiveWindowTitle();
|
||||||
if (activeWindowTitle?.Contains("XAuth request") == true)
|
if (activeWindowTitle?.Contains("XAuth request") == true)
|
||||||
{
|
{
|
||||||
SendKeys.SendWait(_settings.GetSystemPassword());
|
var password = _settings.GetSystemPassword();
|
||||||
SendKeys.SendWait("{ENTER}");
|
if (!string.IsNullOrEmpty(password))
|
||||||
|
{
|
||||||
|
SendKeys.SendWait(password);
|
||||||
|
SendKeys.SendWait("{ENTER}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -66,7 +100,14 @@ namespace SshTunnelMonitor.Services
|
|||||||
MessageBox.Show(ex.Message + ex.StackTrace);
|
MessageBox.Show(ex.Message + ex.StackTrace);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(3), token);
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,5 +115,6 @@ namespace SshTunnelMonitor.Services
|
|||||||
public interface IAuthMonitor
|
public interface IAuthMonitor
|
||||||
{
|
{
|
||||||
Task StartMonitor();
|
Task StartMonitor();
|
||||||
|
void StopMonitor();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Net;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
using System.Runtime.Serialization.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
|
namespace MonsterMonitor.Services
|
||||||
|
{
|
||||||
|
public sealed class GitHubUpdateService
|
||||||
|
{
|
||||||
|
private const string GithubUser = "monster1025";
|
||||||
|
private const string GithubRepo = "monster_monitor_v2";
|
||||||
|
private const string GithubToken = "";
|
||||||
|
|
||||||
|
private readonly LogService _log;
|
||||||
|
private readonly AppSettings _settings;
|
||||||
|
|
||||||
|
public GitHubUpdateService(LogService log, AppSettings settings)
|
||||||
|
{
|
||||||
|
_log = log;
|
||||||
|
_settings = settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CheckAndPrepareUpdateAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var currentVersion = GetCurrentVersion();
|
||||||
|
_log.Info("Проверка обновлений...");
|
||||||
|
_log.Info("Текущая версия: " + currentVersion);
|
||||||
|
|
||||||
|
var release = await GetLatestReleaseAsync();
|
||||||
|
if (release == null)
|
||||||
|
{
|
||||||
|
_log.Warn("Не удалось получить данные о релизе с GitHub.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var latestVersion = ParseVersion(release.TagName);
|
||||||
|
if (latestVersion == null)
|
||||||
|
{
|
||||||
|
_log.Warn("Не удалось распарсить версию релиза: " + (release.TagName ?? "<empty>"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.Info("Версия на GitHub: " + latestVersion);
|
||||||
|
if (latestVersion <= currentVersion)
|
||||||
|
{
|
||||||
|
_log.Info("Обновление не требуется.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.Info("Найдена новая версия. Начинаю загрузку обновления...");
|
||||||
|
var zipAsset = FindZipAsset(release.Assets);
|
||||||
|
if (zipAsset == null)
|
||||||
|
{
|
||||||
|
_log.Warn("У релиза нет .zip-ассета для автообновления.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var appDir = AppDomain.CurrentDomain.BaseDirectory;
|
||||||
|
var packageDir = Path.Combine(appDir, "update", latestVersion.ToString());
|
||||||
|
var packageZip = Path.Combine(packageDir, "update.zip");
|
||||||
|
var extractDir = Path.Combine(packageDir, "extracted");
|
||||||
|
Directory.CreateDirectory(packageDir);
|
||||||
|
|
||||||
|
await DownloadFileAsync(GetAssetDownloadUrl(zipAsset), packageZip);
|
||||||
|
_log.Info("Архив обновления загружен: " + zipAsset.Name);
|
||||||
|
|
||||||
|
if (Directory.Exists(extractDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(extractDir, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
ZipFile.ExtractToDirectory(packageZip, extractDir);
|
||||||
|
_log.Info("Архив обновления распакован.");
|
||||||
|
|
||||||
|
var exePath = Application.ExecutablePath;
|
||||||
|
var updaterBat = Path.Combine(packageDir, "apply_update.bat");
|
||||||
|
File.WriteAllText(updaterBat, BuildUpdaterScript(appDir, extractDir, exePath), Encoding.ASCII);
|
||||||
|
|
||||||
|
_log.Info("Обновление подготовлено.");
|
||||||
|
var restartNow = MessageBox.Show(
|
||||||
|
"Обновление загружено и готово к установке. Перезапустить приложение сейчас?",
|
||||||
|
"Monster Monitor",
|
||||||
|
MessageBoxButtons.YesNo,
|
||||||
|
MessageBoxIcon.Question);
|
||||||
|
|
||||||
|
if (restartNow == DialogResult.Yes)
|
||||||
|
{
|
||||||
|
_log.Info("Перезапуск приложения для применения обновления...");
|
||||||
|
StartUpdaterAndExit(updaterBat);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.Warn("Перезапуск отложен. Обновление будет применено после следующего запуска через обновлятор.");
|
||||||
|
}
|
||||||
|
catch (WebException ex)
|
||||||
|
{
|
||||||
|
var response = ex.Response as HttpWebResponse;
|
||||||
|
var statusCode = response != null ? ((int)response.StatusCode).ToString(CultureInfo.InvariantCulture) : "n/a";
|
||||||
|
var statusText = response != null ? response.StatusCode.ToString() : "unknown";
|
||||||
|
_log.Error("Ошибка обновления (HTTP): " + statusCode + " " + statusText + ". " + ex.Message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Error("Ошибка обновления: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Version GetCurrentVersion()
|
||||||
|
{
|
||||||
|
var fileVersion = TryParseVersion(FileVersionInfo.GetVersionInfo(Application.ExecutablePath).ProductVersion);
|
||||||
|
if (fileVersion != null)
|
||||||
|
{
|
||||||
|
return fileVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
|
||||||
|
if (assemblyVersion != null)
|
||||||
|
{
|
||||||
|
return assemblyVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
var productVersion = TryParseVersion(Application.ProductVersion);
|
||||||
|
if (productVersion != null)
|
||||||
|
{
|
||||||
|
return productVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.Warn("Не удалось определить текущую версию приложения, использую 1.0.0.");
|
||||||
|
return new Version(1, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Version TryParseVersion(string raw)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(raw))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = raw.Trim();
|
||||||
|
var plusIndex = value.IndexOf('+');
|
||||||
|
if (plusIndex > 0)
|
||||||
|
{
|
||||||
|
value = value.Substring(0, plusIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.StartsWith("v", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
value = value.Substring(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Version version;
|
||||||
|
return Version.TryParse(value, out version) ? version : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Version ParseVersion(string rawVersion)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(rawVersion))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var normalized = rawVersion.Trim();
|
||||||
|
if (normalized.StartsWith("v", true, CultureInfo.InvariantCulture))
|
||||||
|
{
|
||||||
|
normalized = normalized.Substring(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Version version;
|
||||||
|
if (Version.TryParse(normalized, out version))
|
||||||
|
{
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<GithubRelease> GetLatestReleaseAsync()
|
||||||
|
{
|
||||||
|
var url = string.Format(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
"https://api.github.com/repos/{0}/{1}/releases/latest",
|
||||||
|
GithubUser,
|
||||||
|
GithubRepo);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var request = CreateGithubRequest(url, "application/vnd.github+json");
|
||||||
|
using (var response = (HttpWebResponse)await request.GetResponseAsync())
|
||||||
|
using (var stream = response.GetResponseStream())
|
||||||
|
{
|
||||||
|
if (stream == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var serializer = new DataContractJsonSerializer(typeof(GithubRelease));
|
||||||
|
return serializer.ReadObject(stream) as GithubRelease;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (WebException ex)
|
||||||
|
{
|
||||||
|
var response = ex.Response as HttpWebResponse;
|
||||||
|
if (response != null && response.StatusCode == HttpStatusCode.NotFound)
|
||||||
|
{
|
||||||
|
_log.Warn("Релиз /latest не найден. Пробую получить список релизов...");
|
||||||
|
return await GetLatestReleaseFromListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<GithubRelease> GetLatestReleaseFromListAsync()
|
||||||
|
{
|
||||||
|
var url = string.Format(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
"https://api.github.com/repos/{0}/{1}/releases",
|
||||||
|
GithubUser,
|
||||||
|
GithubRepo);
|
||||||
|
|
||||||
|
var request = CreateGithubRequest(url, "application/vnd.github+json");
|
||||||
|
using (var response = (HttpWebResponse)await request.GetResponseAsync())
|
||||||
|
using (var stream = response.GetResponseStream())
|
||||||
|
{
|
||||||
|
if (stream == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var serializer = new DataContractJsonSerializer(typeof(List<GithubRelease>));
|
||||||
|
var releases = serializer.ReadObject(stream) as List<GithubRelease>;
|
||||||
|
if (releases == null || releases.Count == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return releases[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task DownloadFileAsync(string url, string filePath)
|
||||||
|
{
|
||||||
|
var request = CreateGithubRequest(url, "application/octet-stream");
|
||||||
|
|
||||||
|
using (var response = (HttpWebResponse)await request.GetResponseAsync())
|
||||||
|
using (var responseStream = response.GetResponseStream())
|
||||||
|
using (var fileStream = File.Create(filePath))
|
||||||
|
{
|
||||||
|
if (responseStream == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Пустой поток ответа при загрузке файла.");
|
||||||
|
}
|
||||||
|
|
||||||
|
await responseStream.CopyToAsync(fileStream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GithubAsset FindZipAsset(IList<GithubAsset> assets)
|
||||||
|
{
|
||||||
|
if (assets == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var asset in assets)
|
||||||
|
{
|
||||||
|
if (asset == null || string.IsNullOrWhiteSpace(asset.Name))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (asset.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return asset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetAssetDownloadUrl(GithubAsset asset)
|
||||||
|
{
|
||||||
|
if (asset == null)
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(asset.ApiUrl))
|
||||||
|
{
|
||||||
|
return asset.ApiUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return asset.DownloadUrl ?? string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpWebRequest CreateGithubRequest(string url, string accept)
|
||||||
|
{
|
||||||
|
var request = (HttpWebRequest)WebRequest.Create(url);
|
||||||
|
request.Method = "GET";
|
||||||
|
request.Accept = accept;
|
||||||
|
request.UserAgent = "MonsterMonitorUpdater/1.0";
|
||||||
|
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||||
|
if (!string.IsNullOrWhiteSpace(GithubToken))
|
||||||
|
{
|
||||||
|
request.Headers.Add("Authorization", "Bearer " + GithubToken);
|
||||||
|
}
|
||||||
|
if (!string.IsNullOrWhiteSpace(_settings.Proxy))
|
||||||
|
{
|
||||||
|
request.Proxy = GetProxy(_settings.Proxy);
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebProxy GetProxy(string proxyUri)
|
||||||
|
{
|
||||||
|
var proxy = new WebProxy(new Uri(proxyUri), false);
|
||||||
|
var cc = new CredentialCache();
|
||||||
|
cc.Add(
|
||||||
|
new Uri(proxyUri),
|
||||||
|
"Negotiate", // if we don't set it to "Kerberos" we get error 407 with ---> the function requested is not supported.
|
||||||
|
CredentialCache.DefaultNetworkCredentials);
|
||||||
|
proxy.Credentials = cc;
|
||||||
|
return proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildUpdaterScript(string appDir, string extractDir, string exePath)
|
||||||
|
{
|
||||||
|
return "@echo off" + Environment.NewLine +
|
||||||
|
"setlocal" + Environment.NewLine +
|
||||||
|
"timeout /t 2 /nobreak >nul" + Environment.NewLine +
|
||||||
|
"xcopy \"" + extractDir + "\\*\" \"" + appDir + "\\\" /E /I /Y /Q >nul" + Environment.NewLine +
|
||||||
|
"start \"\" \"" + exePath + "\"" + Environment.NewLine +
|
||||||
|
"endlocal" + Environment.NewLine;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StartUpdaterAndExit(string updaterBat)
|
||||||
|
{
|
||||||
|
var psi = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = updaterBat,
|
||||||
|
WorkingDirectory = Path.GetDirectoryName(updaterBat) ?? AppDomain.CurrentDomain.BaseDirectory,
|
||||||
|
UseShellExecute = true,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
WindowStyle = ProcessWindowStyle.Hidden
|
||||||
|
};
|
||||||
|
|
||||||
|
Process.Start(psi);
|
||||||
|
Application.Exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[DataContract]
|
||||||
|
public sealed class GithubRelease
|
||||||
|
{
|
||||||
|
[DataMember(Name = "tag_name")]
|
||||||
|
public string TagName { get; set; }
|
||||||
|
|
||||||
|
[DataMember(Name = "assets")]
|
||||||
|
public List<GithubAsset> Assets { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[DataContract]
|
||||||
|
public sealed class GithubAsset
|
||||||
|
{
|
||||||
|
[DataMember(Name = "url")]
|
||||||
|
public string ApiUrl { get; set; }
|
||||||
|
|
||||||
|
[DataMember(Name = "name")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
[DataMember(Name = "browser_download_url")]
|
||||||
|
public string DownloadUrl { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public enum LogLevel
|
public enum LogLevel
|
||||||
{
|
{
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public sealed class PowerManagementService
|
public sealed class PowerManagementService
|
||||||
{
|
{
|
||||||
+1
-1
@@ -2,7 +2,7 @@ using System;
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public sealed class ProcessMonitorService : IDisposable
|
public sealed class ProcessMonitorService : IDisposable
|
||||||
{
|
{
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using SshTunnelMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public sealed class SsConfigService
|
public sealed class SsConfigService
|
||||||
{
|
{
|
||||||
@@ -28,6 +28,7 @@ namespace SshTunnelMonitor.Services
|
|||||||
|
|
||||||
var config = "users admin:CL:" + password + "\r\n" +
|
var config = "users admin:CL:" + password + "\r\n" +
|
||||||
"auth strong\r\n" +
|
"auth strong\r\n" +
|
||||||
|
"maxconn 2000\r\n" +
|
||||||
$"socks -i127.0.0.1 -p{port}";
|
$"socks -i127.0.0.1 -p{port}";
|
||||||
|
|
||||||
var configPath = GetConfigPath();
|
var configPath = GetConfigPath();
|
||||||
@@ -2,11 +2,11 @@ using System;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using MonsterMonitor.Models;
|
||||||
using Renci.SshNet;
|
using Renci.SshNet;
|
||||||
using Renci.SshNet.Common;
|
using Renci.SshNet.Common;
|
||||||
using SshTunnelMonitor.Models;
|
|
||||||
|
|
||||||
namespace SshTunnelMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public sealed class SshTunnelService : IDisposable
|
public sealed class SshTunnelService : IDisposable
|
||||||
{
|
{
|
||||||
@@ -32,7 +32,16 @@ namespace SshTunnelMonitor.Services
|
|||||||
public void Start(AppSettings settings)
|
public void Start(AppSettings settings)
|
||||||
{
|
{
|
||||||
_settings = settings;
|
_settings = settings;
|
||||||
Connect();
|
try
|
||||||
|
{
|
||||||
|
Connect();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Error("Не удалось запустить SSH-туннель с первого раза: " + ex.Message);
|
||||||
|
ReconnectSoon();
|
||||||
|
}
|
||||||
|
|
||||||
StartMonitor();
|
StartMonitor();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,27 +1,36 @@
|
|||||||
using SshTunnelMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
using SshTunnelMonitor.Services;
|
using MonsterMonitor.Services;
|
||||||
using System;
|
using System;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
using static System.Net.Mime.MediaTypeNames;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.UI
|
namespace MonsterMonitor.UI
|
||||||
{
|
{
|
||||||
public sealed class MainForm : Form
|
public sealed class MainForm : Form
|
||||||
{
|
{
|
||||||
|
private const int EmGetFirstVisibleLine = 0x00CE;
|
||||||
|
private const int EmLineScroll = 0x00B6;
|
||||||
|
|
||||||
private readonly RichTextBox _console = new RichTextBox();
|
private readonly RichTextBox _console = new RichTextBox();
|
||||||
private readonly Button _btnSettings = new Button();
|
private readonly Button _btnSettings = new Button();
|
||||||
private readonly Button _btnExit = new Button();
|
private readonly Button _btnExit = new Button();
|
||||||
private readonly NotifyIcon _notifyIcon = new NotifyIcon();
|
private readonly NotifyIcon _notifyIcon = new NotifyIcon();
|
||||||
|
private readonly Timer _updateTimer = new Timer();
|
||||||
private readonly Icon _trayIcon;
|
private readonly Icon _trayIcon;
|
||||||
private readonly LogService _log = new LogService();
|
private readonly LogService _log = new LogService();
|
||||||
private readonly PowerManagementService _power = new PowerManagementService();
|
private readonly PowerManagementService _power = new PowerManagementService();
|
||||||
|
private GitHubUpdateService _updateService;
|
||||||
private AppController _controller;
|
private AppController _controller;
|
||||||
private AppSettings _settings;
|
private AppSettings _settings;
|
||||||
private bool _allowClose;
|
private bool _allowClose;
|
||||||
|
private bool _isUpdateCheckRunning;
|
||||||
|
|
||||||
public MainForm()
|
public MainForm()
|
||||||
{
|
{
|
||||||
Text = "Monster Monitor";
|
Text = string.Format("Monster Monitor v{0}", System.Windows.Forms.Application.ProductVersion);
|
||||||
Width = 980;
|
Width = 980;
|
||||||
Height = 620;
|
Height = 620;
|
||||||
StartPosition = FormStartPosition.CenterScreen;
|
StartPosition = FormStartPosition.CenterScreen;
|
||||||
@@ -39,7 +48,10 @@ namespace SshTunnelMonitor.UI
|
|||||||
|
|
||||||
_settings = AppSettings.Load();
|
_settings = AppSettings.Load();
|
||||||
_controller = new AppController(_log, _power);
|
_controller = new AppController(_log, _power);
|
||||||
|
_updateService = new GitHubUpdateService(_log, _settings);
|
||||||
RestartServices();
|
RestartServices();
|
||||||
|
ConfigureUpdateTimer();
|
||||||
|
_ = RunUpdateCheckAsync(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void BuildUi()
|
private void BuildUi()
|
||||||
@@ -128,6 +140,33 @@ namespace SshTunnelMonitor.UI
|
|||||||
Activate();
|
Activate();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void RestoreAndActivateFromExternalSignal()
|
||||||
|
{
|
||||||
|
if (InvokeRequired)
|
||||||
|
{
|
||||||
|
BeginInvoke(new Action(RestoreAndActivateFromExternalSignal));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.Info("Получен сигнал активации от второго инстанса.");
|
||||||
|
|
||||||
|
if (!Visible)
|
||||||
|
{
|
||||||
|
Show();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (WindowState == FormWindowState.Minimized)
|
||||||
|
{
|
||||||
|
WindowState = FormWindowState.Normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Небольшой трюк для надежного вывода окна на передний план.
|
||||||
|
TopMost = true;
|
||||||
|
Activate();
|
||||||
|
TopMost = false;
|
||||||
|
Focus();
|
||||||
|
}
|
||||||
|
|
||||||
private void ExitApplication()
|
private void ExitApplication()
|
||||||
{
|
{
|
||||||
_allowClose = true;
|
_allowClose = true;
|
||||||
@@ -144,24 +183,107 @@ namespace SshTunnelMonitor.UI
|
|||||||
}
|
}
|
||||||
|
|
||||||
_notifyIcon.Visible = false;
|
_notifyIcon.Visible = false;
|
||||||
|
_updateTimer.Stop();
|
||||||
|
_updateTimer.Dispose();
|
||||||
_controller?.Dispose();
|
_controller?.Dispose();
|
||||||
_trayIcon?.Dispose();
|
_trayIcon?.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void AppendLog(LogEntry entry)
|
private void AppendLog(LogEntry entry)
|
||||||
{
|
{
|
||||||
|
if (_console.Text.Length > 100000)
|
||||||
|
{
|
||||||
|
_console.ResetText();
|
||||||
|
}
|
||||||
|
System.Windows.Forms.Application.DoEvents();
|
||||||
|
|
||||||
if (InvokeRequired)
|
if (InvokeRequired)
|
||||||
{
|
{
|
||||||
BeginInvoke(new Action<LogEntry>(AppendLog), entry);
|
BeginInvoke(new Action<LogEntry>(AppendLog), entry);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
System.Windows.Forms.Application.DoEvents();
|
||||||
|
|
||||||
|
var wasNearBottom = IsConsoleNearBottom();
|
||||||
|
var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console);
|
||||||
|
|
||||||
_console.SelectionStart = _console.TextLength;
|
_console.SelectionStart = _console.TextLength;
|
||||||
_console.SelectionLength = 0;
|
_console.SelectionLength = 0;
|
||||||
_console.SelectionColor = GetColor(entry.Level);
|
_console.SelectionColor = GetColor(entry.Level);
|
||||||
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
||||||
_console.SelectionColor = _console.ForeColor;
|
_console.SelectionColor = _console.ForeColor;
|
||||||
_console.ScrollToCaret();
|
System.Windows.Forms.Application.DoEvents();
|
||||||
|
|
||||||
|
if (wasNearBottom)
|
||||||
|
{
|
||||||
|
_console.ScrollToCaret();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
System.Windows.Forms.Application.DoEvents();
|
||||||
|
|
||||||
|
var firstVisibleLineAfterAppend = GetFirstVisibleLine(_console);
|
||||||
|
var linesToRestore = firstVisibleLineBeforeAppend - firstVisibleLineAfterAppend;
|
||||||
|
if (linesToRestore != 0)
|
||||||
|
{
|
||||||
|
SendMessage(_console.Handle, EmLineScroll, IntPtr.Zero, (IntPtr)linesToRestore);
|
||||||
|
}
|
||||||
|
System.Windows.Forms.Application.DoEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsConsoleNearBottom()
|
||||||
|
{
|
||||||
|
if (_console.TextLength == 0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var bottomLeftPoint = new Point(1, Math.Max(0, _console.ClientSize.Height - 1));
|
||||||
|
var lastVisibleCharIndex = _console.GetCharIndexFromPosition(bottomLeftPoint);
|
||||||
|
return lastVisibleCharIndex >= _console.TextLength - 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int GetFirstVisibleLine(RichTextBox richTextBox)
|
||||||
|
{
|
||||||
|
return SendMessage(richTextBox.Handle, EmGetFirstVisibleLine, IntPtr.Zero, IntPtr.Zero).ToInt32();
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll", CharSet = CharSet.Auto)]
|
||||||
|
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
||||||
|
|
||||||
|
private void ConfigureUpdateTimer()
|
||||||
|
{
|
||||||
|
_updateTimer.Interval = (int)TimeSpan.FromHours(1).TotalMilliseconds;
|
||||||
|
_updateTimer.Tick += async (_, __) => await RunUpdateCheckAsync(false);
|
||||||
|
_updateTimer.Start();
|
||||||
|
_log.Info("Автопроверка обновлений включена (раз в 1 час).");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RunUpdateCheckAsync(bool isInitialCheck)
|
||||||
|
{
|
||||||
|
if (_isUpdateCheckRunning)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_isUpdateCheckRunning = true;
|
||||||
|
if (isInitialCheck)
|
||||||
|
{
|
||||||
|
// Небольшая задержка, чтобы окно и лог уже успели инициализироваться.
|
||||||
|
await Task.Delay(1000);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_log.Info("Плановая проверка обновлений...");
|
||||||
|
}
|
||||||
|
|
||||||
|
await _updateService.CheckAndPrepareUpdateAsync();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_isUpdateCheckRunning = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Color GetColor(LogLevel level)
|
private static Color GetColor(LogLevel level)
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
using System;
|
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
using SshTunnelMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.UI
|
namespace MonsterMonitor.UI
|
||||||
{
|
{
|
||||||
public sealed class SettingsForm : Form
|
public sealed class SettingsForm : Form
|
||||||
{
|
{
|
||||||
@@ -18,6 +17,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
private readonly NumericUpDown _numLocalPort = new NumericUpDown();
|
private readonly NumericUpDown _numLocalPort = new NumericUpDown();
|
||||||
private readonly NumericUpDown _numMaxFailures = new NumericUpDown();
|
private readonly NumericUpDown _numMaxFailures = new NumericUpDown();
|
||||||
private readonly NumericUpDown _numReconnectTimeout = new NumericUpDown();
|
private readonly NumericUpDown _numReconnectTimeout = new NumericUpDown();
|
||||||
|
private readonly TextBox _txtProxy = new TextBox();
|
||||||
private readonly TextBox _txtSsPath = new TextBox();
|
private readonly TextBox _txtSsPath = new TextBox();
|
||||||
private readonly TextBox _txtSsArgs = new TextBox();
|
private readonly TextBox _txtSsArgs = new TextBox();
|
||||||
private readonly TextBox _txtSystemPassword = new TextBox();
|
private readonly TextBox _txtSystemPassword = new TextBox();
|
||||||
@@ -31,7 +31,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
_settings = settings;
|
_settings = settings;
|
||||||
Text = "Настройки";
|
Text = "Настройки";
|
||||||
Width = 560;
|
Width = 560;
|
||||||
Height = 520;
|
Height = 560;
|
||||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||||
MaximizeBox = false;
|
MaximizeBox = false;
|
||||||
MinimizeBox = false;
|
MinimizeBox = false;
|
||||||
@@ -48,7 +48,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
Dock = DockStyle.Fill,
|
Dock = DockStyle.Fill,
|
||||||
Padding = new Padding(10),
|
Padding = new Padding(10),
|
||||||
ColumnCount = 2,
|
ColumnCount = 2,
|
||||||
RowCount = 14
|
RowCount = 15
|
||||||
};
|
};
|
||||||
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 44f));
|
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 44f));
|
||||||
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 56f));
|
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 56f));
|
||||||
@@ -66,10 +66,11 @@ namespace SshTunnelMonitor.UI
|
|||||||
AddRow(panel, "Локальный порт:", _numLocalPort, 6);
|
AddRow(panel, "Локальный порт:", _numLocalPort, 6);
|
||||||
AddRow(panel, "Макс. потерь:", _numMaxFailures, 7);
|
AddRow(panel, "Макс. потерь:", _numMaxFailures, 7);
|
||||||
AddRow(panel, "Таймаут reconnect (сек):", _numReconnectTimeout, 8);
|
AddRow(panel, "Таймаут reconnect (сек):", _numReconnectTimeout, 8);
|
||||||
AddRow(panel, "Путь к ss:", _txtSsPath, 9);
|
AddRow(panel, "Прокси (http://host:port):", _txtProxy, 9);
|
||||||
AddRow(panel, "Аргументы ss:", _txtSsArgs, 10);
|
AddRow(panel, "Путь к ss:", _txtSsPath, 10);
|
||||||
BuildSystemPasswordRow(panel, 11);
|
AddRow(panel, "Аргументы ss:", _txtSsArgs, 11);
|
||||||
BuildThreeProxyPasswordRow(panel, 12);
|
BuildSystemPasswordRow(panel, 12);
|
||||||
|
BuildThreeProxyPasswordRow(panel, 13);
|
||||||
|
|
||||||
foreach (var num in new[] { _numSshPort, _numRemotePort, _numLocalPort })
|
foreach (var num in new[] { _numSshPort, _numRemotePort, _numLocalPort })
|
||||||
{
|
{
|
||||||
@@ -94,7 +95,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
|
|
||||||
buttonsPanel.Controls.Add(btnSave);
|
buttonsPanel.Controls.Add(btnSave);
|
||||||
buttonsPanel.Controls.Add(btnCancel);
|
buttonsPanel.Controls.Add(btnCancel);
|
||||||
panel.Controls.Add(buttonsPanel, 0, 13);
|
panel.Controls.Add(buttonsPanel, 0, 14);
|
||||||
panel.SetColumnSpan(buttonsPanel, 2);
|
panel.SetColumnSpan(buttonsPanel, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,6 +202,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
_numLocalPort.Value = _settings.LocalPort;
|
_numLocalPort.Value = _settings.LocalPort;
|
||||||
_numMaxFailures.Value = _settings.MaxPingFailures;
|
_numMaxFailures.Value = _settings.MaxPingFailures;
|
||||||
_numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
|
_numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
|
||||||
|
_txtProxy.Text = _settings.Proxy;
|
||||||
_txtSsPath.Text = _settings.SsProcessPath;
|
_txtSsPath.Text = _settings.SsProcessPath;
|
||||||
_txtSsArgs.Text = _settings.SsArguments;
|
_txtSsArgs.Text = _settings.SsArguments;
|
||||||
_txtSystemPassword.Text = _settings.GetSystemPassword();
|
_txtSystemPassword.Text = _settings.GetSystemPassword();
|
||||||
@@ -224,6 +226,7 @@ namespace SshTunnelMonitor.UI
|
|||||||
_settings.LocalPort = (int)_numLocalPort.Value;
|
_settings.LocalPort = (int)_numLocalPort.Value;
|
||||||
_settings.MaxPingFailures = (int)_numMaxFailures.Value;
|
_settings.MaxPingFailures = (int)_numMaxFailures.Value;
|
||||||
_settings.ReconnectTimeoutSec = (int)_numReconnectTimeout.Value;
|
_settings.ReconnectTimeoutSec = (int)_numReconnectTimeout.Value;
|
||||||
|
_settings.Proxy = _txtProxy.Text.Trim();
|
||||||
_settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text)
|
_settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text)
|
||||||
? System.IO.Path.Combine("App_Data", "ss", "ss.exe")
|
? System.IO.Path.Combine("App_Data", "ss", "ss.exe")
|
||||||
: _txtSsPath.Text.Trim();
|
: _txtSsPath.Text.Trim();
|
||||||
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
@@ -1,35 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Windows.Forms;
|
|
||||||
using SshTunnelMonitor.UI;
|
|
||||||
|
|
||||||
namespace SshTunnelMonitor
|
|
||||||
{
|
|
||||||
internal static class Program
|
|
||||||
{
|
|
||||||
[STAThread]
|
|
||||||
private static void Main()
|
|
||||||
{
|
|
||||||
Application.ThreadException += (sender, args) =>
|
|
||||||
{
|
|
||||||
MessageBox.Show(
|
|
||||||
args.Exception.ToString(),
|
|
||||||
"Необработанное исключение UI-потока",
|
|
||||||
MessageBoxButtons.OK,
|
|
||||||
MessageBoxIcon.Error);
|
|
||||||
};
|
|
||||||
|
|
||||||
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
|
|
||||||
{
|
|
||||||
MessageBox.Show(
|
|
||||||
args.ExceptionObject.ToString(),
|
|
||||||
"Критическое исключение",
|
|
||||||
MessageBoxButtons.OK,
|
|
||||||
MessageBoxIcon.Error);
|
|
||||||
};
|
|
||||||
|
|
||||||
Application.EnableVisualStyles();
|
|
||||||
Application.SetCompatibleTextRenderingDefault(false);
|
|
||||||
Application.Run(new MainForm());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using System.Reflection;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
// General Information about an assembly is controlled through the following
|
|
||||||
// set of attributes. Change these attribute values to modify the information
|
|
||||||
// associated with an assembly.
|
|
||||||
[assembly: AssemblyTitle("MonsterMonitor")]
|
|
||||||
[assembly: AssemblyDescription("")]
|
|
||||||
[assembly: AssemblyConfiguration("")]
|
|
||||||
[assembly: AssemblyCompany("")]
|
|
||||||
[assembly: AssemblyProduct("MonsterMonitor")]
|
|
||||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
|
||||||
[assembly: AssemblyTrademark("")]
|
|
||||||
[assembly: AssemblyCulture("")]
|
|
||||||
// Setting ComVisible to false makes the types in this assembly not visible
|
|
||||||
// to COM components. If you need to access a type in this assembly from
|
|
||||||
// COM, set the ComVisible attribute to true on that type.
|
|
||||||
[assembly: ComVisible(false)]
|
|
||||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
|
||||||
[assembly: Guid("0fb13d01-79ef-4d33-82ee-20f411e173fa")]
|
|
||||||
// Version information for an assembly consists of the following four values:
|
|
||||||
//
|
|
||||||
// Major Version
|
|
||||||
// Minor Version
|
|
||||||
// Build Number
|
|
||||||
// Revision
|
|
||||||
//
|
|
||||||
// You can specify all the values or you can default the Build and Revision Numbers
|
|
||||||
// by using the '*' as shown below:
|
|
||||||
[assembly: AssemblyVersion("1.0.2")]
|
|
||||||
[assembly: AssemblyFileVersion("1.0.2")]
|
|
||||||
[assembly: AssemblyInformationalVersion("1.0.2")]
|
|
||||||
+41
-28
@@ -9,39 +9,52 @@ set informationalversion=%1
|
|||||||
if [%2] NEQ [] SET fileversion=%2
|
if [%2] NEQ [] SET fileversion=%2
|
||||||
if [%3] NEQ [] SET informationalversion=%3
|
if [%3] NEQ [] SET informationalversion=%3
|
||||||
|
|
||||||
echo Setting assembly version information
|
echo Setting version in *.csproj files
|
||||||
|
set "script=%TEMP%\setversion-csproj.ps1"
|
||||||
|
(
|
||||||
|
echo param^(
|
||||||
|
echo [string]$Version,
|
||||||
|
echo [string]$FileVersion,
|
||||||
|
echo [string]$InformationalVersion
|
||||||
|
echo ^)
|
||||||
|
echo $ErrorActionPreference = "Stop"
|
||||||
|
echo $projects = Get-ChildItem -Path ^(Get-Location^) -Filter *.csproj -Recurse
|
||||||
|
echo foreach ^($project in $projects^) ^{
|
||||||
|
echo Write-Host "^> $($project.FullName)"
|
||||||
|
echo [xml]$xml = Get-Content -Path $project.FullName
|
||||||
|
echo $propertyGroup = $xml.Project.PropertyGroup ^| Select-Object -First 1
|
||||||
|
echo if ^(-not $propertyGroup^) ^{
|
||||||
|
echo $propertyGroup = $xml.CreateElement^("PropertyGroup"^)
|
||||||
|
echo [void]$xml.Project.AppendChild^($propertyGroup^)
|
||||||
|
echo ^}
|
||||||
|
echo function Set-Or-CreateTag ^([xml]$doc, [System.Xml.XmlElement]$group, [string]$tagName, [string]$value^) ^{
|
||||||
|
echo $node = $group.SelectSingleNode^($tagName^)
|
||||||
|
echo if ^($node^) ^{
|
||||||
|
echo $node.InnerText = $value
|
||||||
|
echo ^} else ^{
|
||||||
|
echo $newNode = $doc.CreateElement^($tagName^)
|
||||||
|
echo $newNode.InnerText = $value
|
||||||
|
echo [void]$group.AppendChild^($newNode^)
|
||||||
|
echo ^}
|
||||||
|
echo ^}
|
||||||
|
echo Set-Or-CreateTag $xml $propertyGroup "Version" $Version
|
||||||
|
echo Set-Or-CreateTag $xml $propertyGroup "AssemblyVersion" $Version
|
||||||
|
echo Set-Or-CreateTag $xml $propertyGroup "FileVersion" $FileVersion
|
||||||
|
echo Set-Or-CreateTag $xml $propertyGroup "InformationalVersion" $InformationalVersion
|
||||||
|
echo $xml.Save^($project.FullName^)
|
||||||
|
echo ^}
|
||||||
|
) > "%script%"
|
||||||
|
|
||||||
for /F "delims=" %%f in ('dir /s /b Assemblyinfo.cs') do (
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%script%" "%version%" "%fileversion%" "%informationalversion%"
|
||||||
echo ^> %%f
|
set exit_code=%ERRORLEVEL%
|
||||||
|
del /q "%script%" >nul 2>&1
|
||||||
pushd %%~dpf
|
if not %exit_code%==0 exit /b %exit_code%
|
||||||
|
echo Done!
|
||||||
for /F "usebackq delims=" %%g in ("AssemblyInfo.cs") do (
|
|
||||||
set ln=%%g
|
|
||||||
set skip=0
|
|
||||||
|
|
||||||
if "!ln:AssemblyVersion=!" NEQ "!ln!" set skip=1
|
|
||||||
if "!ln:AssemblyFileVersion=!" NEQ "!ln!" set skip=1
|
|
||||||
if "!ln:AssemblyInformationalVersion=!" NEQ "!ln!" set skip=1
|
|
||||||
|
|
||||||
if !skip!==0 echo !ln! >> AssemblyInfo.cs.versioned
|
|
||||||
)
|
|
||||||
|
|
||||||
echo [assembly: AssemblyVersion^("%version%"^)] >> AssemblyInfo.cs.versioned
|
|
||||||
echo [assembly: AssemblyFileVersion^("%fileversion%"^)] >> AssemblyInfo.cs.versioned
|
|
||||||
echo [assembly: AssemblyInformationalVersion^("%informationalversion%"^)] >> AssemblyInfo.cs.versioned
|
|
||||||
|
|
||||||
copy /y AssemblyInfo.cs AssemblyInfo.cs.orig
|
|
||||||
move /y AssemblyInfo.cs.versioned AssemblyInfo.cs
|
|
||||||
|
|
||||||
popd
|
|
||||||
)
|
|
||||||
echo Done^^!
|
|
||||||
|
|
||||||
GOTO:EOF
|
GOTO:EOF
|
||||||
|
|
||||||
:USAGE
|
:USAGE
|
||||||
echo Usage:
|
echo Usage:
|
||||||
echo.
|
echo.
|
||||||
echo SetVersion.bat Version [FileVersion] [InformationalVersion]
|
echo SetVersion.cmd Version [FileVersion] [InformationalVersion]
|
||||||
echo.
|
echo.
|
||||||
Reference in New Issue
Block a user