From 6e9dab3f9a2746b07c8b86194737bb47c6b45a28 Mon Sep 17 00:00:00 2001 From: Kimura Youichi Date: Sun, 29 Jun 2014 12:28:43 +0900 Subject: [PATCH] =?utf8?q?HttpConnection=E3=82=AF=E3=83=A9=E3=82=B9?= =?utf8?q?=E3=81=AB=E3=81=82=E3=82=8B=E9=80=9A=E4=BF=A1=E8=A8=AD=E5=AE=9A?= =?utf8?q?=E3=81=AE=E5=88=9D=E6=9C=9F=E5=8C=96=E3=81=AA=E3=81=A9=E3=81=AE?= =?utf8?q?=E5=87=A6=E7=90=86=E3=82=92Networking=E3=82=AF=E3=83=A9=E3=82=B9?= =?utf8?q?=E3=81=AB=E7=A7=BB=E5=8B=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 移動したプロパティ等: * HttpConnection.DefaultTimeout -> Networking.DefaultTimeout * HttpConnection.proxyKind -> Networking.ProxyType * HttpConnection.proxy -> Networking.Proxy * HttpConnection.GlobalHttpClient -> Networking.Http * HttpConnection.WebProxyChanged -> Networking.WebProxyChanged * HttpConnection.InitializeConnection() -> Networking.Initialize() * HttpConnection.SetWebProxy() -> Networking.SetWebProxy() * HttpConnection.CreateHttpClient() -> Networking.CreateHttpClient() * MyCommon.GetUserAgentString() -> Networking.GetUserAgentString() --- OpenTween.Tests/Connection/NetworkingTest.cs | 61 +++++++ OpenTween.Tests/MyCommonTest.cs | 24 --- OpenTween.Tests/OpenTween.Tests.csproj | 1 + OpenTween/AppendSettingDialog.cs | 26 +-- OpenTween/Bing.cs | 3 +- OpenTween/Connection/HttpConnection.cs | 166 +------------------ OpenTween/Connection/HttpVarious.cs | 3 +- OpenTween/Connection/Imgur.cs | 2 +- OpenTween/Connection/Networking.cs | 175 +++++++++++++++++++++ OpenTween/ImageCache.cs | 3 +- OpenTween/MyCommon.cs | 8 - OpenTween/OpenTween.csproj | 1 + OpenTween/Setting/SettingLocal.cs | 3 +- OpenTween/ShortUrl.cs | 5 +- OpenTween/Thumbnail/Services/FoursquareCheckin.cs | 3 +- OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs | 3 +- .../Thumbnail/Services/MetaThumbnailService.cs | 3 +- OpenTween/Thumbnail/Services/Nicovideo.cs | 3 +- OpenTween/Thumbnail/Services/Pixiv.cs | 3 +- OpenTween/Thumbnail/Services/Tinami.cs | 3 +- OpenTween/Thumbnail/Services/TonTwitterCom.cs | 3 +- OpenTween/Thumbnail/Services/ViaMe.cs | 3 +- OpenTween/Thumbnail/Services/Vimeo.cs | 3 +- OpenTween/Thumbnail/ThumbnailInfo.cs | 3 +- OpenTween/Tween.cs | 24 ++- OpenTween/Twitter.cs | 3 +- OpenTween/UserInfoDialog.cs | 3 +- OpenTween/Win32Api.cs | 9 +- 28 files changed, 312 insertions(+), 238 deletions(-) create mode 100644 OpenTween.Tests/Connection/NetworkingTest.cs create mode 100644 OpenTween/Connection/Networking.cs diff --git a/OpenTween.Tests/Connection/NetworkingTest.cs b/OpenTween.Tests/Connection/NetworkingTest.cs new file mode 100644 index 00000000..5ce4f14d --- /dev/null +++ b/OpenTween.Tests/Connection/NetworkingTest.cs @@ -0,0 +1,61 @@ +// OpenTween - Client of Twitter +// Copyright (c) 2014 kim_upsilon (@kim_upsilon) +// All rights reserved. +// +// This file is part of OpenTween. +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program. If not, see , or write to +// the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, +// Boston, MA 02110-1301, USA. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using NSubstitute; +using Xunit; +using Xunit.Extensions; + +namespace OpenTween.Connection +{ + public class NetworkingTest + { + [Fact] + public void GetUserAgentString_Test() + { + var mockAssembly = Substitute.For<_Assembly>(); + mockAssembly.GetName().Returns(new AssemblyName("OpenTween")); + + MyCommon.EntryAssembly = mockAssembly; + MyCommon.FileVersion = "1.0.0.0"; + + Assert.Equal("OpenTween/1.0.0.0", Networking.GetUserAgentString()); + } + + [Fact] + public void GetUserAgentString_FakeMSIETest() + { + var mockAssembly = Substitute.For<_Assembly>(); + mockAssembly.GetName().Returns(new AssemblyName("OpenTween")); + + MyCommon.EntryAssembly = mockAssembly; + MyCommon.FileVersion = "1.0.0.0"; + + Assert.Equal("OpenTween/1.0.0.0 (compatible; MSIE 10.0)", Networking.GetUserAgentString(fakeMSIE: true)); + } + } +} diff --git a/OpenTween.Tests/MyCommonTest.cs b/OpenTween.Tests/MyCommonTest.cs index 4b70f1b7..9a9fc5e1 100644 --- a/OpenTween.Tests/MyCommonTest.cs +++ b/OpenTween.Tests/MyCommonTest.cs @@ -254,30 +254,6 @@ namespace OpenTween } [Fact] - public void GetUserAgentString_Test() - { - var mockAssembly = Substitute.For<_Assembly>(); - mockAssembly.GetName().Returns(new AssemblyName("OpenTween")); - - MyCommon.EntryAssembly = mockAssembly; - MyCommon.FileVersion = "1.0.0.0"; - - Assert.Equal("OpenTween/1.0.0.0", MyCommon.GetUserAgentString()); - } - - [Fact] - public void GetUserAgentString_FakeMSIETest() - { - var mockAssembly = Substitute.For<_Assembly>(); - mockAssembly.GetName().Returns(new AssemblyName("OpenTween")); - - MyCommon.EntryAssembly = mockAssembly; - MyCommon.FileVersion = "1.0.0.0"; - - Assert.Equal("OpenTween/1.0.0.0 (compatible; MSIE 10.0)", MyCommon.GetUserAgentString(fakeMSIE: true)); - } - - [Fact] public void GetErrorLogPathTest() { if (Environment.OSVersion.Platform == PlatformID.Win32NT) diff --git a/OpenTween.Tests/OpenTween.Tests.csproj b/OpenTween.Tests/OpenTween.Tests.csproj index 1eccfa48..2d9fb764 100644 --- a/OpenTween.Tests/OpenTween.Tests.csproj +++ b/OpenTween.Tests/OpenTween.Tests.csproj @@ -65,6 +65,7 @@ + diff --git a/OpenTween/AppendSettingDialog.cs b/OpenTween/AppendSettingDialog.cs index 38ca503e..c57a67fc 100644 --- a/OpenTween/AppendSettingDialog.cs +++ b/OpenTween/AppendSettingDialog.cs @@ -36,6 +36,7 @@ using System.Threading; using System.IO; using System.Resources; using OpenTween.Api; +using OpenTween.Connection; using OpenTween.Thumbnail; using System.Threading.Tasks; using OpenTween.Setting.Panel; @@ -46,7 +47,7 @@ namespace OpenTween { private static AppendSettingDialog _instance = new AppendSettingDialog(); private Twitter tw; - private HttpConnection.ProxyType _MyProxyType; + private ProxyType _MyProxyType; private bool _ValidationError = false; private MyCommon.EVENTTYPE _MyEventNotifyFlag; @@ -377,15 +378,15 @@ namespace OpenTween ShortUrl.Instance.DisableExpanding = !TinyUrlResolve; if (this.ProxyPanel.RadioProxyNone.Checked) { - _MyProxyType = HttpConnection.ProxyType.None; + _MyProxyType = ProxyType.None; } else if (this.ProxyPanel.RadioProxyIE.Checked) { - _MyProxyType = HttpConnection.ProxyType.IE; + _MyProxyType = ProxyType.IE; } else { - _MyProxyType = HttpConnection.ProxyType.Specified; + _MyProxyType = ProxyType.Specified; } ProxyAddress = this.ProxyPanel.TextProxyAddress.Text.Trim(); ProxyPort = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim()); @@ -723,10 +724,10 @@ namespace OpenTween this.ShortUrlPanel.CheckTinyURL.Checked = TinyUrlResolve; switch (_MyProxyType) { - case HttpConnection.ProxyType.None: + case ProxyType.None: this.ProxyPanel.RadioProxyNone.Checked = true; break; - case HttpConnection.ProxyType.IE: + case ProxyType.IE: this.ProxyPanel.RadioProxyIE.Checked = true; break; default: @@ -1139,7 +1140,7 @@ namespace OpenTween public bool TinyUrlResolve { get; set; } public bool SortOrderLock { get; set; } - public HttpConnection.ProxyType SelectedProxyType + public ProxyType SelectedProxyType { get { return _MyProxyType; @@ -1237,18 +1238,18 @@ namespace OpenTween private bool StartAuth() { //現在の設定内容で通信 - HttpConnection.ProxyType ptype; + ProxyType ptype; if (this.ProxyPanel.RadioProxyNone.Checked) { - ptype = HttpConnection.ProxyType.None; + ptype = ProxyType.None; } else if (this.ProxyPanel.RadioProxyIE.Checked) { - ptype = HttpConnection.ProxyType.IE; + ptype = ProxyType.IE; } else { - ptype = HttpConnection.ProxyType.Specified; + ptype = ProxyType.Specified; } string padr = this.ProxyPanel.TextProxyAddress.Text.Trim(); int pport = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim()); @@ -1256,7 +1257,8 @@ namespace OpenTween string ppw = this.ProxyPanel.TextProxyPassword.Text.Trim(); //通信基底クラス初期化 - HttpConnection.InitializeConnection(20, ptype, padr, pport, pusr, ppw); + Networking.DefaultTimeout = TimeSpan.FromSeconds(20); + Networking.SetWebProxy(ptype, padr, pport, pusr, ppw); HttpTwitter.TwitterUrl = this.ConnectionPanel.TwitterAPIText.Text.Trim(); tw.Initialize("", "", "", 0); //this.AuthStateLabel.Text = Properties.Resources.AuthorizeButton_Click4; diff --git a/OpenTween/Bing.cs b/OpenTween/Bing.cs index 377ce58b..292f69f7 100644 --- a/OpenTween/Bing.cs +++ b/OpenTween/Bing.cs @@ -32,6 +32,7 @@ using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; +using OpenTween.Connection; namespace OpenTween { @@ -170,7 +171,7 @@ namespace OpenTween protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Connection/HttpConnection.cs b/OpenTween/Connection/HttpConnection.cs index fe3000ec..ea393734 100644 --- a/OpenTween/Connection/HttpConnection.cs +++ b/OpenTween/Connection/HttpConnection.cs @@ -34,6 +34,7 @@ using System; using System.Collections.Generic; using System.IO.Compression; using System.Drawing; +using OpenTween.Connection; /// ///HttpWebRequest,HttpWebResponseを使用した基本的な通信機能を提供する @@ -46,28 +47,6 @@ namespace OpenTween { public class HttpConnection { - /// - ///プロキシ - /// - private static IWebProxy proxy = null; - - /// - ///ユーザーが選択したプロキシの方式 - /// - private static ProxyType proxyKind = ProxyType.IE; - - /// - ///初期化済みフラグ - /// - private static bool isInitialize = false; - - public enum ProxyType - { - None, - IE, - Specified, - } - /// /// リクエスト間で Cookie を保持するか否か /// @@ -98,7 +77,7 @@ namespace OpenTween Uri requestUri, Dictionary param) { - if (!isInitialize) throw new Exception("Sequence error.(not initialized)"); + Networking.CheckInitialized(); //GETメソッドの場合はクエリとurlを結合 UriBuilder ub = new UriBuilder(requestUri.AbsoluteUri); @@ -112,7 +91,7 @@ namespace OpenTween webReq.ReadWriteTimeout = 90 * 1000; //Streamの読み込みは90秒でタイムアウト(デフォルト5分) //プロキシ設定 - if (proxyKind != ProxyType.IE) webReq.Proxy = proxy; + if (Networking.ProxyType != ProxyType.IE) webReq.Proxy = Networking.Proxy; webReq.Method = method; if (method == "POST" || method == "PUT") @@ -127,9 +106,9 @@ namespace OpenTween //cookie設定 if (this.UseCookie) webReq.CookieContainer = this.cookieContainer; //タイムアウト設定 - webReq.Timeout = this.InstanceTimeout ?? HttpConnection.DefaultTimeout; + webReq.Timeout = this.InstanceTimeout ?? (int)Networking.DefaultTimeout.TotalMilliseconds; - webReq.UserAgent = MyCommon.GetUserAgentString(); + webReq.UserAgent = Networking.GetUserAgentString(); return webReq; } @@ -150,7 +129,7 @@ namespace OpenTween Dictionary param, List> binaryFileInfo) { - if (!isInitialize) throw new Exception("Sequence error.(not initialized)"); + Networking.CheckInitialized(); //methodはPOST,PUTのみ許可 UriBuilder ub = new UriBuilder(requestUri.AbsoluteUri); @@ -162,7 +141,7 @@ namespace OpenTween HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(ub.Uri); //プロキシ設定 - if (proxyKind != ProxyType.IE) webReq.Proxy = proxy; + if (Networking.ProxyType != ProxyType.IE) webReq.Proxy = Networking.Proxy; webReq.Method = method; if (method == "POST" || method == "PUT") @@ -277,7 +256,7 @@ namespace OpenTween //cookie設定 if (this.UseCookie) webReq.CookieContainer = this.cookieContainer; //タイムアウト設定 - webReq.Timeout = this.InstanceTimeout ?? HttpConnection.DefaultTimeout; + webReq.Timeout = this.InstanceTimeout ?? (int)Networking.DefaultTimeout.TotalMilliseconds; return webReq; } @@ -585,134 +564,5 @@ namespace OpenTween } } #endregion - - #region "DefaultTimeout" - /// - ///通信タイムアウト時間(ms) - /// - private static int timeout = 20000; - - /// - ///通信タイムアウト時間(ms)。10~120秒の範囲で指定。範囲外は20秒とする - /// - protected static int DefaultTimeout - { - get { return timeout; } - set - { - const int TimeoutMinValue = 10000; - const int TimeoutMaxValue = 120000; - const int TimeoutDefaultValue = 20000; - if (value < TimeoutMinValue || value > TimeoutMaxValue) - // 範囲外ならデフォルト値設定 - timeout = TimeoutDefaultValue; - else - timeout = value; - } - } - #endregion - - /// - /// OpenTween 内で共通して使用する HttpClient インスタンス - /// - public static HttpClient GlobalHttpClient - { - get { return globalHttpClient; } - } - - /// - /// Webプロキシの設定が変更された場合に発生します - /// - public static event EventHandler WebProxyChanged; - - private static HttpClient globalHttpClient = CreateHttpClient(new HttpClientHandler()); - - /// - ///通信クラスの初期化処理。タイムアウト値とプロキシを設定する - /// - /// - ///通信開始前に最低一度呼び出すこと - /// - ///タイムアウト値(秒) - ///なし・指定・IEデフォルト - ///プロキシのホスト名orIPアドレス - ///プロキシのポート番号 - ///プロキシ認証が必要な場合のユーザ名。不要なら空文字 - ///プロキシ認証が必要な場合のパスワード。不要なら空文字 - public static void InitializeConnection(int timeout, - ProxyType proxyType, string proxyAddress, int proxyPort, - string proxyUser, string proxyPassword) - { - HttpConnection.isInitialize = true; - HttpConnection.DefaultTimeout = timeout * 1000; // s -> ms - - ServicePointManager.Expect100Continue = false; - - SetWebProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword); - } - - public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort, - string proxyUser, string proxyPassword) - { - IWebProxy proxy; - switch (proxyType) - { - case ProxyType.None: - proxy = null; - break; - case ProxyType.Specified: - proxy = new WebProxy(proxyAddress, proxyPort); - if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword)) - proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword); - break; - case ProxyType.IE: - default: - proxy = WebRequest.GetSystemWebProxy(); - break; - } - - HttpConnection.proxyKind = proxyType; - HttpConnection.proxy = proxy; - - Win32Api.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword); - - OnWebProxyChanged(EventArgs.Empty); - } - - /// - /// プロキシ等の設定を施した HttpClient インスタンスを生成します - /// - /// - /// 通常は HttpConnection.GlobalHttpClient を使用すべきです。 - /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。 - /// - public static HttpClient CreateHttpClient(HttpClientHandler handler) - { - if (HttpConnection.proxy != null) - { - handler.UseProxy = true; - handler.Proxy = HttpConnection.proxy; - } - else - { - handler.UseProxy = false; - } - - var client = new HttpClient(handler); - client.Timeout = TimeSpan.FromMilliseconds(HttpConnection.DefaultTimeout); - client.DefaultRequestHeaders.Add("User-Agent", MyCommon.GetUserAgentString()); - - return client; - } - - private static void OnWebProxyChanged(EventArgs e) - { - var newClient = HttpConnection.CreateHttpClient(new HttpClientHandler()); - var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient); - oldClient.Dispose(); - - if (WebProxyChanged != null) - WebProxyChanged(null, e); - } } } \ No newline at end of file diff --git a/OpenTween/Connection/HttpVarious.cs b/OpenTween/Connection/HttpVarious.cs index f84396bc..08094f70 100644 --- a/OpenTween/Connection/HttpVarious.cs +++ b/OpenTween/Connection/HttpVarious.cs @@ -32,6 +32,7 @@ using System.Text; using System.Drawing; using System.IO; using System.Drawing.Drawing2D; +using OpenTween.Connection; namespace OpenTween @@ -228,7 +229,7 @@ namespace OpenTween { HttpWebRequest req = CreateRequest(GetMethod, new Uri(Url), null); req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; - req.UserAgent = MyCommon.GetUserAgentString(); + req.UserAgent = Networking.GetUserAgentString(); using (FileStream strm = new FileStream(savePath, FileMode.Create, FileAccess.Write)) { try diff --git a/OpenTween/Connection/Imgur.cs b/OpenTween/Connection/Imgur.cs index ba7fc085..cf2d06bc 100644 --- a/OpenTween/Connection/Imgur.cs +++ b/OpenTween/Connection/Imgur.cs @@ -153,7 +153,7 @@ namespace OpenTween.Connection new AuthenticationHeaderValue("Client-ID", ApplicationSettings.ImgurClientID); request.Content = content; - using (var response = await HttpConnection.GlobalHttpClient.SendAsync(request).ConfigureAwait(false)) + using (var response = await Networking.Http.SendAsync(request).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); diff --git a/OpenTween/Connection/Networking.cs b/OpenTween/Connection/Networking.cs new file mode 100644 index 00000000..4cba411c --- /dev/null +++ b/OpenTween/Connection/Networking.cs @@ -0,0 +1,175 @@ +// OpenTween - Client of Twitter +// Copyright (c) 2014 kim_upsilon (@kim_upsilon) +// All rights reserved. +// +// This file is part of OpenTween. +// +// This program is free software; you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation; either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program. If not, see , or write to +// the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, +// Boston, MA 02110-1301, USA. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenTween.Connection +{ + public static class Networking + { + public static TimeSpan DefaultTimeout { get; set; } + + /// + /// 通信に使用するプロキシの種類 + /// + public static ProxyType ProxyType + { + get { return proxyType; } + } + + /// + /// 通信に使用するプロキシ + /// + public static IWebProxy Proxy + { + get { return proxy; } + } + + /// + /// OpenTween 内で共通して使用する HttpClient インスタンス + /// + public static HttpClient Http + { + get { return globalHttpClient; } + } + + /// + /// Webプロキシの設定が変更された場合に発生します + /// + public static event EventHandler WebProxyChanged; + + private static bool initialized = false; + private static HttpClient globalHttpClient; + private static ProxyType proxyType = ProxyType.IE; + private static IWebProxy proxy = null; + + static Networking() + { + DefaultTimeout = TimeSpan.FromSeconds(20); + globalHttpClient = CreateHttpClient(new HttpClientHandler()); + } + + /// + /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。 + /// + public static void Initialize() + { + Networking.initialized = true; + + ServicePointManager.Expect100Continue = false; + } + + public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort, + string proxyUser, string proxyPassword) + { + IWebProxy proxy; + switch (proxyType) + { + case ProxyType.None: + proxy = null; + break; + case ProxyType.Specified: + proxy = new WebProxy(proxyAddress, proxyPort); + if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword)) + proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword); + break; + case ProxyType.IE: + default: + proxy = WebRequest.GetSystemWebProxy(); + break; + } + + Networking.proxyType = proxyType; + Networking.proxy = proxy; + + Win32Api.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword); + + OnWebProxyChanged(EventArgs.Empty); + } + + /// + /// プロキシ等の設定を施した HttpClient インスタンスを生成します + /// + /// + /// 通常は Networking.Http を使用すべきです。 + /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。 + /// + public static HttpClient CreateHttpClient(HttpClientHandler handler) + { + if (Networking.Proxy != null) + { + handler.UseProxy = true; + handler.Proxy = Networking.Proxy; + } + else + { + handler.UseProxy = false; + } + + var client = new HttpClient(handler); + client.Timeout = Networking.DefaultTimeout; + client.DefaultRequestHeaders.Add("User-Agent", Networking.GetUserAgentString()); + + return client; + } + + public static string GetUserAgentString(bool fakeMSIE = false) + { + if (fakeMSIE) + return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion + " (compatible; MSIE 10.0)"; + else + return MyCommon.GetAssemblyName() + "/" + MyCommon.FileVersion; + } + + /// + /// Initialize() メソッドが事前に呼ばれているか確認します + /// + internal static void CheckInitialized() + { + if (!Networking.initialized) + throw new InvalidOperationException("Sequence error.(not initialized)"); + } + + private static void OnWebProxyChanged(EventArgs e) + { + var newClient = Networking.CreateHttpClient(new HttpClientHandler()); + var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient); + oldClient.Dispose(); + + if (WebProxyChanged != null) + WebProxyChanged(null, e); + } + } + + public enum ProxyType + { + None, + IE, + Specified, + } +} diff --git a/OpenTween/ImageCache.cs b/OpenTween/ImageCache.cs index 1fa3c705..5b2e16d7 100644 --- a/OpenTween/ImageCache.cs +++ b/OpenTween/ImageCache.cs @@ -28,6 +28,7 @@ using System.Net; using System.Threading; using System.Xml.Serialization; using System.Net.Http; +using OpenTween.Connection; namespace OpenTween { @@ -122,7 +123,7 @@ namespace OpenTween private async Task FetchImageAsync(string uri, CancellationToken cancelToken) { - using (var response = await HttpConnection.GlobalHttpClient.GetAsync(uri, cancelToken).ConfigureAwait(false)) + using (var response = await Networking.Http.GetAsync(uri, cancelToken).ConfigureAwait(false)) { var imageStream = await response.Content.ReadAsStreamAsync() .ConfigureAwait(false); diff --git a/OpenTween/MyCommon.cs b/OpenTween/MyCommon.cs index c5bf3527..0e142fa2 100644 --- a/OpenTween/MyCommon.cs +++ b/OpenTween/MyCommon.cs @@ -752,14 +752,6 @@ namespace OpenTween //RTByMe } - public static string GetUserAgentString(bool fakeMSIE = false) - { - if (fakeMSIE) - return GetAssemblyName() + "/" + FileVersion + " (compatible; MSIE 10.0)"; - else - return GetAssemblyName() + "/" + FileVersion; - } - public static TwitterApiStatus TwitterApiInfo = new TwitterApiStatus(); public static bool IsAnimatedGif(string filename) diff --git a/OpenTween/OpenTween.csproj b/OpenTween/OpenTween.csproj index fa3f2263..cc64a45e 100644 --- a/OpenTween/OpenTween.csproj +++ b/OpenTween/OpenTween.csproj @@ -114,6 +114,7 @@ + Form diff --git a/OpenTween/Setting/SettingLocal.cs b/OpenTween/Setting/SettingLocal.cs index c762d9c1..c439f902 100644 --- a/OpenTween/Setting/SettingLocal.cs +++ b/OpenTween/Setting/SettingLocal.cs @@ -30,6 +30,7 @@ using System.Linq; using System.Text; using System.Drawing; using System.Xml.Serialization; +using OpenTween.Connection; namespace OpenTween { @@ -70,7 +71,7 @@ namespace OpenTween public int DisplayIndex7 = 0; public int DisplayIndex8 = 7; public string BrowserPath = ""; - public HttpConnection.ProxyType ProxyType = HttpConnection.ProxyType.IE; + public ProxyType ProxyType = ProxyType.IE; public string ProxyAddress = "127.0.0.1"; public int ProxyPort = 80; public string ProxyUser = ""; diff --git a/OpenTween/ShortUrl.cs b/OpenTween/ShortUrl.cs index 4250c47a..50a3b935 100644 --- a/OpenTween/ShortUrl.cs +++ b/OpenTween/ShortUrl.cs @@ -34,6 +34,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web; +using OpenTween.Connection; namespace OpenTween { @@ -129,7 +130,7 @@ namespace OpenTween internal ShortUrl() : this(CreateDefaultHttpClient()) { - HttpConnection.WebProxyChanged += (o, e) => + Networking.WebProxyChanged += (o, e) => { var newClient = CreateDefaultHttpClient(); var oldClient = Interlocked.Exchange(ref this.http, newClient); @@ -497,7 +498,7 @@ namespace OpenTween AllowAutoRedirect = false, }; - var http = HttpConnection.CreateHttpClient(handler); + var http = Networking.CreateHttpClient(handler); http.Timeout = TimeSpan.FromSeconds(5); return http; diff --git a/OpenTween/Thumbnail/Services/FoursquareCheckin.cs b/OpenTween/Thumbnail/Services/FoursquareCheckin.cs index bd105cc4..0a7a16e6 100644 --- a/OpenTween/Thumbnail/Services/FoursquareCheckin.cs +++ b/OpenTween/Thumbnail/Services/FoursquareCheckin.cs @@ -30,6 +30,7 @@ using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -42,7 +43,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs b/OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs index 03fab2f0..d888d6fc 100644 --- a/OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs +++ b/OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs @@ -29,6 +29,7 @@ using System.Xml.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -45,7 +46,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/Services/MetaThumbnailService.cs b/OpenTween/Thumbnail/Services/MetaThumbnailService.cs index ff4b1a7f..5d692748 100644 --- a/OpenTween/Thumbnail/Services/MetaThumbnailService.cs +++ b/OpenTween/Thumbnail/Services/MetaThumbnailService.cs @@ -28,6 +28,7 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -41,7 +42,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/Services/Nicovideo.cs b/OpenTween/Thumbnail/Services/Nicovideo.cs index a2c1bb8a..47588807 100644 --- a/OpenTween/Thumbnail/Services/Nicovideo.cs +++ b/OpenTween/Thumbnail/Services/Nicovideo.cs @@ -32,6 +32,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -54,7 +55,7 @@ namespace OpenTween.Thumbnail.Services var src = ""; var imgurl = ""; string errmsg; - if ((new HttpVarious()).GetData(apiUrl, null, out src, 0, out errmsg, MyCommon.GetUserAgentString())) + if ((new HttpVarious()).GetData(apiUrl, null, out src, 0, out errmsg, Networking.GetUserAgentString())) { var sb = new StringBuilder(); var xdoc = new XmlDocument(); diff --git a/OpenTween/Thumbnail/Services/Pixiv.cs b/OpenTween/Thumbnail/Services/Pixiv.cs index 9716a1b8..57036e91 100644 --- a/OpenTween/Thumbnail/Services/Pixiv.cs +++ b/OpenTween/Thumbnail/Services/Pixiv.cs @@ -28,6 +28,7 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -68,7 +69,7 @@ namespace OpenTween.Thumbnail.Services { var request = new HttpRequestMessage(HttpMethod.Get, this.ThumbnailUrl); - request.Headers.Add("User-Agent", MyCommon.GetUserAgentString(fakeMSIE: true)); + request.Headers.Add("User-Agent", Networking.GetUserAgentString(fakeMSIE: true)); request.Headers.Referrer = new Uri(this.ImageUrl); using (var response = await http.SendAsync(request, cancellationToken).ConfigureAwait(false)) diff --git a/OpenTween/Thumbnail/Services/Tinami.cs b/OpenTween/Thumbnail/Services/Tinami.cs index e5bd1b3c..4b4c40a4 100644 --- a/OpenTween/Thumbnail/Services/Tinami.cs +++ b/OpenTween/Thumbnail/Services/Tinami.cs @@ -30,6 +30,7 @@ using System.Threading.Tasks; using System.Web; using System.Xml.Linq; using System.Xml.XPath; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -40,7 +41,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/Services/TonTwitterCom.cs b/OpenTween/Thumbnail/Services/TonTwitterCom.cs index b76f7e40..b17a399a 100644 --- a/OpenTween/Thumbnail/Services/TonTwitterCom.cs +++ b/OpenTween/Thumbnail/Services/TonTwitterCom.cs @@ -28,6 +28,7 @@ using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -72,7 +73,7 @@ namespace OpenTween.Thumbnail.Services TonTwitterCom.InitializeOAuthToken(oauth); Stream response = null; - var statusCode = oauth.GetContent("GET", new Uri(this.ThumbnailUrl), null, ref response, MyCommon.GetUserAgentString()); + var statusCode = oauth.GetContent("GET", new Uri(this.ThumbnailUrl), null, ref response, Networking.GetUserAgentString()); using (response) { diff --git a/OpenTween/Thumbnail/Services/ViaMe.cs b/OpenTween/Thumbnail/Services/ViaMe.cs index 08f26cd4..be5efb50 100644 --- a/OpenTween/Thumbnail/Services/ViaMe.cs +++ b/OpenTween/Thumbnail/Services/ViaMe.cs @@ -32,6 +32,7 @@ using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -42,7 +43,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/Services/Vimeo.cs b/OpenTween/Thumbnail/Services/Vimeo.cs index b1a40ca4..69987bf0 100644 --- a/OpenTween/Thumbnail/Services/Vimeo.cs +++ b/OpenTween/Thumbnail/Services/Vimeo.cs @@ -32,6 +32,7 @@ using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; +using OpenTween.Connection; namespace OpenTween.Thumbnail.Services { @@ -42,7 +43,7 @@ namespace OpenTween.Thumbnail.Services protected HttpClient http { - get { return this.localHttpClient ?? HttpConnection.GlobalHttpClient; } + get { return this.localHttpClient ?? Networking.Http; } } private readonly HttpClient localHttpClient; diff --git a/OpenTween/Thumbnail/ThumbnailInfo.cs b/OpenTween/Thumbnail/ThumbnailInfo.cs index c9940dac..b5c2c1a4 100644 --- a/OpenTween/Thumbnail/ThumbnailInfo.cs +++ b/OpenTween/Thumbnail/ThumbnailInfo.cs @@ -26,6 +26,7 @@ using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; +using OpenTween.Connection; namespace OpenTween.Thumbnail { @@ -43,7 +44,7 @@ namespace OpenTween.Thumbnail public Task LoadThumbnailImageAsync(CancellationToken cancellationToken) { - return this.LoadThumbnailImageAsync(HttpConnection.GlobalHttpClient, cancellationToken); + return this.LoadThumbnailImageAsync(Networking.Http, cancellationToken); } public async virtual Task LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken) diff --git a/OpenTween/Tween.cs b/OpenTween/Tween.cs index f2ceadb8..1cad0105 100644 --- a/OpenTween/Tween.cs +++ b/OpenTween/Tween.cs @@ -914,6 +914,8 @@ namespace OpenTween _initial = true; + Networking.Initialize(); + //アイコンリスト作成 this.IconCache = new ImageCache(); @@ -992,12 +994,10 @@ namespace OpenTween } //Twitter用通信クラス初期化 - HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut, - SettingDialog.SelectedProxyType, - SettingDialog.ProxyAddress, - SettingDialog.ProxyPort, - SettingDialog.ProxyUser, - SettingDialog.ProxyPassword); + Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut); + Networking.SetWebProxy(this.SettingDialog.SelectedProxyType, + this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort, + this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword); tw.RestrictFavCheck = SettingDialog.RestrictFavCheck; tw.ReadOwnPost = SettingDialog.ReadOwnPost; @@ -3915,12 +3915,10 @@ namespace OpenTween ShortUrl.Instance.BitlyKey = SettingDialog.BitlyPwd; HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl; - HttpConnection.InitializeConnection(SettingDialog.DefaultTimeOut, - SettingDialog.SelectedProxyType, - SettingDialog.ProxyAddress, - SettingDialog.ProxyPort, - SettingDialog.ProxyUser, - SettingDialog.ProxyPassword); + Networking.DefaultTimeout = TimeSpan.FromSeconds(this.SettingDialog.DefaultTimeOut); + Networking.SetWebProxy(this.SettingDialog.SelectedProxyType, + this.SettingDialog.ProxyAddress, this.SettingDialog.ProxyPort, + this.SettingDialog.ProxyUser, this.SettingDialog.ProxyPassword); ImageSelector.Reset(tw, SettingDialog.TwitterConfiguration); @@ -5914,7 +5912,7 @@ namespace OpenTween var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount); - var responseText = await HttpConnection.GlobalHttpClient.GetStringAsync(versionInfoUrl) + var responseText = await Networking.Http.GetStringAsync(versionInfoUrl) .ConfigureAwait(false); // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト) diff --git a/OpenTween/Twitter.cs b/OpenTween/Twitter.cs index aeb3b996..04788af8 100644 --- a/OpenTween/Twitter.cs +++ b/OpenTween/Twitter.cs @@ -45,6 +45,7 @@ using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using OpenTween.Api; +using OpenTween.Connection; namespace OpenTween { @@ -3756,7 +3757,7 @@ namespace OpenTween { Started(); } - var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, MyCommon.GetUserAgentString()); + var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString()); switch (res) { diff --git a/OpenTween/UserInfoDialog.cs b/OpenTween/UserInfoDialog.cs index 4a695c6d..92afd4ae 100644 --- a/OpenTween/UserInfoDialog.cs +++ b/OpenTween/UserInfoDialog.cs @@ -38,6 +38,7 @@ using System.Web; using System.IO; using System.Net; using OpenTween.Api; +using OpenTween.Connection; namespace OpenTween { @@ -165,7 +166,7 @@ namespace OpenTween { var uri = imageUri.Replace("_normal", "_bigger"); - var imageStream = await HttpConnection.GlobalHttpClient.GetStreamAsync(uri) + var imageStream = await Networking.Http.GetStreamAsync(uri) .ConfigureAwait(false); return await MemoryImage.CopyFromStreamAsync(imageStream) diff --git a/OpenTween/Win32Api.cs b/OpenTween/Win32Api.cs index c6b04aba..4cbe35ed 100644 --- a/OpenTween/Win32Api.cs +++ b/OpenTween/Win32Api.cs @@ -31,6 +31,7 @@ using System.Net; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; +using OpenTween.Connection; namespace OpenTween { @@ -365,18 +366,18 @@ namespace OpenTween } } - public static void SetProxy(HttpConnection.ProxyType pType, string host, int port, string username, string password) + public static void SetProxy(ProxyType pType, string host, int port, string username, string password) { string proxy = null; switch (pType) { - case HttpConnection.ProxyType.IE: + case ProxyType.IE: proxy = null; break; - case HttpConnection.ProxyType.None: + case ProxyType.None: proxy = ""; break; - case HttpConnection.ProxyType.Specified: + case ProxyType.Specified: proxy = host + (port > 0 ? ":" + port.ToString() : ""); break; } -- 2.11.0