// (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
// (c) 2011 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.
-//
+// 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.
+#nullable enable
+
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
+using System.IO;
using System.Linq;
+using System.Net.Http;
+using System.Resources;
using System.Text;
-using System.Windows.Forms;
using System.Threading;
-using System.IO;
-using System.Resources;
+using System.Threading.Tasks;
+using System.Windows.Forms;
using OpenTween.Api;
using OpenTween.Connection;
-using OpenTween.Thumbnail;
-using System.Threading.Tasks;
using OpenTween.Setting.Panel;
+using OpenTween.Thumbnail;
namespace OpenTween
{
public partial class AppendSettingDialog : OTBaseForm
{
- public event EventHandler<IntervalChangedEventArgs> IntervalChanged;
-
- internal Twitter tw;
- internal TwitterApi twitterApi;
-
- private bool _ValidationError = false;
+ public event EventHandler<IntervalChangedEventArgs>? IntervalChanged;
public AppendSettingDialog()
{
this.CooperatePanel.LoadConfig(settingCommon);
this.ConnectionPanel.LoadConfig(settingCommon);
this.NotifyPanel.LoadConfig(settingCommon);
-
- var activeUser = settingCommon.UserAccounts.FirstOrDefault(x => x.UserId == this.tw.UserId);
- if (activeUser != null)
- {
- this.BasedPanel.AuthUserCombo.SelectedItem = activeUser;
- }
}
public void SaveConfig(SettingCommon settingCommon, SettingLocal settingLocal)
this.CooperatePanel.SaveConfig(settingCommon);
this.ConnectionPanel.SaveConfig(settingCommon);
this.NotifyPanel.SaveConfig(settingCommon);
-
- var userAccountIdx = this.BasedPanel.AuthUserCombo.SelectedIndex;
- if (userAccountIdx != -1)
- {
- var u = settingCommon.UserAccounts[userAccountIdx];
- this.tw.Initialize(u.Token, u.TokenSecret, u.Username, u.UserId);
- this.twitterApi.Initialize(u.Token, u.TokenSecret, u.UserId, u.Username);
-
- if (u.UserId == 0)
- {
- this.tw.VerifyCredentials();
- u.UserId = this.tw.UserId;
- }
- }
- else
- {
- this.tw.ClearAuthInfo();
- this.tw.Initialize("", "", "", 0);
- }
}
private void TreeViewSetting_BeforeSelect(object sender, TreeViewCancelEventArgs e)
if (pnl == null) return;
pnl.Enabled = true;
pnl.Visible = true;
-
- if (pnl.Name == "PreviewPanel")
- {
- if (GrowlHelper.IsDllExists)
- {
- this.PreviewPanel.IsNotifyUseGrowlCheckBox.Enabled = true;
- }
- else
- {
- this.PreviewPanel.IsNotifyUseGrowlCheckBox.Enabled = false;
- }
- }
- }
-
- 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;
- }
}
private void Setting_FormClosing(object sender, FormClosingEventArgs e)
{
- if (MyCommon._endingFlag) return;
+ if (MyCommon.EndingFlag) return;
if (this.BasedPanel.AuthUserCombo.SelectedIndex == -1 && e.CloseReason == CloseReason.None)
{
e.Cancel = true;
}
}
- if (_ValidationError)
- {
- e.Cancel = true;
- }
- if (e.Cancel == false && TreeViewSetting.SelectedNode != null)
+ if (e.Cancel == false && this.TreeViewSetting.SelectedNode != null)
{
- var curPanel = (SettingPanelBase)TreeViewSetting.SelectedNode.Tag;
+ var curPanel = (SettingPanelBase)this.TreeViewSetting.SelectedNode.Tag;
curPanel.Visible = false;
curPanel.Enabled = false;
}
private void Setting_Load(object sender, EventArgs e)
{
- this.TreeViewSetting.Nodes["BasedNode"].Tag = BasedPanel;
- 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["ActionNode"].Tag = ActionPanel;
- this.TreeViewSetting.Nodes["ActionNode"].Nodes["TweetActNode"].Tag = TweetActPanel;
- this.TreeViewSetting.Nodes["PreviewNode"].Tag = PreviewPanel;
- this.TreeViewSetting.Nodes["PreviewNode"].Nodes["TweetPrvNode"].Tag = TweetPrvPanel;
- this.TreeViewSetting.Nodes["PreviewNode"].Nodes["NotifyNode"].Tag = NotifyPanel;
- this.TreeViewSetting.Nodes["FontNode"].Tag = FontPanel;
- this.TreeViewSetting.Nodes["FontNode"].Nodes["FontNode2"].Tag = FontPanel2;
- this.TreeViewSetting.Nodes["ConnectionNode"].Tag = ConnectionPanel;
- this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ProxyNode"].Tag = ProxyPanel;
- this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["CooperateNode"].Tag = CooperatePanel;
- this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"].Tag = ShortUrlPanel;
+ this.TreeViewSetting.Nodes["BasedNode"].Tag = this.BasedPanel;
+ this.TreeViewSetting.Nodes["BasedNode"].Nodes["PeriodNode"].Tag = this.GetPeriodPanel;
+ this.TreeViewSetting.Nodes["BasedNode"].Nodes["StartUpNode"].Tag = this.StartupPanel;
+ this.TreeViewSetting.Nodes["BasedNode"].Nodes["GetCountNode"].Tag = this.GetCountPanel;
+ this.TreeViewSetting.Nodes["ActionNode"].Tag = this.ActionPanel;
+ this.TreeViewSetting.Nodes["ActionNode"].Nodes["TweetActNode"].Tag = this.TweetActPanel;
+ this.TreeViewSetting.Nodes["PreviewNode"].Tag = this.PreviewPanel;
+ this.TreeViewSetting.Nodes["PreviewNode"].Nodes["TweetPrvNode"].Tag = this.TweetPrvPanel;
+ this.TreeViewSetting.Nodes["PreviewNode"].Nodes["NotifyNode"].Tag = this.NotifyPanel;
+ this.TreeViewSetting.Nodes["FontNode"].Tag = this.FontPanel;
+ this.TreeViewSetting.Nodes["FontNode"].Nodes["FontNode2"].Tag = this.FontPanel2;
+ this.TreeViewSetting.Nodes["ConnectionNode"].Tag = this.ConnectionPanel;
+ this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ProxyNode"].Tag = this.ProxyPanel;
+ this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["CooperateNode"].Tag = this.CooperatePanel;
+ this.TreeViewSetting.Nodes["ConnectionNode"].Nodes["ShortUrlNode"].Tag = this.ShortUrlPanel;
this.TreeViewSetting.SelectedNode = this.TreeViewSetting.Nodes[0];
this.TreeViewSetting.ExpandAll();
- ActiveControl = BasedPanel.StartAuthButton;
+ this.ActiveControl = this.BasedPanel.StartAuthButton;
}
private void UReadMng_CheckedChanged(object sender, EventArgs e)
}
}
- 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 appToken = this.SelectAuthType();
+ if (appToken == null)
+ return;
- var authUserCombo = this.BasedPanel.AuthUserCombo;
+ UserAccount newAccount;
+ if (appToken.AuthType == APIAuthType.TwitterComCookie)
+ {
+ newAccount = new()
+ {
+ TwitterAuthType = appToken.AuthType,
+ TwitterComCookie = appToken.TwitterComCookie,
+ };
+
+ using var twitterApi = new TwitterApi();
+ twitterApi.Initialize(new TwitterCredentialCookie(appToken), 0L, "");
+ var twitterUser = await twitterApi.AccountVerifyCredentials();
+ newAccount.UserId = twitterUser.Id;
+ newAccount.Username = twitterUser.ScreenName;
+ }
+ else
+ {
+ var account = await this.PinAuth(appToken);
+ if (account == null)
+ return;
+ newAccount = account;
+ }
- var oldAccount = authUserCombo.Items.Cast<UserAccount>()
- .FirstOrDefault(x => x.UserId == this.tw.UserId);
+ var authUserCombo = this.BasedPanel.AuthUserCombo;
- int idx;
- if (oldAccount != null)
- {
- idx = authUserCombo.Items.IndexOf(oldAccount);
- authUserCombo.Items[idx] = newAccount;
+ 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;
+ }
+ else
+ {
+ idx = authUserCombo.Items.Add(newAccount);
+ }
+
+ authUserCombo.SelectedIndex = idx;
+
+ MessageBox.Show(
+ this,
+ Properties.Resources.AuthorizeButton_Click1,
+ "Authenticate",
+ MessageBoxButtons.OK);
}
- else
+ catch (TwitterApiException ex)
{
- idx = authUserCombo.Items.Add(newAccount);
- }
-
- authUserCombo.SelectedIndex = idx;
+ var message = Properties.Resources.AuthorizeButton_Click2 + Environment.NewLine +
+ string.Join(Environment.NewLine, ex.LongMessages);
- 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);
+ MessageBox.Show(this, message, "Authenticate", MessageBoxButtons.OK);
+ }
}
}
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 TwitterAppToken? SelectAuthType()
+ {
+ using var dialog = new AuthTypeSelectDialog();
+
+ var ret = dialog.ShowDialog(this);
+ if (ret != DialogResult.OK)
+ return null;
+
+ return dialog.Result;
}
- private UserAccount PinAuth()
+ private async Task<UserAccount?> PinAuth(TwitterAppToken appToken)
{
- this.tw.Initialize("", "", "", 0);
+ var requestToken = await TwitterApiConnection.GetRequestTokenAsync(appToken);
- var pinPageUrl = this.tw.StartAuthentication();
+ var pinPageUrl = TwitterApiConnection.GetAuthorizeUri(requestToken);
- var pin = AuthDialog.DoAuth(this, pinPageUrl);
- if (string.IsNullOrEmpty(pin))
+ var browserPath = this.ActionPanel.BrowserPathText.Text;
+ var pin = AuthDialog.DoAuth(this, pinPageUrl, browserPath);
+ if (MyCommon.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,
+ TwitterAuthType = appToken.AuthType,
+ TwitterOAuth1ConsumerKey = appToken.OAuth1CustomConsumerKey?.Value ?? "",
+ TwitterOAuth1ConsumerSecret = appToken.OAuth1CustomConsumerSecret?.Value ?? "",
+ 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;
private void Setting_Shown(object sender, EventArgs e)
{
{
Thread.Sleep(10);
if (this.Disposing || this.IsDisposed) return;
- } 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;
- }
-
- 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; // 規定外応答:通信エラーの可能性があるためとりあえずチェックを通ったことにする
- }
- }
+ while (!this.IsHandleCreated);
+ this.TopMost = this.PreviewPanel.CheckAlwaysTop.Checked;
- private void Cancel_Click(object sender, EventArgs e)
- {
- _ValidationError = false;
+ this.GetPeriodPanel.LabelPostAndGet.Visible = this.GetPeriodPanel.CheckPostAndGet.Checked;
}
- private void OpenUrl(string url)
+ private async Task OpenUrl(string url)
{
- string myPath = url;
- string path = this.ActionPanel.BrowserPathText.Text;
- try
- {
- if (!string.IsNullOrEmpty(path))
- {
- if (path.StartsWith("\"", StringComparison.Ordinal) && path.Length > 2 && path.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
- {
- int sep = path.IndexOf("\"", 2, StringComparison.Ordinal);
- string browserPath = path.Substring(1, sep - 1);
- string arg = "";
- if (sep < path.Length - 1)
- {
- arg = path.Substring(sep + 1);
- }
- myPath = arg + " " + myPath;
- System.Diagnostics.Process.Start(browserPath, myPath);
- }
- else
- {
- System.Diagnostics.Process.Start(path, myPath);
- }
- }
- else
- {
- System.Diagnostics.Process.Start(myPath);
- }
- }
- catch(Exception)
- {
- }
+ var browserPathWithArgs = this.ActionPanel.BrowserPathText.Text;
+ await MyCommon.OpenInBrowserAsync(this, browserPathWithArgs, url);
}
- private void CreateAccountButton_Click(object sender, EventArgs e)
- {
- this.OpenUrl("https://twitter.com/signup");
- }
+ private async void CreateAccountButton_Click(object sender, EventArgs e)
+ => await this.OpenUrl("https://twitter.com/signup");
private void GetPeriodPanel_IntervalChanged(object sender, IntervalChangedEventArgs e)
- {
- this.IntervalChanged?.Invoke(sender, e);
- }
+ => this.IntervalChanged?.Invoke(sender, e);
}
public class IntervalChangedEventArgs : EventArgs
{
- public bool UserStream;
public bool Timeline;
public bool Reply;
public bool DirectMessage;
public bool Lists;
public bool UserTimeline;
- public static IntervalChangedEventArgs ResetAll
+ public static IntervalChangedEventArgs ResetAll => new()
{
- get
- {
- return new IntervalChangedEventArgs()
- {
- UserStream = true,
- Timeline = true,
- Reply = true,
- DirectMessage = true,
- PublicSearch = true,
- Lists = true,
- UserTimeline = true,
- };
- }
- }
+ Timeline = true,
+ Reply = true,
+ DirectMessage = true,
+ PublicSearch = true,
+ Lists = true,
+ UserTimeline = true,
+ };
}
}