Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d30ee4af1 | ||
|
|
1db62a8574 | ||
|
|
83801d78c4 | ||
|
|
7db3401799 | ||
|
|
2da1eac443 | ||
|
|
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.25
|
||||
|
||||
@@ -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 --tags
|
||||
git push
|
||||
GOTO End
|
||||
pause
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.32929.386
|
||||
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
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -4,7 +4,7 @@ using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace SshTunnelMonitor.Models
|
||||
namespace MonsterMonitor.Models
|
||||
{
|
||||
public sealed class AppSettings
|
||||
{
|
||||
@@ -21,6 +21,7 @@ namespace SshTunnelMonitor.Models
|
||||
public int LocalPort { get; set; } = 7829;
|
||||
public int MaxPingFailures { get; set; } = 3;
|
||||
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 SsArguments { get; set; } = string.Empty;
|
||||
|
||||
@@ -58,7 +59,7 @@ namespace SshTunnelMonitor.Models
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(SystemPasswordProtected))
|
||||
{
|
||||
return "STerra";
|
||||
return "";
|
||||
}
|
||||
|
||||
if (!SystemPasswordProtected.StartsWith(ProtectedPrefix, StringComparison.Ordinal))
|
||||
@@ -163,13 +164,15 @@ namespace SshTunnelMonitor.Models
|
||||
result.LocalPort = GetInt(map, nameof(LocalPort), result.LocalPort);
|
||||
result.MaxPingFailures = GetInt(map, nameof(MaxPingFailures), result.MaxPingFailures);
|
||||
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.SsArguments = Get(map, nameof(SsArguments), result.SsArguments);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(result.SystemPasswordProtected))
|
||||
{
|
||||
// Значение по умолчанию применяется только в памяти.
|
||||
// Раньше здесь вызывался Save() — лишний дисковый I/O на каждом чтении настроек.
|
||||
result.SetSystemPassword("STerra");
|
||||
result.Save();
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -191,6 +194,7 @@ namespace SshTunnelMonitor.Models
|
||||
$"{nameof(LocalPort)}={LocalPort}",
|
||||
$"{nameof(MaxPingFailures)}={MaxPingFailures}",
|
||||
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
|
||||
$"{nameof(Proxy)}={Proxy}",
|
||||
$"{nameof(SsProcessPath)}={SsProcessPath}",
|
||||
$"{nameof(SsArguments)}={SsArguments}"
|
||||
};
|
||||
@@ -1,11 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<RootNamespace>SshTunnelMonitor</RootNamespace>
|
||||
<AssemblyName>MonsterMonitor</AssemblyName>
|
||||
<RootNamespace>MonsterMonitor</RootNamespace>
|
||||
<AssemblyName>devenv</AssemblyName>
|
||||
<AssemblyVersion>1.0.25</AssemblyVersion>
|
||||
<Version>1.0.25</Version>
|
||||
<FileVersion>1.0.25</FileVersion>
|
||||
<InformationalVersion>1.0.25</InformationalVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
||||
@@ -14,7 +18,9 @@
|
||||
<PackageReference Include="Fody" Version="6.9.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<Reference Include="System.IO.Compression.FileSystem" />
|
||||
<Reference Include="System.Security" />
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<PackageReference Include="SSH.NET" Version="2025.1.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
@@ -28,4 +34,4 @@
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</None>
|
||||
</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,8 @@
|
||||
using System;
|
||||
using SshTunnelMonitor.Models;
|
||||
using System.Threading.Tasks;
|
||||
using MonsterMonitor.Models;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public sealed class AppController : IDisposable
|
||||
{
|
||||
@@ -10,6 +11,7 @@ namespace SshTunnelMonitor.Services
|
||||
private readonly SsConfigService _ssConfig;
|
||||
private ProcessMonitorService _processMonitor;
|
||||
private SshTunnelService _sshTunnel;
|
||||
private IAuthMonitor _authMonitor;
|
||||
|
||||
public AppController(LogService log, PowerManagementService power)
|
||||
{
|
||||
@@ -25,10 +27,14 @@ namespace SshTunnelMonitor.Services
|
||||
_power.PreventSleep();
|
||||
_processMonitor = new ProcessMonitorService(_log);
|
||||
_sshTunnel = new SshTunnelService(_log);
|
||||
_authMonitor = new AuthMonitor(settings, _log);
|
||||
|
||||
_ssConfig.EnsureConfig(settings);
|
||||
_processMonitor.Start(settings.SsProcessPath, settings.SsArguments);
|
||||
_sshTunnel.Start(settings);
|
||||
_authMonitor.StartMonitor().ContinueWith(
|
||||
t => _log.Error("Ошибка запуска монитора авторизации: " + t.Exception?.GetBaseException().Message),
|
||||
TaskContinuationOptions.OnlyOnFaulted);
|
||||
|
||||
_log.Info("Сервисы приложения запущены.");
|
||||
}
|
||||
@@ -38,6 +44,9 @@ namespace SshTunnelMonitor.Services
|
||||
_sshTunnel?.Dispose();
|
||||
_sshTunnel = null;
|
||||
|
||||
_authMonitor?.StopMonitor();
|
||||
_authMonitor = null;
|
||||
|
||||
_processMonitor?.Dispose();
|
||||
_processMonitor = null;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using MonsterMonitor.Models;
|
||||
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public class AuthMonitor : IAuthMonitor
|
||||
{
|
||||
private const string AuthWindowMarker = "XAuth request";
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Auto)]
|
||||
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetWindowTextLength(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private readonly AppSettings _settings;
|
||||
private readonly LogService _log;
|
||||
private CancellationTokenSource _monitorCancellation;
|
||||
private Task _monitorTask;
|
||||
|
||||
public AuthMonitor(AppSettings settings, LogService log)
|
||||
{
|
||||
_settings = settings;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
private static string GetWindowTitle(IntPtr handle)
|
||||
{
|
||||
var length = GetWindowTextLength(handle);
|
||||
if (length <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var buff = new StringBuilder(length + 1);
|
||||
return GetWindowText(handle, buff, buff.Capacity) > 0 ? buff.ToString() : null;
|
||||
}
|
||||
|
||||
private static string GetActiveWindowTitle()
|
||||
{
|
||||
return GetWindowTitle(GetForegroundWindow());
|
||||
}
|
||||
|
||||
// Ищет окно авторизации через перечисление окон (без перебора всех процессов
|
||||
// и без утечки хендлов Process). Возвращает первое видимое подходящее окно.
|
||||
private static IntPtr FindAuthWindow()
|
||||
{
|
||||
var found = IntPtr.Zero;
|
||||
EnumWindows((hWnd, lParam) =>
|
||||
{
|
||||
if (!IsWindowVisible(hWnd))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var title = GetWindowTitle(hWnd);
|
||||
if (title != null && title.IndexOf(AuthWindowMarker, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
found = hWnd;
|
||||
return false; // прекращаем перечисление
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
public async Task StartMonitor()
|
||||
{
|
||||
StopMonitor();
|
||||
_monitorCancellation = new CancellationTokenSource();
|
||||
_monitorTask = Task.Run(async () => await CheckProcess(_monitorCancellation.Token));
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void StopMonitor()
|
||||
{
|
||||
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
|
||||
{
|
||||
var authWindow = FindAuthWindow();
|
||||
if (authWindow != IntPtr.Zero)
|
||||
{
|
||||
SetForegroundWindow(authWindow);
|
||||
|
||||
var activeWindowTitle = GetActiveWindowTitle();
|
||||
if (activeWindowTitle?.IndexOf(AuthWindowMarker, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
{
|
||||
var password = _settings.GetSystemPassword();
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
{
|
||||
SendKeys.SendWait(password);
|
||||
SendKeys.SendWait("{ENTER}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Раньше здесь был MessageBox.Show из фонового потока — при повторяющемся
|
||||
// исключении он заваливал рабочий стол окнами. Теперь просто пишем в лог.
|
||||
_log.Warn("Ошибка мониторинга авторизации: " + ex.Message);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3), token);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface IAuthMonitor
|
||||
{
|
||||
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;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public enum LogLevel
|
||||
{
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public sealed class PowerManagementService
|
||||
{
|
||||
@@ -0,0 +1,273 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public sealed class ProcessMonitorService : IDisposable
|
||||
{
|
||||
private readonly LogService _log;
|
||||
private readonly object _sync = new object();
|
||||
private readonly Timer _watchdogTimer;
|
||||
private Process _process;
|
||||
private string _path;
|
||||
private string _arguments;
|
||||
private bool _stopping;
|
||||
private string _lastStartError;
|
||||
|
||||
public ProcessMonitorService(LogService log)
|
||||
{
|
||||
_log = log;
|
||||
_watchdogTimer = new Timer(WatchdogTick, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
|
||||
public void Start(string path, string arguments)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_path = path;
|
||||
_arguments = arguments ?? string.Empty;
|
||||
_stopping = false;
|
||||
// Подчищаем ss.exe, оставшийся от предыдущей (аварийно закрытой) копии
|
||||
// приложения — иначе его занятый порт не даст новому 3proxy стартовать,
|
||||
// и watchdog будет бесконечно перезапускать мгновенно умирающий процесс.
|
||||
KillOrphanedProcesses();
|
||||
EnsureStarted();
|
||||
_watchdogTimer.Change(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureStarted()
|
||||
{
|
||||
if (IsProcessRunning(_process))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_process != null)
|
||||
{
|
||||
_process.Dispose();
|
||||
}
|
||||
_process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _path,
|
||||
Arguments = _arguments,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
},
|
||||
EnableRaisingEvents = true
|
||||
};
|
||||
_process.Start();
|
||||
|
||||
// ss (3proxy) при занятом порту завершается почти мгновенно.
|
||||
// Если процесс умер сразу после старта — не рапортуем «запущен» и не
|
||||
// крутим бесконечный цикл рестартов, а один раз пишем понятную причину.
|
||||
if (_process.WaitForExit(500))
|
||||
{
|
||||
var exitCode = SafeGetExitCode(_process);
|
||||
var message = "Процесс ss завершился сразу после запуска (код " + exitCode +
|
||||
"). Вероятно, локальный порт уже занят другим процессом ss.";
|
||||
if (_lastStartError != message)
|
||||
{
|
||||
_lastStartError = message;
|
||||
_log.Error(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_lastStartError = null;
|
||||
_log.Info("Процесс ss запущен.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Watchdog тикает каждые 10с; при неверном пути не флудим лог
|
||||
// одинаковой ошибкой — пишем её только при изменении.
|
||||
if (_lastStartError != ex.Message)
|
||||
{
|
||||
_lastStartError = ex.Message;
|
||||
_log.Error("Ошибка запуска ss: " + ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void WatchdogTick(object state)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_stopping)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
EnsureStarted();
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_stopping = true;
|
||||
_watchdogTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
|
||||
try
|
||||
{
|
||||
if (IsProcessRunning(_process))
|
||||
{
|
||||
_process.Kill();
|
||||
_process.WaitForExit(5000);
|
||||
_log.Info("Процесс ss остановлен.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Не удалось корректно завершить ss: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_process != null)
|
||||
{
|
||||
_process.Dispose();
|
||||
}
|
||||
_process = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsProcessRunning(Process process)
|
||||
{
|
||||
if (process == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return !process.HasExited;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Завершает «осиротевшие» экземпляры ss.exe, оставшиеся от прошлой копии
|
||||
// приложения. Сопоставление по полному пути к исполняемому файлу, чтобы не
|
||||
// задеть посторонние одноимённые процессы.
|
||||
private void KillOrphanedProcesses()
|
||||
{
|
||||
string targetName;
|
||||
string targetFullPath;
|
||||
try
|
||||
{
|
||||
targetName = Path.GetFileNameWithoutExtension(_path);
|
||||
targetFullPath = Path.GetFullPath(_path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(targetName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var ownPid = _process != null && IsProcessRunning(_process) ? SafeGetId(_process) : -1;
|
||||
|
||||
Process[] candidates;
|
||||
try
|
||||
{
|
||||
candidates = Process.GetProcessesByName(targetName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Не удалось перечислить процессы ss: " + ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var proc in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (proc.Id == ownPid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Убиваем только процессы из нашего каталога ss.exe.
|
||||
if (!PathsEqual(SafeGetProcessPath(proc), targetFullPath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
proc.Kill();
|
||||
proc.WaitForExit(3000);
|
||||
_log.Warn("Завершен осиротевший процесс ss (PID " + proc.Id + ") от предыдущего запуска.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Не удалось завершить осиротевший ss: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
proc.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool PathsEqual(string a, string b)
|
||||
{
|
||||
return !string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b) &&
|
||||
string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string SafeGetProcessPath(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
return process.MainModule?.FileName;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Доступ к MainModule может быть запрещён (другой пользователь/разрядность).
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int SafeGetId(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
return process.Id;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int SafeGetExitCode(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
return process.ExitCode;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_watchdogTimer.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using SshTunnelMonitor.Models;
|
||||
using MonsterMonitor.Models;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public sealed class SsConfigService
|
||||
{
|
||||
@@ -28,6 +28,7 @@ namespace SshTunnelMonitor.Services
|
||||
|
||||
var config = "users admin:CL:" + password + "\r\n" +
|
||||
"auth strong\r\n" +
|
||||
"maxconn 2000\r\n" +
|
||||
$"socks -i127.0.0.1 -p{port}";
|
||||
|
||||
var configPath = GetConfigPath();
|
||||
+128
-70
@@ -2,26 +2,31 @@ using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MonsterMonitor.Models;
|
||||
using Renci.SshNet;
|
||||
using Renci.SshNet.Common;
|
||||
using SshTunnelMonitor.Models;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
namespace MonsterMonitor.Services
|
||||
{
|
||||
public sealed class SshTunnelService : IDisposable
|
||||
{
|
||||
private readonly LogService _log;
|
||||
private readonly object _sync = new object();
|
||||
|
||||
// Сериализует реконнект: перекрывающиеся запросы (из событий и из монитора)
|
||||
// отбрасываются, а не выполняются параллельно и не копятся в очередь.
|
||||
private readonly SemaphoreSlim _reconnectGate = new SemaphoreSlim(1, 1);
|
||||
|
||||
private SshClient _client;
|
||||
private ForwardedPortRemote _forwardedPort;
|
||||
private SshCommand _heartbeatCommand;
|
||||
private CancellationTokenSource _heartbeatReadTokenSource;
|
||||
private Task _heartbeatReadTask;
|
||||
private CancellationTokenSource _monitorTokenSource;
|
||||
private Task _monitorTask;
|
||||
private AppSettings _settings;
|
||||
private bool _disposed;
|
||||
private bool _reconnectInProgress;
|
||||
private DateTime _lastHeartbeatUtc = DateTime.MinValue;
|
||||
private volatile bool _disposed;
|
||||
private long _lastHeartbeatTicks;
|
||||
private bool _remoteIsWindows;
|
||||
|
||||
public SshTunnelService(LogService log)
|
||||
@@ -32,7 +37,16 @@ namespace SshTunnelMonitor.Services
|
||||
public void Start(AppSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
Connect();
|
||||
try
|
||||
{
|
||||
Connect();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error("Не удалось запустить SSH-туннель с первого раза: " + ex.Message);
|
||||
ReconnectSoon();
|
||||
}
|
||||
|
||||
StartMonitor();
|
||||
}
|
||||
|
||||
@@ -46,6 +60,10 @@ namespace SshTunnelMonitor.Services
|
||||
var authMethod = new PasswordAuthenticationMethod(_settings.SshUsername, password);
|
||||
var connectionInfo = new ConnectionInfo(_settings.SshHost, _settings.SshPort, _settings.SshUsername, authMethod);
|
||||
|
||||
// Ограничиваем блокирующий Connect(), чтобы он не висел бесконечно.
|
||||
var timeoutSec = Math.Min(60, Math.Max(5, _settings.ReconnectTimeoutSec));
|
||||
connectionInfo.Timeout = TimeSpan.FromSeconds(timeoutSec);
|
||||
|
||||
_client = new SshClient(connectionInfo);
|
||||
_client.ErrorOccurred += ClientOnErrorOccurred;
|
||||
_client.Connect();
|
||||
@@ -76,7 +94,7 @@ namespace SshTunnelMonitor.Services
|
||||
private void StartMonitor()
|
||||
{
|
||||
_monitorTokenSource = new CancellationTokenSource();
|
||||
Task.Run(() => MonitorLoop(_monitorTokenSource.Token));
|
||||
_monitorTask = Task.Run(() => MonitorLoop(_monitorTokenSource.Token));
|
||||
}
|
||||
|
||||
private async Task MonitorLoop(CancellationToken token)
|
||||
@@ -85,18 +103,23 @@ namespace SshTunnelMonitor.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
var silenceThresholdSec = Math.Max(
|
||||
5,
|
||||
_settings.MaxPingFailures);
|
||||
|
||||
var lastHeartbeat = _lastHeartbeatUtc;
|
||||
var isHeartbeatAlive = lastHeartbeat != DateTime.MinValue &&
|
||||
(DateTime.UtcNow - lastHeartbeat).TotalSeconds <= silenceThresholdSec;
|
||||
|
||||
if (!IsConnected() || !isHeartbeatAlive)
|
||||
// Пропускаем проверку, пока идёт реконнект — иначе получаем лог-флуд
|
||||
// и лишние пробуждения, дёргающие уже занятый шлюз реконнекта.
|
||||
if (_reconnectGate.CurrentCount > 0)
|
||||
{
|
||||
_log.Warn("Нет живого вывода heartbeat-команды на удаленном сервере. Переподключаю SSH.");
|
||||
await Reconnect().ConfigureAwait(false);
|
||||
// heartbeat присылается раз в секунду; MaxPingFailures трактуем
|
||||
// как допустимое число пропущенных ответов (≈ секунд тишины).
|
||||
var silenceThresholdSec = Math.Max(10, _settings.MaxPingFailures);
|
||||
|
||||
var lastHeartbeatTicks = Interlocked.Read(ref _lastHeartbeatTicks);
|
||||
var isHeartbeatAlive = lastHeartbeatTicks != 0 &&
|
||||
(DateTime.UtcNow - new DateTime(lastHeartbeatTicks, DateTimeKind.Utc)).TotalSeconds <= silenceThresholdSec;
|
||||
|
||||
if (!IsConnected() || !isHeartbeatAlive)
|
||||
{
|
||||
_log.Warn("Нет живого вывода heartbeat-команды на удаленном сервере. Переподключаю SSH.");
|
||||
await Reconnect().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -106,9 +129,9 @@ namespace SshTunnelMonitor.Services
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), token).ConfigureAwait(false);
|
||||
await Task.Delay(TimeSpan.FromSeconds(3), token).ConfigureAwait(false);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -127,39 +150,51 @@ namespace SshTunnelMonitor.Services
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000).ConfigureAwait(false);
|
||||
await Reconnect().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000).ConfigureAwait(false);
|
||||
await Reconnect().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// fire-and-forget: гарантированно не роняем процесс необработанным исключением.
|
||||
_log.Warn("Ошибка отложенного переподключения SSH: " + ex.Message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task Reconnect()
|
||||
{
|
||||
if (_reconnectInProgress || _disposed)
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Неблокирующая попытка захватить шлюз: если реконнект уже идёт — выходим,
|
||||
// не создавая второй параллельный Connect() и не накапливая очередь.
|
||||
if (!await _reconnectGate.WaitAsync(0).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_reconnectInProgress = true;
|
||||
try
|
||||
{
|
||||
var timeout = Math.Min(60, Math.Max(5, _settings.ReconnectTimeoutSec));
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_log.Warn("Перезапуск SSH-соединения...");
|
||||
|
||||
var reconnectTask = Task.Run(() =>
|
||||
// Connect() ограничен ConnectionInfo.Timeout, поэтому не зависнет навсегда.
|
||||
// Ждём завершения задачи (без брошенного WhenAny) — нет орфанных SshClient.
|
||||
await Task.Run(() =>
|
||||
{
|
||||
DisconnectCore();
|
||||
Connect();
|
||||
});
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
var completed = await Task.WhenAny(reconnectTask, Task.Delay(TimeSpan.FromSeconds(timeout))).ConfigureAwait(false);
|
||||
if (completed != reconnectTask)
|
||||
{
|
||||
_log.Error("Переподключение превысило таймаут " + timeout + "с.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Info("SSH-соединение восстановлено.");
|
||||
}
|
||||
_log.Info("SSH-соединение восстановлено.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -167,46 +202,51 @@ namespace SshTunnelMonitor.Services
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reconnectInProgress = false;
|
||||
_reconnectGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void DisconnectCore()
|
||||
{
|
||||
StopRemoteHeartbeatNoLock();
|
||||
lock (_sync)
|
||||
{
|
||||
StopRemoteHeartbeatNoLock();
|
||||
|
||||
try
|
||||
{
|
||||
if (_forwardedPort != null)
|
||||
try
|
||||
{
|
||||
if (_forwardedPort.IsStarted)
|
||||
if (_forwardedPort != null)
|
||||
{
|
||||
_forwardedPort.Stop();
|
||||
if (_forwardedPort.IsStarted)
|
||||
{
|
||||
_forwardedPort.Stop();
|
||||
}
|
||||
_forwardedPort.Exception -= ForwardedPortOnException;
|
||||
_forwardedPort.Dispose();
|
||||
_forwardedPort = null;
|
||||
}
|
||||
_forwardedPort.Dispose();
|
||||
_forwardedPort = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore errors on shutdown.
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore errors on shutdown.
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_client != null)
|
||||
try
|
||||
{
|
||||
if (_client.IsConnected)
|
||||
if (_client != null)
|
||||
{
|
||||
_client.Disconnect();
|
||||
_client.ErrorOccurred -= ClientOnErrorOccurred;
|
||||
if (_client.IsConnected)
|
||||
{
|
||||
_client.Disconnect();
|
||||
}
|
||||
_client.Dispose();
|
||||
_client = null;
|
||||
}
|
||||
_client.Dispose();
|
||||
_client = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore errors on shutdown.
|
||||
catch
|
||||
{
|
||||
// Ignore errors on shutdown.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +266,7 @@ namespace SshTunnelMonitor.Services
|
||||
|
||||
_heartbeatCommand = _client.CreateCommand(heartbeatCommand);
|
||||
_heartbeatReadTokenSource = new CancellationTokenSource();
|
||||
_lastHeartbeatUtc = DateTime.UtcNow;
|
||||
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks);
|
||||
_heartbeatCommand.BeginExecute();
|
||||
|
||||
_heartbeatReadTask = Task.Run(() =>
|
||||
@@ -278,7 +318,7 @@ namespace SshTunnelMonitor.Services
|
||||
continue;
|
||||
}
|
||||
|
||||
_lastHeartbeatUtc = DateTime.UtcNow;
|
||||
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks);
|
||||
_log.Debug("HB: " + line);
|
||||
}
|
||||
}
|
||||
@@ -296,9 +336,11 @@ namespace SshTunnelMonitor.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = _client.CreateCommand("cmd /c ver");
|
||||
var output = command.Execute() ?? string.Empty;
|
||||
return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
using (var command = _client.CreateCommand("cmd /c ver"))
|
||||
{
|
||||
var output = command.Execute() ?? string.Empty;
|
||||
return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -308,19 +350,35 @@ namespace SshTunnelMonitor.Services
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_monitorTokenSource?.Cancel();
|
||||
_monitorTokenSource?.Dispose();
|
||||
var monitorTokenSource = _monitorTokenSource;
|
||||
var monitorTask = _monitorTask;
|
||||
_monitorTokenSource = null;
|
||||
lock (_sync)
|
||||
_monitorTask = null;
|
||||
|
||||
try
|
||||
{
|
||||
DisconnectCore();
|
||||
monitorTokenSource?.Cancel();
|
||||
// Дожидаемся завершения цикла монитора до освобождения CTS,
|
||||
// иначе Task.Delay(token) может словить ObjectDisposedException.
|
||||
monitorTask?.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore shutdown errors.
|
||||
}
|
||||
finally
|
||||
{
|
||||
monitorTokenSource?.Dispose();
|
||||
}
|
||||
|
||||
DisconnectCore();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
Stop();
|
||||
_reconnectGate.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
using MonsterMonitor.Models;
|
||||
using MonsterMonitor.Services;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Drawing;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace MonsterMonitor.UI
|
||||
{
|
||||
public sealed class MainForm : Form
|
||||
{
|
||||
private const int EmGetFirstVisibleLine = 0x00CE;
|
||||
private const int EmLineScroll = 0x00B6;
|
||||
private const int WmSetRedraw = 0x000B;
|
||||
|
||||
// Ограничение размера буфера консоли, чтобы текст не рос бесконечно.
|
||||
private const int ConsoleMaxChars = 100000;
|
||||
private const int ConsoleTrimToChars = 80000;
|
||||
|
||||
private readonly RichTextBox _console = new RichTextBox();
|
||||
private readonly Button _btnSettings = new Button();
|
||||
private readonly Button _btnExit = new Button();
|
||||
private readonly NotifyIcon _notifyIcon = new NotifyIcon();
|
||||
private readonly Timer _updateTimer = new Timer();
|
||||
private readonly Timer _logFlushTimer = new Timer();
|
||||
private readonly ConcurrentQueue<LogEntry> _pendingLogs = new ConcurrentQueue<LogEntry>();
|
||||
private readonly Icon _trayIcon;
|
||||
private readonly LogService _log = new LogService();
|
||||
private readonly PowerManagementService _power = new PowerManagementService();
|
||||
private GitHubUpdateService _updateService;
|
||||
private AppController _controller;
|
||||
private AppSettings _settings;
|
||||
private bool _allowClose;
|
||||
private bool _isUpdateCheckRunning;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
Text = string.Format("Monster Monitor v{0}", Application.ProductVersion);
|
||||
Width = 980;
|
||||
Height = 620;
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
_trayIcon = LoadTrayIcon();
|
||||
Icon = _trayIcon;
|
||||
|
||||
BuildUi();
|
||||
BindEvents();
|
||||
}
|
||||
|
||||
protected override void OnLoad(EventArgs e)
|
||||
{
|
||||
base.OnLoad(e);
|
||||
|
||||
_settings = AppSettings.Load();
|
||||
_controller = new AppController(_log, _power);
|
||||
_updateService = new GitHubUpdateService(_log, _settings);
|
||||
ConfigureLogFlushTimer();
|
||||
RestartServices();
|
||||
ConfigureUpdateTimer();
|
||||
_ = RunUpdateCheckAsync(true);
|
||||
}
|
||||
|
||||
private void BuildUi()
|
||||
{
|
||||
var topPanel = new Panel { Dock = DockStyle.Top, Height = 42 };
|
||||
_btnSettings.Text = "Настройки";
|
||||
_btnSettings.Width = 110;
|
||||
_btnSettings.Location = new Point(10, 8);
|
||||
|
||||
_btnExit.Text = "Выход";
|
||||
_btnExit.Width = 110;
|
||||
_btnExit.Location = new Point(130, 8);
|
||||
|
||||
topPanel.Controls.Add(_btnSettings);
|
||||
topPanel.Controls.Add(_btnExit);
|
||||
|
||||
_console.Dock = DockStyle.Fill;
|
||||
_console.ReadOnly = true;
|
||||
_console.BackColor = Color.Black;
|
||||
_console.ForeColor = Color.White;
|
||||
_console.Font = new Font("Consolas", 10f);
|
||||
|
||||
Controls.Add(_console);
|
||||
Controls.Add(topPanel);
|
||||
|
||||
_notifyIcon.Text = "Monster Monitor";
|
||||
_notifyIcon.Icon = _trayIcon;
|
||||
_notifyIcon.Visible = true;
|
||||
var trayMenu = new ContextMenuStrip();
|
||||
trayMenu.Items.Add("Открыть", null, (_, __) => RestoreFromTray());
|
||||
trayMenu.Items.Add("Выход", null, (_, __) => ExitApplication());
|
||||
_notifyIcon.ContextMenuStrip = trayMenu;
|
||||
}
|
||||
|
||||
private void BindEvents()
|
||||
{
|
||||
Resize += MainFormOnResize;
|
||||
FormClosing += MainFormOnFormClosing;
|
||||
_notifyIcon.DoubleClick += (_, __) => RestoreFromTray();
|
||||
_btnSettings.Click += (_, __) => OpenSettings();
|
||||
_btnExit.Click += (_, __) => ExitApplication();
|
||||
_log.LogReceived += AppendLog;
|
||||
}
|
||||
|
||||
private void OpenSettings()
|
||||
{
|
||||
using (var form = new SettingsForm(_settings))
|
||||
{
|
||||
if (form.ShowDialog(this) == DialogResult.OK)
|
||||
{
|
||||
_log.Info("Настройки обновлены. Перезапускаю сервисы.");
|
||||
RestartServices();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RestartServices()
|
||||
{
|
||||
try
|
||||
{
|
||||
_controller.Start(_settings);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error("Ошибка запуска сервисов: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void MainFormOnResize(object sender, EventArgs e)
|
||||
{
|
||||
if (WindowState != FormWindowState.Minimized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Hide();
|
||||
_notifyIcon.BalloonTipTitle = "Monster Monitor";
|
||||
_notifyIcon.BalloonTipText = "Приложение свернуто в трей.";
|
||||
_notifyIcon.ShowBalloonTip(1000);
|
||||
}
|
||||
|
||||
private void RestoreFromTray()
|
||||
{
|
||||
Show();
|
||||
WindowState = FormWindowState.Normal;
|
||||
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()
|
||||
{
|
||||
_allowClose = true;
|
||||
Close();
|
||||
}
|
||||
|
||||
private void MainFormOnFormClosing(object sender, FormClosingEventArgs e)
|
||||
{
|
||||
if (!_allowClose && e.CloseReason == CloseReason.UserClosing)
|
||||
{
|
||||
e.Cancel = true;
|
||||
WindowState = FormWindowState.Minimized;
|
||||
return;
|
||||
}
|
||||
|
||||
// Останавливаем таймеры заранее, чтобы не было тиков во время разрушения формы.
|
||||
_logFlushTimer.Stop();
|
||||
_updateTimer.Stop();
|
||||
_notifyIcon.Visible = false;
|
||||
}
|
||||
|
||||
private void ConfigureLogFlushTimer()
|
||||
{
|
||||
// Логи копятся в очереди и выводятся пачкой ~10 раз в секунду,
|
||||
// а не по одной строке за событие — это снимает нагрузку на CPU и убирает мерцание.
|
||||
_logFlushTimer.Interval = 100;
|
||||
_logFlushTimer.Tick += (_, __) => FlushLogs();
|
||||
_logFlushTimer.Start();
|
||||
}
|
||||
|
||||
// Вызывается из фоновых потоков — только кладём запись в очередь, без обращения к UI.
|
||||
private void AppendLog(LogEntry entry)
|
||||
{
|
||||
_pendingLogs.Enqueue(entry);
|
||||
}
|
||||
|
||||
// Выполняется всегда в UI-потоке (таймер WinForms).
|
||||
private void FlushLogs()
|
||||
{
|
||||
if (_pendingLogs.IsEmpty || !_console.IsHandleCreated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var wasNearBottom = IsConsoleNearBottom();
|
||||
var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console);
|
||||
|
||||
// Замораживаем отрисовку на время пакетного добавления — одна перерисовка вместо десятков.
|
||||
SendMessage(_console.Handle, WmSetRedraw, IntPtr.Zero, IntPtr.Zero);
|
||||
try
|
||||
{
|
||||
while (_pendingLogs.TryDequeue(out var entry))
|
||||
{
|
||||
_console.SelectionStart = _console.TextLength;
|
||||
_console.SelectionLength = 0;
|
||||
_console.SelectionColor = GetColor(entry.Level);
|
||||
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
||||
_console.SelectionColor = _console.ForeColor;
|
||||
}
|
||||
|
||||
TrimConsole();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SendMessage(_console.Handle, WmSetRedraw, (IntPtr)1, IntPtr.Zero);
|
||||
_console.Invalidate();
|
||||
}
|
||||
|
||||
if (wasNearBottom)
|
||||
{
|
||||
_console.SelectionStart = _console.TextLength;
|
||||
_console.SelectionLength = 0;
|
||||
_console.ScrollToCaret();
|
||||
return;
|
||||
}
|
||||
|
||||
var firstVisibleLineAfterAppend = GetFirstVisibleLine(_console);
|
||||
var linesToRestore = firstVisibleLineBeforeAppend - firstVisibleLineAfterAppend;
|
||||
if (linesToRestore != 0)
|
||||
{
|
||||
SendMessage(_console.Handle, EmLineScroll, IntPtr.Zero, (IntPtr)linesToRestore);
|
||||
}
|
||||
}
|
||||
|
||||
// Обрезаем старые строки, а не сбрасываем весь буфер — плавно и без рывка скролла.
|
||||
private void TrimConsole()
|
||||
{
|
||||
if (_console.TextLength <= ConsoleMaxChars)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var removeUpTo = _console.TextLength - ConsoleTrimToChars;
|
||||
var line = _console.GetLineFromCharIndex(removeUpTo);
|
||||
var cut = _console.GetFirstCharIndexFromLine(line + 1);
|
||||
if (cut <= 0)
|
||||
{
|
||||
cut = removeUpTo;
|
||||
}
|
||||
|
||||
_console.Select(0, cut);
|
||||
_console.SelectedText = string.Empty;
|
||||
_console.SelectionStart = _console.TextLength;
|
||||
_console.SelectionLength = 0;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// async void (Timer.Tick) — необработанное исключение уронило бы приложение.
|
||||
_log.Error("Ошибка проверки обновлений: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isUpdateCheckRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Color GetColor(LogLevel level)
|
||||
{
|
||||
switch (level)
|
||||
{
|
||||
case LogLevel.Debug:
|
||||
return Color.Silver;
|
||||
case LogLevel.Warn:
|
||||
return Color.Orange;
|
||||
case LogLevel.Error:
|
||||
return Color.Red;
|
||||
default:
|
||||
return Color.White;
|
||||
}
|
||||
}
|
||||
|
||||
private static Icon LoadTrayIcon()
|
||||
{
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
|
||||
return ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_log.LogReceived -= AppendLog;
|
||||
|
||||
_logFlushTimer.Stop();
|
||||
_logFlushTimer.Dispose();
|
||||
_updateTimer.Stop();
|
||||
_updateTimer.Dispose();
|
||||
|
||||
_controller?.Dispose();
|
||||
|
||||
_notifyIcon.Visible = false;
|
||||
_notifyIcon.Dispose();
|
||||
_trayIcon?.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Security.Cryptography;
|
||||
using System.Windows.Forms;
|
||||
using SshTunnelMonitor.Models;
|
||||
using MonsterMonitor.Models;
|
||||
|
||||
namespace SshTunnelMonitor.UI
|
||||
namespace MonsterMonitor.UI
|
||||
{
|
||||
public sealed class SettingsForm : Form
|
||||
{
|
||||
@@ -18,6 +17,7 @@ namespace SshTunnelMonitor.UI
|
||||
private readonly NumericUpDown _numLocalPort = new NumericUpDown();
|
||||
private readonly NumericUpDown _numMaxFailures = new NumericUpDown();
|
||||
private readonly NumericUpDown _numReconnectTimeout = new NumericUpDown();
|
||||
private readonly TextBox _txtProxy = new TextBox();
|
||||
private readonly TextBox _txtSsPath = new TextBox();
|
||||
private readonly TextBox _txtSsArgs = new TextBox();
|
||||
private readonly TextBox _txtSystemPassword = new TextBox();
|
||||
@@ -31,7 +31,7 @@ namespace SshTunnelMonitor.UI
|
||||
_settings = settings;
|
||||
Text = "Настройки";
|
||||
Width = 560;
|
||||
Height = 520;
|
||||
Height = 560;
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||
MaximizeBox = false;
|
||||
MinimizeBox = false;
|
||||
@@ -48,7 +48,7 @@ namespace SshTunnelMonitor.UI
|
||||
Dock = DockStyle.Fill,
|
||||
Padding = new Padding(10),
|
||||
ColumnCount = 2,
|
||||
RowCount = 14
|
||||
RowCount = 15
|
||||
};
|
||||
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 44f));
|
||||
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 56f));
|
||||
@@ -66,10 +66,11 @@ namespace SshTunnelMonitor.UI
|
||||
AddRow(panel, "Локальный порт:", _numLocalPort, 6);
|
||||
AddRow(panel, "Макс. потерь:", _numMaxFailures, 7);
|
||||
AddRow(panel, "Таймаут reconnect (сек):", _numReconnectTimeout, 8);
|
||||
AddRow(panel, "Путь к ss:", _txtSsPath, 9);
|
||||
AddRow(panel, "Аргументы ss:", _txtSsArgs, 10);
|
||||
BuildSystemPasswordRow(panel, 11);
|
||||
BuildThreeProxyPasswordRow(panel, 12);
|
||||
AddRow(panel, "Прокси (http://host:port):", _txtProxy, 9);
|
||||
AddRow(panel, "Путь к ss:", _txtSsPath, 10);
|
||||
AddRow(panel, "Аргументы ss:", _txtSsArgs, 11);
|
||||
BuildSystemPasswordRow(panel, 12);
|
||||
BuildThreeProxyPasswordRow(panel, 13);
|
||||
|
||||
foreach (var num in new[] { _numSshPort, _numRemotePort, _numLocalPort })
|
||||
{
|
||||
@@ -94,7 +95,7 @@ namespace SshTunnelMonitor.UI
|
||||
|
||||
buttonsPanel.Controls.Add(btnSave);
|
||||
buttonsPanel.Controls.Add(btnCancel);
|
||||
panel.Controls.Add(buttonsPanel, 0, 13);
|
||||
panel.Controls.Add(buttonsPanel, 0, 14);
|
||||
panel.SetColumnSpan(buttonsPanel, 2);
|
||||
}
|
||||
|
||||
@@ -193,20 +194,38 @@ namespace SshTunnelMonitor.UI
|
||||
private void LoadValues()
|
||||
{
|
||||
_txtHost.Text = _settings.SshHost;
|
||||
_numSshPort.Value = _settings.SshPort;
|
||||
_numSshPort.Value = Clamp(_numSshPort, _settings.SshPort);
|
||||
_txtUser.Text = _settings.SshUsername;
|
||||
_txtPassword.Text = _settings.GetPassword();
|
||||
_chkSavePassword.Checked = _settings.SavePassword;
|
||||
_numRemotePort.Value = _settings.RemotePort;
|
||||
_numLocalPort.Value = _settings.LocalPort;
|
||||
_numMaxFailures.Value = _settings.MaxPingFailures;
|
||||
_numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
|
||||
_numRemotePort.Value = Clamp(_numRemotePort, _settings.RemotePort);
|
||||
_numLocalPort.Value = Clamp(_numLocalPort, _settings.LocalPort);
|
||||
_numMaxFailures.Value = Clamp(_numMaxFailures, _settings.MaxPingFailures);
|
||||
_numReconnectTimeout.Value = Clamp(_numReconnectTimeout, _settings.ReconnectTimeoutSec);
|
||||
_txtProxy.Text = _settings.Proxy;
|
||||
_txtSsPath.Text = _settings.SsProcessPath;
|
||||
_txtSsArgs.Text = _settings.SsArguments;
|
||||
_txtSystemPassword.Text = _settings.GetSystemPassword();
|
||||
_txtThreeProxyPassword.Text = _settings.GetThreeProxyPassword();
|
||||
}
|
||||
|
||||
// Приводит значение из настроек к допустимому диапазону контрола,
|
||||
// иначе NumericUpDown.Value бросит ArgumentOutOfRangeException и окно не откроется.
|
||||
private static decimal Clamp(NumericUpDown control, int value)
|
||||
{
|
||||
if (value < control.Minimum)
|
||||
{
|
||||
return control.Minimum;
|
||||
}
|
||||
|
||||
if (value > control.Maximum)
|
||||
{
|
||||
return control.Maximum;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private void SaveAndClose()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_txtHost.Text))
|
||||
@@ -224,6 +243,7 @@ namespace SshTunnelMonitor.UI
|
||||
_settings.LocalPort = (int)_numLocalPort.Value;
|
||||
_settings.MaxPingFailures = (int)_numMaxFailures.Value;
|
||||
_settings.ReconnectTimeoutSec = (int)_numReconnectTimeout.Value;
|
||||
_settings.Proxy = _txtProxy.Text.Trim();
|
||||
_settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text)
|
||||
? System.IO.Path.Combine("App_Data", "ss", "ss.exe")
|
||||
: _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")]
|
||||
@@ -1,78 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using SshTunnelMonitor.Models;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
{
|
||||
public class AuthMonitor: IAuthMonitor
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
|
||||
|
||||
private readonly AppSettings _settings;
|
||||
|
||||
public AuthMonitor(AppSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
}
|
||||
|
||||
private string GetActiveWindowTitle()
|
||||
{
|
||||
const int nChars = 256;
|
||||
var buff = new StringBuilder(nChars);
|
||||
var handle = GetForegroundWindow();
|
||||
return GetWindowText(handle, buff, nChars) > 0 ? buff.ToString() : null;
|
||||
}
|
||||
|
||||
public async Task StartMonitor()
|
||||
{
|
||||
_ = Task.Run(async () => await CheckProcess());
|
||||
}
|
||||
|
||||
private async Task CheckProcess()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
Process[] processlist = Process.GetProcesses();
|
||||
foreach (Process process in processlist)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(process.MainWindowTitle) && process.MainWindowTitle.Contains("XAuth request"))
|
||||
{
|
||||
SetForegroundWindow(process.MainWindowHandle);
|
||||
}
|
||||
}
|
||||
|
||||
var activeWindowTitle = GetActiveWindowTitle();
|
||||
if (activeWindowTitle?.Contains("XAuth request") == true)
|
||||
{
|
||||
SendKeys.SendWait(_settings.GetSystemPassword());
|
||||
SendKeys.SendWait("{ENTER}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message + ex.StackTrace);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface IAuthMonitor
|
||||
{
|
||||
Task StartMonitor();
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace SshTunnelMonitor.Services
|
||||
{
|
||||
public sealed class ProcessMonitorService : IDisposable
|
||||
{
|
||||
private readonly LogService _log;
|
||||
private readonly object _sync = new object();
|
||||
private readonly Timer _watchdogTimer;
|
||||
private Process _process;
|
||||
private string _path;
|
||||
private string _arguments;
|
||||
private bool _stopping;
|
||||
|
||||
public ProcessMonitorService(LogService log)
|
||||
{
|
||||
_log = log;
|
||||
_watchdogTimer = new Timer(WatchdogTick, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
|
||||
public void Start(string path, string arguments)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_path = path;
|
||||
_arguments = arguments ?? string.Empty;
|
||||
_stopping = false;
|
||||
EnsureStarted();
|
||||
_watchdogTimer.Change(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureStarted()
|
||||
{
|
||||
if (IsProcessRunning(_process))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_process != null)
|
||||
{
|
||||
_process.Exited -= ProcessOnExited;
|
||||
_process.Dispose();
|
||||
}
|
||||
_process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _path,
|
||||
Arguments = _arguments,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
},
|
||||
EnableRaisingEvents = true
|
||||
};
|
||||
//_process.Exited += ProcessOnExited;
|
||||
_process.Start();
|
||||
_log.Info("Процесс ss запущен.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error("Ошибка запуска ss: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessOnExited(object sender, EventArgs e)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_stopping)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_log.Warn("Процесс ss завершился, запускаю заново.");
|
||||
EnsureStarted();
|
||||
}
|
||||
}
|
||||
|
||||
private void WatchdogTick(object state)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_stopping)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
EnsureStarted();
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_stopping = true;
|
||||
_watchdogTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
|
||||
try
|
||||
{
|
||||
if (IsProcessRunning(_process))
|
||||
{
|
||||
_process.Kill();
|
||||
_process.WaitForExit(5000);
|
||||
_log.Info("Процесс ss остановлен.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Не удалось корректно завершить ss: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_process != null)
|
||||
{
|
||||
_process.Exited -= ProcessOnExited;
|
||||
_process.Dispose();
|
||||
}
|
||||
_process = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsProcessRunning(Process process)
|
||||
{
|
||||
if (process == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return !process.HasExited;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_watchdogTimer.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
using SshTunnelMonitor.Models;
|
||||
using SshTunnelMonitor.Services;
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace SshTunnelMonitor.UI
|
||||
{
|
||||
public sealed class MainForm : Form
|
||||
{
|
||||
private readonly RichTextBox _console = new RichTextBox();
|
||||
private readonly Button _btnSettings = new Button();
|
||||
private readonly Button _btnExit = new Button();
|
||||
private readonly NotifyIcon _notifyIcon = new NotifyIcon();
|
||||
private readonly Icon _trayIcon;
|
||||
private readonly LogService _log = new LogService();
|
||||
private readonly PowerManagementService _power = new PowerManagementService();
|
||||
private AppController _controller;
|
||||
private AppSettings _settings;
|
||||
private bool _allowClose;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
Text = "Monster Monitor";
|
||||
Width = 980;
|
||||
Height = 620;
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
_trayIcon = LoadTrayIcon();
|
||||
|
||||
BuildUi();
|
||||
BindEvents();
|
||||
}
|
||||
|
||||
protected override void OnLoad(EventArgs e)
|
||||
{
|
||||
base.OnLoad(e);
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
|
||||
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
||||
|
||||
_settings = AppSettings.Load();
|
||||
_controller = new AppController(_log, _power);
|
||||
RestartServices();
|
||||
}
|
||||
|
||||
private void BuildUi()
|
||||
{
|
||||
var topPanel = new Panel { Dock = DockStyle.Top, Height = 42 };
|
||||
_btnSettings.Text = "Настройки";
|
||||
_btnSettings.Width = 110;
|
||||
_btnSettings.Location = new Point(10, 8);
|
||||
|
||||
_btnExit.Text = "Выход";
|
||||
_btnExit.Width = 110;
|
||||
_btnExit.Location = new Point(130, 8);
|
||||
|
||||
topPanel.Controls.Add(_btnSettings);
|
||||
topPanel.Controls.Add(_btnExit);
|
||||
|
||||
_console.Dock = DockStyle.Fill;
|
||||
_console.ReadOnly = true;
|
||||
_console.BackColor = Color.Black;
|
||||
_console.ForeColor = Color.White;
|
||||
_console.Font = new Font("Consolas", 10f);
|
||||
|
||||
Controls.Add(_console);
|
||||
Controls.Add(topPanel);
|
||||
|
||||
_notifyIcon.Text = "Monster Monitor";
|
||||
_notifyIcon.Icon = _trayIcon;
|
||||
_notifyIcon.Visible = true;
|
||||
var trayMenu = new ContextMenuStrip();
|
||||
trayMenu.Items.Add("Открыть", null, (_, __) => RestoreFromTray());
|
||||
trayMenu.Items.Add("Выход", null, (_, __) => ExitApplication());
|
||||
_notifyIcon.ContextMenuStrip = trayMenu;
|
||||
}
|
||||
|
||||
private void BindEvents()
|
||||
{
|
||||
Resize += MainFormOnResize;
|
||||
FormClosing += MainFormOnFormClosing;
|
||||
_notifyIcon.DoubleClick += (_, __) => RestoreFromTray();
|
||||
_btnSettings.Click += (_, __) => OpenSettings();
|
||||
_btnExit.Click += (_, __) => ExitApplication();
|
||||
_log.LogReceived += AppendLog;
|
||||
}
|
||||
|
||||
private void OpenSettings()
|
||||
{
|
||||
using (var form = new SettingsForm(_settings))
|
||||
{
|
||||
if (form.ShowDialog(this) == DialogResult.OK)
|
||||
{
|
||||
_log.Info("Настройки обновлены. Перезапускаю сервисы.");
|
||||
RestartServices();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RestartServices()
|
||||
{
|
||||
try
|
||||
{
|
||||
_controller.Start(_settings);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error("Ошибка запуска сервисов: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void MainFormOnResize(object sender, EventArgs e)
|
||||
{
|
||||
if (WindowState != FormWindowState.Minimized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Hide();
|
||||
_notifyIcon.BalloonTipTitle = "Monster Monitor";
|
||||
_notifyIcon.BalloonTipText = "Приложение свернуто в трей.";
|
||||
_notifyIcon.ShowBalloonTip(1000);
|
||||
}
|
||||
|
||||
private void RestoreFromTray()
|
||||
{
|
||||
Show();
|
||||
WindowState = FormWindowState.Normal;
|
||||
Activate();
|
||||
}
|
||||
|
||||
private void ExitApplication()
|
||||
{
|
||||
_allowClose = true;
|
||||
Close();
|
||||
}
|
||||
|
||||
private void MainFormOnFormClosing(object sender, FormClosingEventArgs e)
|
||||
{
|
||||
if (!_allowClose && e.CloseReason == CloseReason.UserClosing)
|
||||
{
|
||||
e.Cancel = true;
|
||||
WindowState = FormWindowState.Minimized;
|
||||
return;
|
||||
}
|
||||
|
||||
_notifyIcon.Visible = false;
|
||||
_controller?.Dispose();
|
||||
_trayIcon?.Dispose();
|
||||
}
|
||||
|
||||
private void AppendLog(LogEntry entry)
|
||||
{
|
||||
if (InvokeRequired)
|
||||
{
|
||||
BeginInvoke(new Action<LogEntry>(AppendLog), entry);
|
||||
return;
|
||||
}
|
||||
|
||||
_console.SelectionStart = _console.TextLength;
|
||||
_console.SelectionLength = 0;
|
||||
_console.SelectionColor = GetColor(entry.Level);
|
||||
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
||||
_console.SelectionColor = _console.ForeColor;
|
||||
_console.ScrollToCaret();
|
||||
}
|
||||
|
||||
private static Color GetColor(LogLevel level)
|
||||
{
|
||||
switch (level)
|
||||
{
|
||||
case LogLevel.Debug:
|
||||
return Color.Silver;
|
||||
case LogLevel.Warn:
|
||||
return Color.Orange;
|
||||
case LogLevel.Error:
|
||||
return Color.Red;
|
||||
default:
|
||||
return Color.White;
|
||||
}
|
||||
}
|
||||
|
||||
private static Icon LoadTrayIcon()
|
||||
{
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
|
||||
return ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
||||
}
|
||||
|
||||
private void InitializeComponent()
|
||||
{
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// MainForm
|
||||
//
|
||||
this.ClientSize = new System.Drawing.Size(284, 261);
|
||||
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
||||
this.Name = "MainForm";
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
-28
@@ -9,39 +9,52 @@ set informationalversion=%1
|
||||
if [%2] NEQ [] SET fileversion=%2
|
||||
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 (
|
||||
echo ^> %%f
|
||||
|
||||
pushd %%~dpf
|
||||
|
||||
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^^!
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%script%" "%version%" "%fileversion%" "%informationalversion%"
|
||||
set exit_code=%ERRORLEVEL%
|
||||
del /q "%script%" >nul 2>&1
|
||||
if not %exit_code%==0 exit /b %exit_code%
|
||||
echo Done!
|
||||
|
||||
GOTO:EOF
|
||||
|
||||
:USAGE
|
||||
echo Usage:
|
||||
echo.
|
||||
echo SetVersion.bat Version [FileVersion] [InformationalVersion]
|
||||
echo SetVersion.cmd Version [FileVersion] [InformationalVersion]
|
||||
echo.
|
||||
Reference in New Issue
Block a user