开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (4)
标签 (15)
main
security-fixes
dev
Avalonia
v1.6
v1.5.3
v1.5.2
v1.5.1
v1.5.0
v1.4.2
v1.4
v1.3.1
v1.3
v1.2.3
v1.2.2.0
v1.2.1.0
v1.2.0.2
v1.2.0.1
v1.1.0
main
分支 (4)
标签 (15)
main
security-fixes
dev
Avalonia
v1.6
v1.5.3
v1.5.2
v1.5.1
v1.5.0
v1.4.2
v1.4
v1.3.1
v1.3
v1.2.3
v1.2.2.0
v1.2.1.0
v1.2.0.2
v1.2.0.1
v1.1.0
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (4)
标签 (15)
main
security-fixes
dev
Avalonia
v1.6
v1.5.3
v1.5.2
v1.5.1
v1.5.0
v1.4.2
v1.4
v1.3.1
v1.3
v1.2.3
v1.2.2.0
v1.2.1.0
v1.2.0.2
v1.2.0.1
v1.1.0
ShellViewModel.cs 32.54 KB
一键复制 编辑 原始数据 按行查看 历史
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
using HttpFileServer.Core;
using HttpFileServer.Infrastructure;
using HttpFileServer.Models;
using HttpFileServer.Servers;
using HttpFileServer.Services;
using HttpFileServer.Utils;
using HttpFileServer.Views;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace HttpFileServer.ViewModels
{
public class ShellViewModel : ViewModelBase
{
#region Fields
private ConfigService _cfgSrv;
private Config _config;
private bool _enableUpload = false;
private bool _enableAuth = true;
private bool _strictAuthMode = false;
private bool _enableHttps = false;
private ushort _httpsPort = 443;
private ImageSource _ipv4QrImage;
private string _ipv4Text;
private ImageSource _ipv6QrImage;
private string _ipv6Text;
private bool _isRunning = false;
private ushort _listenPort = 80;
private string _logContent = string.Empty;
private bool _logIsReadOnly = false;
private ObservableCollection<NetworkAdapterModel> _networkAdapters = new ObservableCollection<NetworkAdapterModel>();
private NetworkAdapterModel _selectedNetworkAdapter;
private int _selectedTabIndex = 0;
private bool _shareTabEnabled = false;
private string _sourceDir;
private ServerStatus _status = ServerStatus.Ready;
private string _themeMode = "Light";
private bool _useWebServer = false;
private string _siteName = "HttpFileServer";
// Light / Dark / System
private ObservableCollection<VirtualDirectoryInfo> _virtualDirectoryItems = new ObservableCollection<VirtualDirectoryInfo>();
private VirtualDirectoryInfo _selectedVirtualDirectoryItem;
private ObservableCollection<UserAccount> _userItems = new ObservableCollection<UserAccount>();
private UserAccount _selectedUserItem;
#endregion Fields
#region Constructors
public ShellViewModel()
{
Title = "File Server";
// capture app instance if available
var _app = Application.Current as App;
RequestModels = new ObservableCollection<RequestModel>();
CommandStartServer = new CommandImpl(OnRequestStartServer, CanStartServer);
CommandStopServer = new CommandImpl(OnRequestStopServer, CanStopServer);
CommandToggleTheme = new CommandImpl(OnToggleTheme);
CommandAddVirtualDir = new CommandImpl(OnAddVirtualDir);
CommandRemoveVirtualDir = new CommandImpl(OnRemoveVirtualDir);
CommandApplyVirtualDirs = new CommandImpl(OnApplyVirtualDirs);
CommandAddUser = new CommandImpl(OnAddUser);
CommandRemoveUser = new CommandImpl(OnRemoveUser);
CommandApplyUsers = new CommandImpl(OnApplyUsers);
// 默认:选中 配置 tab,分享禁用,日志在停止时可编辑
SelectedTabIndex = 0;
ShareTabEnabled = false;
LogIsReadOnly = IsRunning; // false by default
_cfgSrv = new ConfigService();
// 初始根据系统主题
ThemeMode = DetectSystemTheme();
ApplyThemeResources();
}
#endregion Constructors
#region Properties
private bool _autoStartOnLaunch = false;
private bool _autoStartWithSystem = false;
private bool _MinimizeToTrayAfterAutoStart = true;
public bool AutoStartOnLaunch
{
get => _autoStartOnLaunch;
set => SetProperty(ref _autoStartOnLaunch, value);
}
public bool AutoStartWithSystem
{
get => _autoStartWithSystem;
set
{
if (SetProperty(ref _autoStartWithSystem, value))
{
AutoStartHelper.SetAutoStart(value);
}
}
}
public CommandImpl CommandStartServer { get; private set; }
public CommandImpl CommandStopServer { get; private set; }
public CommandImpl CommandToggleTheme { get; private set; }
public CommandImpl CommandAddVirtualDir { get; private set; }
public CommandImpl CommandRemoveVirtualDir { get; private set; }
public CommandImpl CommandApplyVirtualDirs { get; private set; }
public CommandImpl CommandAddUser { get; private set; }
public CommandImpl CommandRemoveUser { get; private set; }
public CommandImpl CommandApplyUsers { get; private set; }
/// <summary>
/// 虚拟目录列表(绑定到 DataGrid)
/// </summary>
public ObservableCollection<VirtualDirectoryInfo> VirtualDirectoryItems
{
get => _virtualDirectoryItems;
set => SetProperty(ref _virtualDirectoryItems, value);
}
/// <summary>
/// 选中的虚拟目录项
/// </summary>
public VirtualDirectoryInfo SelectedVirtualDirectoryItem
{
get => _selectedVirtualDirectoryItem;
set => SetProperty(ref _selectedVirtualDirectoryItem, value);
}
public ObservableCollection<UserAccount> UserItems
{
get => _userItems;
set => SetProperty(ref _userItems, value);
}
public UserAccount SelectedUserItem
{
get => _selectedUserItem;
set => SetProperty(ref _selectedUserItem, value);
}
public Dispatcher Dispatcher { get; set; }
public bool EnableUpload
{
get => _enableUpload;
set => SetProperty(ref _enableUpload, value);
}
/// <summary>
/// 是否启用用户认证与权限控制
/// </summary>
public bool EnableAuth
{
get => _enableAuth;
set
{
if (SetProperty(ref _enableAuth, value) && !value)
StrictAuthMode = false; // 禁用认证时自动关闭严格模式
}
}
/// <summary>
/// 严格认证模式:未登录用户访问任何 URL 均跳转到独立登录页
/// </summary>
public bool StrictAuthMode
{
get => _strictAuthMode;
set => SetProperty(ref _strictAuthMode, value);
}
/// <summary>
/// 是否启用 HTTPS
/// </summary>
public bool EnableHttps
{
get => _enableHttps;
set
{
if (IsRunning)
return;
SetProperty(ref _enableHttps, value);
}
}
/// <summary>
/// HTTPS 端口
/// </summary>
public ushort HttpsPort
{
get => _httpsPort;
set
{
if (IsRunning)
return;
if (SetProperty(ref _httpsPort, value))
{
UpdateShareInfo();
}
}
}
public IFileServer FileServer { get; private set; }
public ImageSource IPv4QrImage { get => _ipv4QrImage; private set => SetProperty(ref _ipv4QrImage, value); }
public string IPv4Text { get => _ipv4Text; private set => SetProperty(ref _ipv4Text, value); }
public ImageSource IPv6QrImage { get => _ipv6QrImage; private set => SetProperty(ref _ipv6QrImage, value); }
public string IPv6Text { get => _ipv6Text; private set => SetProperty(ref _ipv6Text, value); }
public bool IsRunning
{
get => _isRunning;
set => SetProperty(ref _isRunning, value);
}
public ushort ListenPort
{
get => _listenPort;
set
{
// Prevent changing the listen port while server is running
if (IsRunning)
return;
if (SetProperty(ref _listenPort, value))
{
// Update share info in UI to reflect new port immediately
UpdateShareInfo();
}
}
}
public string LogContent
{
get => _logContent;
private set => SetProperty(ref _logContent, value);
}
public bool LogIsReadOnly
{
get => _logIsReadOnly;
set => SetProperty(ref _logIsReadOnly, value);
}
public bool MinimizeToTrayAfterAutoStart
{
get => _MinimizeToTrayAfterAutoStart;
set => SetProperty(ref _MinimizeToTrayAfterAutoStart, value);
}
public ObservableCollection<NetworkAdapterModel> NetworkAdapters { get => _networkAdapters; }
public ObservableCollection<RequestModel> RequestModels { get; private set; }
public NetworkAdapterModel SelectedNetworkAdapter
{
get => _selectedNetworkAdapter;
set
{
if (SetProperty(ref _selectedNetworkAdapter, value))
{
UpdateShareInfo();
}
}
}
public int SelectedTabIndex
{
get => _selectedTabIndex;
set => SetProperty(ref _selectedTabIndex, value);
}
public bool ShareTabEnabled
{
get => _shareTabEnabled;
set => SetProperty(ref _shareTabEnabled, value);
}
public string SourceDir
{
get => _sourceDir;
set => SetProperty(ref _sourceDir, value);
}
public ServerStatus Status
{
get => _status;
set => SetProperty(ref _status, value);
}
public string ThemeMode { get => _themeMode; set => SetProperty(ref _themeMode, value); }
public bool UseWebServer
{
get => _useWebServer;
set => SetProperty(ref _useWebServer, value);
}
/// <summary>
/// 站点名称
/// </summary>
public string SiteName
{
get => _siteName;
set
{
if (SetProperty(ref _siteName, value))
{
// 服务运行时即时推送到服务器并清缓存
if (IsRunning && FileServer is HttpFileServerBase hfs)
{
hfs.UpdateSiteName(value);
}
}
}
}
#endregion Properties
#region Methods
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName.Equals("SourceDir"))
{
CommandStartServer?.RaiseCanExecuteChanged();
}
}
protected override void OnViewLoaded(object sender)
{
base.OnViewLoaded(sender);
var cfg = _cfgSrv.GetConfig<Config>();
if (cfg == null)
cfg = new Config();
cfg.RemoveDuplicates(); //清除重复数据
_config = cfg;
SourceDir = cfg.RootDir;
ListenPort = cfg.Port;
EnableUpload = cfg.EnableUpload;
EnableAuth = cfg.EnableAuth;
StrictAuthMode = cfg.StrictAuthMode;
EnableHttps = cfg.EnableHttps;
HttpsPort = cfg.HttpsPort;
UseWebServer = cfg.UseWebServer;
SiteName = cfg.SiteName ?? "HttpFileServer";
// 加载虚拟目录配置(ViewModel 层去重)
VirtualDirectoryItems.Clear();
if (cfg.VirtualDirectories != null)
{
var distinctVdirs = cfg.VirtualDirectories
.GroupBy(v => $"{v.Name ?? ""}|{v.PhysicalPath?.TrimEnd('\\', '/') ?? ""}", StringComparer.OrdinalIgnoreCase)
.Select(g => g.First());
foreach (var vdir in distinctVdirs)
{
VirtualDirectoryItems.Add(new VirtualDirectoryInfo
{
Name = vdir.Name,
PhysicalPath = vdir.PhysicalPath,
Description = vdir.Description,
AllowUpload = vdir.AllowUpload
});
}
}
// 加载用户配置(ViewModel 层去重,不修改 _config 原始数据)
UserItems.Clear();
if (cfg.Users != null)
{
var distinctUsers = cfg.Users
.GroupBy(u => u.Username, StringComparer.OrdinalIgnoreCase)
.Select(g => g.First());
foreach (var u in distinctUsers)
{
UserItems.Add(new UserAccount
{
Username = u.Username,
Password = u.Password,
AllowedVirtualDirs = u.AllowedVirtualDirs?.ToList(),
CanUpload = u.CanUpload
});
}
}
AutoStartOnLaunch = cfg.AutoStartOnLaunch;
AutoStartWithSystem = cfg.AutoStartWithSystem;
MinimizeToTrayAfterAutoStart = cfg.MinimizeToTrayAfterAutoStart;
// 加载保存的主题模式
if (!string.IsNullOrWhiteSpace(cfg.ThemeMode)) ThemeMode = cfg.ThemeMode; else ThemeMode = DetectSystemTheme();
ApplyThemeResources();
if (AutoStartHelper.IsProcessRunWithAutoStart() && _config.MinimizeToTrayAfterAutoStart)
{
var shell = sender as ShellView;
shell.WindowState = WindowState.Minimized;
}
// If application started with --debug-resource, show debug info in title
string debugRes = null;
try
{
var app = System.Windows.Application.Current as App;
if (app != null)
debugRes = app.DebugResourcePath;
}
catch { }
if (!string.IsNullOrWhiteSpace(debugRes))
{
Title = $"File Server - [ Html Debug ] -- {debugRes}";
LogContent += ($"[ Html Debug ]{Environment.NewLine}{debugRes}{Environment.NewLine}{Environment.NewLine}");
}
if ((AutoStartHelper.IsProcessRunWithAutoStart() && _config.AutoStartWithSystem) || _config.AutoStartOnLaunch)
{
OnRequestStartServer();
}
Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
// Populate network adapters for Share tab
LoadNetworkAdapters();
}
protected override void OnViewUnLoaded(object sender)
{
if (IsRunning)
OnRequestStopServer();
_config.RootDir = SourceDir;
_config.Port = (ushort)ListenPort;
_config.EnableUpload = EnableUpload;
_config.EnableAuth = EnableAuth;
_config.StrictAuthMode = StrictAuthMode;
_config.EnableHttps = EnableHttps;
_config.HttpsPort = HttpsPort;
_config.UseWebServer = UseWebServer;
_config.ThemeMode = ThemeMode; // 保存当前主题模式
_config.SiteName = SiteName;
// 保存虚拟目录配置
_config.VirtualDirectories = VirtualDirectoryItems.ToList();
// 保存用户配置
_config.Users = UserItems.ToList();
_config.AutoStartOnLaunch = AutoStartOnLaunch;
_config.AutoStartWithSystem = AutoStartWithSystem;
_config.MinimizeToTrayAfterAutoStart = MinimizeToTrayAfterAutoStart;
_cfgSrv.SaveConfig(_config);
base.OnViewUnLoaded(sender);
}
private void ApplyThemeResources()
{
var dict = GetWindowResources();
string mode = ThemeMode == "System" ? DetectSystemTheme() : ThemeMode;
if (mode == "Dark")
{
dict["WindowBackgroundBrush"] = new SolidColorBrush(Color.FromRgb(0x1E, 0x1E, 0x1E));
dict["WindowForegroundBrush"] = new SolidColorBrush(Colors.WhiteSmoke);
dict["PanelBackgroundBrush"] = new SolidColorBrush(Color.FromRgb(0x2A, 0x2A, 0x2A));
dict["PanelBorderBrush"] = new SolidColorBrush(Color.FromRgb(0x44, 0x44, 0x44));
dict["AccentBrush"] = new SolidColorBrush(Color.FromRgb(0x3B, 0x82, 0xF6));
// softer off-white for QR background in dark mode to reduce glare
dict["QrBackgroundBrush"] = new SolidColorBrush(Color.FromRgb(0xEE, 0xEE, 0xEE));
}
else // Light
{
dict["WindowBackgroundBrush"] = new SolidColorBrush(Colors.White);
dict["WindowForegroundBrush"] = new SolidColorBrush(Color.FromRgb(0x11, 0x11, 0x11));
dict["PanelBackgroundBrush"] = new SolidColorBrush(Color.FromRgb(0xF5, 0xF5, 0xF5));
dict["PanelBorderBrush"] = new SolidColorBrush(Color.FromRgb(0xDD, 0xDD, 0xDD));
dict["AccentBrush"] = new SolidColorBrush(Color.FromRgb(0x3B, 0x82, 0xF6));
// standard white QR background in light mode
dict["QrBackgroundBrush"] = new SolidColorBrush(Colors.White);
}
}
private bool CanStartServer()
{
return !IsRunning && !string.IsNullOrWhiteSpace(SourceDir);
}
private bool CanStopServer()
{
return IsRunning;
}
private string DetectSystemTheme()
{
// 简单使用系统窗口颜色亮度判断
var col = SystemParameters.WindowGlassColor; // Win7+ Aero色
var brightness = (col.R * 299 + col.G * 587 + col.B * 114) / 1000;
return brightness < 128 ? "Dark" : "Light";
}
private void Dispatcher_ShutdownStarted(object sender, EventArgs e)
{
OnViewUnLoaded(sender);
}
private void FileServer_LogGenerated(object sender, string e)
{
LogContent += $"{e}{Environment.NewLine}";
}
private void FileServer_NewReqeustIn(object sender, RequestModel e)
{
Dispatcher?.InvokeAsync(() =>
{
RequestModels.Add(e);
});
}
private void FileServer_RequestOut(object sender, RequestModel e)
{
Dispatcher?.InvokeAsync(() =>
{
RequestModels.Remove(e);
});
}
private ImageSource GenerateQrImage(string text)
{
try
{
using (var gen = new QRCodeGenerator())
{
var data = gen.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
var pngQr = new PngByteQRCode(data);
var pngBytes = pngQr.GetGraphic(10);
using (var ms = new MemoryStream(pngBytes))
{
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = ms;
img.EndInit();
img.Freeze();
return img;
}
}
}
catch
{
return null;
}
}
private ResourceDictionary GetWindowResources()
{
foreach (Window w in Application.Current.Windows)
{
if (w.DataContext == this)
return w.Resources; // 当前窗口资源
}
return Application.Current.Resources; //退回应用级
}
private bool IsPortInUse(int port)
{
try
{
var ipProps = IPGlobalProperties.GetIPGlobalProperties();
var listeners = ipProps.GetActiveTcpListeners();
foreach (var ep in listeners)
{
if (ep.Port == port)
return true;
}
}
catch
{
// If check fails, conservatively assume port is not in use
}
return false;
}
private void LoadNetworkAdapters()
{
try
{
NetworkAdapters.Clear();
var nics = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback);
foreach (var nic in nics)
{
var props = nic.GetIPProperties();
var addrs = props.UnicastAddresses
.Where(u => u.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork || u.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
.Select(u => u.Address).ToArray();
var model = new NetworkAdapterModel
{
Id = nic.Id,
Name = string.IsNullOrWhiteSpace(nic.Description) ? nic.Name : nic.Description,
IPv4 = addrs.FirstOrDefault(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString(),
IPv6 = addrs.FirstOrDefault(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)?.ToString()
};
NetworkAdapters.Add(model);
}
SelectedNetworkAdapter = NetworkAdapters.FirstOrDefault();
}
catch { }
}
private void OnRequestStartServer()
{
if (IsRunning)
return;
// Check if desired HTTP port is already in use by another process
if (IsPortInUse(ListenPort))
{
LogContent += $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} HTTP 端口 {ListenPort} 已被占用,启动被拒绝。{Environment.NewLine}";
// Switch to logs tab so the user can see the failure message
SelectedTabIndex = 1; // 日志 tab
// Server not running, ensure logs are editable/readable
LogIsReadOnly = false;
// Sharing remains disabled when server failed to start
ShareTabEnabled = false;
return;
}
// Check HTTPS port availability when SSL is enabled
if (EnableHttps && IsPortInUse(HttpsPort))
{
LogContent += $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} HTTPS 端口 {HttpsPort} 已被占用,启动被拒绝。{Environment.NewLine}";
SelectedTabIndex = 1;
LogIsReadOnly = false;
ShareTabEnabled = false;
return;
}
Directory.CreateDirectory(SourceDir);
// If application started with --debug-resource, prefer HtmlDebugServer
string debugRes = null;
var app = System.Windows.Application.Current as App;
if (app != null)
debugRes = app.DebugResourcePath;
var virtualDirs = _config.VirtualDirectories ?? new List<VirtualDirectoryInfo>();
var authService = new AuthService(_config.Users ?? new List<UserAccount>());
if (UseWebServer)
{
FileServer = new StaticWebHostServer(ListenPort, SourceDir, true, EnableUpload, virtualDirs, authService,
EnableHttps, HttpsPort, debugRes);
}
else
{
FileServer = new DefaultFileServer(ListenPort, SourceDir, true, EnableUpload, virtualDirs, authService,
EnableHttps, HttpsPort, debugRes);
}
FileServer.LogGenerated += FileServer_LogGenerated;
FileServer.NewReqeustIn += FileServer_NewReqeustIn;
FileServer.RequestOut += FileServer_RequestOut;
// 传递预览扩展名、站点名称、站点Logo、认证开关等配置到服务器
if (FileServer is HttpFileServerBase hfsBase)
{
hfsBase.EnableAuth = EnableAuth;
hfsBase.StrictAuthMode = StrictAuthMode;
hfsBase.PreviewImageExtensions = _config.PreviewImageExtensions?.ToList();
hfsBase.PreviewTextExtensions = _config.PreviewTextExtensions?.ToList();
hfsBase.SiteName = SiteName;
hfsBase.SiteLogoPath = _config.SiteLogoPath ?? "";
hfsBase.FaviconPath = _config.FaviconPath ?? "";
}
Status = ServerStatus.Starting;
FileServer.Start();
var ips = IPHelper.GetAllLocalIP();
foreach (var ip in ips)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
LogContent += $"http://{ip}:{ListenPort}/{Environment.NewLine}";
if (EnableHttps)
{
LogContent += $"https://{ip}:{HttpsPort}/{Environment.NewLine}";
}
}
else if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
var ipstr = ip.ToString();
if (ipstr.Contains("%"))
ipstr = ipstr.Substring(0, ipstr.IndexOf("%"));
LogContent += $"http://[{ipstr}]:{ListenPort}/{Environment.NewLine}";
if (EnableHttps)
{
LogContent += $"https://[{ipstr}]:{HttpsPort}/{Environment.NewLine}";
}
}
}
IsRunning = true;
Status = ServerStatus.Running;
// Ensure share info (QR and text) reflect the currently active port
UpdateShareInfo();
CommandStartServer?.RaiseCanExecuteChanged();
CommandStopServer?.RaiseCanExecuteChanged();
// Switch UI: show logs tab, enable share tab, make logs read-only
SelectedTabIndex = 1; // 日志 tab
ShareTabEnabled = true;
LogIsReadOnly = true;
}
private void OnRequestStopServer()
{
if (!IsRunning)
return;
Status = ServerStatus.Stoping;
FileServer.Stop();
FileServer.LogGenerated -= FileServer_LogGenerated;
FileServer.NewReqeustIn -= FileServer_NewReqeustIn;
FileServer.RequestOut -= FileServer_RequestOut;
// release reference to allow new server instance with different port
FileServer = null;
// Refresh share info to clear/reflect stopped state
UpdateShareInfo();
IsRunning = false;
Status = ServerStatus.Stopped;
CommandStartServer?.RaiseCanExecuteChanged();
CommandStopServer?.RaiseCanExecuteChanged();
// Switch UI: show config tab, disable share tab, make logs editable/readable
SelectedTabIndex = 0; // 配置 tab
ShareTabEnabled = false;
LogIsReadOnly = false;
}
private void OnToggleTheme()
{
if (ThemeMode == "Light") ThemeMode = "Dark";
else if (ThemeMode == "Dark") ThemeMode = "System";
else ThemeMode = "Light";
ApplyThemeResources();
// 实时保存配置
_config.ThemeMode = ThemeMode;
_cfgSrv.SaveConfig(_config);
}
private void OnAddVirtualDir()
{
VirtualDirectoryItems.Add(new VirtualDirectoryInfo
{
Name = "NewShare",
PhysicalPath = @"C:\",
Description = "",
AllowUpload = false
});
ApplyVirtualDirectoriesToServer();
RefreshVirtualDirDisplay();
}
private void OnRemoveVirtualDir()
{
if (SelectedVirtualDirectoryItem != null)
{
VirtualDirectoryItems.Remove(SelectedVirtualDirectoryItem);
SelectedVirtualDirectoryItem = null;
ApplyVirtualDirectoriesToServer();
RefreshVirtualDirDisplay();
}
}
private void OnAddUser()
{
UserItems.Add(new UserAccount
{
Username = "newuser",
Password = "password",
AllowedVirtualDirs = null,
CanUpload = true
});
}
private void OnRemoveUser()
{
if (SelectedUserItem != null)
{
UserItems.Remove(SelectedUserItem);
SelectedUserItem = null;
}
}
private void OnApplyUsers()
{
var users = UserItems.ToList();
// 持久化到配置文件
_config.Users = users;
_cfgSrv.SaveConfig(_config);
// 热更新运行中的服务器
if (IsRunning && FileServer is HttpFileServerBase hfs)
{
hfs.UpdateUsers(users);
LogContent += $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} 用户配置已热更新{Environment.NewLine}";
}
}
private void OnApplyVirtualDirs()
{
ApplyVirtualDirectoriesToServer();
RefreshVirtualDirDisplay();
}
/// <summary>
/// 刷新虚拟目录 DataGrid 显示,使属性变更即时反映到界面
/// </summary>
public void RefreshVirtualDirDisplay()
{
var view = System.Windows.Data.CollectionViewSource.GetDefaultView(VirtualDirectoryItems);
view?.Refresh();
}
/// <summary>
/// 将当前虚拟目录配置推送到运行中的服务器,并持久化到配置文件
/// </summary>
private void ApplyVirtualDirectoriesToServer()
{
var vdirs = VirtualDirectoryItems.ToList();
// 同步到配置对象并保存文件,确保下次启动时生效
_config.VirtualDirectories = vdirs;
_cfgSrv.SaveConfig(_config);
if (IsRunning && FileServer is HttpFileServerBase hfs)
{
hfs.UpdateVirtualDirectories(vdirs);
LogContent += $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} 虚拟目录配置已热更新{Environment.NewLine}";
}
UpdateShareInfo();
}
private void UpdateShareInfo()
{
// Ensure updates happen on the UI thread
var uiDispatcher = Dispatcher ?? Application.Current?.Dispatcher;
Action work = () =>
{
if (SelectedNetworkAdapter == null)
{
IPv4QrImage = null;
IPv6QrImage = null;
IPv4Text = string.Empty;
IPv6Text = string.Empty;
return;
}
// Determine protocol and port based on SSL setting
string scheme = EnableHttps && IsRunning ? "https" : "http";
int displayPort = EnableHttps && IsRunning ? HttpsPort : ListenPort;
// Build URLs
if (!string.IsNullOrWhiteSpace(SelectedNetworkAdapter.IPv4))
{
var url = $"{scheme}://{SelectedNetworkAdapter.IPv4}:{displayPort}/";
IPv4Text = url;
IPv4QrImage = GenerateQrImage(url);
}
else
{
IPv4Text = string.Empty;
IPv4QrImage = null;
}
if (!string.IsNullOrWhiteSpace(SelectedNetworkAdapter.IPv6))
{
var ip = SelectedNetworkAdapter.IPv6;
if (ip.Contains("%")) ip = ip.Substring(0, ip.IndexOf('%'));
var url = $"{scheme}://[{ip}]:{displayPort}/";
IPv6Text = url;
IPv6QrImage = GenerateQrImage(url);
}
else
{
IPv6Text = string.Empty;
IPv6QrImage = null;
}
};
if (uiDispatcher != null && !uiDispatcher.CheckAccess())
uiDispatcher.BeginInvoke(work);
else
work();
}
#endregion Methods
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

http文件服务器 可用于局域网内目录浏览和文件下载、上传 http server for browse directory and download / upload files 支持将目录信息响应为json格式(发起HTTP请求时将Header中的Accept设置为application/json)
暂无标签
MIT
使用 MIT 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/AITechInfo/HttpFileServer.git
git@gitee.com:AITechInfo/HttpFileServer.git
AITechInfo
HttpFileServer
HttpFileServer
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /