OSDN Git Service

bit.ly のAPIキーの検証が常に失敗する不具合を修正
[opentween/open-tween.git] / OpenTween / AppendSettingDialog.cs
index 275d71e..2523f82 100644 (file)
@@ -30,6 +30,7 @@ using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
+using System.Net.Http;
 using System.Text;
 using System.Windows.Forms;
 using System.Threading;
@@ -112,12 +113,6 @@ namespace OpenTween
             {
                 var u = settingCommon.UserAccounts[userAccountIdx];
                 this.tw.Initialize(u.Token, u.TokenSecret, u.Username, u.UserId);
-
-                if (u.UserId == 0)
-                {
-                    this.tw.VerifyCredentials();
-                    u.UserId = this.tw.UserId;
-                }
             }
             else
             {
@@ -174,7 +169,7 @@ namespace OpenTween
                     return;
                 }
 
-                if (!BitlyValidation(this.ShortUrlPanel.TextBitlyId.Text, this.ShortUrlPanel.TextBitlyPw.Text))
+                if (!BitlyValidation(this.ShortUrlPanel.TextBitlyId.Text, this.ShortUrlPanel.TextBitlyPw.Text).Result)
                 {
                     MessageBox.Show(Properties.Resources.SettingSave_ClickText1);
                     _ValidationError = true;
@@ -253,41 +248,44 @@ namespace OpenTween
             }
         }
 
-        private void StartAuthButton_Click(object sender, EventArgs e)
+        private async void StartAuthButton_Click(object sender, EventArgs e)
         {
-            try
+            using (ControlTransaction.Disabled(this.BasedPanel.StartAuthButton))
             {
-                this.ApplyNetworkSettings();
+                try
+                {
+                    this.ApplyNetworkSettings();
 
-                var newAccount = this.PinAuth();
-                if (newAccount == null)
-                    return;
+                    var newAccount = await this.PinAuth();
+                    if (newAccount == null)
+                        return;
 
-                var authUserCombo = this.BasedPanel.AuthUserCombo;
+                    var authUserCombo = this.BasedPanel.AuthUserCombo;
 
-                var oldAccount = authUserCombo.Items.Cast<UserAccount>()
-                    .FirstOrDefault(x => x.UserId == this.tw.UserId);
+                    var oldAccount = authUserCombo.Items.Cast<UserAccount>()
+                        .FirstOrDefault(x => x.UserId == newAccount.UserId);
 
-                int idx;
-                if (oldAccount != null)
-                {
-                    idx = authUserCombo.Items.IndexOf(oldAccount);
-                    authUserCombo.Items[idx] = newAccount;
+                    int idx;
+                    if (oldAccount != null)
+                    {
+                        idx = authUserCombo.Items.IndexOf(oldAccount);
+                        authUserCombo.Items[idx] = newAccount;
+                    }
+                    else
+                    {
+                        idx = authUserCombo.Items.Add(newAccount);
+                    }
+
+                    authUserCombo.SelectedIndex = idx;
+
+                    MessageBox.Show(this, Properties.Resources.AuthorizeButton_Click1,
+                        "Authenticate", MessageBoxButtons.OK);
                 }
-                else
+                catch (WebApiException ex)
                 {
-                    idx = authUserCombo.Items.Add(newAccount);
+                    var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + ex.Message;
+                    MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
                 }
-
-                authUserCombo.SelectedIndex = idx;
-
-                MessageBox.Show(this, Properties.Resources.AuthorizeButton_Click1,
-                    "Authenticate", MessageBoxButtons.OK);
-            }
-            catch (WebApiException ex)
-            {
-                var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + ex.Message;
-                MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
             }
         }
 
@@ -313,29 +311,32 @@ namespace OpenTween
             var timeout = int.Parse(this.ConnectionPanel.ConnectionTimeOut.Text.Trim());
             Networking.DefaultTimeout = TimeSpan.FromSeconds(timeout);
 
+            var uploadImageTimeout = int.Parse(this.ConnectionPanel.UploadImageTimeout.Text.Trim());
+            Networking.UploadImageTimeout = TimeSpan.FromSeconds(uploadImageTimeout);
+
             Networking.ForceIPv4 = this.ConnectionPanel.checkBoxForceIPv4.Checked;
 
-            HttpTwitter.TwitterUrl = this.ConnectionPanel.TwitterAPIText.Text.Trim();
+            TwitterApiConnection.RestApiHost = this.ConnectionPanel.TwitterAPIText.Text.Trim();
         }
 
