Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a2639f96c | ||
|
|
fbd94ae1e6 | ||
|
|
cf01546b0b | ||
|
|
ec80bea024 | ||
|
|
b88006f02d | ||
|
|
c5ac1681f2 | ||
|
|
06f2ebb1ac | ||
|
|
9912ca8ba4 | ||
|
|
427f16cde0 | ||
|
|
fe8abb589f | ||
|
|
ae787373dc | ||
|
|
4f2fe7b292 | ||
|
|
635a489cc1 | ||
|
|
5b82edb9ee | ||
|
|
84e0fbb959 | ||
|
|
fdebc16b37 | ||
|
|
8467399001 | ||
|
|
2fb673661f |
+1
-1
@@ -1 +1 @@
|
|||||||
1.0.1
|
1.0.19
|
||||||
|
|||||||
@@ -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`.
|
||||||
|
|||||||
@@ -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.19</AssemblyVersion>
|
||||||
|
<Version>1.0.19</Version>
|
||||||
|
<FileVersion>1.0.19</FileVersion>
|
||||||
|
<InformationalVersion>1.0.19</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>
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
using SshTunnelMonitor.UI;
|
using MonsterMonitor.UI;
|
||||||
|
|
||||||
namespace SshTunnelMonitor
|
namespace MonsterMonitor
|
||||||
{
|
{
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
@@ -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
|
||||||
{
|
{
|
||||||
@@ -4,9 +4,9 @@ using System.Runtime.InteropServices;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
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
|
||||||
{
|
{
|
||||||
@@ -57,8 +57,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)
|
||||||
@@ -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,10 +1,11 @@
|
|||||||
using SshTunnelMonitor.Models;
|
|
||||||
using SshTunnelMonitor.Services;
|
|
||||||
using System;
|
using System;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
|
using MonsterMonitor.Models;
|
||||||
|
using MonsterMonitor.Services;
|
||||||
|
|
||||||
namespace SshTunnelMonitor.UI
|
namespace MonsterMonitor.UI
|
||||||
{
|
{
|
||||||
public sealed class MainForm : Form
|
public sealed class MainForm : Form
|
||||||
{
|
{
|
||||||
@@ -12,16 +13,19 @@ namespace SshTunnelMonitor.UI
|
|||||||
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}", Application.ProductVersion);
|
||||||
Width = 980;
|
Width = 980;
|
||||||
Height = 620;
|
Height = 620;
|
||||||
StartPosition = FormStartPosition.CenterScreen;
|
StartPosition = FormStartPosition.CenterScreen;
|
||||||
@@ -39,7 +43,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()
|
||||||
@@ -144,6 +151,8 @@ namespace SshTunnelMonitor.UI
|
|||||||
}
|
}
|
||||||
|
|
||||||
_notifyIcon.Visible = false;
|
_notifyIcon.Visible = false;
|
||||||
|
_updateTimer.Stop();
|
||||||
|
_updateTimer.Dispose();
|
||||||
_controller?.Dispose();
|
_controller?.Dispose();
|
||||||
_trayIcon?.Dispose();
|
_trayIcon?.Dispose();
|
||||||
}
|
}
|
||||||
@@ -164,6 +173,42 @@ namespace SshTunnelMonitor.UI
|
|||||||
_console.ScrollToCaret();
|
_console.ScrollToCaret();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
{
|
{
|
||||||
switch (level)
|
switch (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 |
+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