OSDN Git Service

varを使用する (IDE0007)
[opentween/open-tween.git] / OpenTween / AppendSettingDialog.cs
index 0b37067..5f21754 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;
@@ -45,17 +46,22 @@ namespace OpenTween
 {
     public partial class AppendSettingDialog : OTBaseForm
     {
-        internal Twitter tw;
-
-        private bool _ValidationError = false;
+        public event EventHandler<IntervalChangedEventArgs> IntervalChanged;
 
-        private long? InitialUserId;
+        internal Twitter tw;
+        internal TwitterApi twitterApi;
 
-        public TwitterConfiguration TwitterConfiguration = TwitterConfiguration.DefaultConfiguration();
+        public AppendSettingDialog()
+        {
+            this.InitializeComponent();
 
-        private string _pin;
+            this.BasedPanel.StartAuthButton.Click += this.StartAuthButton_Click;
+            this.BasedPanel.CreateAccountButton.Click += this.CreateAccountButton_Click;
+            this.GetPeriodPanel.CheckPostAndGet.CheckedChanged += this.CheckPostAndGet_CheckedChanged;
+            this.ActionPanel.UReadMng.CheckedChanged += this.UReadMng_CheckedChanged;
 
-        public event EventHandler<IntervalChangedEventArgs> IntervalChanged;
+            this.Icon = Properties.Resources.MIcon;
+        }
 
         public void LoadConfig(SettingCommon settingCommon, SettingLocal settingLocal)
         {
@@ -79,7 +85,6 @@ namespace OpenTween
             if (activeUser != null)
             {
                 this.BasedPanel.AuthUserCombo.SelectedItem = activeUser;
-                this.InitialUserId = activeUser.UserId;
             }
         }
 
@@ -106,12 +111,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
             {
@@ -150,87 +149,17 @@ namespace OpenTween
             }
         }
 
-        private void Save_Click(object sender, EventArgs e)
-        {
-            if (MyCommon.IsNetworkAvailable() &&
-                (this.ShortUrlPanel.ComboBoxAutoShortUrlFirst.SelectedIndex == (int)MyCommon.UrlConverter.Bitly || this.ShortUrlPanel.ComboBoxAutoShortUrlFirst.SelectedIndex == (int)MyCommon.UrlConverter.Jmp))
-            {
-                // bit.ly 短縮機能実装のプライバシー問題の暫定対応
-                // bit.ly 使用時はログインIDとAPIキーの指定を必須とする
-                // 参照: http://sourceforge.jp/projects/opentween/lists/archive/dev/2012-January/000020.html
-                if (string.IsNullOrEmpty(this.ShortUrlPanel.TextBitlyId.Text) || string.IsNullOrEmpty(this.ShortUrlPanel.TextBitlyPw.Text))
-                {
-                    MessageBox.Show("bit.ly のログイン名とAPIキーの指定は必須項目です。", Application.ProductName);
-                    _ValidationError = true;
-                    TreeViewSetting.SelectedNode = TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"]; // 動作タブを選択
-                    TreeViewSetting.Select();
-                    this.ShortUrlPanel.TextBitlyId.Focus();
-                    return;
-                }
-
-                if (!BitlyValidation(this.ShortUrlPanel.TextBitlyId.Text, this.ShortUrlPanel.TextBitlyPw.Text))
-                {
-                    MessageBox.Show(Properties.Resources.SettingSave_ClickText1);
-                    _ValidationError = true;
-                    TreeViewSetting.SelectedNode = TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"]; // 動作タブを選択
-                    TreeViewSetting.Select();
-                    this.ShortUrlPanel.TextBitlyId.Focus();
-                    return;
-                }
-                else
-                {
-                    _ValidationError = false;
-                }
-            }
-            else
-            {
-                _ValidationError = false;
-            }
-
-#if UA
-            //フォロー
-            if (this.FollowCheckBox.Checked)
-            {
-                //現在の設定内容で通信
-                HttpConnection.ProxyType ptype;
-                if (RadioProxyNone.Checked)
-                {
-                    ptype = HttpConnection.ProxyType.None;
-                }
-                else if (RadioProxyIE.Checked)
-                {
-                    ptype = HttpConnection.ProxyType.IE;
-                }
-                else
-                {
-                    ptype = HttpConnection.ProxyType.Specified;
-                }
-                string padr = TextProxyAddress.Text.Trim();
-                int pport = int.Parse(TextProxyPort.Text.Trim());
-                string pusr = TextProxyUser.Text.Trim();
-                string ppw = TextProxyPassword.Text.Trim();
-                HttpConnection.InitializeConnection(20, ptype, padr, pport, pusr, ppw);
-
-                string ret = tw.PostFollowCommand(ApplicationSettings.FeedbackTwitterName);
-            }
-#endif
-        }
-
         private void Setting_FormClosing(object sender, FormClosingEventArgs e)
         {
             if (MyCommon._endingFlag) return;
 
-            if (tw != null && string.IsNullOrEmpty(tw.Username) && e.CloseReason == CloseReason.None)
+            if (this.BasedPanel.AuthUserCombo.SelectedIndex == -1 && e.CloseReason == CloseReason.None)
             {
                 if (MessageBox.Show(Properties.Resources.Setting_FormClosing1, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                 {
                     e.Cancel = true;
                 }
             }
-            if (_ValidationError)
-            {
-                e.Cancel = true;
-            }
             if (e.Cancel == false && TreeViewSetting.SelectedNode != null)
             {
                 var curPanel = (SettingPanelBase)TreeViewSetting.SelectedNode.Tag;
@@ -245,7 +174,6 @@ namespace OpenTween
             this.TreeViewSetting.Nodes["BasedNode"].Nodes["PeriodNode"].Tag = GetPeriodPanel;
             this.TreeViewSetting.Nodes["BasedNode"].Nodes["StartUpNode"].Tag = StartupPanel;
             this.TreeViewSetting.Nodes["BasedNode"].Nodes["GetCountNode"].Tag = GetCountPanel;
-            //this.TreeViewSetting.Nodes["BasedNode"].Nodes["UserStreamNode"].Tag = UserStreamPanel;
             this.TreeViewSetting.Nodes["ActionNode"].Tag = ActionPanel;
             this.TreeViewSetting.Nodes["ActionNode"].Nodes["TweetActNode"].Tag = TweetActPanel;
             this.TreeViewSetting.Nodes["PreviewNode"].Tag = PreviewPanel;
@@ -261,7 +189,6 @@ namespace OpenTween
             this.TreeViewSetting.SelectedNode = this.TreeViewSetting.Nodes[0];
             this.TreeViewSetting.ExpandAll();
 
-            //TreeViewSetting.SelectedNode = TreeViewSetting.TopNode;
             ActiveControl = BasedPanel.StartAuthButton;
         }
 
@@ -277,126 +204,100 @@ namespace OpenTween
             }
         }
 
-        private bool StartAuth()
+        private async void StartAuthButton_Click(object sender, EventArgs e)
         {
-            //現在の設定内容で通信
-            ProxyType ptype;
-            if (this.ProxyPanel.RadioProxyNone.Checked)
-            {
-                ptype = ProxyType.None;
-            }
-            else if (this.ProxyPanel.RadioProxyIE.Checked)
-            {
-                ptype = ProxyType.IE;
-            }
-            else
-            {
-                ptype = ProxyType.Specified;
-            }
-            string padr = this.ProxyPanel.TextProxyAddress.Text.Trim();
-            int pport = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim());
-            string pusr = this.ProxyPanel.TextProxyUser.Text.Trim();
-            string ppw = this.ProxyPanel.TextProxyPassword.Text.Trim();
-
-            //通信基底クラス初期化
-            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;
-            //this.AuthUserLabel.Text = "";
-            string pinPageUrl = "";
-            string rslt = tw.StartAuthentication(ref pinPageUrl);
-            if (string.IsNullOrEmpty(rslt))
+            using (ControlTransaction.Disabled(this.BasedPanel.StartAuthButton))
             {
-                string pin = AuthDialog.DoAuth(this, pinPageUrl);
-                if (!string.IsNullOrEmpty(pin))
+                try
                 {
-                    this._pin = pin;
-                    return true;
-                }
-                else
-                {
-                    return false;
-                }
-            }
-            else
-            {
-                MessageBox.Show(Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + rslt, "Authenticate", MessageBoxButtons.OK);
-                return false;
-            }
-        }
+                    this.ApplyNetworkSettings();
 
-        private bool PinAuth()
-        {
-            string pin = this._pin;   //PIN Code
+                    var newAccount = await this.PinAuth();
+                    if (newAccount == null)
+                        return;
 
-            string rslt = tw.Authenticate(pin);
-            if (string.IsNullOrEmpty(rslt))
-            {
-                MessageBox.Show(Properties.Resources.AuthorizeButton_Click1, "Authenticate", MessageBoxButtons.OK);
-                //this.AuthStateLabel.Text = Properties.Resources.AuthorizeButton_Click3;
-                //this.AuthUserLabel.Text = tw.Username;
-                int idx = -1;
-                UserAccount user = new UserAccount();
-                user.Username = tw.Username;
-                user.UserId = tw.UserId;
-                user.Token = tw.AccessToken;
-                user.TokenSecret = tw.AccessTokenSecret;
-
-                foreach (object u in this.BasedPanel.AuthUserCombo.Items)
-                {
-                    if (((UserAccount)u).Username.ToLower() == tw.Username.ToLower())
+                    var authUserCombo = this.BasedPanel.AuthUserCombo;
+
+                    var oldAccount = authUserCombo.Items.Cast<UserAccount>()
+                        .FirstOrDefault(x => x.UserId == newAccount.UserId);
+
+                    int idx;
+                    if (oldAccount != null)
                     {
-                        idx = this.BasedPanel.AuthUserCombo.Items.IndexOf(u);
-                        break;
+                        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);
                 }
-                if (idx > -1)
-                {
-                    this.BasedPanel.AuthUserCombo.Items.RemoveAt(idx);
-                    this.BasedPanel.AuthUserCombo.Items.Insert(idx, user);
-                    this.BasedPanel.AuthUserCombo.SelectedIndex = idx;
-                }
-                else
+                catch (WebApiException ex)
                 {
-                    this.BasedPanel.AuthUserCombo.SelectedIndex = this.BasedPanel.AuthUserCombo.Items.Add(user);
+                    var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + ex.Message;
+                    MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
                 }
-                //if (TwitterApiInfo.AccessLevel = ApiAccessLevel.ReadWrite)
-                //{
-                //    this.AuthStateLabel.Text += "(xAuth)";
-                //}
-                //else if (TwitterApiInfo.AccessLevel == ApiAccessLevel.ReadWriteAndDirectMessage)
-                //{
-                //    this.AuthStateLabel.Text += "(OAuth)";
-                //}
-                return true;
             }
+        }
+
+        /// <summary>
+        /// 現在設定画面に入力されているネットワーク関係の設定を適用します
+        /// </summary>
+        public void ApplyNetworkSettings()
+        {
+            ProxyType proxyType;
+            if (this.ProxyPanel.RadioProxyNone.Checked)
+                proxyType = ProxyType.None;
+            else if (this.ProxyPanel.RadioProxyIE.Checked)
+                proxyType = ProxyType.IE;
             else
-            {
-                MessageBox.Show(Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + rslt, "Authenticate", MessageBoxButtons.OK);
-                //this.AuthStateLabel.Text = Properties.Resources.AuthorizeButton_Click4;
-                //this.AuthUserLabel.Text = "";
-                return false;
-            }
+                proxyType = ProxyType.Specified;
+
+            var proxyAddress = this.ProxyPanel.TextProxyAddress.Text.Trim();
+            var proxyPort = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim());
+            var proxyUser = this.ProxyPanel.TextProxyUser.Text.Trim();
+            var proxyPassword = this.ProxyPanel.TextProxyPassword.Text.Trim();
+            Networking.SetWebProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
+
+            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;
+
+            TwitterApiConnection.RestApiHost = this.ConnectionPanel.TwitterAPIText.Text.Trim();
         }
 