-        private UserAccount PinAuth()
+        private async Task<UserAccount> PinAuth()
         {
-            this.tw.Initialize("", "", "", 0);
+            var requestToken = await TwitterApiConnection.GetRequestTokenAsync();
 
-            var pinPageUrl = this.tw.StartAuthentication();
+            var pinPageUrl = TwitterApiConnection.GetAuthorizeUri(requestToken);
 
             var pin = AuthDialog.DoAuth(this, pinPageUrl);
             if (string.IsNullOrEmpty(pin))
                 return null; // キャンセルされた場合
 
-            this.tw.Authenticate(pin);
+            var accessTokenResponse = await TwitterApiConnection.GetAccessTokenAsync(requestToken, pin);
 
             return new UserAccount
             {
-                Username = this.tw.Username,
-                UserId = this.tw.UserId,
-                Token = this.tw.AccessToken,
-                TokenSecret = this.tw.AccessTokenSecret,
+                Username = accessTokenResponse["screen_name"],
+                UserId = long.Parse(accessTokenResponse["user_id"]),
+                Token = accessTokenResponse["oauth_token"],
+                TokenSecret = accessTokenResponse["oauth_token_secret"],
             };
         }
 
@@ -357,39 +358,38 @@ namespace OpenTween
             this.GetPeriodPanel.LabelUserStreamActive.Visible = tw.UserStreamActive;
         }
 
-        private bool BitlyValidation(string id, string apikey)
+        private async Task<bool> BitlyValidation(string id, string apikey)
         {
             if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(apikey))
             {
                 return false;
             }
 
-            string req = "http://api.bit.ly/v3/validate";
-            string content = "";
-            Dictionary<string, string> param = new Dictionary<string, string>();
+            try
+            {
+                var requestUri = new Uri("http://api.bit.ly/v3/validate");
+                var param = new Dictionary<string, string>
+                {
+                    ["login"] = ApplicationSettings.BitlyLoginId,
+                    ["apiKey"] = ApplicationSettings.BitlyApiKey,
+                    ["x_login"] = id,
+                    ["x_apiKey"] = apikey,
+                    ["format"] = "txt",
+                };
 
-            param.Add("login", ApplicationSettings.BitlyLoginId);
-            param.Add("apiKey", ApplicationSettings.BitlyApiKey);
-            param.Add("x_login", id);
-            param.Add("x_apiKey", apikey);
-            param.Add("format", "txt");
+                using (var postContent = new FormUrlEncodedContent(param))
+                using (var response = await Networking.Http.PostAsync(requestUri, postContent).ConfigureAwait(false))
+                {
+                    var responseText = await response.Content.ReadAsStringAsync()
+                        .ConfigureAwait(false);
 
-            if (!(new HttpVarious()).PostData(req, param, out content))
-            {
-                return true;             // 通信エラーの場合はとりあえずチェックを通ったことにする
-            }
-            else if (content.Trim() == "1")
-            {
-                return true;             // 検証成功
-            }
-            else if (content.Trim() == "0")
-            {
-                return false;            // 検証失敗 APIキーとIDの組み合わせが違う
-            }
-            else
-            {
-                return true;             // 規定外応答:通信エラーの可能性があるためとりあえずチェックを通ったことにする
+                    return responseText.TrimEnd() == "1";
+                }
             }
+            catch (OperationCanceledException) { }
+            catch (HttpRequestException) { }
+
+            return false;
         }
 
         private void Cancel_Click(object sender, EventArgs e)
@@ -457,7 +457,7 @@ namespace OpenTween
         {
             get
             {
-                return new IntervalChangedEventArgs()
+                return new IntervalChangedEventArgs
                 {
                     UserStream = true,
                     Timeline = true,