Initial NginxMan release

This commit is contained in:
2026-08-27 09:05:06 +08:00
commit 6b5e9a991c
47 changed files with 25567 additions and 0 deletions
+710
View File
@@ -0,0 +1,710 @@
using System.ComponentModel;
using System.Diagnostics;
namespace NginxMan;
public sealed class MainForm : Form
{
private readonly NginxManager _manager;
private readonly BindingList<RouteEntry> _binding = new();
private DataGridView _grid = null!;
private TextBox _txtDomain = null!;
private TextBox _txtUpstream = null!;
private TextBox _txtWebsiteName = null!;
private TextBox _txtDescription = null!;
private NumericUpDown _numPort = null!;
private TextBox _txtNginxExe = null!;
private TextBox _txtConfigPath = null!;
private Label _lblStatus = null!;
private Button _btnAdd = null!;
private Button _btnUpdate = null!;
private Button _btnDelete = null!;
private Button _btnClear = null!;
private Button _btnRender = null!;
private Button _btnStart = null!;
private Button _btnReload = null!;
private Button _btnStop = null!;
private Button _btnRefreshStatus = null!;
private string? _selectedDomain;
public MainForm(NginxManager manager)
{
_manager = manager;
InitializeComponent();
RefreshBasicInfo();
LoadDataGrid();
RefreshStatus();
ClearForm();
}
private void InitializeComponent()
{
Text = "NginxMan - 域名代理管理";
var executableIcon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
if (executableIcon is not null)
{
Icon = executableIcon;
}
MinimumSize = new Size(900, 590);
var workArea = Screen.PrimaryScreen?.WorkingArea ?? Screen.GetWorkingArea(this);
Size = new Size(
Math.Min(1080, workArea.Width - 24),
Math.Min(680, workArea.Height - 24));
StartPosition = FormStartPosition.CenterScreen;
Font = new Font("Microsoft YaHei UI", 9F);
var root = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 1,
RowCount = 4,
Padding = new Padding(10),
BackColor = Color.FromArgb(245, 247, 250),
AutoScroll = true
};
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 96));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 88));
root.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 154));
root.Controls.Add(CreateHeaderPanel(), 0, 0);
root.Controls.Add(CreateNginxActionsPanel(), 0, 1);
root.Controls.Add(CreateRouteListPanel(), 0, 2);
root.Controls.Add(CreateEditorPanel(), 0, 3);
Controls.Add(root);
}
private Control CreateHeaderPanel()
{
var panel = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 4,
RowCount = 3,
BackColor = Color.White,
Padding = new Padding(10, 8, 10, 8)
};
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 76));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 104));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 104));
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));
_txtConfigPath = new TextBox { Dock = DockStyle.Fill, ReadOnly = true, BorderStyle = BorderStyle.FixedSingle };
_txtNginxExe = new TextBox { Dock = DockStyle.Fill, ReadOnly = true, BorderStyle = BorderStyle.FixedSingle };
_lblStatus = new Label
{
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleLeft,
Padding = new Padding(8, 0, 0, 0),
Font = new Font(Font, FontStyle.Bold)
};
var btnOpenConfig = CreateButton("打开配置文件", 96);
btnOpenConfig.Click += (s, e) => OpenConfigFile();
var btnOpenFolder = CreateButton("打开文件夹", 96);
btnOpenFolder.Click += (s, e) => OpenConfigFolder();
var btnBrowseExe = CreateButton("浏览...", 96);
btnBrowseExe.Click += (s, e) => BrowseNginxExe();
_btnRefreshStatus = CreateButton("刷新状态", 96);
_btnRefreshStatus.Click += (s, e) => RefreshStatus();
panel.Controls.Add(CreateLabel("配置文件"), 0, 0);
panel.Controls.Add(_txtConfigPath, 1, 0);
panel.Controls.Add(btnOpenConfig, 2, 0);
panel.Controls.Add(btnOpenFolder, 3, 0);
panel.Controls.Add(CreateLabel("nginx.exe"), 0, 1);
panel.Controls.Add(_txtNginxExe, 1, 1);
panel.Controls.Add(btnBrowseExe, 2, 1);
panel.SetColumnSpan(btnBrowseExe, 2);
panel.Controls.Add(CreateLabel("运行状态"), 0, 2);
panel.Controls.Add(_lblStatus, 1, 2);
panel.Controls.Add(_btnRefreshStatus, 2, 2);
return panel;
}
private Control CreateRouteListPanel()
{
_grid = new DataGridView
{
Dock = DockStyle.Fill,
ReadOnly = true,
AllowUserToAddRows = false,
AllowUserToDeleteRows = false,
AllowUserToResizeRows = false,
MultiSelect = false,
SelectionMode = DataGridViewSelectionMode.FullRowSelect,
AutoGenerateColumns = false,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
BackgroundColor = Color.White,
BorderStyle = BorderStyle.Fixed3D,
RowHeadersVisible = false,
EnableHeadersVisualStyles = false,
ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
{
BackColor = Color.FromArgb(220, 235, 248),
ForeColor = Color.FromArgb(28, 62, 86),
Font = new Font(Font, FontStyle.Bold)
},
AlternatingRowsDefaultCellStyle = new DataGridViewCellStyle
{
BackColor = Color.FromArgb(248, 251, 253)
}
};
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "网站名称",
DataPropertyName = nameof(RouteEntry.WebsiteName),
FillWeight = 20,
MinimumWidth = 140
});
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "域名",
DataPropertyName = nameof(RouteEntry.Domain),
FillWeight = 22,
MinimumWidth = 180
});
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "上游接口",
DataPropertyName = nameof(RouteEntry.Upstream),
FillWeight = 32,
MinimumWidth = 240
});
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "监听端口",
DataPropertyName = nameof(RouteEntry.ListenPort),
FillWeight = 12,
MinimumWidth = 90
});
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "网站简介",
DataPropertyName = nameof(RouteEntry.Description),
FillWeight = 30,
MinimumWidth = 220
});
_grid.SelectionChanged += (s, e) => OnSelectRow();
_grid.CellDoubleClick += (s, e) => _txtDomain.Focus();
return CreateSectionPanel("域名映射列表", _grid);
}
private Control CreateEditorPanel()
{
var layout = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 6,
RowCount = 3,
Padding = new Padding(4, 2, 4, 0)
};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 72));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 32));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 66));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 68));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 72));
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 82));
layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 32));
layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 32));
layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 34));
_txtDomain = new TextBox { Dock = DockStyle.Fill };
_txtUpstream = new TextBox
{
Dock = DockStyle.Fill,
PlaceholderText = "同机服务示例:http://127.0.0.1:803"
};
_txtWebsiteName = new TextBox
{
Dock = DockStyle.Fill,
PlaceholderText = "例如:Team Workspace"
};
_txtDescription = new TextBox
{
Dock = DockStyle.Fill,
PlaceholderText = "显示在 www.m3frame.com 入口卡片上的简介"
};
_numPort = new NumericUpDown
{
Dock = DockStyle.Left,
Width = 130,
Minimum = 1,
Maximum = 65535,
Value = 80
};
_btnAdd = CreateButton("新增", 82);
_btnUpdate = CreateButton("保存修改", 94);
_btnDelete = CreateButton("删除", 82);
_btnClear = CreateButton("清空", 82);
_btnAdd.Click += (s, e) => AddRoute();
_btnUpdate.Click += (s, e) => UpdateRoute();
_btnDelete.Click += (s, e) => DeleteRoute();
_btnClear.Click += (s, e) => ClearForm();
var editActions = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
Padding = new Padding(0, 1, 0, 0)
};
editActions.Controls.AddRange([_btnAdd, _btnUpdate, _btnDelete, _btnClear]);
layout.Controls.Add(CreateLabel("域名"), 0, 0);
layout.Controls.Add(_txtDomain, 1, 0);
layout.Controls.Add(CreateLabel("上游接口"), 2, 0);
layout.Controls.Add(_txtUpstream, 3, 0);
layout.Controls.Add(CreateLabel("监听端口"), 4, 0);
layout.Controls.Add(_numPort, 5, 0);
layout.Controls.Add(CreateLabel("网站名称"), 0, 1);
layout.Controls.Add(_txtWebsiteName, 1, 1);
layout.Controls.Add(CreateLabel("网站简介"), 2, 1);
layout.Controls.Add(_txtDescription, 3, 1);
layout.SetColumnSpan(_txtDescription, 3);
layout.Controls.Add(editActions, 0, 2);
layout.SetColumnSpan(editActions, 6);
return CreateSectionPanel("编辑映射", layout);
}
private Control CreateNginxActionsPanel()
{
var actions = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
Padding = new Padding(4, 5, 0, 0)
};
_btnRender = CreateButton("生成配置", 110);
_btnStart = CreateButton("启动代理", 110, Color.FromArgb(37, 123, 80), Color.White);
_btnReload = CreateButton("重新加载", 110);
_btnStop = CreateButton("停止代理", 110, Color.FromArgb(177, 53, 53), Color.White);
_btnRender.Click += async (s, e) => await RenderOnlyAsync();
_btnStart.Click += async (s, e) => await RunNginxAsync("启动", _manager.Start, expectedRunning: true);
_btnReload.Click += async (s, e) => await RunNginxAsync("重新加载", _manager.Reload, expectedRunning: true);
_btnStop.Click += async (s, e) => await RunNginxAsync("停止", _manager.Stop, expectedRunning: false);
actions.Controls.AddRange([_btnRender, _btnStart, _btnReload, _btnStop]);
return CreateSectionPanel("Nginx 操作", actions);
}
private Control CreateSectionPanel(string title, Control content)
{
var section = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = 1,
RowCount = 2,
Margin = new Padding(3),
Padding = new Padding(8, 3, 8, 7),
BackColor = Color.White,
BorderStyle = BorderStyle.FixedSingle
};
section.RowStyles.Add(new RowStyle(SizeType.Absolute, 24));
section.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
var titleLabel = new Label
{
Text = title,
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleLeft,
ForeColor = Color.FromArgb(35, 55, 70),
Font = new Font(Font, FontStyle.Bold)
};
content.Dock = DockStyle.Fill;
section.Controls.Add(titleLabel, 0, 0);
section.Controls.Add(content, 0, 1);
return section;
}
private static Label CreateLabel(string text) => new()
{
Text = text,
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleLeft
};
private static Button CreateButton(string text, int width, Color? backColor = null, Color? foreColor = null) => new()
{
Text = text,
Width = width,
Height = 28,
Margin = new Padding(0, 0, 8, 0),
FlatStyle = FlatStyle.Flat,
BackColor = backColor ?? SystemColors.Control,
ForeColor = foreColor ?? SystemColors.ControlText,
UseVisualStyleBackColor = false
};
private void RefreshBasicInfo()
{
_txtConfigPath.Text = _manager.ConfigPath;
_txtNginxExe.Text = _manager.NginxExePath;
_txtNginxExe.BackColor = HasConfiguredNginxExe()
? Color.White
: Color.FromArgb(255, 244, 214);
}
private void LoadDataGrid()
{
_binding.Clear();
foreach (var route in _manager.Routes)
{
_binding.Add(new RouteEntry
{
Domain = route.Domain,
Upstream = route.Upstream,
ListenPort = route.ListenPort,
WebsiteName = route.WebsiteName,
Description = route.Description
});
}
_grid.DataSource = null;
_grid.DataSource = _binding;
}
private void RefreshStatus()
{
if (!HasConfiguredNginxExe())
{
_lblStatus.Text = "● 未配置 nginx.exe";
_lblStatus.ForeColor = Color.FromArgb(131, 88, 0);
_lblStatus.BackColor = Color.FromArgb(255, 246, 214);
_btnRender.Enabled = true;
_btnRefreshStatus.Enabled = true;
_btnStart.Enabled = true;
_btnReload.Enabled = false;
_btnStop.Enabled = false;
return;
}
var isRunning = _manager.IsRunning;
_lblStatus.Text = isRunning ? "● 运行中" : "● 未运行";
_lblStatus.ForeColor = isRunning ? Color.FromArgb(20, 112, 62) : Color.FromArgb(174, 45, 45);
_lblStatus.BackColor = isRunning ? Color.FromArgb(232, 247, 237) : Color.FromArgb(253, 235, 235);
_btnRender.Enabled = true;
_btnRefreshStatus.Enabled = true;
_btnStart.Enabled = !isRunning;
_btnReload.Enabled = isRunning;
_btnStop.Enabled = isRunning;
}
private async Task RunNginxAsync(string actionName, Func<int> action, bool expectedRunning)
{
if (!EnsureNginxExeConfigured())
{
RefreshStatus();
return;
}
try
{
SetNginxActionsEnabled(false);
_lblStatus.Text = "● 正在执行...";
_lblStatus.ForeColor = Color.FromArgb(131, 88, 0);
_lblStatus.BackColor = Color.FromArgb(255, 246, 214);
await Task.Run(action);
await WaitForNginxStateAsync(expectedRunning);
MessageBox.Show($"{actionName}完成", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
RefreshStatus();
}
}
private async Task WaitForNginxStateAsync(bool expectedRunning)
{
for (var attempt = 0; attempt < 20; attempt++)
{
if (_manager.IsRunning == expectedRunning)
{
return;
}
await Task.Delay(150);
}
}
private void SetNginxActionsEnabled(bool enabled)
{
_btnRender.Enabled = enabled;
_btnStart.Enabled = enabled;
_btnReload.Enabled = enabled;
_btnStop.Enabled = enabled;
_btnRefreshStatus.Enabled = enabled;
}
private async Task RenderOnlyAsync()
{
try
{
_btnRender.Enabled = false;
var path = await Task.Run(() => _manager.RenderConfig());
MessageBox.Show(
$"Nginx 配置和入口页已生成:\n{path}",
"NginxMan",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
_btnRender.Enabled = true;
}
}
private void AddRoute()
{
try
{
var (domain, upstream, port, websiteName, description) = GetInput();
if (_manager.Routes.Any(x => x.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase)))
{
throw new InvalidOperationException($"域名已存在: {domain}。请使用“保存修改”。");
}
_manager.AddOrUpdateRoute(domain, upstream, port, websiteName, description);
_manager.RenderConfig();
LoadDataGrid();
ClearForm();
MessageBox.Show("新增成功,Nginx 配置和入口页已同步生成。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void UpdateRoute()
{
if (string.IsNullOrWhiteSpace(_selectedDomain))
{
MessageBox.Show("请先在列表中选择一条记录。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
try
{
var (domain, upstream, port, websiteName, description) = GetInput();
if (_manager.UpdateRoute(_selectedDomain, domain, upstream, port, websiteName, description))
{
_manager.RenderConfig();
LoadDataGrid();
ClearForm();
MessageBox.Show("修改成功,Nginx 配置和入口页已同步生成。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("未找到选中记录。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void DeleteRoute()
{
if (string.IsNullOrWhiteSpace(_selectedDomain))
{
MessageBox.Show("请先在列表中选择一条记录。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
var confirm = MessageBox.Show($"确认删除域名映射 [{_selectedDomain}] 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirm != DialogResult.Yes)
{
return;
}
try
{
if (!_manager.RemoveRoute(_selectedDomain))
{
MessageBox.Show("未找到选中记录。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
_manager.RenderConfig();
LoadDataGrid();
ClearForm();
MessageBox.Show("删除成功,Nginx 配置和入口页已同步生成。", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void OnSelectRow()
{
if (_grid.CurrentRow?.DataBoundItem is not RouteEntry item)
{
return;
}
_selectedDomain = item.Domain;
_txtDomain.Text = item.Domain;
_txtUpstream.Text = item.Upstream;
_numPort.Value = item.ListenPort is >= 1 and <= 65535 ? item.ListenPort : 80;
_txtWebsiteName.Text = item.WebsiteName;
_txtDescription.Text = item.Description;
// Keep adding available while a row is selected. The add handler already
// rejects duplicate domains, so disabling the button only prevents users
// from entering another mapping without first clearing the selection.
_btnAdd.Enabled = true;
_btnUpdate.Enabled = true;
_btnDelete.Enabled = true;
}
private (string Domain, string Upstream, int Port, string WebsiteName, string Description) GetInput()
{
var domain = _txtDomain.Text.Trim();
var upstream = _txtUpstream.Text.Trim();
var port = (int)_numPort.Value;
var websiteName = _txtWebsiteName.Text.Trim();
var description = _txtDescription.Text.Trim();
if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(upstream))
{
throw new ArgumentException("域名和上游接口不能为空。");
}
if (string.IsNullOrWhiteSpace(websiteName) || string.IsNullOrWhiteSpace(description))
{
throw new ArgumentException("网站名称和网站简介不能为空。");
}
if (domain.Contains("://", StringComparison.Ordinal) || domain.Contains('/') ||
domain.Any(char.IsWhiteSpace) || Uri.CheckHostName(domain) == UriHostNameType.Unknown)
{
throw new ArgumentException("请输入有效域名,例如 team.m3frame.com。");
}
if (!Uri.TryCreate(upstream, UriKind.Absolute, out var upstreamUri) ||
(upstreamUri.Scheme != Uri.UriSchemeHttp && upstreamUri.Scheme != Uri.UriSchemeHttps))
{
throw new ArgumentException("上游接口必须是有效的 http:// 或 https:// 地址。");
}
return (domain, upstream, port, websiteName, description);
}
private void ClearForm()
{
_selectedDomain = null;
_txtDomain.Text = string.Empty;
_txtUpstream.Text = string.Empty;
_txtWebsiteName.Text = string.Empty;
_txtDescription.Text = string.Empty;
_numPort.Value = 80;
_grid.ClearSelection();
_btnAdd.Enabled = true;
_btnUpdate.Enabled = false;
_btnDelete.Enabled = false;
_txtDomain.Focus();
}
private bool HasConfiguredNginxExe() => File.Exists(GetConfiguredNginxExePath());
private string GetConfiguredNginxExePath()
{
var configuredPath = _manager.NginxExePath;
return Path.IsPathFullyQualified(configuredPath)
? configuredPath
: Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, configuredPath));
}
private bool EnsureNginxExeConfigured()
{
if (HasConfiguredNginxExe())
{
return true;
}
var answer = MessageBox.Show(
"未找到 nginx.exe。是否现在选择服务器上实际安装的 nginx.exe?\n\n例如:C:\\nginx\\nginx.exe",
"需要配置 Nginx",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (answer == DialogResult.Yes)
{
BrowseNginxExe();
}
return HasConfiguredNginxExe();
}
private void BrowseNginxExe()
{
using var ofd = new OpenFileDialog
{
Filter = "nginx 可执行文件 (nginx.exe)|nginx.exe|全部文件 (*.*)|*.*",
FileName = "nginx.exe"
};
if (ofd.ShowDialog(this) != DialogResult.OK)
{
return;
}
_manager.NginxExePath = ofd.FileName;
RefreshBasicInfo();
RefreshStatus();
}
private void OpenConfigFile()
{
try
{
_manager.SaveConfig();
Process.Start(new ProcessStartInfo { FileName = _manager.ConfigPath, UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"无法打开配置文件:\n{ex.Message}", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void OpenConfigFolder()
{
try
{
var directory = Path.GetDirectoryName(_manager.ConfigPath);
if (string.IsNullOrWhiteSpace(directory))
{
throw new InvalidOperationException("无法确定配置文件所在目录。");
}
Process.Start(new ProcessStartInfo { FileName = directory, UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"无法打开配置文件夹:\n{ex.Message}", "NginxMan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}