-        private void StartAuthButton_Click(object sender, EventArgs e)
+        private async Task<UserAccount> PinAuth()
         {
-            //this.Save.Enabled = false;
-            if (StartAuth())
+            var requestToken = await TwitterApiConnection.GetRequestTokenAsync();
+
+            var pinPageUrl = TwitterApiConnection.GetAuthorizeUri(requestToken);
+
+            var pin = AuthDialog.DoAuth(this, pinPageUrl);
+            if (string.IsNullOrEmpty(pin))
+                return null; // キャンセルされた場合
+
+            var accessTokenResponse = await TwitterApiConnection.GetAccessTokenAsync(requestToken, pin);
+
+            return new UserAccount
             {
-                if (PinAuth())
-                {
-                    //this.Save.Enabled = true;
-                }
-            }
+                Username = accessTokenResponse["screen_name"],
+                UserId = long.Parse(accessTokenResponse["user_id"]),
+                Token = accessTokenResponse["oauth_token"],
+                TokenSecret = accessTokenResponse["oauth_token_secret"],
+            };
         }
 
         private void CheckPostAndGet_CheckedChanged(object sender, EventArgs e)
-        {
-            this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamEnabled;
-        }
+            => this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamActive;
 
         private void Setting_Shown(object sender, EventArgs e)
         {
@@ -407,101 +308,23 @@ namespace OpenTween
             } while (!this.IsHandleCreated);
             this.TopMost = this.PreviewPanel.CheckAlwaysTop.Checked;
 
