OSDN Git Service

varを使用する (IDE0007)
[opentween/open-tween.git] / OpenTween / AppendSettingDialog.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General Public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General Public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 using System;
28 using System.Collections.Generic;
29 using System.ComponentModel;
30 using System.Data;
31 using System.Drawing;
32 using System.Linq;
33 using System.Net.Http;
34 using System.Text;
35 using System.Windows.Forms;
36 using System.Threading;
37 using System.IO;
38 using System.Resources;
39 using OpenTween.Api;
40 using OpenTween.Connection;
41 using OpenTween.Thumbnail;
42 using System.Threading.Tasks;
43 using OpenTween.Setting.Panel;
44
45 namespace OpenTween
46 {
47     public partial class AppendSettingDialog : OTBaseForm
48     {
49         public event EventHandler<IntervalChangedEventArgs> IntervalChanged;
50
51         internal Twitter tw;
52         internal TwitterApi twitterApi;
53
54         public AppendSettingDialog()
55         {
56             this.InitializeComponent();
57
58             this.BasedPanel.StartAuthButton.Click += this.StartAuthButton_Click;
59             this.BasedPanel.CreateAccountButton.Click += this.CreateAccountButton_Click;
60             this.GetPeriodPanel.CheckPostAndGet.CheckedChanged += this.CheckPostAndGet_CheckedChanged;
61             this.ActionPanel.UReadMng.CheckedChanged += this.UReadMng_CheckedChanged;
62
63             this.Icon = Properties.Resources.MIcon;
64         }
65
66         public void LoadConfig(SettingCommon settingCommon, SettingLocal settingLocal)
67         {
68             this.BasedPanel.LoadConfig(settingCommon);
69             this.GetPeriodPanel.LoadConfig(settingCommon);
70             this.StartupPanel.LoadConfig(settingCommon);
71             this.TweetPrvPanel.LoadConfig(settingCommon);
72             this.TweetActPanel.LoadConfig(settingCommon, settingLocal);
73             this.ActionPanel.LoadConfig(settingCommon, settingLocal);
74             this.FontPanel.LoadConfig(settingLocal);
75             this.FontPanel2.LoadConfig(settingLocal);
76             this.PreviewPanel.LoadConfig(settingCommon);
77             this.GetCountPanel.LoadConfig(settingCommon);
78             this.ShortUrlPanel.LoadConfig(settingCommon);
79             this.ProxyPanel.LoadConfig(settingLocal);
80             this.CooperatePanel.LoadConfig(settingCommon);
81             this.ConnectionPanel.LoadConfig(settingCommon);
82             this.NotifyPanel.LoadConfig(settingCommon);
83
84             var activeUser = settingCommon.UserAccounts.FirstOrDefault(x => x.UserId == this.tw.UserId);
85             if (activeUser != null)
86             {
87                 this.BasedPanel.AuthUserCombo.SelectedItem = activeUser;
88             }
89         }
90
91         public void SaveConfig(SettingCommon settingCommon, SettingLocal settingLocal)
92         {
93             this.BasedPanel.SaveConfig(settingCommon);
94             this.GetPeriodPanel.SaveConfig(settingCommon);
95             this.StartupPanel.SaveConfig(settingCommon);
96             this.TweetPrvPanel.SaveConfig(settingCommon);
97             this.TweetActPanel.SaveConfig(settingCommon, settingLocal);
98             this.ActionPanel.SaveConfig(settingCommon, settingLocal);
99             this.FontPanel.SaveConfig(settingLocal);
100             this.FontPanel2.SaveConfig(settingLocal);
101             this.PreviewPanel.SaveConfig(settingCommon);
102             this.GetCountPanel.SaveConfig(settingCommon);
103             this.ShortUrlPanel.SaveConfig(settingCommon);
104             this.ProxyPanel.SaveConfig(settingLocal);
105             this.CooperatePanel.SaveConfig(settingCommon);
106             this.ConnectionPanel.SaveConfig(settingCommon);
107             this.NotifyPanel.SaveConfig(settingCommon);
108
109             var userAccountIdx = this.BasedPanel.AuthUserCombo.SelectedIndex;
110             if (userAccountIdx != -1)
111             {
112                 var u = settingCommon.UserAccounts[userAccountIdx];
113                 this.tw.Initialize(u.Token, u.TokenSecret, u.Username, u.UserId);
114             }
115             else
116             {
117                 this.tw.ClearAuthInfo();
118                 this.tw.Initialize("", "", "", 0);
119             }
120         }
121
122         private void TreeViewSetting_BeforeSelect(object sender, TreeViewCancelEventArgs e)
123         {
124             if (this.TreeViewSetting.SelectedNode == null) return;
125             var pnl = (SettingPanelBase)this.TreeViewSetting.SelectedNode.Tag;
126             if (pnl == null) return;
127             pnl.Enabled = false;
128             pnl.Visible = false;
129         }
130
131         private void TreeViewSetting_AfterSelect(object sender, TreeViewEventArgs e)
132         {
133             if (e.Node == null) return;
134             var pnl = (SettingPanelBase)e.Node.Tag;
135             if (pnl == null) return;
136             pnl.Enabled = true;
137             pnl.Visible = true;
138
139             if (pnl.Name == "PreviewPanel")
140             {
141                 if (GrowlHelper.IsDllExists)
142                 {
143                     this.PreviewPanel.IsNotifyUseGrowlCheckBox.Enabled = true;
144                 }
145                 else
146                 {
147                     this.PreviewPanel.IsNotifyUseGrowlCheckBox.Enabled = false;
148                 }
149             }
150         }
151
152         private void Setting_FormClosing(object sender, FormClosingEventArgs e)
153         {
154             if (MyCommon._endingFlag) return;
155
156             if (this.BasedPanel.AuthUserCombo.SelectedIndex == -1 && e.CloseReason == CloseReason.None)
157             {
158                 if (MessageBox.Show(Properties.Resources.Setting_FormClosing1, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
159                 {
160                     e.Cancel = true;
161                 }
162             }
163             if (e.Cancel == false && TreeViewSetting.SelectedNode != null)
164             {
165                 var curPanel = (SettingPanelBase)TreeViewSetting.SelectedNode.Tag;
166                 curPanel.Visible = false;
167                 curPanel.Enabled = false;
168             }
169         }
170
171         private void Setting_Load(object sender, EventArgs e)
172         {
173             this.TreeViewSetting.Nodes["BasedNode"].Tag = BasedPanel;
174             this.TreeViewSetting.Nodes["BasedNode"].Nodes["PeriodNode"].Tag = GetPeriodPanel;
175             this.TreeViewSetting.Nodes["BasedNode"].Nodes["StartUpNode"].Tag = StartupPanel;
176             this.TreeViewSetting.Nodes["BasedNode"].Nodes["GetCountNode"].Tag = GetCountPanel;
177             this.TreeViewSetting.Nodes["ActionNode"].Tag = ActionPanel;
178             this.TreeViewSetting.Nodes["ActionNode"].Nodes["TweetActNode"].Tag = TweetActPanel;
179             this.TreeViewSetting.Nodes["PreviewNode"].Tag = PreviewPanel;
180             this.TreeViewSetting.Nodes["PreviewNode"].Nodes["TweetPrvNode"].Tag = TweetPrvPanel;
181             this.TreeViewSetting.Nodes["PreviewNode"].Nodes["NotifyNode"].Tag = NotifyPanel;
182             this.TreeViewSetting.Nodes["FontNode"].Tag = FontPanel;
183             this.TreeViewSetting.Nodes["FontNode"].Nodes["FontNode2"].Tag = FontPanel2;
184             this.TreeViewSetting.Nodes["ConnectionNode"].Tag = ConnectionPanel;
185             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ProxyNode"].Tag = ProxyPanel;
186             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["CooperateNode"].Tag = CooperatePanel;
187             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"].Tag = ShortUrlPanel;
188
189             this.TreeViewSetting.SelectedNode = this.TreeViewSetting.Nodes[0];
190             this.TreeViewSetting.ExpandAll();
191
192             ActiveControl = BasedPanel.StartAuthButton;
193         }
194
195         private void UReadMng_CheckedChanged(object sender, EventArgs e)
196         {
197             if (this.ActionPanel.UReadMng.Checked == true)
198             {
199                 this.StartupPanel.StartupReaded.Enabled = true;
200             }
201             else
202             {
203                 this.StartupPanel.StartupReaded.Enabled = false;
204             }
205         }
206
207         private async void StartAuthButton_Click(object sender, EventArgs e)
208         {
209             using (ControlTransaction.Disabled(this.BasedPanel.StartAuthButton))
210             {
211                 try
212                 {
213                     this.ApplyNetworkSettings();
214
215                     var newAccount = await this.PinAuth();
216                     if (newAccount == null)
217                         return;
218
219                     var authUserCombo = this.BasedPanel.AuthUserCombo;
220
221                     var oldAccount = authUserCombo.Items.Cast<UserAccount>()
222                         .FirstOrDefault(x => x.UserId == newAccount.UserId);
223
224                     int idx;
225                     if (oldAccount != null)
226                     {
227                         idx = authUserCombo.Items.IndexOf(oldAccount);
228                         authUserCombo.Items[idx] = newAccount;
229                     }
230                     else
231                     {
232                         idx = authUserCombo.Items.Add(newAccount);
233                     }
234
235                     authUserCombo.SelectedIndex = idx;
236
237                     MessageBox.Show(this, Properties.Resources.AuthorizeButton_Click1,
238                         "Authenticate", MessageBoxButtons.OK);
239                 }
240                 catch (WebApiException ex)
241                 {
242                     var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + ex.Message;
243                     MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
244                 }
245             }
246         }
247
248         /// <summary>
249         /// 現在設定画面に入力されているネットワーク関係の設定を適用します
250         /// </summary>
251         public void ApplyNetworkSettings()
252         {
253             ProxyType proxyType;
254             if (this.ProxyPanel.RadioProxyNone.Checked)
255                 proxyType = ProxyType.None;
256             else if (this.ProxyPanel.RadioProxyIE.Checked)
257                 proxyType = ProxyType.IE;
258             else
259                 proxyType = ProxyType.Specified;
260
261             var proxyAddress = this.ProxyPanel.TextProxyAddress.Text.Trim();
262             var proxyPort = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim());
263             var proxyUser = this.ProxyPanel.TextProxyUser.Text.Trim();
264             var proxyPassword = this.ProxyPanel.TextProxyPassword.Text.Trim();
265             Networking.SetWebProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
266
267             var timeout = int.Parse(this.ConnectionPanel.ConnectionTimeOut.Text.Trim());
268             Networking.DefaultTimeout = TimeSpan.FromSeconds(timeout);
269
270             var uploadImageTimeout = int.Parse(this.ConnectionPanel.UploadImageTimeout.Text.Trim());
271             Networking.UploadImageTimeout = TimeSpan.FromSeconds(uploadImageTimeout);
272
273             Networking.ForceIPv4 = this.ConnectionPanel.checkBoxForceIPv4.Checked;
274
275             TwitterApiConnection.RestApiHost = this.ConnectionPanel.TwitterAPIText.Text.Trim();
276         }
277
278         private async Task<UserAccount> PinAuth()
279         {
280             var requestToken = await TwitterApiConnection.GetRequestTokenAsync();
281
282             var pinPageUrl = TwitterApiConnection.GetAuthorizeUri(requestToken);
283
284             var pin = AuthDialog.DoAuth(this, pinPageUrl);
285             if (string.IsNullOrEmpty(pin))
286                 return null; // キャンセルされた場合
287
288             var accessTokenResponse = await TwitterApiConnection.GetAccessTokenAsync(requestToken, pin);
289
290             return new UserAccount
291             {
292                 Username = accessTokenResponse["screen_name"],
293                 UserId = long.Parse(accessTokenResponse["user_id"]),
294                 Token = accessTokenResponse["oauth_token"],
295                 TokenSecret = accessTokenResponse["oauth_token_secret"],
296             };
297         }
298
299         private void CheckPostAndGet_CheckedChanged(object sender, EventArgs e)
300             => this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamActive;
301
302         private void Setting_Shown(object sender, EventArgs e)
303         {
304             do
305             {
306                 Thread.Sleep(10);
307                 if (this.Disposing || this.IsDisposed) return;
308             } while (!this.IsHandleCreated);
309             this.TopMost = this.PreviewPanel.CheckAlwaysTop.Checked;
310
311             this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked && !tw.UserStreamActive;
312             this.GetPeriodPanel.LabelUserStreamActive.Visible = tw.UserStreamActive;
313         }
314
315         private void OpenUrl(string url)
316         {
317             var myPath = url;
318             var path = this.ActionPanel.BrowserPathText.Text;
319             try
320             {
321                 if (!string.IsNullOrEmpty(path))
322                 {
323                     if (path.StartsWith("\"", StringComparison.Ordinal) && path.Length > 2 && path.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
324                     {
325                         var sep = path.IndexOf("\"", 2, StringComparison.Ordinal);
326                         var browserPath = path.Substring(1, sep - 1);
327                         var arg = "";
328                         if (sep < path.Length - 1)
329                         {
330                             arg = path.Substring(sep + 1);
331                         }
332                         myPath = arg + " " + myPath;
333                         System.Diagnostics.Process.Start(browserPath, myPath);
334                     }
335                     else
336                     {
337                         System.Diagnostics.Process.Start(path, myPath);
338                     }
339                 }
340                 else
341                 {
342                     System.Diagnostics.Process.Start(myPath);
343                 }
344             }
345             catch(Exception)
346             {
347             }
348         }
349
350         private void CreateAccountButton_Click(object sender, EventArgs e)
351             => this.OpenUrl("https://twitter.com/signup");
352
353         private void GetPeriodPanel_IntervalChanged(object sender, IntervalChangedEventArgs e)
354             => this.IntervalChanged?.Invoke(sender, e);
355     }
356
357     public class IntervalChangedEventArgs : EventArgs
358     {
359         public bool UserStream;
360         public bool Timeline;
361         public bool Reply;
362         public bool DirectMessage;
363         public bool PublicSearch;
364         public bool Lists;
365         public bool UserTimeline;
366
367         public static IntervalChangedEventArgs ResetAll => new IntervalChangedEventArgs
368         {
369             UserStream = true,
370             Timeline = true,
371             Reply = true,
372             DirectMessage = true,
373             PublicSearch = true,
374             Lists = true,
375             UserTimeline = true,
376         };
377     }
378 }