Dataset Viewer
Auto-converted to Parquet
repo
stringclasses
183 values
ref
stringlengths
40
40
path
stringlengths
8
198
prompt
stringlengths
0
24.6k
suffix
stringlengths
0
24.5k
canonical_solution
stringlengths
30
18.1k
lang
stringclasses
12 values
timestamp
timestamp[us]date
2019-12-19 23:00:04
2025-03-02 18:12:33
2dust/v2rayN
79a0538ca0ea952ff7b14b368e9bbabf7928019c
v2rayN/ServiceLib/Global.cs
namespace ServiceLib { public class Global { #region const public const string AppName = "v2rayN"; public const string GithubUrl = "https://github.com"; public const string GithubApiUrl = "https://api.github.com/repos"; public const string GeoUrl = "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/{0}.dat"; public const string SpeedPingTestUrl = @"https://www.google.com/generate_204"; public const string SingboxRulesetUrl = @"https://raw.githubusercontent.com/2dust/sing-box-rules/rule-set-{0}/{1}.srs"; public const string IPAPIUrl = "https://api.ip.sb/geoip"; public const string PromotionUrl = @"aHR0cHM6Ly85LjIzNDQ1Ni54eXovYWJjLmh0bWw="; public const string ConfigFileName = "guiNConfig.json"; public const string CoreConfigFileName = "config.json"; public const string CorePreConfigFileName = "configPre.json"; public const string CoreSpeedtestConfigFileName = "configSpeedtest.json"; public const string CoreMultipleLoadConfigFileName = "configMultipleLoad.json"; public const string ClashMixinConfigFileName = "Mixin.yaml"; public const string NamespaceSample = "ServiceLib.Sample."; public const string V2raySampleClient = NamespaceSample + "SampleClientConfig"; public const string SingboxSampleClient = NamespaceSample + "SingboxSampleClientConfig"; public const string V2raySampleHttpRequestFileName = NamespaceSample + "SampleHttpRequest"; public const string V2raySampleHttpResponseFileName = NamespaceSample + "SampleHttpResponse"; public const string V2raySampleInbound = NamespaceSample + "SampleInbound"; public const string V2raySampleOutbound = NamespaceSample + "SampleOutbound"; public const string SingboxSampleOutbound = NamespaceSample + "SingboxSampleOutbound"; public const string CustomRoutingFileName = NamespaceSample + "custom_routing_"; public const string TunSingboxDNSFileName = NamespaceSample + "tun_singbox_dns"; public const string TunSingboxInboundFileName = NamespaceSample + "tun_singbox_inbound"; public const string TunSingboxRulesFileName = NamespaceSample + "tun_singbox_rules"; public const string DNSV2rayNormalFileName = NamespaceSample + "dns_v2ray_normal"; public const string DNSSingboxNormalFileName = NamespaceSample + "dns_singbox_normal"; public const string ClashMixinYaml = NamespaceSample + "clash_mixin_yaml"; public const string ClashTunYaml = NamespaceSample + "clash_tun_yaml"; public const string LinuxAutostartConfig = NamespaceSample + "linux_autostart_config"; public const string PacFileName = NamespaceSample + "pac"; public const string DefaultSecurity = "auto"; public const string DefaultNetwork = "tcp"; public const string TcpHeaderHttp = "http"; public const string None = "none"; public const string ProxyTag = "proxy"; public const string DirectTag = "direct"; public const string BlockTag = "block"; public const string StreamSecurity = "tls"; public const string StreamSecurityReality = "reality"; public const string Loopback = "127.0.0.1"; public const string InboundAPIProtocol = "dokodemo-door"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string SocksProtocol = "socks://"; public const string Socks5Protocol = "socks5://"; public const string UserEMail = "t@t.tt"; public const string AutoRunRegPath = @"Software\Microsoft\Windows\CurrentVersion\Run"; public const string AutoRunName = "v2rayNAutoRun"; public const string SystemProxyExceptionsWindows = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*"; public const string SystemProxyExceptionsLinux = "localhost,127.0.0.0/8,::1"; public const string RoutingRuleComma = "<COMMA>"; public const string GrpcGunMode = "gun"; public const string GrpcMultiMode = "multi"; public const int MaxPort = 65536; public const string DelayUnit = ""; public const string SpeedUnit = ""; public const int MinFontSize = 8; public const string RebootAs = "rebootas"; public const string AvaAssets = "avares://v2rayN/Assets/"; public const string LocalAppData = "V2RAYN_LOCAL_APPLICATION_DATA"; public const string V2RayLocalAsset = "V2RAY_LOCATION_ASSET"; public const string XrayLocalAsset = "XRAY_LOCATION_ASSET"; public static readonly List<string> IEProxyProtocols = [ "{ip}:{http_port}", "socks={ip}:{socks_port}", "http={ip}:{http_port};https={ip}:{http_port};ftp={ip}:{http_port};socks={ip}:{socks_port}", "http=http://{ip}:{http_port};https=http://{ip}:{http_port}", "" ]; public static readonly List<string> SubConvertUrls = [ @"https://sub.xeton.dev/sub?url={0}", @"https://api.dler.io/sub?url={0}", @"http://127.0.0.1:25500/sub?url={0}", "" ]; public static readonly List<string> SubConvertConfig = [@"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"]; public static readonly List<string> SubConvertTargets = [ "", "mixed", "v2ray", "clash", "ss" ]; public static readonly List<string> SpeedTestUrls = [ @"https://speed.cloudflare.com/__down?bytes=100000000", @"https://speed.cloudflare.com/__down?bytes=50000000", @"https://speed.cloudflare.com/__down?bytes=10000000", @"https://cachefly.cachefly.net/50mb.test" ]; public static readonly List<string> SpeedPingTestUrls = [ @"https://www.google.com/generate_204", @"https://www.gstatic.com/generate_204", @"https://www.apple.com/library/test/success.html", @"http://www.msftconnecttest.com/connecttest.txt" ]; public static readonly List<string> GeoFilesSources = [ "", @"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/{0}.dat", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-v2ray-rules@release/{0}.dat" ]; public static readonly List<string> SingboxRulesetSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-rules-dat@release/sing-box/rule-set-{0}/{1}.srs", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-sing-box-rules@rule-set/{1}.srs" ]; public static readonly List<string> RoutingRulesSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/template.json", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/template.json" ]; public static readonly List<string> DNSTemplateSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/" ]; public static readonly Dictionary<string, string> UserAgentTexts = new() { {"chrome","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" }, {"firefox","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" }, {"safari","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15" }, {"edge","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.70" }, {"none",""} }; public const string Hysteria2ProtocolShare = "hy2://"; public static readonly Dictionary<EConfigType, string> ProtocolShares = new() { { EConfigType.VMess, "vmess://" }, { EConfigType.Shadowsocks, "ss://" }, { EConfigType.SOCKS, "socks://" }, { EConfigType.VLESS, "vless://" }, { EConfigType.Trojan, "trojan://" }, { EConfigType.Hysteria2, "hysteria2://" }, { EConfigType.TUIC, "tuic://" }, { EConfigType.WireGuard, "wireguard://" } }; public static readonly Dictionary<EConfigType, string> ProtocolTypes = new() { { EConfigType.VMess, "vmess" }, { EConfigType.Shadowsocks, "shadowsocks" }, { EConfigType.SOCKS, "socks" }, { EConfigType.HTTP, "http" }, { EConfigType.VLESS, "vless" }, { EConfigType.Trojan, "trojan" }, { EConfigType.Hysteria2, "hysteria2" }, { EConfigType.TUIC, "tuic" }, { EConfigType.WireGuard, "wireguard" } }; public static readonly List<string> VmessSecurities = [ "aes-128-gcm", "chacha20-poly1305", "auto", "none", "zero" ]; public static readonly List<string> SsSecurities = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "none", "plain" ]; public static readonly List<string> SsSecuritiesInXray = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "xchacha20-poly1305", "xchacha20-ietf-poly1305", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305" ]; public static readonly List<string> SsSecuritiesInSingbox = [ "aes-256-gcm", "aes-192-gcm", "aes-128-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "none", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "rc4-md5", "chacha20-ietf", "xchacha20" ]; public static readonly List<string> Flows = [ "", "xtls-rprx-vision", "xtls-rprx-vision-udp443" ]; public static readonly List<string> Networks = [ "tcp", "kcp", "ws", "httpupgrade", "xhttp", "h2", "quic", "grpc" ]; public static readonly List<string> KcpHeaderTypes = [ "srtp", "utp", "wechat-video", "dtls", "wireguard" ]; public static readonly List<string> CoreTypes = [ "Xray", "sing_box" ]; public static readonly List<string> DomainStrategies = [ "AsIs", "IPIfNonMatch", "IPOnDemand" ]; public static readonly List<string> DomainStrategies4Singbox = [ "ipv4_only", "ipv6_only", "prefer_ipv4", "prefer_ipv6", "" ]; public static readonly List<string> DomainMatchers = [ "linear", "mph", "" ]; public static readonly List<string> Fingerprints = [ "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized", "" ]; public static readonly List<string> UserAgent = [ "chrome", "firefox", "safari", "edge", "none" ]; public static readonly List<string> XhttpMode = [ "auto", "packet-up", "stream-up", "stream-one" ]; public static readonly List<string> AllowInsecure = [ "true", "false", "" ]; public static readonly List<string> DomainStrategy4Freedoms = [ "AsIs", "UseIP", "UseIPv4", "UseIPv6", "" ]; public static readonly List<string> SingboxDomainStrategy4Out = [ "ipv4_only", "prefer_ipv4", "prefer_ipv6", "ipv6_only", "" ]; public static readonly List<string> DomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "localhost" ]; public static readonly List<string> SingboxDomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "dhcp://auto" ]; public static readonly List<string> Languages = [ "zh-Hans", "zh-Hant", "en", "fa-Ir", "ru", "hu" ]; public static readonly List<string> Alpns = [ "h3", "h2", "http/1.1", "h3,h2", "h2,http/1.1", "h3,h2,http/1.1", "" ]; public static readonly List<string> LogLevels = [ "debug", "info", "warning", "error", "none" ]; public static readonly List<string> InboundTags = [ "socks", "socks2", "socks3" ]; public static readonly List<string> RuleProtocols = [ "http", "tls", "bittorrent" ]; public static readonly List<string> RuleNetworks = [ "", "tcp", "udp", "tcp,udp" ]; public static readonly List<string> destOverrideProtocols = [ "http", "tls", "quic", "fakedns", "fakedns+others" ]; public static readonly List<string> TunMtus = [ "1280", "1408", "1500", "9000" ]; public static readonly List<string> TunStacks = [ "gvisor", "system", "mixed" ]; public static readonly List<string> PresetMsgFilters = [ "proxy", "direct", "block", "" ]; public static readonly List<string> SingboxMuxs = [ "h2mux", "smux", "yamux", "" ]; public static readonly List<string> TuicCongestionControls = [ "cubic", "new_reno", "bbr" ]; public static readonly List<string> allowSelectType = [ "selector", "urltest", "loadbalance", "fallback" ]; public static readonly List<string> notAllowTestType = [ "selector", "urltest", "direct", "reject", "compatible", "pass", "loadbalance", "fallback" ]; public static readonly List<string> proxyVehicleType = [ "file", "http" ];
#endregion const } }
public static readonly Dictionary<ECoreType, string> CoreUrls = new() { { ECoreType.v2fly, "v2fly/v2ray-core" }, { ECoreType.v2fly_v5, "v2fly/v2ray-core" }, { ECoreType.Xray, "XTLS/Xray-core" }, { ECoreType.sing_box, "SagerNet/sing-box" }, { ECoreType.mihomo, "MetaCubeX/mihomo" }, { ECoreType.hysteria, "apernet/hysteria" }, { ECoreType.hysteria2, "apernet/hysteria" }, { ECoreType.naiveproxy, "klzgrad/naiveproxy" }, { ECoreType.tuic, "EAimTY/tuic" }, { ECoreType.juicity, "juicity/juicity" }, { ECoreType.brook, "txthinking/brook" }, { ECoreType.overtls, "ShadowsocksR-Live/overtls" }, { ECoreType.v2rayN, "2dust/v2rayN" }, };
csharp
2025-02-03T12:19:20
2dust/v2rayN
e6b27d17e40ad392d33bfda4ff5cd926bbea54a5
v2rayN/ServiceLib/Global.cs
namespace ServiceLib { public class Global { #region const public const string AppName = "v2rayN"; public const string GithubUrl = "https://github.com"; public const string GithubApiUrl = "https://api.github.com/repos"; public const string V2flyCoreUrl = "https://github.com/v2fly/v2ray-core/releases"; public const string XrayCoreUrl = "https://github.com/XTLS/Xray-core/releases"; public const string NUrl = @"https://github.com/2dust/v2rayN/releases"; public const string MihomoCoreUrl = "https://github.com/MetaCubeX/mihomo/releases"; public const string HysteriaCoreUrl = "https://github.com/apernet/hysteria/releases"; public const string NaiveproxyCoreUrl = "https://github.com/klzgrad/naiveproxy/releases"; public const string TuicCoreUrl = "https://github.com/EAimTY/tuic/releases"; public const string SingboxCoreUrl = "https://github.com/SagerNet/sing-box/releases"; public const string GeoUrl = "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/{0}.dat"; public const string SpeedPingTestUrl = @"https://www.google.com/generate_204"; public const string JuicityCoreUrl = "https://github.com/juicity/juicity/releases"; public const string BrookCoreUrl = "https://github.com/txthinking/brook/releases";
public const string SingboxRulesetUrl = @"https://raw.githubusercontent.com/2dust/sing-box-rules/rule-set-{0}/{1}.srs"; public const string IPAPIUrl = "https://api.ip.sb/geoip"; public const string PromotionUrl = @"aHR0cHM6Ly85LjIzNDQ1Ni54eXovYWJjLmh0bWw="; public const string ConfigFileName = "guiNConfig.json"; public const string CoreConfigFileName = "config.json"; public const string CorePreConfigFileName = "configPre.json"; public const string CoreSpeedtestConfigFileName = "configSpeedtest.json"; public const string CoreMultipleLoadConfigFileName = "configMultipleLoad.json"; public const string ClashMixinConfigFileName = "Mixin.yaml"; public const string NamespaceSample = "ServiceLib.Sample."; public const string V2raySampleClient = NamespaceSample + "SampleClientConfig"; public const string SingboxSampleClient = NamespaceSample + "SingboxSampleClientConfig"; public const string V2raySampleHttpRequestFileName = NamespaceSample + "SampleHttpRequest"; public const string V2raySampleHttpResponseFileName = NamespaceSample + "SampleHttpResponse"; public const string V2raySampleInbound = NamespaceSample + "SampleInbound"; public const string V2raySampleOutbound = NamespaceSample + "SampleOutbound"; public const string SingboxSampleOutbound = NamespaceSample + "SingboxSampleOutbound"; public const string CustomRoutingFileName = NamespaceSample + "custom_routing_"; public const string TunSingboxDNSFileName = NamespaceSample + "tun_singbox_dns"; public const string TunSingboxInboundFileName = NamespaceSample + "tun_singbox_inbound"; public const string TunSingboxRulesFileName = NamespaceSample + "tun_singbox_rules"; public const string DNSV2rayNormalFileName = NamespaceSample + "dns_v2ray_normal"; public const string DNSSingboxNormalFileName = NamespaceSample + "dns_singbox_normal"; public const string ClashMixinYaml = NamespaceSample + "clash_mixin_yaml"; public const string ClashTunYaml = NamespaceSample + "clash_tun_yaml"; public const string LinuxAutostartConfig = NamespaceSample + "linux_autostart_config"; public const string PacFileName = NamespaceSample + "pac"; public const string DefaultSecurity = "auto"; public const string DefaultNetwork = "tcp"; public const string TcpHeaderHttp = "http"; public const string None = "none"; public const string ProxyTag = "proxy"; public const string DirectTag = "direct"; public const string BlockTag = "block"; public const string StreamSecurity = "tls"; public const string StreamSecurityReality = "reality"; public const string Loopback = "127.0.0.1"; public const string InboundAPIProtocol = "dokodemo-door"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string SocksProtocol = "socks://"; public const string Socks5Protocol = "socks5://"; public const string UserEMail = "t@t.tt"; public const string AutoRunRegPath = @"Software\Microsoft\Windows\CurrentVersion\Run"; public const string AutoRunName = "v2rayNAutoRun"; public const string SystemProxyExceptionsWindows = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*"; public const string SystemProxyExceptionsLinux = "localhost,127.0.0.0/8,::1"; public const string RoutingRuleComma = "<COMMA>"; public const string GrpcGunMode = "gun"; public const string GrpcMultiMode = "multi"; public const int MaxPort = 65536; public const string DelayUnit = ""; public const string SpeedUnit = ""; public const int MinFontSize = 8; public const string RebootAs = "rebootas"; public const string AvaAssets = "avares://v2rayN/Assets/"; public const string LocalAppData = "V2RAYN_LOCAL_APPLICATION_DATA"; public const string V2RayLocalAsset = "V2RAY_LOCATION_ASSET"; public const string XrayLocalAsset = "XRAY_LOCATION_ASSET"; public static readonly List<string> IEProxyProtocols = [ "{ip}:{http_port}", "socks={ip}:{socks_port}", "http={ip}:{http_port};https={ip}:{http_port};ftp={ip}:{http_port};socks={ip}:{socks_port}", "http=http://{ip}:{http_port};https=http://{ip}:{http_port}", "" ]; public static readonly List<string> SubConvertUrls = [ @"https://sub.xeton.dev/sub?url={0}", @"https://api.dler.io/sub?url={0}", @"http://127.0.0.1:25500/sub?url={0}", "" ]; public static readonly List<string> SubConvertConfig = [@"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"]; public static readonly List<string> SubConvertTargets = [ "", "mixed", "v2ray", "clash", "ss" ]; public static readonly List<string> SpeedTestUrls = [ @"https://speed.cloudflare.com/__down?bytes=100000000", @"https://speed.cloudflare.com/__down?bytes=50000000", @"https://speed.cloudflare.com/__down?bytes=10000000", @"https://cachefly.cachefly.net/50mb.test" ]; public static readonly List<string> SpeedPingTestUrls = [ @"https://www.google.com/generate_204", @"https://www.gstatic.com/generate_204", @"https://www.apple.com/library/test/success.html", @"http://www.msftconnecttest.com/connecttest.txt" ]; public static readonly List<string> GeoFilesSources = [ "", @"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/{0}.dat", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-v2ray-rules@release/{0}.dat" ]; public static readonly List<string> SingboxRulesetSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-rules-dat@release/sing-box/rule-set-{0}/{1}.srs", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-sing-box-rules@rule-set/{1}.srs" ]; public static readonly List<string> RoutingRulesSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/template.json", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/template.json" ]; public static readonly List<string> DNSTemplateSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/" ]; public static readonly Dictionary<string, string> UserAgentTexts = new() { {"chrome","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" }, {"firefox","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" }, {"safari","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15" }, {"edge","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.70" }, {"none",""} }; public const string Hysteria2ProtocolShare = "hy2://"; public static readonly Dictionary<EConfigType, string> ProtocolShares = new() { {EConfigType.VMess,"vmess://"}, {EConfigType.Shadowsocks,"ss://"}, {EConfigType.SOCKS,"socks://"}, {EConfigType.VLESS,"vless://"}, {EConfigType.Trojan,"trojan://"}, {EConfigType.Hysteria2,"hysteria2://"}, {EConfigType.TUIC,"tuic://"}, {EConfigType.WireGuard,"wireguard://"} }; public static readonly Dictionary<EConfigType, string> ProtocolTypes = new() { {EConfigType.VMess,"vmess"}, {EConfigType.Shadowsocks,"shadowsocks"}, {EConfigType.SOCKS,"socks"}, {EConfigType.HTTP,"http"}, {EConfigType.VLESS,"vless"}, {EConfigType.Trojan,"trojan"}, {EConfigType.Hysteria2,"hysteria2"}, {EConfigType.TUIC,"tuic"}, {EConfigType.WireGuard,"wireguard"} }; public static readonly List<string> VmessSecurities = [ "aes-128-gcm", "chacha20-poly1305", "auto", "none", "zero" ]; public static readonly List<string> SsSecurities = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "none", "plain" ]; public static readonly List<string> SsSecuritiesInXray = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "xchacha20-poly1305", "xchacha20-ietf-poly1305", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305" ]; public static readonly List<string> SsSecuritiesInSingbox = [ "aes-256-gcm", "aes-192-gcm", "aes-128-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "none", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "rc4-md5", "chacha20-ietf", "xchacha20" ]; public static readonly List<string> Flows = [ "", "xtls-rprx-vision", "xtls-rprx-vision-udp443" ]; public static readonly List<string> Networks = [ "tcp", "kcp", "ws", "httpupgrade", "xhttp", "h2", "quic", "grpc" ]; public static readonly List<string> KcpHeaderTypes = [ "srtp", "utp", "wechat-video", "dtls", "wireguard" ]; public static readonly List<string> CoreTypes = [ "Xray", "sing_box" ]; public static readonly List<string> DomainStrategies = [ "AsIs", "IPIfNonMatch", "IPOnDemand" ]; public static readonly List<string> DomainStrategies4Singbox = [ "ipv4_only", "ipv6_only", "prefer_ipv4", "prefer_ipv6", "" ]; public static readonly List<string> DomainMatchers = [ "linear", "mph", "" ]; public static readonly List<string> Fingerprints = [ "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized", "" ]; public static readonly List<string> UserAgent = [ "chrome", "firefox", "safari", "edge", "none" ]; public static readonly List<string> XhttpMode = [ "auto", "packet-up", "stream-up", "stream-one" ]; public static readonly List<string> AllowInsecure = [ "true", "false", "" ]; public static readonly List<string> DomainStrategy4Freedoms = [ "AsIs", "UseIP", "UseIPv4", "UseIPv6", "" ]; public static readonly List<string> SingboxDomainStrategy4Out = [ "ipv4_only", "prefer_ipv4", "prefer_ipv6", "ipv6_only", "" ]; public static readonly List<string> DomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "localhost" ]; public static readonly List<string> SingboxDomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "dhcp://auto" ]; public static readonly List<string> Languages = [ "zh-Hans", "zh-Hant", "en", "fa-Ir", "ru", "hu" ]; public static readonly List<string> Alpns = [ "h3", "h2", "http/1.1", "h3,h2", "h2,http/1.1", "h3,h2,http/1.1", "" ]; public static readonly List<string> LogLevels = [ "debug", "info", "warning", "error", "none" ]; public static readonly List<string> InboundTags = [ "socks", "socks2", "socks3" ]; public static readonly List<string> RuleProtocols = [ "http", "tls", "bittorrent" ]; public static readonly List<string> RuleNetworks = [ "", "tcp", "udp", "tcp,udp" ]; public static readonly List<string> destOverrideProtocols = [ "http", "tls", "quic", "fakedns", "fakedns+others" ]; public static readonly List<string> TunMtus = [ "1280", "1408", "1500", "9000" ]; public static readonly List<string> TunStacks = [ "gvisor", "system", "mixed" ]; public static readonly List<string> PresetMsgFilters = [ "proxy", "direct", "block", "" ]; public static readonly List<string> SingboxMuxs = [ "h2mux", "smux", "yamux", "" ]; public static readonly List<string> TuicCongestionControls = [ "cubic", "new_reno", "bbr" ]; public static readonly List<string> allowSelectType = [ "selector", "urltest", "loadbalance", "fallback" ]; public static readonly List<string> notAllowTestType = [ "selector", "urltest", "direct", "reject", "compatible", "pass", "loadbalance", "fallback" ]; public static readonly List<string> proxyVehicleType = [ "file", "http" ]; #endregion const } }
public const string OvertlsCoreUrl = "https://github.com/ShadowsocksR-Live/overtls/releases";
csharp
2025-02-03T07:43:26
2dust/v2rayN
e6b27d17e40ad392d33bfda4ff5cd926bbea54a5
v2rayN/ServiceLib/Handler/CoreInfoHandler.cs
namespace ServiceLib.Handler { public sealed class CoreInfoHandler { private static readonly Lazy<CoreInfoHandler> _instance = new(() => new()); private List<CoreInfo>? _coreInfo; public static CoreInfoHandler Instance => _instance.Value; public CoreInfoHandler() { InitCoreInfo(); } public CoreInfo? GetCoreInfo(ECoreType coreType) { if (_coreInfo == null) { InitCoreInfo(); } return _coreInfo?.FirstOrDefault(t => t.CoreType == coreType); } public List<CoreInfo> GetCoreInfo() { if (_coreInfo == null) { InitCoreInfo(); } return _coreInfo ?? []; } public string GetCoreExecFile(CoreInfo? coreInfo, out string msg) { var fileName = string.Empty; msg = string.Empty; foreach (var name in coreInfo?.CoreExes) { var vName = Utils.GetBinPath(Utils.GetExeName(name), coreInfo.CoreType.ToString()); if (File.Exists(vName)) { fileName = vName; break; } } if (fileName.IsNullOrEmpty()) { msg = string.Format(ResUI.NotFoundCore, Utils.GetBinPath("", coreInfo?.CoreType.ToString()), coreInfo?.CoreExes?.LastOrDefault(), coreInfo?.Url); Logging.SaveLog(msg); } return fileName; } private void InitCoreInfo() { _coreInfo = [ new CoreInfo { CoreType = ECoreType.v2rayN, Url = Global.NUrl, ReleaseApiUrl = Global.NUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), DownloadUrlWin64 = Global.NUrl + "/download/{0}/v2rayN-windows-64.zip", DownloadUrlWinArm64 = Global.NUrl + "/download/{0}/v2rayN-windows-arm64.zip", DownloadUrlLinux64 = Global.NUrl + "/download/{0}/v2rayN-linux-64.zip", DownloadUrlLinuxArm64 = Global.NUrl + "/download/{0}/v2rayN-linux-arm64.zip", DownloadUrlOSX64 = Global.NUrl + "/download/{0}/v2rayN-macos-64.zip", DownloadUrlOSXArm64 = Global.NUrl + "/download/{0}/v2rayN-macos-arm64.zip", }, new CoreInfo { CoreType = ECoreType.v2fly, CoreExes = ["wv2ray", "v2ray"], Arguments = "{0}", Url = Global.V2flyCoreUrl, ReleaseApiUrl = Global.V2flyCoreUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), Match = "V2Ray", VersionArg = "-version", }, new CoreInfo { CoreType = ECoreType.v2fly_v5, CoreExes = ["v2ray"], Arguments = "run -c {0} -format jsonv5", Url = Global.V2flyCoreUrl, ReleaseApiUrl = Global.V2flyCoreUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), Match = "V2Ray", VersionArg = "version", }, new CoreInfo { CoreType = ECoreType.Xray, CoreExes = ["wxray","xray"], Arguments = "run -c {0}", Url = Global.XrayCoreUrl, ReleaseApiUrl = Global.XrayCoreUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), DownloadUrlWin64 = Global.XrayCoreUrl + "/download/{0}/Xray-windows-64.zip", DownloadUrlWinArm64 = Global.XrayCoreUrl + "/download/{0}/Xray-windows-arm64-v8a.zip", DownloadUrlLinux64 = Global.XrayCoreUrl + "/download/{0}/Xray-linux-64.zip", DownloadUrlLinuxArm64 = Global.XrayCoreUrl + "/download/{0}/Xray-linux-arm64-v8a.zip", DownloadUrlOSX64 = Global.XrayCoreUrl + "/download/{0}/Xray-macos-64.zip", DownloadUrlOSXArm64 = Global.XrayCoreUrl + "/download/{0}/Xray-macos-arm64-v8a.zip", Match = "Xray", VersionArg = "-version", }, new CoreInfo { CoreType = ECoreType.mihomo, CoreExes = ["mihomo-windows-amd64-compatible", "mihomo-windows-amd64", "mihomo-linux-amd64", "clash", "mihomo"], Arguments = "-f {0}" + PortableMode(), Url = Global.MihomoCoreUrl, ReleaseApiUrl = Global.MihomoCoreUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), DownloadUrlWin64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-windows-amd64-compatible-{0}.zip", DownloadUrlWinArm64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-windows-arm64-{0}.zip", DownloadUrlLinux64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-linux-amd64-compatible-{0}.gz", DownloadUrlLinuxArm64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-linux-arm64-{0}.gz", DownloadUrlOSX64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-darwin-amd64-compatible-{0}.gz", DownloadUrlOSXArm64 = Global.MihomoCoreUrl + "/download/{0}/mihomo-darwin-arm64-{0}.gz", Match = "Mihomo", VersionArg = "-v", }, new CoreInfo { CoreType = ECoreType.hysteria, CoreExes = ["hysteria-windows-amd64", "hysteria"], Arguments = "-c {0}", Url = Global.HysteriaCoreUrl, }, new CoreInfo { CoreType = ECoreType.naiveproxy, CoreExes = [ "naive", "naiveproxy"], Arguments = "{0}", Url = Global.NaiveproxyCoreUrl, }, new CoreInfo { CoreType = ECoreType.tuic, CoreExes = ["tuic-client", "tuic"], Arguments = "-c {0}", Url = Global.TuicCoreUrl, }, new CoreInfo { CoreType = ECoreType.sing_box, CoreExes = ["sing-box-client", "sing-box"], Arguments = "run -c {0} --disable-color", Url = Global.SingboxCoreUrl, ReleaseApiUrl = Global.SingboxCoreUrl.Replace(Global.GithubUrl, Global.GithubApiUrl), DownloadUrlWin64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-windows-amd64.zip", DownloadUrlWinArm64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-windows-arm64.zip", DownloadUrlLinux64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-linux-amd64.tar.gz", DownloadUrlLinuxArm64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-linux-arm64.tar.gz", DownloadUrlOSX64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-darwin-amd64.tar.gz", DownloadUrlOSXArm64 = Global.SingboxCoreUrl + "/download/{0}/sing-box-{1}-darwin-arm64.tar.gz", Match = "sing-box", VersionArg = "version", }, new CoreInfo { CoreType = ECoreType.juicity, CoreExes = ["juicity-client", "juicity"], Arguments = "run -c {0}", Url = Global.JuicityCoreUrl }, new CoreInfo { CoreType = ECoreType.hysteria2, CoreExes = ["hysteria-windows-amd64", "hysteria-linux-amd64", "hysteria"], Arguments = "-c {0}", Url = Global.HysteriaCoreUrl, }, new CoreInfo { CoreType = ECoreType.brook, CoreExes = ["brook_windows_amd64", "brook_linux_amd64", "brook"], Arguments = " {0}", Url = Global.BrookCoreUrl, AbsolutePath = true,
} ]; } private string PortableMode() { return $" -d {Utils.GetBinPath("").AppendQuotes()}"; } } }
}, new CoreInfo { CoreType = ECoreType.overtls, CoreExes = [ "overtls-bin", "overtls"], Arguments = "-r client -c {0}", Url = Global.OvertlsCoreUrl, AbsolutePath = false,
csharp
2025-02-03T07:43:26
2dust/v2rayN
2a0012824abb0dc5f2cb893ad510a01b9cd9d703
v2rayN/ServiceLib/Global.cs
namespace ServiceLib { public class Global { #region const public const string AppName = "v2rayN"; public const string GithubUrl = "https://github.com"; public const string GithubApiUrl = "https://api.github.com/repos"; public const string V2flyCoreUrl = "https://github.com/v2fly/v2ray-core/releases"; public const string XrayCoreUrl = "https://github.com/XTLS/Xray-core/releases"; public const string NUrl = @"https://github.com/2dust/v2rayN/releases"; public const string MihomoCoreUrl = "https://github.com/MetaCubeX/mihomo/releases"; public const string HysteriaCoreUrl = "https://github.com/apernet/hysteria/releases"; public const string NaiveproxyCoreUrl = "https://github.com/klzgrad/naiveproxy/releases"; public const string TuicCoreUrl = "https://github.com/EAimTY/tuic/releases"; public const string SingboxCoreUrl = "https://github.com/SagerNet/sing-box/releases"; public const string GeoUrl = "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/{0}.dat"; public const string SpeedPingTestUrl = @"https://www.google.com/generate_204"; public const string JuicityCoreUrl = "https://github.com/juicity/juicity/releases";
public const string SingboxRulesetUrl = @"https://raw.githubusercontent.com/2dust/sing-box-rules/rule-set-{0}/{1}.srs"; public const string IPAPIUrl = "https://api.ip.sb/geoip"; public const string PromotionUrl = @"aHR0cHM6Ly85LjIzNDQ1Ni54eXovYWJjLmh0bWw="; public const string ConfigFileName = "guiNConfig.json"; public const string CoreConfigFileName = "config.json"; public const string CorePreConfigFileName = "configPre.json"; public const string CoreSpeedtestConfigFileName = "configSpeedtest.json"; public const string CoreMultipleLoadConfigFileName = "configMultipleLoad.json"; public const string ClashMixinConfigFileName = "Mixin.yaml"; public const string NamespaceSample = "ServiceLib.Sample."; public const string V2raySampleClient = NamespaceSample + "SampleClientConfig"; public const string SingboxSampleClient = NamespaceSample + "SingboxSampleClientConfig"; public const string V2raySampleHttpRequestFileName = NamespaceSample + "SampleHttpRequest"; public const string V2raySampleHttpResponseFileName = NamespaceSample + "SampleHttpResponse"; public const string V2raySampleInbound = NamespaceSample + "SampleInbound"; public const string V2raySampleOutbound = NamespaceSample + "SampleOutbound"; public const string SingboxSampleOutbound = NamespaceSample + "SingboxSampleOutbound"; public const string CustomRoutingFileName = NamespaceSample + "custom_routing_"; public const string TunSingboxDNSFileName = NamespaceSample + "tun_singbox_dns"; public const string TunSingboxInboundFileName = NamespaceSample + "tun_singbox_inbound"; public const string TunSingboxRulesFileName = NamespaceSample + "tun_singbox_rules"; public const string DNSV2rayNormalFileName = NamespaceSample + "dns_v2ray_normal"; public const string DNSSingboxNormalFileName = NamespaceSample + "dns_singbox_normal"; public const string ClashMixinYaml = NamespaceSample + "clash_mixin_yaml"; public const string ClashTunYaml = NamespaceSample + "clash_tun_yaml"; public const string LinuxAutostartConfig = NamespaceSample + "linux_autostart_config"; public const string PacFileName = NamespaceSample + "pac"; public const string DefaultSecurity = "auto"; public const string DefaultNetwork = "tcp"; public const string TcpHeaderHttp = "http"; public const string None = "none"; public const string ProxyTag = "proxy"; public const string DirectTag = "direct"; public const string BlockTag = "block"; public const string StreamSecurity = "tls"; public const string StreamSecurityReality = "reality"; public const string Loopback = "127.0.0.1"; public const string InboundAPIProtocol = "dokodemo-door"; public const string HttpProtocol = "http://"; public const string HttpsProtocol = "https://"; public const string SocksProtocol = "socks://"; public const string Socks5Protocol = "socks5://"; public const string UserEMail = "t@t.tt"; public const string AutoRunRegPath = @"Software\Microsoft\Windows\CurrentVersion\Run"; public const string AutoRunName = "v2rayNAutoRun"; public const string SystemProxyExceptionsWindows = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*"; public const string SystemProxyExceptionsLinux = "localhost,127.0.0.0/8,::1"; public const string RoutingRuleComma = "<COMMA>"; public const string GrpcGunMode = "gun"; public const string GrpcMultiMode = "multi"; public const int MaxPort = 65536; public const string DelayUnit = ""; public const string SpeedUnit = ""; public const int MinFontSize = 8; public const string RebootAs = "rebootas"; public const string AvaAssets = "avares://v2rayN/Assets/"; public const string LocalAppData = "V2RAYN_LOCAL_APPLICATION_DATA"; public const string V2RayLocalAsset = "V2RAY_LOCATION_ASSET"; public const string XrayLocalAsset = "XRAY_LOCATION_ASSET"; public static readonly List<string> IEProxyProtocols = [ "{ip}:{http_port}", "socks={ip}:{socks_port}", "http={ip}:{http_port};https={ip}:{http_port};ftp={ip}:{http_port};socks={ip}:{socks_port}", "http=http://{ip}:{http_port};https=http://{ip}:{http_port}", "" ]; public static readonly List<string> SubConvertUrls = [ @"https://sub.xeton.dev/sub?url={0}", @"https://api.dler.io/sub?url={0}", @"http://127.0.0.1:25500/sub?url={0}", "" ]; public static readonly List<string> SubConvertConfig = [@"https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"]; public static readonly List<string> SubConvertTargets = [ "", "mixed", "v2ray", "clash", "ss" ]; public static readonly List<string> SpeedTestUrls = [ @"https://speed.cloudflare.com/__down?bytes=100000000", @"https://speed.cloudflare.com/__down?bytes=50000000", @"https://speed.cloudflare.com/__down?bytes=10000000", @"https://cachefly.cachefly.net/50mb.test" ]; public static readonly List<string> SpeedPingTestUrls = [ @"https://www.google.com/generate_204", @"https://www.gstatic.com/generate_204", @"https://www.apple.com/library/test/success.html", @"http://www.msftconnecttest.com/connecttest.txt" ]; public static readonly List<string> GeoFilesSources = [ "", @"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/{0}.dat", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-v2ray-rules@release/{0}.dat" ]; public static readonly List<string> SingboxRulesetSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-rules-dat@release/sing-box/rule-set-{0}/{1}.srs", @"https://cdn.jsdelivr.net/gh/chocolate4u/Iran-sing-box-rules@rule-set/{1}.srs" ]; public static readonly List<string> RoutingRulesSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/template.json", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/template.json" ]; public static readonly List<string> DNSTemplateSources = [ "", @"https://cdn.jsdelivr.net/gh/runetfreedom/russia-v2ray-custom-routing-list@main/v2rayN/", @"https://cdn.jsdelivr.net/gh/Chocolate4U/Iran-v2ray-rules@main/v2rayN/" ]; public static readonly Dictionary<string, string> UserAgentTexts = new() { {"chrome","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" }, {"firefox","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" }, {"safari","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15" }, {"edge","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.70" }, {"none",""} }; public const string Hysteria2ProtocolShare = "hy2://"; public static readonly Dictionary<EConfigType, string> ProtocolShares = new() { {EConfigType.VMess,"vmess://"}, {EConfigType.Shadowsocks,"ss://"}, {EConfigType.SOCKS,"socks://"}, {EConfigType.VLESS,"vless://"}, {EConfigType.Trojan,"trojan://"}, {EConfigType.Hysteria2,"hysteria2://"}, {EConfigType.TUIC,"tuic://"}, {EConfigType.WireGuard,"wireguard://"} }; public static readonly Dictionary<EConfigType, string> ProtocolTypes = new() { {EConfigType.VMess,"vmess"}, {EConfigType.Shadowsocks,"shadowsocks"}, {EConfigType.SOCKS,"socks"}, {EConfigType.HTTP,"http"}, {EConfigType.VLESS,"vless"}, {EConfigType.Trojan,"trojan"}, {EConfigType.Hysteria2,"hysteria2"}, {EConfigType.TUIC,"tuic"}, {EConfigType.WireGuard,"wireguard"} }; public static readonly List<string> VmessSecurities = [ "aes-128-gcm", "chacha20-poly1305", "auto", "none", "zero" ]; public static readonly List<string> SsSecurities = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "none", "plain" ]; public static readonly List<string> SsSecuritiesInXray = [ "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "xchacha20-poly1305", "xchacha20-ietf-poly1305", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305" ]; public static readonly List<string> SsSecuritiesInSingbox = [ "aes-256-gcm", "aes-192-gcm", "aes-128-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "none", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "rc4-md5", "chacha20-ietf", "xchacha20" ]; public static readonly List<string> Flows = [ "", "xtls-rprx-vision", "xtls-rprx-vision-udp443" ]; public static readonly List<string> Networks = [ "tcp", "kcp", "ws", "httpupgrade", "xhttp", "h2", "quic", "grpc" ]; public static readonly List<string> KcpHeaderTypes = [ "srtp", "utp", "wechat-video", "dtls", "wireguard" ]; public static readonly List<string> CoreTypes = [ "Xray", "sing_box" ]; public static readonly List<string> DomainStrategies = [ "AsIs", "IPIfNonMatch", "IPOnDemand" ]; public static readonly List<string> DomainStrategies4Singbox = [ "ipv4_only", "ipv6_only", "prefer_ipv4", "prefer_ipv6", "" ]; public static readonly List<string> DomainMatchers = [ "linear", "mph", "" ]; public static readonly List<string> Fingerprints = [ "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized", "" ]; public static readonly List<string> UserAgent = [ "chrome", "firefox", "safari", "edge", "none" ]; public static readonly List<string> XhttpMode = [ "auto", "packet-up", "stream-up", "stream-one" ]; public static readonly List<string> AllowInsecure = [ "true", "false", "" ]; public static readonly List<string> DomainStrategy4Freedoms = [ "AsIs", "UseIP", "UseIPv4", "UseIPv6", "" ]; public static readonly List<string> SingboxDomainStrategy4Out = [ "ipv4_only", "prefer_ipv4", "prefer_ipv6", "ipv6_only", "" ]; public static readonly List<string> DomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "localhost" ]; public static readonly List<string> SingboxDomainDNSAddress = [ "223.5.5.5", "223.6.6.6", "dhcp://auto" ]; public static readonly List<string> Languages = [ "zh-Hans", "zh-Hant", "en", "fa-Ir", "ru", "hu" ]; public static readonly List<string> Alpns = [ "h3", "h2", "http/1.1", "h3,h2", "h2,http/1.1", "h3,h2,http/1.1", "" ]; public static readonly List<string> LogLevels = [ "debug", "info", "warning", "error", "none" ]; public static readonly List<string> InboundTags = [ "socks", "socks2", "socks3" ]; public static readonly List<string> RuleProtocols = [ "http", "tls", "bittorrent" ]; public static readonly List<string> RuleNetworks = [ "", "tcp", "udp", "tcp,udp" ]; public static readonly List<string> destOverrideProtocols = [ "http", "tls", "quic", "fakedns", "fakedns+others" ]; public static readonly List<string> TunMtus = [ "1280", "1408", "1500", "9000" ]; public static readonly List<string> TunStacks = [ "gvisor", "system", "mixed" ]; public static readonly List<string> PresetMsgFilters = [ "proxy", "direct", "block", "" ]; public static readonly List<string> SingboxMuxs = [ "h2mux", "smux", "yamux", "" ]; public static readonly List<string> TuicCongestionControls = [ "cubic", "new_reno", "bbr" ]; public static readonly List<string> allowSelectType = [ "selector", "urltest", "loadbalance", "fallback" ]; public static readonly List<string> notAllowTestType = [ "selector", "urltest", "direct", "reject", "compatible", "pass", "loadbalance", "fallback" ]; public static readonly List<string> proxyVehicleType = [ "file", "http" ]; #endregion const } }
public const string BrookCoreUrl = "https://github.com/txthinking/brook/releases";
csharp
2025-02-03T07:06:21
2dust/v2rayN
b2feaf3ba986863ce337b1de8f0731a7ca27c791
v2rayN/ServiceLib/Handler/AutoStartupHandler.cs
using System.Diagnostics; using System.Security.Principal; using System.Text.RegularExpressions; namespace ServiceLib.Handler { public static class AutoStartupHandler { private static readonly string _tag = "AutoStartupHandler"; public static async Task<bool> UpdateTask(Config config) { if (Utils.IsWindows()) { await ClearTaskWindows(); if (config.GuiItem.AutoRun) { await SetTaskWindows(); } } else if (Utils.IsLinux()) { await ClearTaskLinux(); if (config.GuiItem.AutoRun) { await SetTaskLinux(); } } else if (Utils.IsOSX()) { await ClearTaskOSX(); if (config.GuiItem.AutoRun) { await SetTaskOSX(); } } return true; } #region Windows private static async Task ClearTaskWindows() { var autoRunName = GetAutoRunNameWindows(); WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, ""); if (Utils.IsAdministrator()) { AutoStartTaskService(autoRunName, "", ""); } await Task.CompletedTask; } private static async Task SetTaskWindows() { try { var autoRunName = GetAutoRunNameWindows(); var exePath = Utils.GetExePath(); if (Utils.IsAdministrator()) { AutoStartTaskService(autoRunName, exePath, ""); } else { WindowsUtils.RegWriteValue(Global.AutoRunRegPath, autoRunName, exePath.AppendQuotes()); } } catch (Exception ex) { Logging.SaveLog(_tag, ex); } await Task.CompletedTask; } /// <summary> /// Auto Start via TaskService /// </summary> /// <param name="taskName"></param> /// <param name="fileName"></param> /// <param name="description"></param> /// <exception cref="ArgumentNullException"></exception> public static void AutoStartTaskService(string taskName, string fileName, string description) { if (Utils.IsNullOrEmpty(taskName)) { return; } var logonUser = WindowsIdentity.GetCurrent().Name; using var taskService = new Microsoft.Win32.TaskScheduler.TaskService(); var tasks = taskService.RootFolder.GetTasks(new Regex(taskName)); if (Utils.IsNullOrEmpty(fileName)) { foreach (var t in tasks) { taskService.RootFolder.DeleteTask(t.Name); } return; } var task = taskService.NewTask(); task.RegistrationInfo.Description = description; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.StopIfGoingOnBatteries = false; task.Settings.RunOnlyIfIdle = false; task.Settings.IdleSettings.StopOnIdleEnd = false; task.Settings.ExecutionTimeLimit = TimeSpan.Zero; task.Triggers.Add(new Microsoft.Win32.TaskScheduler.LogonTrigger { UserId = logonUser, Delay = TimeSpan.FromSeconds(10) }); task.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest; task.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(fileName.AppendQuotes(), null, Path.GetDirectoryName(fileName))); taskService.RootFolder.RegisterTaskDefinition(taskName, task); } private static string GetAutoRunNameWindows() { return $"{Global.AutoRunName}_{Utils.GetMd5(Utils.StartupPath())}"; } #endregion Windows #region Linux private static async Task ClearTaskLinux() { try { File.Delete(GetHomePathLinux()); } catch (Exception ex) { Logging.SaveLog(_tag, ex); } await Task.CompletedTask; } private static async Task SetTaskLinux() { try { var linuxConfig = Utils.GetEmbedText(Global.LinuxAutostartConfig); if (linuxConfig.IsNotEmpty()) { linuxConfig = linuxConfig.Replace("$ExecPath$", Utils.GetExePath()); Logging.SaveLog(linuxConfig); var homePath = GetHomePathLinux(); await File.WriteAllTextAsync(homePath, linuxConfig); } } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } private static string GetHomePathLinux() { var homePath = Path.Combine(Utils.GetHomePath(), ".config", "autostart", $"{Global.AppName}.desktop"); Directory.CreateDirectory(Path.GetDirectoryName(homePath)); return homePath; } #endregion Linux
} }
#region macOS private static async Task ClearTaskOSX() { try { var launchAgentPath = GetLaunchAgentPathMacOS(); if (File.Exists(launchAgentPath)) { var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" }; await Utils.GetCliWrapOutput("/bin/bash", args); File.Delete(launchAgentPath); } } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } private static async Task SetTaskOSX() { try { var plistContent = GenerateLaunchAgentPlist(); var launchAgentPath = GetLaunchAgentPathMacOS(); await File.WriteAllTextAsync(launchAgentPath, plistContent); var args = new[] { "-c", $"launchctl load -w \"{launchAgentPath}\"" }; await Utils.GetCliWrapOutput("/bin/bash", args); } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } private static string GetLaunchAgentPathMacOS() { var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var launchAgentPath = Path.Combine(homePath, "Library", "LaunchAgents", $"{Global.AppName}-LaunchAgent.plist"); Directory.CreateDirectory(Path.GetDirectoryName(launchAgentPath)); return launchAgentPath; } private static string GenerateLaunchAgentPlist() { var exePath = Utils.GetExePath(); var appName = Path.GetFileNameWithoutExtension(exePath); return $@"<?xml version=""1.0"" encoding=""UTF-8""?> <!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd""> <plist version=""1.0""> <dict> <key>Label</key> <string>{Global.AppName}-LaunchAgent</string> <key>ProgramArguments</key> <array> <string>/bin/sh</string> <string>-c</string> <string>if ! pgrep -x ""{appName}"" > /dev/null; then ""{exePath}""; fi</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <false/> </dict> </plist>"; } #endregion macOS
csharp
2025-01-30T05:24:01
2dust/v2rayN
c0f8b6b84ca3920992b0f310d4f51538f52a83c0
v2rayN/v2rayN.Desktop/Views/MainWindow.axaml.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.Notifications; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.ReactiveUI; using Avalonia.Threading; using DialogHostAvalonia; using MsBox.Avalonia.Enums; using ReactiveUI; using Splat; using System.Reactive.Disposables; using v2rayN.Desktop.Common; namespace v2rayN.Desktop.Views { public partial class MainWindow : ReactiveWindow<MainWindowViewModel> { private static Config _config; private WindowNotificationManager? _manager; private CheckUpdateView? _checkUpdateView; private BackupAndRestoreView? _backupAndRestoreView; private bool _blCloseByUser = false; public MainWindow() { InitializeComponent(); _config = AppHandler.Instance.Config; _manager = new WindowNotificationManager(TopLevel.GetTopLevel(this)) { MaxItems = 3, Position = NotificationPosition.BottomRight }; this.KeyDown += MainWindow_KeyDown; menuSettingsSetUWP.Click += menuSettingsSetUWP_Click; menuPromotion.Click += menuPromotion_Click; menuCheckUpdate.Click += MenuCheckUpdate_Click; menuBackupAndRestore.Click += MenuBackupAndRestore_Click; menuClose.Click += MenuClose_Click; MessageBus.Current.Listen<string>(EMsgCommand.SendSnackMsg.ToString()).Subscribe(DelegateSnackMsg); ViewModel = new MainWindowViewModel(UpdateViewHandler); Locator.CurrentMutable.RegisterLazySingleton(() => ViewModel, typeof(MainWindowViewModel)); switch (_config.UiItem.MainGirdOrientation) { case EGirdOrientation.Horizontal: tabProfiles.Content ??= new ProfilesView(this); tabMsgView.Content ??= new MsgView(); tabClashProxies.Content ??= new ClashProxiesView(); tabClashConnections.Content ??= new ClashConnectionsView(); gridMain.IsVisible = true; break; case EGirdOrientation.Vertical: tabProfiles1.Content ??= new ProfilesView(this); tabMsgView1.Content ??= new MsgView(); tabClashProxies1.Content ??= new ClashProxiesView(); tabClashConnections1.Content ??= new ClashConnectionsView(); gridMain1.IsVisible = true; break; case EGirdOrientation.Tab: default: tabProfiles2.Content ??= new ProfilesView(this); tabMsgView2.Content ??= new MsgView(); tabClashProxies2.Content ??= new ClashProxiesView(); tabClashConnections2.Content ??= new ClashConnectionsView(); gridMain2.IsVisible = true; break; } conTheme.Content ??= new ThemeSettingView(); this.WhenActivated(disposables => { //servers this.BindCommand(ViewModel, vm => vm.AddVmessServerCmd, v => v.menuAddVmessServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddVlessServerCmd, v => v.menuAddVlessServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddShadowsocksServerCmd, v => v.menuAddShadowsocksServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddSocksServerCmd, v => v.menuAddSocksServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddHttpServerCmd, v => v.menuAddHttpServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddTrojanServerCmd, v => v.menuAddTrojanServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddHysteria2ServerCmd, v => v.menuAddHysteria2Server).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddTuicServerCmd, v => v.menuAddTuicServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddWireguardServerCmd, v => v.menuAddWireguardServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddCustomServerCmd, v => v.menuAddCustomServer).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddServerViaClipboardCmd, v => v.menuAddServerViaClipboard).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddServerViaScanCmd, v => v.menuAddServerViaScan).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.AddServerViaImageCmd, v => v.menuAddServerViaImage).DisposeWith(disposables); //sub this.BindCommand(ViewModel, vm => vm.SubSettingCmd, v => v.menuSubSetting).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SubUpdateCmd, v => v.menuSubUpdate).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SubUpdateViaProxyCmd, v => v.menuSubUpdateViaProxy).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SubGroupUpdateCmd, v => v.menuSubGroupUpdate).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SubGroupUpdateViaProxyCmd, v => v.menuSubGroupUpdateViaProxy).DisposeWith(disposables); //setting this.BindCommand(ViewModel, vm => vm.OptionSettingCmd, v => v.menuOptionSetting).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.RoutingSettingCmd, v => v.menuRoutingSetting).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.DNSSettingCmd, v => v.menuDNSSetting).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.GlobalHotkeySettingCmd, v => v.menuGlobalHotkeySetting).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.RebootAsAdminCmd, v => v.menuRebootAsAdmin).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.ClearServerStatisticsCmd, v => v.menuClearServerStatistics).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.OpenTheFileLocationCmd, v => v.menuOpenTheFileLocation).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.RegionalPresetDefaultCmd, v => v.menuRegionalPresetsDefault).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.RegionalPresetRussiaCmd, v => v.menuRegionalPresetsRussia).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.RegionalPresetIranCmd, v => v.menuRegionalPresetsIran).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.ReloadCmd, v => v.menuReload).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.BlReloadEnabled, v => v.menuReload.IsEnabled).DisposeWith(disposables); switch (_config.UiItem.MainGirdOrientation) { case EGirdOrientation.Horizontal: this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabMsgView.IsVisible).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashProxies.IsVisible).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashConnections.IsVisible).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TabMainSelectedIndex, v => v.tabMain.SelectedIndex).DisposeWith(disposables); break; case EGirdOrientation.Vertical: this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabMsgView1.IsVisible).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashProxies1.IsVisible).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashConnections1.IsVisible).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TabMainSelectedIndex, v => v.tabMain1.SelectedIndex).DisposeWith(disposables); break; case EGirdOrientation.Tab: default: this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashProxies2.IsVisible).DisposeWith(disposables); this.OneWayBind(ViewModel, vm => vm.ShowClashUI, v => v.tabClashConnections2.IsVisible).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TabMainSelectedIndex, v => v.tabMain2.SelectedIndex).DisposeWith(disposables); break; } }); this.Title = $"{Utils.GetVersion()}"; if (Utils.IsWindows()) { ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false); menuGlobalHotkeySetting.IsVisible = false; } else { if (AppHandler.Instance.IsAdministrator) { this.Title = $"{Utils.GetVersion()} - {ResUI.TbSettingsLinuxSudoPasswordNotSudoRunApp}"; NoticeHandler.Instance.SendMessageAndEnqueue(ResUI.TbSettingsLinuxSudoPasswordNotSudoRunApp); } menuRebootAsAdmin.IsVisible = false; menuSettingsSetUWP.IsVisible = false; menuGlobalHotkeySetting.IsVisible = false; } menuAddServerViaScan.IsVisible = false; RestoreUI(); AddHelpMenuItem(); //WindowsHandler.Instance.RegisterGlobalHotkey(_config, OnHotkeyHandler, null); MessageBus.Current.Listen<string>(EMsgCommand.AppExit.ToString()).Subscribe(StorageUI); } #region Event private void OnProgramStarted(object state, bool timeout) { Dispatcher.UIThread.Post(() => ShowHideWindow(true), DispatcherPriority.Default); } private void DelegateSnackMsg(string content) { Dispatcher.UIThread.Post(() => _manager?.Show(new Notification(null, content, NotificationType.Information)), DispatcherPriority.Normal); } private async Task<bool> UpdateViewHandler(EViewAction action, object? obj) { switch (action) { case EViewAction.AddServerWindow: if (obj is null) return false; return await new AddServerWindow((ProfileItem)obj).ShowDialog<bool>(this); case EViewAction.AddServer2Window: if (obj is null) return false; return await new AddServer2Window((ProfileItem)obj).ShowDialog<bool>(this); case EViewAction.DNSSettingWindow: return await new DNSSettingWindow().ShowDialog<bool>(this); case EViewAction.RoutingSettingWindow: return await new RoutingSettingWindow().ShowDialog<bool>(this); case EViewAction.OptionSettingWindow: return await new OptionSettingWindow().ShowDialog<bool>(this); case EViewAction.GlobalHotkeySettingWindow: return await new GlobalHotkeySettingWindow().ShowDialog<bool>(this); case EViewAction.SubSettingWindow: return await new SubSettingWindow().ShowDialog<bool>(this); case EViewAction.ShowHideWindow: Dispatcher.UIThread.Post(() => ShowHideWindow((bool?)obj), DispatcherPriority.Default); break; case EViewAction.DispatcherStatistics: if (obj is null) return false; Dispatcher.UIThread.Post(() => ViewModel?.SetStatisticsResult((ServerSpeedItem)obj), DispatcherPriority.Default); break; case EViewAction.DispatcherReload: Dispatcher.UIThread.Post(() => ViewModel?.ReloadResult(), DispatcherPriority.Default); break; case EViewAction.Shutdown: if (obj != null && _blCloseByUser == false) { _blCloseByUser = (bool)obj; } StorageUI(); if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.Shutdown(); } break; case EViewAction.ScanScreenTask: await ScanScreenTaskAsync(); break; case EViewAction.ScanImageTask: await ScanImageTaskAsync(); break; case EViewAction.AddServerViaClipboard: var clipboardData = await AvaUtils.GetClipboardData(this); ViewModel?.AddServerViaClipboardAsync(clipboardData); break; case EViewAction.AdjustMainLvColWidth: Dispatcher.UIThread.Post(() => Locator.Current.GetService<ProfilesViewModel>()?.AutofitColumnWidthAsync(), DispatcherPriority.Default); break; } return await Task.FromResult(true); } private void OnHotkeyHandler(EGlobalHotkey e) { switch (e) { case EGlobalHotkey.ShowForm: ShowHideWindow(null); break; //case EGlobalHotkey.SystemProxyClear: // ViewModel?.SetListenerType(ESysProxyType.ForcedClear); // break; //case EGlobalHotkey.SystemProxySet: // ViewModel?.SetListenerType(ESysProxyType.ForcedChange); // break; //case EGlobalHotkey.SystemProxyUnchanged: // ViewModel?.SetListenerType(ESysProxyType.Unchanged); // break; //case EGlobalHotkey.SystemProxyPac: // ViewModel?.SetListenerType(ESysProxyType.Pac); // break; } } protected override async void OnClosing(WindowClosingEventArgs e) { if (_blCloseByUser) { return; } Logging.SaveLog("OnClosing -> " + e.CloseReason.ToString()); switch (e.CloseReason) { case WindowCloseReason.OwnerWindowClosing or WindowCloseReason.WindowClosing: e.Cancel = true; ShowHideWindow(false); break; case WindowCloseReason.ApplicationShutdown or WindowCloseReason.OSShutdown: await ViewModel?.MyAppExitAsync(true); break; } base.OnClosing(e); } private async void MainWindow_KeyDown(object? sender, KeyEventArgs e) { if (e.KeyModifiers is KeyModifiers.Control or KeyModifiers.Meta) { switch (e.Key) { case Key.V: var clipboardData = await AvaUtils.GetClipboardData(this); ViewModel?.AddServerViaClipboardAsync(clipboardData); break; case Key.S: await ScanScreenTaskAsync(); break; } } else { if (e.Key == Key.F5) { ViewModel?.Reload(); } } } private void menuPromotion_Click(object? sender, RoutedEventArgs e) { ProcUtils.ProcessStart($"{Utils.Base64Decode(Global.PromotionUrl)}?t={DateTime.Now.Ticks}"); } private void menuSettingsSetUWP_Click(object? sender, RoutedEventArgs e) { ProcUtils.ProcessStart(Utils.GetBinPath("EnableLoopback.exe")); } public async Task ScanScreenTaskAsync() { //ShowHideWindow(false); NoticeHandler.Instance.SendMessageAndEnqueue("Not yet implemented.(还未实现)"); return; //if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) //{ // //var bytes = QRCodeHelper.CaptureScreen(desktop); // //await ViewModel?.ScanScreenResult(bytes); //} //ShowHideWindow(true); } private async Task ScanImageTaskAsync() { var fileName = await UI.OpenFileDialog(this, null); if (fileName.IsNullOrEmpty()) { return; } await ViewModel?.ScanImageResult(fileName); } private void MenuCheckUpdate_Click(object? sender, RoutedEventArgs e) { _checkUpdateView ??= new CheckUpdateView(); DialogHost.Show(_checkUpdateView); } private void MenuBackupAndRestore_Click(object? sender, RoutedEventArgs e) { _backupAndRestoreView ??= new BackupAndRestoreView(this); DialogHost.Show(_backupAndRestoreView); } private async void MenuClose_Click(object? sender, RoutedEventArgs e) { if (await UI.ShowYesNo(this, ResUI.menuExitTips) == ButtonResult.No) { return; } _blCloseByUser = true; StorageUI(); await ViewModel?.MyAppExitAsync(false); } #endregion Event #region UI public void ShowHideWindow(bool? blShow) { var bl = blShow ?? (!_config.UiItem.ShowInTaskbar ^ (WindowState==WindowState.Minimized)); if (bl) { this.Show(); if (this.WindowState == WindowState.Minimized) { this.WindowState = WindowState.Normal; } this.Activate(); this.Focus(); } else { if (Utils.IsOSX() || _config.UiItem.Hide2TrayWhenClose) {
this.Hide(); } else { this.WindowState = WindowState.Minimized; } } _config.UiItem.ShowInTaskbar = bl; } private void RestoreUI() { if (_config.UiItem.MainWidth > 0 && _config.UiItem.MainHeight > 0) { Width = _config.UiItem.MainWidth; Height = _config.UiItem.MainHeight; } if (_config.UiItem.MainGirdHeight1 > 0 && _config.UiItem.MainGirdHeight2 > 0) { if (_config.UiItem.MainGirdOrientation == EGirdOrientation.Horizontal) { gridMain.ColumnDefinitions[0].Width = new GridLength(_config.UiItem.MainGirdHeight1, GridUnitType.Star); gridMain.ColumnDefinitions[2].Width = new GridLength(_config.UiItem.MainGirdHeight2, GridUnitType.Star); } else if (_config.UiItem.MainGirdOrientation == EGirdOrientation.Vertical) { gridMain1.RowDefinitions[0].Height = new GridLength(_config.UiItem.MainGirdHeight1, GridUnitType.Star); gridMain1.RowDefinitions[2].Height = new GridLength(_config.UiItem.MainGirdHeight2, GridUnitType.Star); } } } private void StorageUI(string? n = null) { _config.UiItem.MainWidth = Utils.ToInt(this.Width); _config.UiItem.MainHeight = Utils.ToInt(this.Height); if (_config.UiItem.MainGirdOrientation == EGirdOrientation.Horizontal) { _config.UiItem.MainGirdHeight1 = Math.Ceiling(gridMain.ColumnDefinitions[0].ActualWidth + 0.1); _config.UiItem.MainGirdHeight2 = Math.Ceiling(gridMain.ColumnDefinitions[2].ActualWidth + 0.1); } else if (_config.UiItem.MainGirdOrientation == EGirdOrientation.Vertical) { _config.UiItem.MainGirdHeight1 = Math.Ceiling(gridMain1.RowDefinitions[0].ActualHeight + 0.1); _config.UiItem.MainGirdHeight2 = Math.Ceiling(gridMain1.RowDefinitions[2].ActualHeight + 0.1); } } private void AddHelpMenuItem() { var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(); foreach (var it in coreInfo .Where(t => t.CoreType != ECoreType.v2fly && t.CoreType != ECoreType.hysteria)) { var item = new MenuItem() { Tag = it.Url?.Replace(@"/releases", ""), Header = string.Format(ResUI.menuWebsiteItem, it.CoreType.ToString().Replace("_", " ")).UpperFirstChar() }; item.Click += MenuItem_Click; menuHelp.Items.Add(item); } } private void MenuItem_Click(object? sender, RoutedEventArgs e) { if (sender is MenuItem item) { ProcUtils.ProcessStart(item.Tag?.ToString()); } } #endregion UI } }
foreach (var ownedWindow in this.OwnedWindows) { ownedWindow.Close(); }
csharp
2025-01-30T02:12:59
2dust/v2rayN
54fe669d89fc4c347cbc52fea95bb3a9114a3451
v2rayN/ServiceLib/Handler/CoreHandler.cs
using System.Diagnostics; using System.Text; namespace ServiceLib.Handler { /// <summary> /// Core process processing class /// </summary> public class CoreHandler { private static readonly Lazy<CoreHandler> _instance = new(() => new()); public static CoreHandler Instance => _instance.Value; private Config _config; private Process? _process; private Process? _processPre; private int _linuxSudoPid = -1; private Action<bool, string>? _updateFunc; private const string _tag = "CoreHandler"; public async Task Init(Config config, Action<bool, string> updateFunc) { _config = config; _updateFunc = updateFunc; Environment.SetEnvironmentVariable(Global.V2RayLocalAsset, Utils.GetBinPath(""), EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable(Global.XrayLocalAsset, Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
if (Utils.IsNonWindows()) { var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(); foreach (var it in coreInfo) { if (it.CoreType == ECoreType.v2rayN) { if (Utils.UpgradeAppExists(out var upgradeFileName)) { await Utils.SetLinuxChmod(upgradeFileName); } continue; } foreach (var name in it.CoreExes) { var exe = Utils.GetBinPath(Utils.GetExeName(name), it.CoreType.ToString()); if (File.Exists(exe)) { await Utils.SetLinuxChmod(exe); } } } } } public async Task LoadCore(ProfileItem? node) { if (node == null) { UpdateFunc(false, ResUI.CheckServerSettings); return; } var fileName = Utils.GetConfigPath(Global.CoreConfigFileName); var result = await CoreConfigHandler.GenerateClientConfig(node, fileName); if (result.Success != true) { UpdateFunc(true, result.Msg); return; } UpdateFunc(false, $"{node.GetSummary()}"); UpdateFunc(false, $"{Utils.GetRuntimeInfo()}"); UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))); await CoreStop(); await Task.Delay(100); await CoreStart(node); await CoreStartPreService(node); if (_process != null) { UpdateFunc(true, $"{node.GetSummary()}"); } } public async Task<int> LoadCoreConfigSpeedtest(List<ServerTestItem> selecteds) { var coreType = selecteds.Exists(t => t.ConfigType is EConfigType.Hysteria2 or EConfigType.TUIC or EConfigType.WireGuard) ? ECoreType.sing_box : ECoreType.Xray; var configPath = Utils.GetConfigPath(Global.CoreSpeedtestConfigFileName); var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, configPath, selecteds, coreType); UpdateFunc(false, result.Msg); if (result.Success != true) { return -1; } UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))); UpdateFunc(false, configPath); var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(coreType); var proc = await RunProcess(coreInfo, Global.CoreSpeedtestConfigFileName, true, false); if (proc is null) { return -1; } return proc.Id; } public async Task CoreStop() { try { if (_process != null) { await ProcUtils.ProcessKill(_process, true); _process = null; } if (_processPre != null) { await ProcUtils.ProcessKill(_processPre, true); _processPre = null; } if (_linuxSudoPid > 0) { await KillProcessAsLinuxSudo(); } _linuxSudoPid = -1; } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } #region Private private async Task CoreStart(ProfileItem node) { var coreType = _config.RunningCoreType = AppHandler.Instance.GetCoreType(node, node.ConfigType); var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(coreType); var displayLog = node.ConfigType != EConfigType.Custom || node.DisplayLog; var proc = await RunProcess(coreInfo, Global.CoreConfigFileName, displayLog, true); if (proc is null) { return; } _process = proc; } private async Task CoreStartPreService(ProfileItem node) { if (_process != null && !_process.HasExited) { var coreType = AppHandler.Instance.GetCoreType(node, node.ConfigType); var itemSocks = await ConfigHandler.GetPreSocksItem(_config, node, coreType); if (itemSocks != null) { var preCoreType = itemSocks.CoreType ?? ECoreType.sing_box; var fileName = Utils.GetConfigPath(Global.CorePreConfigFileName); var result = await CoreConfigHandler.GenerateClientConfig(itemSocks, fileName); if (result.Success) { var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(preCoreType); var proc = await RunProcess(coreInfo, Global.CorePreConfigFileName, true, true); if (proc is null) { return; } _processPre = proc; } } } } private void UpdateFunc(bool notify, string msg) { _updateFunc?.Invoke(notify, msg); } private bool IsNeedSudo(ECoreType eCoreType) { return _config.TunModeItem.EnableTun && eCoreType == ECoreType.sing_box && (Utils.IsNonWindows()) //&& _config.TunModeItem.LinuxSudoPwd.IsNotEmpty() ; } #endregion Private #region Process private async Task<Process?> RunProcess(CoreInfo? coreInfo, string configPath, bool displayLog, bool mayNeedSudo) { var fileName = CoreInfoHandler.Instance.GetCoreExecFile(coreInfo, out var msg); if (Utils.IsNullOrEmpty(fileName)) { UpdateFunc(false, msg); return null; } try { Process proc = new() { StartInfo = new() { FileName = fileName, Arguments = string.Format(coreInfo.Arguments, configPath), WorkingDirectory = Utils.GetConfigPath(), UseShellExecute = false, RedirectStandardOutput = displayLog, RedirectStandardError = displayLog, CreateNoWindow = true, StandardOutputEncoding = displayLog ? Encoding.UTF8 : null, StandardErrorEncoding = displayLog ? Encoding.UTF8 : null, } }; var isNeedSudo = mayNeedSudo && IsNeedSudo(coreInfo.CoreType); if (isNeedSudo) { await RunProcessAsLinuxSudo(proc, fileName, coreInfo, configPath); } if (displayLog) { proc.OutputDataReceived += (sender, e) => { if (Utils.IsNullOrEmpty(e.Data)) return; UpdateFunc(false, e.Data + Environment.NewLine); }; proc.ErrorDataReceived += (sender, e) => { if (Utils.IsNullOrEmpty(e.Data)) return; UpdateFunc(false, e.Data + Environment.NewLine); }; } proc.Start(); if (isNeedSudo && _config.TunModeItem.LinuxSudoPwd.IsNotEmpty()) { var pwd = DesUtils.Decrypt(_config.TunModeItem.LinuxSudoPwd); await Task.Delay(10); await proc.StandardInput.WriteLineAsync(pwd); await Task.Delay(10); await proc.StandardInput.WriteLineAsync(pwd); } if (isNeedSudo) _linuxSudoPid = proc.Id; if (displayLog) { proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); } await Task.Delay(500); AppHandler.Instance.AddProcess(proc.Handle); if (proc is null or { HasExited: true }) { throw new Exception(ResUI.FailedToRunCore); } return proc; } catch (Exception ex) { Logging.SaveLog(_tag, ex); UpdateFunc(true, ex.Message); return null; } } #endregion Process #region Linux private async Task RunProcessAsLinuxSudo(Process proc, string fileName, CoreInfo coreInfo, string configPath) { var cmdLine = $"{fileName.AppendQuotes()} {string.Format(coreInfo.Arguments, Utils.GetConfigPath(configPath).AppendQuotes())}"; var shFilePath = await CreateLinuxShellFile(cmdLine, "run_as_sudo.sh"); proc.StartInfo.FileName = shFilePath; proc.StartInfo.Arguments = ""; proc.StartInfo.WorkingDirectory = ""; if (_config.TunModeItem.LinuxSudoPwd.IsNotEmpty()) { proc.StartInfo.StandardInputEncoding = Encoding.UTF8; proc.StartInfo.RedirectStandardInput = true; } } private async Task KillProcessAsLinuxSudo() { var cmdLine = $"kill {_linuxSudoPid}"; var shFilePath = await CreateLinuxShellFile(cmdLine, "kill_as_sudo.sh"); Process proc = new() { StartInfo = new() { FileName = shFilePath, UseShellExecute = false, CreateNoWindow = true, StandardInputEncoding = Encoding.UTF8, RedirectStandardInput = true } }; proc.Start(); if (_config.TunModeItem.LinuxSudoPwd.IsNotEmpty()) { try { var pwd = DesUtils.Decrypt(_config.TunModeItem.LinuxSudoPwd); await Task.Delay(10); await proc.StandardInput.WriteLineAsync(pwd); await Task.Delay(10); await proc.StandardInput.WriteLineAsync(pwd); } catch (Exception) { // ignored } } var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await proc.WaitForExitAsync(timeout.Token); await Task.Delay(3000); } private async Task<string> CreateLinuxShellFile(string cmdLine, string fileName) { //Shell scripts var shFilePath = Utils.GetBinPath(AppHandler.Instance.IsAdministrator ? "root_" + fileName : fileName); File.Delete(shFilePath); var sb = new StringBuilder(); sb.AppendLine("#!/bin/sh"); if (AppHandler.Instance.IsAdministrator) { sb.AppendLine($"{cmdLine}"); } else if (_config.TunModeItem.LinuxSudoPwd.IsNullOrEmpty()) { sb.AppendLine($"pkexec {cmdLine}"); } else { sb.AppendLine($"sudo -S {cmdLine}"); } await File.WriteAllTextAsync(shFilePath, sb.ToString()); await Utils.SetLinuxChmod(shFilePath); Logging.SaveLog(shFilePath); return shFilePath; } #endregion Linux } }
//Copy the bin folder to the storage location (for init) if (Environment.GetEnvironmentVariable(Global.LocalAppData) == "1") { var fromPath = Utils.GetBaseDirectory("bin"); var toPath = Utils.GetBinPath(""); if (fromPath != toPath) { FileManager.CopyDirectory(fromPath, toPath, true, false); } }
csharp
2025-01-18T08:58:44
2dust/v2rayN
cf1a8599eb08efb32b3d984a5c33378853e04fd4
v2rayN/AmazTool/UpgradeApp.cs
using System.Diagnostics; using System.IO.Compression; using System.Text; namespace AmazTool { internal class UpgradeApp { public static void Upgrade(string fileName) { Console.WriteLine($"{Resx.Resource.StartUnzipping}\n{fileName}"); Utils.Waiting(5); if (!File.Exists(fileName)) { Console.WriteLine(Resx.Resource.UpgradeFileNotFound); return; } Console.WriteLine(Resx.Resource.TryTerminateProcess); try { var existing = Process.GetProcessesByName(Utils.V2rayN); foreach (var pp in existing) { var path = pp.MainModule?.FileName ?? ""; if (path.StartsWith(Utils.GetPath(Utils.V2rayN))) { pp?.Kill(); pp?.WaitForExit(1000); } } } catch (Exception ex) { // Access may be denied without admin right. The user may not be an administrator. Console.WriteLine(Resx.Resource.FailedTerminateProcess + ex.StackTrace); } Console.WriteLine(Resx.Resource.StartUnzipping); StringBuilder sb = new(); try { var thisAppOldFile = $"{Utils.GetExePath()}.tmp"; File.Delete(thisAppOldFile); var splitKey = "/"; using var archive = ZipFile.OpenRead(fileName); foreach (var entry in archive.Entries) { try { if (entry.Length == 0) { continue; } Console.WriteLine(entry.FullName); var lst = entry.FullName.Split(splitKey); if (lst.Length == 1) continue; var fullName = string.Join(splitKey, lst[1..lst.Length]); if (string.Equals(Utils.GetExePath(), Utils.GetPath(fullName), StringComparison.OrdinalIgnoreCase)) { File.Move(Utils.GetExePath(), thisAppOldFile); } var entryOutputPath = Utils.GetPath(fullName); Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
entry.ExtractToFile(entryOutputPath, true); Console.WriteLine(entryOutputPath); } catch (Exception ex) { sb.Append(ex.StackTrace); } } } catch (Exception ex) { Console.WriteLine(Resx.Resource.FailedUpgrade + ex.StackTrace); //return; } if (sb.Length > 0) { Console.WriteLine(Resx.Resource.FailedUpgrade + sb.ToString()); //return; } Console.WriteLine(Resx.Resource.Restartv2rayN); Utils.Waiting(2); Utils.StartV2RayN(); } } }
//In the bin folder, if the file already exists, it will be skipped if (fullName.StartsWith("bin") && File.Exists(entryOutputPath)) { continue; }
csharp
2025-01-17T02:27:29
2dust/v2rayN
cf1a8599eb08efb32b3d984a5c33378853e04fd4
v2rayN/AmazTool/Utils.cs
using System.Diagnostics; namespace AmazTool { internal class Utils { public static string GetExePath() { return Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName ?? string.Empty; } public static string StartupPath() { return AppDomain.CurrentDomain.BaseDirectory; } public static string GetPath(string fileName) { string startupPath = StartupPath(); if (string.IsNullOrEmpty(fileName)) { return startupPath; } return Path.Combine(startupPath, fileName); } public static string V2rayN => "v2rayN"; public static void StartV2RayN() { Process process = new() { StartInfo = new() { UseShellExecute = true, FileName = V2rayN, WorkingDirectory = StartupPath() } }; process.Start(); }
} }
public static void Waiting(int second) { for (var i = second; i > 0; i--) { Console.WriteLine(i); Thread.Sleep(1000); } }
csharp
2025-01-17T02:27:29
2dust/v2rayN
de1132c2df5422a16d454be0e49007be8a9c2894
v2rayN/v2rayN.Desktop/Views/OptionSettingWindow.axaml.cs
using Avalonia.Controls; using Avalonia.ReactiveUI; using ReactiveUI; using System.Reactive.Disposables; namespace v2rayN.Desktop.Views { public partial class OptionSettingWindow : ReactiveWindow<OptionSettingViewModel> { private static Config _config; public OptionSettingWindow() { InitializeComponent(); btnCancel.Click += (s, e) => this.Close(); _config = AppHandler.Instance.Config; ViewModel = new OptionSettingViewModel(UpdateViewHandler); clbdestOverride.SelectionChanged += ClbdestOverride_SelectionChanged; Global.destOverrideProtocols.ForEach(it => { clbdestOverride.Items.Add(it); }); _config.Inbound.First().DestOverride?.ForEach(it => { clbdestOverride.SelectedItems.Add(it); }); Global.IEProxyProtocols.ForEach(it => { cmbsystemProxyAdvancedProtocol.Items.Add(it); }); Global.LogLevels.ForEach(it => { cmbloglevel.Items.Add(it); }); Global.Fingerprints.ForEach(it => { cmbdefFingerprint.Items.Add(it); }); Global.UserAgent.ForEach(it => { cmbdefUserAgent.Items.Add(it); }); Global.SingboxMuxs.ForEach(it => { cmbmux4SboxProtocol.Items.Add(it); }); Global.TunMtus.ForEach(it => { cmbMtu.Items.Add(it); }); Global.TunStacks.ForEach(it => { cmbStack.Items.Add(it); }); Global.CoreTypes.ForEach(it => { cmbCoreType1.Items.Add(it); cmbCoreType2.Items.Add(it); cmbCoreType3.Items.Add(it); cmbCoreType4.Items.Add(it); cmbCoreType5.Items.Add(it); cmbCoreType6.Items.Add(it); }); for (int i = 2; i <= 6; i++) { cmbSpeedTestTimeout.Items.Add(i * 5); } Global.SpeedTestUrls.ForEach(it => { cmbSpeedTestUrl.Items.Add(it); }); Global.SpeedPingTestUrls.ForEach(it => { cmbSpeedPingTestUrl.Items.Add(it); }); Global.SubConvertUrls.ForEach(it => { cmbSubConvertUrl.Items.Add(it); }); Global.GeoFilesSources.ForEach(it => { cmbGetFilesSourceUrl.Items.Add(it); }); Global.SingboxRulesetSources.ForEach(it => { cmbSrsFilesSourceUrl.Items.Add(it); }); Global.RoutingRulesSources.ForEach(it => { cmbRoutingRulesSourceUrl.Items.Add(it); }); foreach (EGirdOrientation it in Enum.GetValues(typeof(EGirdOrientation))) { cmbMainGirdOrientation.Items.Add(it.ToString()); } this.WhenActivated(disposables => { this.Bind(ViewModel, vm => vm.localPort, v => v.txtlocalPort.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SecondLocalPortEnabled, v => v.togSecondLocalPortEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.udpEnabled, v => v.togudpEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.sniffingEnabled, v => v.togsniffingEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.routeOnly, v => v.togrouteOnly.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.allowLANConn, v => v.togAllowLANConn.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.togNewPort4LAN.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.txtuser.IsEnabled).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.txtpass.IsEnabled).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.user, v => v.txtuser.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.pass, v => v.txtpass.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.muxEnabled, v => v.togmuxEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.logEnabled, v => v.toglogEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.loglevel, v => v.cmbloglevel.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defAllowInsecure, v => v.togdefAllowInsecure.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defFingerprint, v => v.cmbdefFingerprint.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defUserAgent, v => v.cmbdefUserAgent.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.mux4SboxProtocol, v => v.cmbmux4SboxProtocol.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.enableCacheFile4Sbox, v => v.togenableCacheFile4Sbox.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.hyUpMbps, v => v.txtUpMbps.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.hyDownMbps, v => v.txtDownMbps.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.enableFragment, v => v.togenableFragment.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoRun, v => v.togAutoRun.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableStatistics, v => v.togEnableStatistics.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KeepOlderDedupl, v => v.togKeepOlderDedupl.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableAutoAdjustMainLvColWidth, v => v.togEnableAutoAdjustMainLvColWidth.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableUpdateSubOnlyRemarksExist, v => v.togEnableUpdateSubOnlyRemarksExist.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableSecurityProtocolTls13, v => v.togEnableSecurityProtocolTls13.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoHideStartup, v => v.togAutoHideStartup.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.Hide2TrayWhenClose, v => v.togHide2TrayWhenClose.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DoubleClick2Activate, v => v.togDoubleClick2Activate.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoUpdateInterval, v => v.txtautoUpdateInterval.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CurrentFontFamily, v => v.cmbcurrentFontFamily.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestTimeout, v => v.cmbSpeedTestTimeout.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestUrl, v => v.cmbSpeedTestUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedPingTestUrl, v => v.cmbSpeedPingTestUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestPageSize, v => v.txtSpeedTestPageSize.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SubConvertUrl, v => v.cmbSubConvertUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.MainGirdOrientation, v => v.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.GeoFileSourceUrl, v => v.cmbGetFilesSourceUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SrsFileSourceUrl, v => v.cmbSrsFilesSourceUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.RoutingRulesSourceUrl, v => v.cmbRoutingRulesSourceUrl.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.notProxyLocalAddress, v => v.tognotProxyLocalAddress.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.systemProxyAdvancedProtocol, v => v.cmbsystemProxyAdvancedProtocol.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.systemProxyExceptions, v => v.txtsystemProxyExceptions.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunStrictRoute, v => v.togStrictRoute.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunStack, v => v.cmbStack.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunMtu, v => v.cmbMtu.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunEnableExInbound, v => v.togEnableExInbound.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunEnableIPv6Address, v => v.togEnableIPv6Address.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunLinuxSudoPassword, v => v.txtLinuxSudoPassword.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType1, v => v.cmbCoreType1.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType2, v => v.cmbCoreType2.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType3, v => v.cmbCoreType3.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType4, v => v.cmbCoreType4.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType5, v => v.cmbCoreType5.SelectedValue).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType6, v => v.cmbCoreType6.SelectedValue).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SaveCmd, v => v.btnSave).DisposeWith(disposables); }); if (Utils.IsWindows()) { txbSettingsExceptionTip2.IsVisible = false; } else { txbSettingsExceptionTip.IsVisible = false; panSystemProxyAdvanced.IsVisible = false; } if (Utils.IsOSX()) { tbAutoRun.IsVisible = false; togAutoRun.IsVisible = false; //TODO } } private async Task<bool> UpdateViewHandler(EViewAction action, object? obj) { switch (action) { case EViewAction.CloseWindow: this.Close(true); break; case EViewAction.InitSettingFont: await InitSettingFont(); break; } return await Task.FromResult(true); } private async Task InitSettingFont() { var lstFonts = await GetFonts(); lstFonts.ForEach(it => { cmbcurrentFontFamily.Items.Add(it); }); cmbcurrentFontFamily.Items.Add(string.Empty); } private async Task<List<string>> GetFonts() { var lstFonts = new List<string>(); try { if (Utils.IsWindows()) { return lstFonts; } else if (Utils.IsNonWindows()) { var result = await Utils.GetLinuxFontFamily("zh"); if (result.IsNullOrEmpty()) { return lstFonts; } var lst = result.Split(Environment.NewLine) .Where(t => t.IsNotEmpty()) .ToList() .Select(t => t.Split(",").FirstOrDefault() ?? "") .OrderBy(t => t) .ToList(); return lst; } } catch (Exception ex) { Logging.SaveLog("GetFonts", ex); } return lstFonts; } private void ClbdestOverride_SelectionChanged(object? sender, SelectionChangedEventArgs e) { ViewModel.destOverride = clbdestOverride.SelectedItems.Cast<string>().ToList(); } } }
this.Bind(ViewModel, vm => vm.DisplayRealTimeSpeed, v => v.togDisplayRealTimeSpeed.IsChecked).DisposeWith(disposables);
csharp
2025-01-15T11:45:53
2dust/v2rayN
de1132c2df5422a16d454be0e49007be8a9c2894
v2rayN/v2rayN/Views/OptionSettingWindow.xaml.cs
using ReactiveUI; using System.Globalization; using System.IO; using System.Reactive.Disposables; using System.Windows; using System.Windows.Media; namespace v2rayN.Views { public partial class OptionSettingWindow { private static Config _config; public OptionSettingWindow() { InitializeComponent(); this.Owner = Application.Current.MainWindow; _config = AppHandler.Instance.Config; ViewModel = new OptionSettingViewModel(UpdateViewHandler); clbdestOverride.SelectionChanged += ClbdestOverride_SelectionChanged; Global.destOverrideProtocols.ForEach(it => { clbdestOverride.Items.Add(it); }); _config.Inbound.First().DestOverride?.ForEach(it => { clbdestOverride.SelectedItems.Add(it); }); Global.IEProxyProtocols.ForEach(it => { cmbsystemProxyAdvancedProtocol.Items.Add(it); }); Global.LogLevels.ForEach(it => { cmbloglevel.Items.Add(it); }); Global.Fingerprints.ForEach(it => { cmbdefFingerprint.Items.Add(it); }); Global.UserAgent.ForEach(it => { cmbdefUserAgent.Items.Add(it); }); Global.SingboxMuxs.ForEach(it => { cmbmux4SboxProtocol.Items.Add(it); }); Global.TunMtus.ForEach(it => { cmbMtu.Items.Add(it); }); Global.TunStacks.ForEach(it => { cmbStack.Items.Add(it); }); Global.CoreTypes.ForEach(it => { cmbCoreType1.Items.Add(it); cmbCoreType2.Items.Add(it); cmbCoreType3.Items.Add(it); cmbCoreType4.Items.Add(it); cmbCoreType5.Items.Add(it); cmbCoreType6.Items.Add(it); }); for (int i = 2; i <= 6; i++) { cmbSpeedTestTimeout.Items.Add(i * 5); } Global.SpeedTestUrls.ForEach(it => { cmbSpeedTestUrl.Items.Add(it); }); Global.SpeedPingTestUrls.ForEach(it => { cmbSpeedPingTestUrl.Items.Add(it); }); Global.SubConvertUrls.ForEach(it => { cmbSubConvertUrl.Items.Add(it); }); Global.GeoFilesSources.ForEach(it => { cmbGetFilesSourceUrl.Items.Add(it); }); Global.SingboxRulesetSources.ForEach(it => { cmbSrsFilesSourceUrl.Items.Add(it); }); Global.RoutingRulesSources.ForEach(it => { cmbRoutingRulesSourceUrl.Items.Add(it); }); foreach (EGirdOrientation it in Enum.GetValues(typeof(EGirdOrientation))) { cmbMainGirdOrientation.Items.Add(it.ToString()); } this.WhenActivated(disposables => { this.Bind(ViewModel, vm => vm.localPort, v => v.txtlocalPort.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SecondLocalPortEnabled, v => v.togSecondLocalPortEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.udpEnabled, v => v.togudpEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.sniffingEnabled, v => v.togsniffingEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.routeOnly, v => v.togrouteOnly.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.allowLANConn, v => v.togAllowLANConn.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.togNewPort4LAN.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.txtuser.IsEnabled).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.newPort4LAN, v => v.txtpass.IsEnabled).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.user, v => v.txtuser.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.pass, v => v.txtpass.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.muxEnabled, v => v.togmuxEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.logEnabled, v => v.toglogEnabled.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.loglevel, v => v.cmbloglevel.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defAllowInsecure, v => v.togdefAllowInsecure.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defFingerprint, v => v.cmbdefFingerprint.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.defUserAgent, v => v.cmbdefUserAgent.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.mux4SboxProtocol, v => v.cmbmux4SboxProtocol.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.enableCacheFile4Sbox, v => v.togenableCacheFile4Sbox.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.hyUpMbps, v => v.txtUpMbps.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.hyDownMbps, v => v.txtDownMbps.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.enableFragment, v => v.togenableFragment.IsChecked).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.Kcpmtu, v => v.txtKcpmtu.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.Kcptti, v => v.txtKcptti.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.KcpuplinkCapacity, v => v.txtKcpuplinkCapacity.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.KcpdownlinkCapacity, v => v.txtKcpdownlinkCapacity.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.KcpreadBufferSize, v => v.txtKcpreadBufferSize.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.KcpwriteBufferSize, v => v.txtKcpwriteBufferSize.Text).DisposeWith(disposables); //this.Bind(ViewModel, vm => vm.Kcpcongestion, v => v.togKcpcongestion.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoRun, v => v.togAutoRun.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableStatistics, v => v.togEnableStatistics.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.KeepOlderDedupl, v => v.togKeepOlderDedupl.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableAutoAdjustMainLvColWidth, v => v.togEnableAutoAdjustMainLvColWidth.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableUpdateSubOnlyRemarksExist, v => v.togEnableUpdateSubOnlyRemarksExist.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableSecurityProtocolTls13, v => v.togEnableSecurityProtocolTls13.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoHideStartup, v => v.togAutoHideStartup.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableDragDropSort, v => v.togEnableDragDropSort.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.DoubleClick2Activate, v => v.togDoubleClick2Activate.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.AutoUpdateInterval, v => v.txtautoUpdateInterval.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TrayMenuServersLimit, v => v.txttrayMenuServersLimit.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CurrentFontFamily, v => v.cmbcurrentFontFamily.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestTimeout, v => v.cmbSpeedTestTimeout.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestUrl, v => v.cmbSpeedTestUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedPingTestUrl, v => v.cmbSpeedPingTestUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SpeedTestPageSize, v => v.txtSpeedTestPageSize.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.EnableHWA, v => v.togEnableHWA.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SubConvertUrl, v => v.cmbSubConvertUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.MainGirdOrientation, v => v.cmbMainGirdOrientation.SelectedIndex).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.GeoFileSourceUrl, v => v.cmbGetFilesSourceUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.SrsFileSourceUrl, v => v.cmbSrsFilesSourceUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.RoutingRulesSourceUrl, v => v.cmbRoutingRulesSourceUrl.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.notProxyLocalAddress, v => v.tognotProxyLocalAddress.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.systemProxyAdvancedProtocol, v => v.cmbsystemProxyAdvancedProtocol.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.systemProxyExceptions, v => v.txtsystemProxyExceptions.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunStrictRoute, v => v.togStrictRoute.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunStack, v => v.cmbStack.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunMtu, v => v.cmbMtu.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunEnableExInbound, v => v.togEnableExInbound.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.TunEnableIPv6Address, v => v.togEnableIPv6Address.IsChecked).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType1, v => v.cmbCoreType1.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType2, v => v.cmbCoreType2.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType3, v => v.cmbCoreType3.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType4, v => v.cmbCoreType4.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType5, v => v.cmbCoreType5.Text).DisposeWith(disposables); this.Bind(ViewModel, vm => vm.CoreType6, v => v.cmbCoreType6.Text).DisposeWith(disposables); this.BindCommand(ViewModel, vm => vm.SaveCmd, v => v.btnSave).DisposeWith(disposables); }); WindowsUtils.SetDarkBorder(this, AppHandler.Instance.Config.UiItem.CurrentTheme); } private async Task<bool> UpdateViewHandler(EViewAction action, object? obj) { switch (action) { case EViewAction.CloseWindow: this.DialogResult = true; break; case EViewAction.InitSettingFont: await InitSettingFont(); break; } return await Task.FromResult(true); } private async Task InitSettingFont() { var lstFonts = await GetFonts(Utils.GetFontsPath()); lstFonts.ForEach(it => { cmbcurrentFontFamily.Items.Add(it); }); cmbcurrentFontFamily.Items.Add(string.Empty); } private async Task<List<string>> GetFonts(string path) { var lstFonts = new List<string>(); try { string[] searchPatterns = { "*.ttf", "*.ttc" }; var files = new List<string>(); foreach (var pattern in searchPatterns) { files.AddRange(Directory.GetFiles(path, pattern)); } var culture = _config.UiItem.CurrentLanguage == Global.Languages.First() ? "zh-cn" : "en-us"; var culture2 = "en-us"; foreach (var ttf in files) { var families = Fonts.GetFontFamilies(Utils.GetFontsPath(ttf)); foreach (FontFamily family in families) { var typefaces = family.GetTypefaces(); foreach (Typeface typeface in typefaces) { typeface.TryGetGlyphTypeface(out GlyphTypeface glyph); //var fontFace = glyph.Win32FaceNames[new CultureInfo("en-us")]; //if (!fontFace.Equals("Regular") && !fontFace.Equals("Normal")) //{ // continue; //} var fontFamily = glyph.Win32FamilyNames[new CultureInfo(culture)]; if (Utils.IsNullOrEmpty(fontFamily)) { fontFamily = glyph.Win32FamilyNames[new CultureInfo(culture2)]; if (Utils.IsNullOrEmpty(fontFamily)) { continue; } } lstFonts.Add(fontFamily); break; } } } } catch (Exception ex) { Logging.SaveLog("GetFonts", ex); } var lst = lstFonts.OrderBy(t => t).ToList(); return await Task.FromResult(lst); } private void ClbdestOverride_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { ViewModel.destOverride = clbdestOverride.SelectedItems.Cast<string>().ToList(); } } }
this.Bind(ViewModel, vm => vm.DisplayRealTimeSpeed, v => v.togDisplayRealTimeSpeed.IsChecked).DisposeWith(disposables);
csharp
2025-01-15T11:45:53
2dust/v2rayN
4ad4e27dc102088c42b613e484b10ad745b6fdd5
v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs
using ReactiveUI; using ReactiveUI.Fody.Helpers; using Splat; using System.Reactive; namespace ServiceLib.ViewModels { public class MainWindowViewModel : MyReactiveObject { #region Menu //servers public ReactiveCommand<Unit, Unit> AddVmessServerCmd { get; } public ReactiveCommand<Unit, Unit> AddVlessServerCmd { get; } public ReactiveCommand<Unit, Unit> AddShadowsocksServerCmd { get; } public ReactiveCommand<Unit, Unit> AddSocksServerCmd { get; } public ReactiveCommand<Unit, Unit> AddHttpServerCmd { get; } public ReactiveCommand<Unit, Unit> AddTrojanServerCmd { get; } public ReactiveCommand<Unit, Unit> AddHysteria2ServerCmd { get; } public ReactiveCommand<Unit, Unit> AddTuicServerCmd { get; } public ReactiveCommand<Unit, Unit> AddWireguardServerCmd { get; } public ReactiveCommand<Unit, Unit> AddCustomServerCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaClipboardCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaScanCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaImageCmd { get; } //Subscription public ReactiveCommand<Unit, Unit> SubSettingCmd { get; } public ReactiveCommand<Unit, Unit> SubUpdateCmd { get; } public ReactiveCommand<Unit, Unit> SubUpdateViaProxyCmd { get; } public ReactiveCommand<Unit, Unit> SubGroupUpdateCmd { get; } public ReactiveCommand<Unit, Unit> SubGroupUpdateViaProxyCmd { get; } //Setting public ReactiveCommand<Unit, Unit> OptionSettingCmd { get; } public ReactiveCommand<Unit, Unit> RoutingSettingCmd { get; } public ReactiveCommand<Unit, Unit> DNSSettingCmd { get; } public ReactiveCommand<Unit, Unit> GlobalHotkeySettingCmd { get; } public ReactiveCommand<Unit, Unit> RebootAsAdminCmd { get; } public ReactiveCommand<Unit, Unit> ClearServerStatisticsCmd { get; } public ReactiveCommand<Unit, Unit> OpenTheFileLocationCmd { get; } //Presets public ReactiveCommand<Unit, Unit> RegionalPresetDefaultCmd { get; } public ReactiveCommand<Unit, Unit> RegionalPresetRussiaCmd { get; } public ReactiveCommand<Unit, Unit> RegionalPresetIranCmd { get; } public ReactiveCommand<Unit, Unit> ReloadCmd { get; } [Reactive] public bool BlReloadEnabled { get; set; } [Reactive] public bool ShowClashUI { get; set; } [Reactive] public int TabMainSelectedIndex { get; set; } #endregion Menu private bool _hasNextReloadJob = false; #region Init public MainWindowViewModel(Func<EViewAction, object?, Task<bool>>? updateView) { _config = AppHandler.Instance.Config; _updateView = updateView; #region WhenAnyValue && ReactiveCommand //servers AddVmessServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.VMess); }); AddVlessServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.VLESS); }); AddShadowsocksServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Shadowsocks); }); AddSocksServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.SOCKS); }); AddHttpServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.HTTP); }); AddTrojanServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Trojan); }); AddHysteria2ServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Hysteria2); }); AddTuicServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.TUIC); }); AddWireguardServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.WireGuard); }); AddCustomServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Custom); }); AddServerViaClipboardCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaClipboardAsync(null); }); AddServerViaScanCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaScanAsync(); }); AddServerViaImageCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaImageAsync(); }); //Subscription SubSettingCmd = ReactiveCommand.CreateFromTask(async () => { await SubSettingAsync(); }); SubUpdateCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess("", false); }); SubUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess("", true); }); SubGroupUpdateCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess(_config.SubIndexId, false); }); SubGroupUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess(_config.SubIndexId, true); }); //Setting OptionSettingCmd = ReactiveCommand.CreateFromTask(async () => { await OptionSettingAsync(); }); RoutingSettingCmd = ReactiveCommand.CreateFromTask(async () => { await RoutingSettingAsync(); }); DNSSettingCmd = ReactiveCommand.CreateFromTask(async () => { await DNSSettingAsync(); }); GlobalHotkeySettingCmd = ReactiveCommand.CreateFromTask(async () => { if (await _updateView?.Invoke(EViewAction.GlobalHotkeySettingWindow, null) == true) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); } }); RebootAsAdminCmd = ReactiveCommand.CreateFromTask(async () => { await RebootAsAdmin(); }); ClearServerStatisticsCmd = ReactiveCommand.CreateFromTask(async () => { await ClearServerStatistics(); }); OpenTheFileLocationCmd = ReactiveCommand.CreateFromTask(async () => { await OpenTheFileLocation(); }); ReloadCmd = ReactiveCommand.CreateFromTask(async () => { await Reload(); }); RegionalPresetDefaultCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Default); }); RegionalPresetRussiaCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Russia); }); RegionalPresetIranCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Iran); }); #endregion WhenAnyValue && ReactiveCommand Init(); } private async Task Init() { _config.UiItem.ShowInTaskbar = true; await ConfigHandler.InitBuiltinRouting(_config); await ConfigHandler.InitBuiltinDNS(_config); await ProfileExHandler.Instance.Init(); await CoreHandler.Instance.Init(_config, UpdateHandler); TaskHandler.Instance.RegUpdateTask(_config, UpdateTaskHandler); if (_config.GuiItem.EnableStatistics) { await StatisticsHandler.Instance.Init(_config, UpdateStatisticsHandler); } BlReloadEnabled = true; await Reload(); await AutoHideStartup(); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); } #endregion Init #region Actions private void UpdateHandler(bool notify, string msg) { NoticeHandler.Instance.SendMessage(msg); if (notify) { NoticeHandler.Instance.Enqueue(msg); } } private void UpdateTaskHandler(bool success, string msg) { NoticeHandler.Instance.SendMessageEx(msg); if (success) { var indexIdOld = _config.IndexId; RefreshServers(); if (indexIdOld != _config.IndexId) { Reload(); } if (_config.UiItem.EnableAutoAdjustMainLvColWidth) { _updateView?.Invoke(EViewAction.AdjustMainLvColWidth, null); } } } private void UpdateStatisticsHandler(ServerSpeedItem update) { if (!_config.UiItem.ShowInTaskbar) { return; } _updateView?.Invoke(EViewAction.DispatcherStatistics, update); } public void SetStatisticsResult(ServerSpeedItem update) { try { Locator.Current.GetService<StatusBarViewModel>()?.UpdateStatistics(update); if ((update.ProxyUp + update.ProxyDown) > 0 && DateTime.Now.Second % 9 == 0) { Locator.Current.GetService<ProfilesViewModel>()?.UpdateStatistics(update); } } catch { } } public async Task MyAppExitAsync(bool blWindowsShutDown) { try { Logging.SaveLog("MyAppExitAsync Begin"); MessageBus.Current.SendMessage("", EMsgCommand.AppExit.ToString()); await ConfigHandler.SaveConfig(_config); await SysProxyHandler.UpdateSysProxy(_config, true); await ProfileExHandler.Instance.SaveTo(); await StatisticsHandler.Instance.SaveTo(); StatisticsHandler.Instance.Close(); await CoreHandler.Instance.CoreStop(); Logging.SaveLog("MyAppExitAsync End"); } catch { } finally { if (!blWindowsShutDown) { _updateView?.Invoke(EViewAction.Shutdown, false); } } } public async Task UpgradeApp(string arg) { if (!Utils.UpgradeAppExists(out var upgradeFileName)) { NoticeHandler.Instance.SendMessageAndEnqueue(ResUI.UpgradeAppNotExistTip); Logging.SaveLog("UpgradeApp does not exist"); return; } var id = ProcUtils.ProcessStart(upgradeFileName, arg, Utils.StartupPath()); if (id > 0) { await MyAppExitAsync(false); } } public void ShowHideWindow(bool? blShow) { _updateView?.Invoke(EViewAction.ShowHideWindow, blShow); } public void Shutdown(bool byUser) { _updateView?.Invoke(EViewAction.Shutdown, byUser); } #endregion Actions #region Servers && Groups private void RefreshServers() { MessageBus.Current.SendMessage("", EMsgCommand.RefreshProfiles.ToString()); } private void RefreshSubscriptions() { Locator.Current.GetService<ProfilesViewModel>()?.RefreshSubscriptions(); } #endregion Servers && Groups #region Add Servers public async Task AddServerAsync(bool blNew, EConfigType eConfigType) { ProfileItem item = new() { Subid = _config.SubIndexId, ConfigType = eConfigType, IsSub = false, }; bool? ret = false; if (eConfigType == EConfigType.Custom) { ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); } else { ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); } if (ret == true) { RefreshServers(); if (item.IndexId == _config.IndexId) { await Reload(); } } } public async Task AddServerViaClipboardAsync(string? clipboardData) { if (clipboardData == null) { await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null); return; } int ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); RefreshServers(); NoticeHandler.Instance.Enqueue(string.Format(ResUI.SuccessfullyImportedServerViaClipboard, ret)); } else { NoticeHandler.Instance.Enqueue(ResUI.OperationFailed); } } public async Task AddServerViaScanAsync() { _updateView?.Invoke(EViewAction.ScanScreenTask, null); } public async Task ScanScreenResult(byte[]? bytes) { var result = QRCodeHelper.ParseBarcode(bytes); await AddScanResultAsync(result); } public async Task AddServerViaImageAsync() { _updateView?.Invoke(EViewAction.ScanImageTask, null); } public async Task ScanImageResult(string fileName) { if (Utils.IsNullOrEmpty(fileName)) { return; } var result = QRCodeHelper.ParseBarcode(fileName); await AddScanResultAsync(result); } private async Task AddScanResultAsync(string? result) { if (Utils.IsNullOrEmpty(result)) { NoticeHandler.Instance.Enqueue(ResUI.NoValidQRcodeFound); } else { int ret = await ConfigHandler.AddBatchServers(_config, result, _config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); RefreshServers(); NoticeHandler.Instance.Enqueue(ResUI.SuccessfullyImportedServerViaScan); } else { NoticeHandler.Instance.Enqueue(ResUI.OperationFailed); } } } #endregion Add Servers #region Subscription private async Task SubSettingAsync() { if (await _updateView?.Invoke(EViewAction.SubSettingWindow, null) == true) { RefreshSubscriptions(); } } public async Task UpdateSubscriptionProcess(string subId, bool blProxy) { await (new UpdateService()).UpdateSubscriptionProcess(_config, subId, blProxy, UpdateTaskHandler); } #endregion Subscription #region Setting private async Task OptionSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.OptionSettingWindow, null); if (ret == true) { Locator.Current.GetService<StatusBarViewModel>()?.InboundDisplayStatus(); await Reload(); } } private async Task RoutingSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.RoutingSettingWindow, null); if (ret == true) { await ConfigHandler.InitBuiltinRouting(_config); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); await Reload(); } } private async Task DNSSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.DNSSettingWindow, null); if (ret == true) { await Reload(); } } public async Task RebootAsAdmin() { ProcUtils.RebootAsAdmin(); await MyAppExitAsync(false); } private async Task ClearServerStatistics() { await StatisticsHandler.Instance.ClearAllServerStatistics(); RefreshServers(); } private async Task OpenTheFileLocation() { var path = Utils.StartupPath(); if (Utils.IsWindows()) { ProcUtils.ProcessStart(path); } else if (Utils.IsLinux()) { ProcUtils.ProcessStart("nautilus", path); } else if (Utils.IsOSX()) { ProcUtils.ProcessStart("open", path); } } #endregion Setting #region core job public async Task Reload() { //If there are unfinished reload job, marked with next job. if (!BlReloadEnabled) { _hasNextReloadJob = true; return; } BlReloadEnabled = false; await LoadCore(); Locator.Current.GetService<StatusBarViewModel>()?.TestServerAvailability(); await SysProxyHandler.UpdateSysProxy(_config, false); _updateView?.Invoke(EViewAction.DispatcherReload, null);
} public void ReloadResult() { // BlReloadEnabled = true; //Locator.Current.GetService<StatusBarViewModel>()?.ChangeSystemProxyAsync(_config.systemProxyItem.sysProxyType, false); ShowClashUI = _config.IsRunningCore(ECoreType.sing_box); if (ShowClashUI) { Locator.Current.GetService<ClashProxiesViewModel>()?.ProxiesReload(); } else { TabMainSelectedIndex = 0; } } private async Task LoadCore() { var node = await ConfigHandler.GetDefaultServer(_config); await CoreHandler.Instance.LoadCore(node); } public async Task CloseCore() { await ConfigHandler.SaveConfig(_config); await CoreHandler.Instance.CoreStop(); } private async Task AutoHideStartup() { if (_config.UiItem.AutoHideStartup) { ShowHideWindow(false); } } #endregion core job #region Presets public async Task ApplyRegionalPreset(EPresetType type) { await ConfigHandler.ApplyRegionalPreset(_config, type); await ConfigHandler.InitRouting(_config); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); await ConfigHandler.SaveConfig(_config); await new UpdateService().UpdateGeoFileAll(_config, UpdateHandler); await Reload(); } #endregion Presets } }
BlReloadEnabled = true; if (_hasNextReloadJob) { _hasNextReloadJob = false; await Reload(); }
csharp
2025-01-14T09:05:13
2dust/v2rayN
73706849859bb13f2680355065b488a886565bb8
v2rayN/ServiceLib/Common/FileManager.cs
using System.Formats.Tar; using System.IO.Compression; using System.Text; namespace ServiceLib.Common { public static class FileManager { private static readonly string _tag = "FileManager"; public static bool ByteArrayToFile(string fileName, byte[] content) { try { File.WriteAllBytes(fileName, content); return true; } catch (Exception ex) { Logging.SaveLog(_tag, ex); } return false; } public static void DecompressFile(string fileName, byte[] content) { try { using var fs = File.Create(fileName); using GZipStream input = new(new MemoryStream(content), CompressionMode.Decompress, false); input.CopyTo(fs); } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } public static void DecompressFile(string fileName, string toPath, string? toName) { try { FileInfo fileInfo = new(fileName); using var originalFileStream = fileInfo.OpenRead(); using var decompressedFileStream = File.Create(toName != null ? Path.Combine(toPath, toName) : toPath); using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress); decompressionStream.CopyTo(decompressedFileStream); } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } public static void DecompressTarFile(string fileName, string toPath) { try { using var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); using var gz = new GZipStream(fs, CompressionMode.Decompress, leaveOpen: true); TarFile.ExtractToDirectory(gz, toPath, overwriteFiles: true); } catch (Exception ex) { Logging.SaveLog(_tag, ex); } } public static string NonExclusiveReadAllText(string path) { return NonExclusiveReadAllText(path, Encoding.Default); } private static string NonExclusiveReadAllText(string path, Encoding encoding) { try { using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using StreamReader sr = new(fs, encoding); return sr.ReadToEnd(); } catch (Exception ex) { Logging.SaveLog(_tag, ex); throw; } } public static bool ZipExtractToFile(string fileName, string toPath, string ignoredName) { try { using var archive = ZipFile.OpenRead(fileName); foreach (var entry in archive.Entries) { if (entry.Length == 0) { continue; } try { if (Utils.IsNotEmpty(ignoredName) && entry.Name.Contains(ignoredName)) { continue; } entry.ExtractToFile(Path.Combine(toPath, entry.Name), true); } catch (IOException ex) { Logging.SaveLog(_tag, ex); } } } catch (Exception ex) { Logging.SaveLog(_tag, ex); return false; } return true; } public static List<string>? GetFilesFromZip(string fileName) { if (!File.Exists(fileName)) { return null; } try { using var archive = ZipFile.OpenRead(fileName); return archive.Entries.Select(entry => entry.FullName).ToList(); } catch (Exception ex) { Logging.SaveLog(_tag, ex); return null; } } public static bool CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) { try { if (File.Exists(destinationArchiveFileName)) { File.Delete(destinationArchiveFileName); } ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, CompressionLevel.SmallestSize, true); } catch (Exception ex) { Logging.SaveLog(_tag, ex); return false; } return true; } public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive, string? ignoredName) { // Get information about the source directory var dir = new DirectoryInfo(sourceDir); // Check if the source directory exists if (!dir.Exists) throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}"); // Cache directories before we start copying var dirs = dir.GetDirectories(); // Create the destination directory Directory.CreateDirectory(destinationDir); // Get the files in the source directory and copy to the destination directory foreach (var file in dir.GetFiles()) { if (Utils.IsNotEmpty(ignoredName) && file.Name.Contains(ignoredName)) { continue; } if (file.Extension == file.Name) { continue; } var targetFilePath = Path.Combine(destinationDir, file.Name); file.CopyTo(targetFilePath, true); } // If recursive and copying subdirectories, recursively call this method if (recursive) { foreach (var subDir in dirs) { var newDestinationDir = Path.Combine(destinationDir, subDir.Name); CopyDirectory(subDir.FullName, newDestinationDir, true, ignoredName); } } }
} }
public static void DeleteExpiredFiles(string sourceDir, DateTime dtLine) { try { var files = Directory.GetFiles(sourceDir, "*.*"); foreach (var filePath in files) { var file = new FileInfo(filePath); if (file.CreationTime >= dtLine) { continue; } file.Delete(); } } catch { // ignored } }
csharp
2025-01-14T09:04:43
2dust/v2rayN
5ae58e6a980f0d21ca8f11dad2492840262bcaab
v2rayN/ServiceLib/ViewModels/MainWindowViewModel.cs
using ReactiveUI; using ReactiveUI.Fody.Helpers; using Splat; using System.Reactive; namespace ServiceLib.ViewModels { public class MainWindowViewModel : MyReactiveObject { #region Menu //servers public ReactiveCommand<Unit, Unit> AddVmessServerCmd { get; } public ReactiveCommand<Unit, Unit> AddVlessServerCmd { get; } public ReactiveCommand<Unit, Unit> AddShadowsocksServerCmd { get; } public ReactiveCommand<Unit, Unit> AddSocksServerCmd { get; } public ReactiveCommand<Unit, Unit> AddHttpServerCmd { get; } public ReactiveCommand<Unit, Unit> AddTrojanServerCmd { get; } public ReactiveCommand<Unit, Unit> AddHysteria2ServerCmd { get; } public ReactiveCommand<Unit, Unit> AddTuicServerCmd { get; } public ReactiveCommand<Unit, Unit> AddWireguardServerCmd { get; } public ReactiveCommand<Unit, Unit> AddCustomServerCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaClipboardCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaScanCmd { get; } public ReactiveCommand<Unit, Unit> AddServerViaImageCmd { get; } //Subscription public ReactiveCommand<Unit, Unit> SubSettingCmd { get; } public ReactiveCommand<Unit, Unit> SubUpdateCmd { get; } public ReactiveCommand<Unit, Unit> SubUpdateViaProxyCmd { get; } public ReactiveCommand<Unit, Unit> SubGroupUpdateCmd { get; } public ReactiveCommand<Unit, Unit> SubGroupUpdateViaProxyCmd { get; } //Setting public ReactiveCommand<Unit, Unit> OptionSettingCmd { get; } public ReactiveCommand<Unit, Unit> RoutingSettingCmd { get; } public ReactiveCommand<Unit, Unit> DNSSettingCmd { get; } public ReactiveCommand<Unit, Unit> GlobalHotkeySettingCmd { get; } public ReactiveCommand<Unit, Unit> RebootAsAdminCmd { get; } public ReactiveCommand<Unit, Unit> ClearServerStatisticsCmd { get; } public ReactiveCommand<Unit, Unit> OpenTheFileLocationCmd { get; } //Presets public ReactiveCommand<Unit, Unit> RegionalPresetDefaultCmd { get; } public ReactiveCommand<Unit, Unit> RegionalPresetRussiaCmd { get; } public ReactiveCommand<Unit, Unit> RegionalPresetIranCmd { get; } public ReactiveCommand<Unit, Unit> ReloadCmd { get; } [Reactive] public bool BlReloadEnabled { get; set; } [Reactive] public bool ShowClashUI { get; set; } [Reactive] public int TabMainSelectedIndex { get; set; } #endregion Menu #region Init public MainWindowViewModel(Func<EViewAction, object?, Task<bool>>? updateView) { _config = AppHandler.Instance.Config; _updateView = updateView; #region WhenAnyValue && ReactiveCommand //servers AddVmessServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.VMess); }); AddVlessServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.VLESS); }); AddShadowsocksServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Shadowsocks); }); AddSocksServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.SOCKS); }); AddHttpServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.HTTP); }); AddTrojanServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Trojan); }); AddHysteria2ServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Hysteria2); }); AddTuicServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.TUIC); }); AddWireguardServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.WireGuard); }); AddCustomServerCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerAsync(true, EConfigType.Custom); }); AddServerViaClipboardCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaClipboardAsync(null); }); AddServerViaScanCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaScanAsync(); }); AddServerViaImageCmd = ReactiveCommand.CreateFromTask(async () => { await AddServerViaImageAsync(); }); //Subscription SubSettingCmd = ReactiveCommand.CreateFromTask(async () => { await SubSettingAsync(); }); SubUpdateCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess("", false); }); SubUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess("", true); }); SubGroupUpdateCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess(_config.SubIndexId, false); }); SubGroupUpdateViaProxyCmd = ReactiveCommand.CreateFromTask(async () => { await UpdateSubscriptionProcess(_config.SubIndexId, true); }); //Setting OptionSettingCmd = ReactiveCommand.CreateFromTask(async () => { await OptionSettingAsync(); }); RoutingSettingCmd = ReactiveCommand.CreateFromTask(async () => { await RoutingSettingAsync(); }); DNSSettingCmd = ReactiveCommand.CreateFromTask(async () => { await DNSSettingAsync(); }); GlobalHotkeySettingCmd = ReactiveCommand.CreateFromTask(async () => { if (await _updateView?.Invoke(EViewAction.GlobalHotkeySettingWindow, null) == true) { NoticeHandler.Instance.Enqueue(ResUI.OperationSuccess); } }); RebootAsAdminCmd = ReactiveCommand.CreateFromTask(async () => { await RebootAsAdmin(); }); ClearServerStatisticsCmd = ReactiveCommand.CreateFromTask(async () => { await ClearServerStatistics(); }); OpenTheFileLocationCmd = ReactiveCommand.CreateFromTask(async () => { await OpenTheFileLocation(); }); ReloadCmd = ReactiveCommand.CreateFromTask(async () => { await Reload(); }); RegionalPresetDefaultCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Default); }); RegionalPresetRussiaCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Russia); }); RegionalPresetIranCmd = ReactiveCommand.CreateFromTask(async () => { await ApplyRegionalPreset(EPresetType.Iran); }); #endregion WhenAnyValue && ReactiveCommand Init(); } private async Task Init() { _config.UiItem.ShowInTaskbar = true; await ConfigHandler.InitBuiltinRouting(_config); await ConfigHandler.InitBuiltinDNS(_config); await ProfileExHandler.Instance.Init(); await CoreHandler.Instance.Init(_config, UpdateHandler); TaskHandler.Instance.RegUpdateTask(_config, UpdateTaskHandler); if (_config.GuiItem.EnableStatistics) { await StatisticsHandler.Instance.Init(_config, UpdateStatisticsHandler); } BlReloadEnabled = true; await Reload(); await AutoHideStartup(); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); } #endregion Init #region Actions private void UpdateHandler(bool notify, string msg) { NoticeHandler.Instance.SendMessage(msg); if (notify) { NoticeHandler.Instance.Enqueue(msg); } } private void UpdateTaskHandler(bool success, string msg) { NoticeHandler.Instance.SendMessageEx(msg); if (success) { var indexIdOld = _config.IndexId; RefreshServers(); if (indexIdOld != _config.IndexId) { Reload(); } if (_config.UiItem.EnableAutoAdjustMainLvColWidth) { _updateView?.Invoke(EViewAction.AdjustMainLvColWidth, null); } } } private void UpdateStatisticsHandler(ServerSpeedItem update) { if (!_config.UiItem.ShowInTaskbar) { return; } _updateView?.Invoke(EViewAction.DispatcherStatistics, update); } public void SetStatisticsResult(ServerSpeedItem update) { try { Locator.Current.GetService<StatusBarViewModel>()?.UpdateStatistics(update); if ((update.ProxyUp + update.ProxyDown) > 0 && DateTime.Now.Second % 9 == 0) { Locator.Current.GetService<ProfilesViewModel>()?.UpdateStatistics(update); } } catch { } } public async Task MyAppExitAsync(bool blWindowsShutDown) { try { Logging.SaveLog("MyAppExitAsync Begin"); MessageBus.Current.SendMessage("", EMsgCommand.AppExit.ToString()); await ConfigHandler.SaveConfig(_config); await SysProxyHandler.UpdateSysProxy(_config, true); await ProfileExHandler.Instance.SaveTo(); await StatisticsHandler.Instance.SaveTo(); StatisticsHandler.Instance.Close(); await CoreHandler.Instance.CoreStop(); Logging.SaveLog("MyAppExitAsync End"); } catch { } finally { if (!blWindowsShutDown) { _updateView?.Invoke(EViewAction.Shutdown, false); } } } public async Task UpgradeApp(string arg) { if (!Utils.UpgradeAppExists(out var upgradeFileName)) { NoticeHandler.Instance.SendMessageAndEnqueue(ResUI.UpgradeAppNotExistTip); Logging.SaveLog("UpgradeApp does not exist"); return; } var id = ProcUtils.ProcessStart(upgradeFileName, arg, Utils.StartupPath()); if (id > 0) { await MyAppExitAsync(false); } } public void ShowHideWindow(bool? blShow) { _updateView?.Invoke(EViewAction.ShowHideWindow, blShow); } public void Shutdown(bool byUser) { _updateView?.Invoke(EViewAction.Shutdown, byUser); } #endregion Actions #region Servers && Groups private void RefreshServers() { MessageBus.Current.SendMessage("", EMsgCommand.RefreshProfiles.ToString()); } private void RefreshSubscriptions() { Locator.Current.GetService<ProfilesViewModel>()?.RefreshSubscriptions(); } #endregion Servers && Groups #region Add Servers public async Task AddServerAsync(bool blNew, EConfigType eConfigType) { ProfileItem item = new() { Subid = _config.SubIndexId, ConfigType = eConfigType, IsSub = false, }; bool? ret = false; if (eConfigType == EConfigType.Custom) { ret = await _updateView?.Invoke(EViewAction.AddServer2Window, item); } else { ret = await _updateView?.Invoke(EViewAction.AddServerWindow, item); } if (ret == true) { RefreshServers(); if (item.IndexId == _config.IndexId) { await Reload(); } } } public async Task AddServerViaClipboardAsync(string? clipboardData) { if (clipboardData == null) { await _updateView?.Invoke(EViewAction.AddServerViaClipboard, null); return; } int ret = await ConfigHandler.AddBatchServers(_config, clipboardData, _config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); RefreshServers(); NoticeHandler.Instance.Enqueue(string.Format(ResUI.SuccessfullyImportedServerViaClipboard, ret)); } else { NoticeHandler.Instance.Enqueue(ResUI.OperationFailed); } } public async Task AddServerViaScanAsync() { _updateView?.Invoke(EViewAction.ScanScreenTask, null); } public async Task ScanScreenResult(byte[]? bytes) { var result = QRCodeHelper.ParseBarcode(bytes); await AddScanResultAsync(result); } public async Task AddServerViaImageAsync() { _updateView?.Invoke(EViewAction.ScanImageTask, null); } public async Task ScanImageResult(string fileName) { if (Utils.IsNullOrEmpty(fileName)) { return; } var result = QRCodeHelper.ParseBarcode(fileName); await AddScanResultAsync(result); } private async Task AddScanResultAsync(string? result) { if (Utils.IsNullOrEmpty(result)) { NoticeHandler.Instance.Enqueue(ResUI.NoValidQRcodeFound); } else { int ret = await ConfigHandler.AddBatchServers(_config, result, _config.SubIndexId, false); if (ret > 0) { RefreshSubscriptions(); RefreshServers(); NoticeHandler.Instance.Enqueue(ResUI.SuccessfullyImportedServerViaScan); } else { NoticeHandler.Instance.Enqueue(ResUI.OperationFailed); } } } #endregion Add Servers #region Subscription private async Task SubSettingAsync() { if (await _updateView?.Invoke(EViewAction.SubSettingWindow, null) == true) { RefreshSubscriptions(); } } public async Task UpdateSubscriptionProcess(string subId, bool blProxy) { await (new UpdateService()).UpdateSubscriptionProcess(_config, subId, blProxy, UpdateTaskHandler); } #endregion Subscription #region Setting private async Task OptionSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.OptionSettingWindow, null); if (ret == true) { Locator.Current.GetService<StatusBarViewModel>()?.InboundDisplayStatus(); await Reload(); } } private async Task RoutingSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.RoutingSettingWindow, null); if (ret == true) { await ConfigHandler.InitBuiltinRouting(_config); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); await Reload(); } } private async Task DNSSettingAsync() { var ret = await _updateView?.Invoke(EViewAction.DNSSettingWindow, null); if (ret == true) { await Reload(); } } public async Task RebootAsAdmin() { ProcUtils.RebootAsAdmin(); await MyAppExitAsync(false); } private async Task ClearServerStatistics() { await StatisticsHandler.Instance.ClearAllServerStatistics(); RefreshServers(); } private async Task OpenTheFileLocation() { var path = Utils.StartupPath(); if (Utils.IsWindows()) { ProcUtils.ProcessStart(path); } else if (Utils.IsLinux()) { ProcUtils.ProcessStart("nautilus", path); } else if (Utils.IsOSX()) { ProcUtils.ProcessStart("open", path); } } #endregion Setting #region core job public async Task Reload(int times = 0) {
BlReloadEnabled = false; await LoadCore(); Locator.Current.GetService<StatusBarViewModel>()?.TestServerAvailability(); await SysProxyHandler.UpdateSysProxy(_config, false); _updateView?.Invoke(EViewAction.DispatcherReload, null); } public void ReloadResult() { //Locator.Current.GetService<StatusBarViewModel>()?.ChangeSystemProxyAsync(_config.systemProxyItem.sysProxyType, false); BlReloadEnabled = true; ShowClashUI = _config.IsRunningCore(ECoreType.sing_box); if (ShowClashUI) { Locator.Current.GetService<ClashProxiesViewModel>()?.ProxiesReload(); } else { TabMainSelectedIndex = 0; } } private async Task LoadCore() { var node = await ConfigHandler.GetDefaultServer(_config); await CoreHandler.Instance.LoadCore(node); } public async Task CloseCore() { await ConfigHandler.SaveConfig(_config); await CoreHandler.Instance.CoreStop(); } private async Task AutoHideStartup() { if (_config.UiItem.AutoHideStartup) { ShowHideWindow(false); } } #endregion core job #region Presets public async Task ApplyRegionalPreset(EPresetType type) { await ConfigHandler.ApplyRegionalPreset(_config, type); await ConfigHandler.InitRouting(_config); Locator.Current.GetService<StatusBarViewModel>()?.RefreshRoutingsMenu(); await ConfigHandler.SaveConfig(_config); await new UpdateService().UpdateGeoFileAll(_config, UpdateHandler); await Reload(); } #endregion Presets } }
//If there are unfinished reload job, wait a few seconds and exec again. if (!BlReloadEnabled) { await Task.Delay(3000); if (times > 3) return; await Reload(++times); return; }
csharp
2025-01-14T06:49:17
End of preview. Expand in Data Studio

Real-FIM-Eval Benchmark

Real-FIM-Eval is a benchmark to evaluate Fill-in-the-Middle (FIM) capabilities of code LLMs in scenarios that reflect real-world code completion. Real-FIM-Eval is built using data from GitHub commits between Jan. 2025 and Feb. 2025. These commits originate from 228 permissively licensed GitHub repositories with 10,000+ stars, spanning the top 12 widely-used programming languages.

We process git commits using diff_match_patch (https://github.com/google/diff-match-patch) to identify line-level changes. The commits are then categorized into two splits: Add and Edit.

Construction of Fill-in-the-Middle (FIM) examples for the proposed Real-FIM-Eval benchmark splits, derived from real-world git commits.

  • Add (17,879 examples): This split uses git commits where a developer added a new segment of code into an existing file. To create the FIM prompt, we treat the added code segment as the "middle" part that the language model needs to predict. The code surrounding the addition forms the prefix (code before) and the suffix (code after).

  • Edit (13,922 examples): This split uses git commits where a developer modified existing code by removing a segment and replacing it with a new one. We present this task to LLMs in a conflict-merge format. The prompt includes the code context (prefix and suffix) and marks the original code segment (to be removed). The model is asked to infill the updated code segment.

Evaluation Metric

The evaluation metric is character-level perplexity (lower = better), calculated as:

exp(1n_chars(mid)imidlogpi) \exp\left(-\frac{1}{\mathrm{n\_chars}(\mathrm{mid})} \sum_{i\in\mathrm{mid}} \log p_{i}\right)

In this formula, p_i represents the probability the model assigns to the i-th token of the ground truth (only the "middle" part that the model is tasked to infill), and n_char(mid) is the total number of characters in that ground truth middle segment.

Statistics of Programming Languages

Language Num Examples
Python 6,271
Rust 4,727
Java 3,716
C++ 3,265
TypeScript 3,182
Go 2,587
Ruby 1,686
C# 1,563
JavaScript 1,502
Kotlin 1,440
PHP 1,396
Scala 466

Copyright Information

The dataset is a verbatim snapshot of source‑code files from public GitHub repositories. Each data example retains the exact license chosen by its original author(s). The repository of origin for every file is recorded in that data example’s repo field. To reuse or redistribute any code sample, you must comply with the license found in the upstream repository (see the LICENSE file in that repo for full terms). The dataset organization and the README.md file are licensed under Creative Commons Attribution 4.0 International (CC‑BY‑4.0).

Downloads last month
119