using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using System.Xml; using MediaBrowser.Controller.Entities; namespace Emby.Server.Implementations { public class ProxyHttpClientHandler : HttpClientHandler { public ProxyHttpClientHandler() { base.ServerCertificateCustomValidationCallback = ((HttpRequestMessage message, X509Certificate2 certificate2, X509Chain arg3, SslPolicyErrors arg4) => true); base.UseProxy = true; } protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!(request.Headers.UserAgent?.Count() > 0)) { request.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"); } // 获取插件xml配置 string ProxyType = null; string JsProxy = null; List JsProxyBypass = null; string path = CollectionFolder.ConfigurationManager.ApplicationPaths.PluginConfigurationsPath + "\\EmbyJsProxy.xml"; if (File.Exists(path)) { XmlTextReader xtr = new XmlTextReader(path); while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element) { string name = xtr.LocalName; if (name == "ProxyType") { ProxyType = xtr.ReadString(); } else if (name == "JsProxy") { JsProxy = xtr.ReadString(); } else if (name == "JsProxyBypass") { JsProxyBypass = xtr.ReadString()?.Split(" ,;,;".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries).Select(o => o.Trim()) .Distinct().ToList() ?? new List(); } } } xtr.Close(); } // 初始化 string url = request.RequestUri.ToString(); string org_url = url; // 如果禁用代理 或 域名不匹配 if (ProxyType == null || JsProxy == null || JsProxyBypass == null || ProxyType == "-1" || JsProxyBypass?.All(v => url.IndexOf(v, StringComparison.OrdinalIgnoreCase) == -1) == true) { if (request.Headers.Referrer == null) { request.Headers.Referrer = request.RequestUri; } return base.SendAsync(request, cancellationToken); } // 否则加上代理 int i = org_url.IndexOf("/http/", StringComparison.CurrentCultureIgnoreCase); if (i > 0) { org_url = org_url.Substring(i + 6); } Uri uri_org = new Uri(org_url); if (url.StartsWith(JsProxy, StringComparison.OrdinalIgnoreCase) != true) { url = $"{JsProxy.TrimEnd()}/http/{url}"; request.RequestUri = new Uri(url); } url = request.Headers.Referrer?.ToString(); if (string.IsNullOrWhiteSpace(url)) { request.Headers.Referrer = uri_org; } return base.SendAsync(request, cancellationToken); } } }