OSDN Git Service

HttpConnectionクラスにある通信設定の初期化などの処理をNetworkingクラスに移動
authorKimura Youichi <kim.upsilon@bucyou.net>
Sun, 29 Jun 2014 03:28:43 +0000 (12:28 +0900)
committerKimura Youichi <kim.upsilon@bucyou.net>
Wed, 2 Jul 2014 10:02:57 +0000 (19:02 +0900)
移動したプロパティ等:

 * 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()

28 files changed:
OpenTween.Tests/Connection/NetworkingTest.cs [new file with mode: 0644]
OpenTween.Tests/MyCommonTest.cs
OpenTween.Tests/OpenTween.Tests.csproj
OpenTween/AppendSettingDialog.cs
OpenTween/Bing.cs
OpenTween/Connection/HttpConnection.cs
OpenTween/Connection/HttpVarious.cs
OpenTween/Connection/Imgur.cs
OpenTween/Connection/Networking.cs [new file with mode: 0644]
OpenTween/ImageCache.cs
OpenTween/MyCommon.cs
OpenTween/OpenTween.csproj
OpenTween/Setting/SettingLocal.cs
OpenTween/ShortUrl.cs
OpenTween/Thumbnail/Services/FoursquareCheckin.cs
OpenTween/Thumbnail/Services/ImgAzyobuziNet.cs
OpenTween/Thumbnail/Services/MetaThumbnailService.cs
OpenTween/Thumbnail/Services/Nicovideo.cs
OpenTween/Thumbnail/Services/Pixiv.cs
OpenTween/Thumbnail/Services/Tinami.cs
OpenTween/Thumbnail/Services/TonTwitterCom.cs
OpenTween/Thumbnail/Services/ViaMe.cs
OpenTween/Thumbnail/Services/Vimeo.cs
OpenTween/Thumbnail/ThumbnailInfo.cs
OpenTween/Tween.cs
OpenTween/Twitter.cs
OpenTween/UserInfoDialog.cs
OpenTween/Win32Api.cs

diff --git a/OpenTween.Tests/Connection/NetworkingTest.cs b/OpenTween.Tests/Connection/NetworkingTest.cs
new file mode 100644 (file)
index 0000000..5ce4f14
--- /dev/null
@@ -0,0 +1,61 @@
+// OpenTween - Client of Twitter
+// Copyright (c) 2014 kim_upsilon (@kim_upsilon) <https://upsilo.net/~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 <http://www.gnu.org/licenses/>, 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));
+        }
+    }
+}
index 4b70f1b..9a9fc5e 100644 (file)
@@ -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)
index 1eccfa4..2d9fb76 100644 (file)
@@ -65,6 +65,7 @@
     <Compile Include="Api\ApiLimitTest.cs" />
     <Compile Include="Api\TwitterApiStatusTest.cs" />
     <Compile Include="BingTest.cs" />
+    <Compile Include="Connection\NetworkingTest.cs" />
     <Compile Include="HashtagManageTest.cs" />
     <Compile Include="HttpMessageHandlerMock.cs" />
     <Compile Include="MyApplicationTest.cs" />
index 38ca503..c57a67f 100644 (file)
@@ -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;
index 377ce58..292f69f 100644 (file)
@@ -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;
 
index fe3000e..ea39373 100644 (file)
@@ -34,6 +34,7 @@ using System;
 using System.Collections.Generic;
 using System.IO.Compression;
 using System.Drawing;
+using OpenTween.Connection;
 
 ///<summary>
 ///HttpWebRequest,HttpWebResponseを使用した基本的な通信機能を提供する
