OSDN Git Service

ブロックの括弧を独立した行に書く (SA1500, SA1501, SA1502)
[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 #nullable enable
28
29 using System;
30 using System.Collections.Generic;
31 using System.ComponentModel;
32 using System.Data;
33 using System.Drawing;
34 using System.IO;
35 using System.Linq;
36 using System.Net.Http;
37 using System.Resources;
38 using System.Text;
39 using System.Threading;
40 using System.Threading.Tasks;
41 using System.Windows.Forms;
42 using OpenTween.Api;
43 using OpenTween.Connection;
44 using OpenTween.Setting.Panel;
45 using OpenTween.Thumbnail;
46
47 namespace OpenTween
48 {
49     public partial class AppendSettingDialog : OTBaseForm
50     {
51         public event EventHandler<IntervalChangedEventArgs>? IntervalChanged;
52
53         internal Twitter Tw = null!;
54         internal TwitterApi TwitterApi = null!;
55
56         public AppendSettingDialog()
57         {
58             this.InitializeComponent();
59
60             this.BasedPanel.StartAuthButton.Click += this.StartAuthButton_Click;
61             this.BasedPanel.CreateAccountButton.Click += this.CreateAccountButton_Click;
62             this.GetPeriodPanel.CheckPostAndGet.CheckedChanged += this.CheckPostAndGet_CheckedChanged;
63             this.ActionPanel.UReadMng.CheckedChanged += this.UReadMng_CheckedChanged;
64
65             this.Icon = Properties.Resources.MIcon;
66         }
67
68         public void LoadConfig(SettingCommon settingCommon, SettingLocal settingLocal)
69         {
70             this.BasedPanel.LoadConfig(settingCommon);
71             this.GetPeriodPanel.LoadConfig(settingCommon);
72             this.StartupPanel.LoadConfig(settingCommon);
73             this.TweetPrvPanel.LoadConfig(settingCommon);
74             this.TweetActPanel.LoadConfig(settingCommon, settingLocal);
75             this.ActionPanel.LoadConfig(settingCommon, settingLocal);
76             this.FontPanel.LoadConfig(settingLocal);
77             this.FontPanel2.LoadConfig(settingLocal);
78             this.PreviewPanel.LoadConfig(settingCommon);
79             this.GetCountPanel.LoadConfig(settingCommon);
80             this.ShortUrlPanel.LoadConfig(settingCommon);
81             this.ProxyPanel.LoadConfig(settingLocal);
82             this.CooperatePanel.LoadConfig(settingCommon);
83             this.ConnectionPanel.LoadConfig(settingCommon);
84             this.NotifyPanel.LoadConfig(settingCommon);
85
86             var activeUser = settingCommon.UserAccounts.FirstOrDefault(x => x.UserId == this.Tw.UserId);
87             if (activeUser != null)
88             {
89                 this.BasedPanel.AuthUserCombo.SelectedItem = activeUser;
90             }
91         }
92
93         public void SaveConfig(SettingCommon settingCommon, SettingLocal settingLocal)
94         {
95             this.BasedPanel.SaveConfig(settingCommon);
96             this.GetPeriodPanel.SaveConfig(settingCommon);
97             this.StartupPanel.SaveConfig(settingCommon);
98             this.TweetPrvPanel.SaveConfig(settingCommon);
99             this.TweetActPanel.SaveConfig(settingCommon, settingLocal);
100             this.ActionPanel.SaveConfig(settingCommon, settingLocal);
101             this.FontPanel.SaveConfig(settingLocal);
102             this.FontPanel2.SaveConfig(settingLocal);
103             this.PreviewPanel.SaveConfig(settingCommon);
104             this.GetCountPanel.SaveConfig(settingCommon);
105             this.ShortUrlPanel.SaveConfig(settingCommon);
106             this.ProxyPanel.SaveConfig(settingLocal);
107             this.CooperatePanel.SaveConfig(settingCommon);
108             this.ConnectionPanel.SaveConfig(settingCommon);
109             this.NotifyPanel.SaveConfig(settingCommon);
110
111             var userAccountIdx = this.BasedPanel.AuthUserCombo.SelectedIndex;
112             if (userAccountIdx != -1)
113             {
114                 var u = settingCommon.UserAccounts[userAccountIdx];
115                 this.Tw.Initialize(u.Token, u.TokenSecret, u.Username, u.UserId);
116             }
117             else
118             {
119                 this.Tw.ClearAuthInfo();
120                 this.Tw.Initialize("", "", "", 0);
121             }
122         }
123
124         private void TreeViewSetting_BeforeSelect(object sender, TreeViewCancelEventArgs e)
125         {
126             if (this.TreeViewSetting.SelectedNode == null) return;
127             var pnl = (SettingPanelBase)this.TreeViewSetting.SelectedNode.Tag;
128             if (pnl == null) return;
129             pnl.Enabled = false;
130             pnl.Visible = false;
131         }
132
133         private void TreeViewSetting_AfterSelect(object sender, TreeViewEventArgs e)
134         {
135             if (e.Node == null) return;
136             var pnl = (SettingPanelBase)e.Node.Tag;
137             if (pnl == null) return;
138             pnl.Enabled = true;
139             pnl.Visible = true;
140         }
141
142         private void Setting_FormClosing(object sender, FormClosingEventArgs e)
143         {
144             if (MyCommon.EndingFlag) return;
145
146             if (this.BasedPanel.AuthUserCombo.SelectedIndex == -1 && e.CloseReason == CloseReason.None)
147             {
148                 if (MessageBox.Show(Properties.Resources.Setting_FormClosing1, "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
149                 {
150                     e.Cancel = true;
151                 }
152             }
153             if (e.Cancel == false && this.TreeViewSetting.SelectedNode != null)
154             {
155                 var curPanel = (SettingPanelBase)this.TreeViewSetting.SelectedNode.Tag;
156                 curPanel.Visible = false;
157                 curPanel.Enabled = false;
158             }
159         }
160
161         private void Setting_Load(object sender, EventArgs e)
162         {
163             this.TreeViewSetting.Nodes["BasedNode"].Tag = this.BasedPanel;
164             this.TreeViewSetting.Nodes["BasedNode"].Nodes["PeriodNode"].Tag = this.GetPeriodPanel;
165             this.TreeViewSetting.Nodes["BasedNode"].Nodes["StartUpNode"].Tag = this.StartupPanel;
166             this.TreeViewSetting.Nodes["BasedNode"].Nodes["GetCountNode"].Tag = this.GetCountPanel;
167             this.TreeViewSetting.Nodes["ActionNode"].Tag = this.ActionPanel;
168             this.TreeViewSetting.Nodes["ActionNode"].Nodes["TweetActNode"].Tag = this.TweetActPanel;
169             this.TreeViewSetting.Nodes["PreviewNode"].Tag = this.PreviewPanel;
170             this.TreeViewSetting.Nodes["PreviewNode"].Nodes["TweetPrvNode"].Tag = this.TweetPrvPanel;
171             this.TreeViewSetting.Nodes["PreviewNode"].Nodes["NotifyNode"].Tag = this.NotifyPanel;
172             this.TreeViewSetting.Nodes["FontNode"].Tag = this.FontPanel;
173             this.TreeViewSetting.Nodes["FontNode"].Nodes["FontNode2"].Tag = this.FontPanel2;
174             this.TreeViewSetting.Nodes["ConnectionNode"].Tag = this.ConnectionPanel;
175             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ProxyNode"].Tag = this.ProxyPanel;
176             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["CooperateNode"].Tag = this.CooperatePanel;
177             this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"].Tag = this.ShortUrlPanel;
178
179             this.TreeViewSetting.SelectedNode = this.TreeViewSetting.Nodes[0];
180             this.TreeViewSetting.ExpandAll();
181
182             this.ActiveControl = this.BasedPanel.StartAuthButton;
183         }
184
185         private void UReadMng_CheckedChanged(object sender, EventArgs e)
186         {
187             if (this.ActionPanel.UReadMng.Checked == true)
188             {
189                 this.StartupPanel.StartupReaded.Enabled = true;
190             }
191             else
192             {
193                 this.StartupPanel.StartupReaded.Enabled = false;
194             }
195         }
196
197         private async void StartAuthButton_Click(object sender, EventArgs e)
198         {
199             using (ControlTransaction.Disabled(this.BasedPanel.StartAuthButton))
200             {
201                 try
202                 {
203                     this.ApplyNetworkSettings();
204
205                     var newAccount = await this.PinAuth();
206                     if (newAccount == null)
207                         return;
208
209                     var authUserCombo = this.BasedPanel.AuthUserCombo;
210
211                     var oldAccount = authUserCombo.Items.Cast<UserAccount>()
212                         .FirstOrDefault(x => x.UserId == newAccount.UserId);
213
214                     int idx;
215                     if (oldAccount != null)
216                     {
217                         idx = authUserCombo.Items.IndexOf(oldAccount);
218                         authUserCombo.Items[idx] = newAccount;
219                     }
220                     else
221                     {
222                         idx = authUserCombo.Items.Add(newAccount);
223                     }
224
225                     authUserCombo.SelectedIndex = idx;
226
227                     MessageBox.Show(
228                         this,
229                         Properties.Resources.AuthorizeButton_Click1,
230                         "Authenticate",
231                         MessageBoxButtons.OK);
232                 }
233                 catch (WebApiException ex)
234                 {
235                     var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine + ex.Message;
236                     MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
237                 }
238             }
239         }
240
241         /// <summary>
242         /// 現在設定画面に入力されているネットワーク関係の設定を適用します
243         /// </summary>
244         public void ApplyNetworkSettings()
245         {
246             ProxyType proxyType;
247             if (this.ProxyPanel.RadioProxyNone.Checked)
248                 proxyType = ProxyType.None;
249             else if (this.ProxyPanel.RadioProxyIE.Checked)
250                 proxyType = ProxyType.IE;
251             else
252                 proxyType = ProxyType.Specified;
253
254             var proxyAddress = this.ProxyPanel.TextProxyAddress.Text.Trim();
255             var proxyPort = int.Parse(this.ProxyPanel.TextProxyPort.Text.Trim());
256             var proxyUser = this.ProxyPanel.TextProxyUser.Text.Trim();
257             var proxyPassword = this.ProxyPanel.TextProxyPassword.Text.Trim();
258             Networking.SetWebProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
259
260             var timeout = int.Parse(this.ConnectionPanel.ConnectionTimeOut.Text.Trim());
261             Networking.DefaultTimeout = TimeSpan.FromSeconds(timeout);
262
263             var uploadImageTimeout = int.Parse(this.ConnectionPanel.UploadImageTimeout.Text.Trim());
264             Networking.UploadImageTimeout = TimeSpan.FromSeconds(uploadImageTimeout);
265
266             Networking.ForceIPv4 = this.ConnectionPanel.checkBoxForceIPv4.Checked;
267
268             TwitterApiConnection.RestApiHost = this.ConnectionPanel.TwitterAPIText.Text.Trim();
269         }
270
271         private async Task<UserAccount?> PinAuth()
272         {
273             var requestToken = await TwitterApiConnection.GetRequestTokenAsync();
274
275             var pinPageUrl = TwitterApiConnection.GetAuthorizeUri(requestToken);
276
277             var browserPath = this.ActionPanel.BrowserPathText.Text;
278             var pin = AuthDialog.DoAuth(this, pinPageUrl, browserPath);
279             if (MyCommon.IsNullOrEmpty(pin))
280                 return null; // キャンセルされた場合
281
282             var accessTokenResponse = await TwitterApiConnection.GetAccessTokenAsync(requestToken, pin);
283
284             return new UserAccount
285             {
286                 Username = accessTokenResponse["screen_name"],
287                 UserId = long.Parse(accessTokenResponse["user_id"]),
288                 Token = accessTokenResponse["oauth_token"],
289                 TokenSecret = accessTokenResponse["oauth_token_secret"],
290             };
291         }
292
293         private void CheckPostAndGet_CheckedChanged(object sender, EventArgs e)
294             => this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked;
295
296         private void Setting_Shown(object sender, EventArgs e)
297         {
298             do
299             {
300                 Thread.Sleep(10);
301                 if (this.Disposing || this.IsDisposed) return;
302             }
303             while (!this.IsHandleCreated);
304             this.TopMost = this.PreviewPanel.CheckAlwaysTop.Checked;
305
306             this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked;
307         }
308
309         private async Task OpenUrl(string url)
310         {
311             var browserPathWithArgs = this.ActionPanel.BrowserPathText.Text;
312             await MyCommon.OpenInBrowserAsync(this, browserPathWithArgs, url);
313         }
314
315         private async void CreateAccountButton_Click(object sender, EventArgs e)
316             => await this.OpenUrl("https://twitter.com/signup");
317
318         private void GetPeriodPanel_IntervalChanged(object sender, IntervalChangedEventArgs e)
319             => this.IntervalChanged?.Invoke(sender, e);
320     }
321
322     public class IntervalChangedEventArgs : EventArgs
323     {
324         public bool Timeline;
325         public bool Reply;
326         public bool DirectMessage;
327         public bool PublicSearch;
328         public bool Lists;
329         public bool UserTimeline;
330
331         public static IntervalChangedEventArgs ResetAll => new IntervalChangedEventArgs
332         {
333             Timeline = true,
334             Reply = true,
335             DirectMessage = true,
336             PublicSearch = true,
337             Lists = true,
338             UserTimeline = true,
339         };
340     }
341 }