-            this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamEnabled;
-            this.GetPeriodPanel.LabelUserStreamActive.Visible = tw.UserStreamEnabled;
+            this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamActive;
+            this.GetPeriodPanel.LabelUserStreamActive.Visible = tw.UserStreamActive;
         }
 
-        private 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>();
-
-            param.Add("login", ApplicationSettings.BitlyLoginId);
-            param.Add("apiKey", ApplicationSettings.BitlyApiKey);
-            param.Add("x_login", id);
-            param.Add("x_apiKey", apikey);
-            param.Add("format", "txt");
-
-            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;             // 規定外応答:通信エラーの可能性があるためとりあえずチェックを通ったことにする
-            }
-        }
-
-        private void Cancel_Click(object sender, EventArgs e)
-        {
-            _ValidationError = false;
-        }
-
-        //private void CheckEventNotify_CheckedChanged(object sender, EventArgs e)
-        //                Handles CheckEventNotify.CheckedChanged, CheckFavoritesEvent.CheckStateChanged,
-        //                        CheckUnfavoritesEvent.CheckStateChanged, CheckFollowEvent.CheckStateChanged,
-        //                        CheckListMemberAddedEvent.CheckStateChanged, CheckListMemberRemovedEvent.CheckStateChanged,
-        //                        CheckListCreatedEvent.CheckStateChanged, CheckUserUpdateEvent.CheckStateChanged
-        //{
-        //    EventNotifyEnabled = CheckEventNotify.Checked;
-        //    GetEventNotifyFlag(EventNotifyFlag, IsMyEventNotifyFlag);
-        //    ApplyEventNotifyFlag(EventNotifyEnabled, EventNotifyFlag, IsMyEventNotifyFlag);
-        //}
-
-        //private void CheckForceEventNotify_CheckedChanged(object sender, EventArgs e)
-        //{
-        //    _MyForceEventNotify = CheckEventNotify.Checked;
-        //}
-
-        //private void CheckFavEventUnread_CheckedChanged(object sender, EventArgs e)
-        //{
-        //    _MyFavEventUnread = CheckFavEventUnread.Checked;
-        //}
-
-        //private void ComboBoxTranslateLanguage_SelectedIndexChanged(object sender, EventArgs e)
-        //{
-        //    _MyTranslateLanguage = (new Google()).GetLanguageEnumFromIndex(ComboBoxTranslateLanguage.SelectedIndex);
-        //}
-
-        //private void ComboBoxEventNotifySound_VisibleChanged(object sender, EventArgs e)
-        //{
-        //    SoundFileListup();
-        //}
-
-        //private void ComboBoxEventNotifySound_SelectedIndexChanged(object sender, EventArgs e)
-        //{
-        //   if (_soundfileListup) return;
-
-        //    _MyEventSoundFile = (string)ComboBoxEventNotifySound.SelectedItem;
-        //}
-
         private void OpenUrl(string url)
         {
-            string myPath = url;
-            string path = this.ActionPanel.BrowserPathText.Text;
+            var myPath = url;
+            var path = this.ActionPanel.BrowserPathText.Text;
             try
             {
                 if (!string.IsNullOrEmpty(path))
                 {
-                    if (path.StartsWith("\"") && path.Length > 2 && path.IndexOf("\"", 2) > -1)
+                    if (path.StartsWith("\"", StringComparison.Ordinal) && path.Length > 2 && path.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
                     {
-                        int sep = path.IndexOf("\"", 2);
-                        string browserPath = path.Substring(1, sep - 1);
-                        string arg = "";
+                        var sep = path.IndexOf("\"", 2, StringComparison.Ordinal);
+                        var browserPath = path.Substring(1, sep - 1);
+                        var arg = "";
                         if (sep < path.Length - 1)
                         {
                             arg = path.Substring(sep + 1);
@@ -521,32 +344,14 @@ namespace OpenTween
             }
             catch(Exception)
             {
-//              MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
             }
         }
 
         private void CreateAccountButton_Click(object sender, EventArgs e)
-        {
-            this.OpenUrl("https://twitter.com/signup");
-        }
-
-        public AppendSettingDialog()
-        {
-            InitializeComponent();
-
-            this.BasedPanel.StartAuthButton.Click += this.StartAuthButton_Click;
-            this.BasedPanel.CreateAccountButton.Click += this.CreateAccountButton_Click;
-            this.GetPeriodPanel.CheckPostAndGet.CheckedChanged += this.CheckPostAndGet_CheckedChanged;
-            this.ActionPanel.UReadMng.CheckedChanged += this.UReadMng_CheckedChanged;
-
-            this.Icon = Properties.Resources.MIcon;
-        }
+            => this.OpenUrl("https://twitter.com/signup");
 
         private void GetPeriodPanel_IntervalChanged(object sender, IntervalChangedEventArgs e)
-        {
-            if (this.IntervalChanged != null)
-                this.IntervalChanged(sender, e);
-        }
+            => this.IntervalChanged?.Invoke(sender, e);
     }
 
     public class IntervalChangedEventArgs : EventArgs
@@ -558,5 +363,16 @@ namespace OpenTween
         public bool PublicSearch;
         public bool Lists;
         public bool UserTimeline;
+
+        public static IntervalChangedEventArgs ResetAll => new IntervalChangedEventArgs
+        {
+            UserStream = true,
+            Timeline = true,
+            Reply = true,
+            DirectMessage = true,
+            PublicSearch = true,
+            Lists = true,
+            UserTimeline = true,
+        };
     }
 }