@@ -46,28 +47,6 @@ namespace OpenTween
 {
     public class HttpConnection
     {
-        ///<summary>
-        ///プロキシ
-        ///</summary>
-        private static IWebProxy proxy = null;
-
-        ///<summary>
-        ///ユーザーが選択したプロキシの方式
-        ///</summary>
-        private static ProxyType proxyKind = ProxyType.IE;
-
-        ///<summary>
-        ///初期化済みフラグ
-        ///</summary>
-        private static bool isInitialize = false;
-
-        public enum ProxyType
-        {
-            None,
-            IE,
-            Specified,
-        }
-
         /// <summary>
         /// リクエスト間で Cookie を保持するか否か
         /// </summary>
@@ -98,7 +77,7 @@ namespace OpenTween
                                                Uri requestUri,
                                                Dictionary<string, string> 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<string, string> param,
                                                List<KeyValuePair<String, FileInfo>> 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"
-        ///<summary>
-        ///通信タイムアウト時間(ms)
-        ///</summary>
-        private static int timeout = 20000;
-
-        ///<summary>
-        ///通信タイムアウト時間(ms)。10~120秒の範囲で指定。範囲外は20秒とする
-        ///</summary>
-        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
-
-        /// <summary>
-        /// OpenTween 内で共通して使用する HttpClient インスタンス
-        /// </summary>
-        public static HttpClient GlobalHttpClient
-        {
-            get { return globalHttpClient; }
-        }
-
-        /// <summary>
-        /// Webプロキシの設定が変更された場合に発生します
-        /// </summary>
-        public static event EventHandler WebProxyChanged;
-
-        private static HttpClient globalHttpClient = CreateHttpClient(new HttpClientHandler());
-
-        ///<summary>
-        ///通信クラスの初期化処理。タイムアウト値とプロキシを設定する
-        ///</summary>
-        ///<remarks>
-        ///通信開始前に最低一度呼び出すこと
-        ///</remarks>
-        ///<param name="timeout">タイムアウト値(秒)</param>
-        ///<param name="proxyType">なし・指定・IEデフォルト</param>
-        ///<param name="proxyAddress">プロキシのホスト名orIPアドレス</param>
-        ///<param name="proxyPort">プロキシのポート番号</param>
-        ///<param name="proxyUser">プロキシ認証が必要な場合のユーザ名。不要なら空文字</param>
-        ///<param name="proxyPassword">プロキシ認証が必要な場合のパスワード。不要なら空文字</param>
-        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);
-        }
-
-        /// <summary>
-        /// プロキシ等の設定を施した HttpClient インスタンスを生成します
-        /// </summary>
-        /// <remarks>
-        /// 通常は HttpConnection.GlobalHttpClient を使用すべきです。
-        /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
-        /// </remarks>
-        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
index f84396b..08094f7 100644 (file)
@@ -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
index ba7fc08..cf2d06b 100644 (file)
@@ -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 (file)
index 0000000..4cba411
--- /dev/null
@@ -0,0 +1,175 @@
+// OpenTween - Client of Twitter
+// Copyright (c) 2014 kim_upsilon (@kim_upsilon) <https://upsilo.net/~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 <http://www.gnu.org/licenses/>, 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; }
+
+        /// <summary>
+        /// 通信に使用するプロキシの種類
+        /// </summary>
+        public static ProxyType ProxyType
+        {
+            get { return proxyType; }
+        }
+
+        /// <summary>
+        /// 通信に使用するプロキシ
+        /// </summary>
+        public static IWebProxy Proxy
+        {
+            get { return proxy; }
+        }
+
+        /// <summary>
+        /// OpenTween 内で共通して使用する HttpClient インスタンス
+        /// </summary>
+        public static HttpClient Http
+        {
+            get { return globalHttpClient; }
+        }
+
+        /// <summary>
+        /// Webプロキシの設定が変更された場合に発生します
+        /// </summary>
+        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());
+        }
+
+        /// <summary>
+        /// ネットワーク接続前に行う処理。起動時に一回だけ実行する必要があります。
+        /// </summary>
+        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);
+        }
+
+        /// <summary>
+        /// プロキシ等の設定を施した HttpClient インスタンスを生成します
+        /// </summary>
+        /// <remarks>
+        /// 通常は Networking.Http を使用すべきです。
+        /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
+        /// </remarks>
+        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;
+        }
+
+        /// <summary>
+        /// Initialize() メソッドが事前に呼ばれているか確認します
+        /// </summary>
+        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,
+    }
+}
index 1fa3c70..5b2e16d 100644 (file)
@@ -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<MemoryImage> 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);
index c5bf352..0e142fa 100644 (file)
@@ -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)
index fa3f226..cc64a45 100644 (file)
     <Compile Include="Connection\IMediaUploadService.cs" />
     <Compile Include="Connection\imgly.cs" />
     <Compile Include="Connection\Imgur.cs" />
+    <Compile Include="Connection\Networking.cs" />
     <Compile Include="Connection\TwipplePhoto.cs" />
     <Compile Include="EventViewerDialog.cs">
       <SubType>Form</SubType>
index c762d9c..c439f90 100644 (file)
@@ -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 = "";
index 4250c47..50a3b93 100644 (file)
@@ -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;
index bd105cc..0a7a16e 100644 (file)
@@ -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;
 
index 03fab2f..d888d6f 100644 (file)
@@ -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;
 
index ff4b1a7..5d69274 100644 (file)
@@ -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;
 
index a2c1bb8..4758880 100644 (file)
@@ -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();
index 9716a1b..57036e9 100644 (file)
@@ -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))
index e5bd1b3..4b4c40a 100644 (file)
@@ -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;
 
index b76f7e4..b17a399 100644 (file)
@@ -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)
                     {
index 08f26cd..be5efb5 100644 (file)
@@ -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;
 
index b1a40ca..69987bf 100644 (file)
@@ -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;
 
index c9940da..b5c2c1a 100644 (file)
@@ -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<MemoryImage> LoadThumbnailImageAsync(CancellationToken cancellationToken)
         {
-            return this.LoadThumbnailImageAsync(HttpConnection.GlobalHttpClient, cancellationToken);
+            return this.LoadThumbnailImageAsync(Networking.Http, cancellationToken);
         }
 
         public async virtual Task<MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
index f2ceadb..1cad010 100644 (file)
@@ -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つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
index aeb3b99..04788af 100644 (file)
@@ -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)
                         {
index 4a695c6..92afd4a 100644 (file)
@@ -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)
index c6b04ab..4cbe35e 100644 (file)
@@ -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;
             }