1 // OpenTween - Client of Twitter
2 // Copyright (c) 2014 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
23 using System.Collections.Generic;
24 using System.Diagnostics.CodeAnalysis;
27 using System.Net.Cache;
28 using System.Net.Http;
30 using System.Threading;
31 using System.Threading.Tasks;
33 namespace OpenTween.Connection
35 public static class Networking
37 public static TimeSpan DefaultTimeout { get; set; }
38 public static TimeSpan UploadImageTimeout { get; set; }
43 public static ProxyType ProxyType { get; private set; } = ProxyType.IE;
48 public static IWebProxy Proxy { get; private set; } = null;
51 /// OpenTween 内で共通して使用する HttpClient インスタンス
53 public static HttpClient Http => globalHttpClient;
56 /// pbs.twimg.com で IPv4 を強制的に使用する
58 public static bool ForceIPv4
63 if (forceIPv4 == value)
68 // Network.Http を再作成させる
69 OnWebProxyChanged(EventArgs.Empty);
74 /// Webプロキシの設定が変更された場合に発生します
76 public static event EventHandler WebProxyChanged;
78 private static bool initialized = false;
79 private static HttpClient globalHttpClient;
80 private static bool forceIPv4 = false;
82 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
85 DefaultTimeout = TimeSpan.FromSeconds(20);
86 UploadImageTimeout = TimeSpan.FromSeconds(60);
87 globalHttpClient = CreateHttpClient(new HttpClientHandler());
91 /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。
93 public static void Initialize()
95 Networking.initialized = true;
97 ServicePointManager.Expect100Continue = false;
100 public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort,
101 string proxyUser, string proxyPassword)
109 case ProxyType.Specified:
110 proxy = new WebProxy(proxyAddress, proxyPort);
111 if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword))
112 proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
116 proxy = WebRequest.GetSystemWebProxy();
120 Networking.ProxyType = proxyType;
121 Networking.Proxy = proxy;
123 NativeMethods.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
125 OnWebProxyChanged(EventArgs.Empty);
129 /// OpenTween で必要な設定を施した HttpClientHandler インスタンスを生成します
131 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
132 public static WebRequestHandler CreateHttpClientHandler()
134 var handler = new WebRequestHandler
136 AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
139 if (Networking.Proxy != null)
141 handler.UseProxy = true;
142 handler.Proxy = Networking.Proxy;
146 handler.UseProxy = false;
153 /// OpenTween で必要な設定を施した HttpClient インスタンスを生成します
156 /// 通常は Networking.Http を使用すべきです。
157 /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
159 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
160 public static HttpClient CreateHttpClient(HttpMessageHandler handler)
164 client = new HttpClient(new ForceIPv4Handler(handler));
166 client = new HttpClient(handler);
168 client.Timeout = Networking.DefaultTimeout;
169 client.DefaultRequestHeaders.Add("User-Agent", Networking.GetUserAgentString());
174 public static string GetUserAgentString(bool fakeMSIE = false)
177 return ApplicationSettings.AssemblyName + "/" + MyCommon.FileVersion + " (compatible; MSIE 10.0)";
179 return ApplicationSettings.AssemblyName + "/" + MyCommon.FileVersion;
183 /// Initialize() メソッドが事前に呼ばれているか確認します
185 internal static void CheckInitialized()
187 if (!Networking.initialized)
188 throw new InvalidOperationException("Sequence error.(not initialized)");
191 [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")]
192 private static void OnWebProxyChanged(EventArgs e)
194 var newClient = Networking.CreateHttpClient(Networking.CreateHttpClientHandler());
195 var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient);
198 WebProxyChanged?.Invoke(null, e);
201 private class ForceIPv4Handler : DelegatingHandler
203 private readonly IPAddress ipv4Address;
205 public ForceIPv4Handler(HttpMessageHandler innerHandler)
208 foreach (var address in Dns.GetHostAddresses("pbs.twimg.com"))
209 if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
210 this.ipv4Address = address;
213 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
215 var requestUri = request.RequestUri;
216 if (requestUri.Host == "pbs.twimg.com")
218 var rewriteUriStr = requestUri.GetLeftPart(UriPartial.Scheme) + this.ipv4Address + requestUri.PathAndQuery;
219 request.RequestUri = new Uri(rewriteUriStr);
220 request.Headers.Host = "pbs.twimg.com";
223 return base.SendAsync(request, cancellationToken);
228 public enum ProxyType