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 Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 // (c) 2013 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
11 // This file is part of OpenTween.
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23 // You should have received a copy of the GNU General Public License along
24 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
28 using System.Diagnostics;
32 using System.Net.Http;
33 using System.Runtime.CompilerServices;
34 using System.Runtime.Serialization;
35 using System.Runtime.Serialization.Json;
37 using System.Text.RegularExpressions;
38 using System.Threading;
39 using System.Threading.Tasks;
42 using System.Xml.Linq;
43 using System.Xml.XPath;
45 using System.Reflection;
46 using System.Collections.Generic;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
55 public class Twitter : IDisposable
57 #region Regexp from twitter-text-js
59 // The code in this region code block incorporates works covered by
60 // the following copyright and permission notices:
62 // Copyright 2011 Twitter, Inc.
64 // Licensed under the Apache License, Version 2.0 (the "License"); you
65 // may not use this work except in compliance with the License. You
66 // may obtain a copy of the License in the LICENSE file, or at:
68 // http://www.apache.org/licenses/LICENSE-2.0
70 // Unless required by applicable law or agreed to in writing, software
71 // distributed under the License is distributed on an "AS IS" BASIS,
72 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
73 // implied. See the License for the specific language governing
74 // permissions and limitations under the License.
77 private const string LATIN_ACCENTS = @"\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0100-\u024f\u0253\u0254\u0256\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff";
78 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
79 //private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u3096\u3400-\u4DBF\u4E00-\u9FFF\u20000-\u2A6DF\u2A700-\u2B73F\u2B740-\u2B81F\u2F800-\u2FA1F";
80 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
81 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
82 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
83 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
85 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
87 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
88 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
89 private const string url_invalid_domain_chars = @"\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$\u2000-\u200a\u0009-\u000d\u0020\u0085\u00a0\u1680\u180e\u2028\u2029\u202f\u205f\u3000\ufffe\ufeff\uffff\u202a-\u202e";
90 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
91 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
92 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
93 private const string url_valid_GTLD = @"(?:(?:aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xxx)(?=[^0-9a-zA-Z]|$))";
94 private const string url_valid_CCTLD = @"(?:(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?=[^0-9a-zA-Z]|$))";
95 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
96 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
97 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
98 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
99 private const string url_valid_port_number = @"[0-9]+";
101 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
102 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
103 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
104 private const string pth = "(?:" +
106 url_valid_general_path_chars + "*" +
107 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
108 url_valid_path_ending_chars +
109 ")|(?:@" + url_valid_general_path_chars + "+/)" +
111 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
112 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
113 "(?<url>(?<protocol>https?://)?" +
114 "(?<domain>" + url_valid_domain + ")" +
115 "(?::" + url_valid_port_number + ")?" +
116 "(?<path>/" + pth + "*)?" +
123 /// Twitter API のステータスページのURL
125 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
128 /// ツイートへのパーマリンクURLを判定する正規表現
130 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
133 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
135 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
136 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
137 | favstar\.fm/t/ # Favstar (short)
138 | aclog\.koba789\.com/i/ # aclog
139 | frtrt\.net/solo_status\.php\?status= # RtRT
140 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
143 /// DM送信かどうかを判定する正規表現
145 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
147 public TwitterApi Api { get; }
148 public TwitterConfiguration Configuration { get; private set; }
150 delegate void GetIconImageDelegate(PostClass post);
151 private readonly object LockObj = new object();
152 private ISet<long> followerId = new HashSet<long>();
153 private bool _GetFollowerResult = false;
154 private long[] noRTId = new long[0];
155 private bool _GetNoRetweetResult = false;
158 private string _uname;
160 private bool _readOwnPost;
161 private List<string> _hashList = new List<string>();
163 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
164 private long minHomeTimeline = long.MaxValue;
165 private long minMentions = long.MaxValue;
166 private long minDirectmessage = long.MaxValue;
167 private long minDirectmessageSent = long.MaxValue;
169 //private FavoriteQueue favQueue;
171 private HttpTwitter twCon = new HttpTwitter();
173 //private List<PostClass> _deletemessages = new List<PostClass>();
175 public Twitter() : this(new TwitterApi())
179 public Twitter(TwitterApi api)
182 this.Configuration = TwitterConfiguration.DefaultConfiguration();
185 public TwitterApiAccessLevel AccessLevel
189 return MyCommon.TwitterApiInfo.AccessLevel;
193 protected void ResetApiStatus()
195 MyCommon.TwitterApiInfo.Reset();
198 public void ClearAuthInfo()
200 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
201 this.ResetApiStatus();
202 twCon.ClearAuthInfo();
206 public void VerifyCredentials()
210 this.VerifyCredentialsAsync().Wait();
212 catch (AggregateException ex) when (ex.InnerException is WebApiException)
214 throw new WebApiException(ex.InnerException.Message, ex);
218 public async Task VerifyCredentialsAsync()
220 var user = await this.Api.AccountVerifyCredentials()
221 .ConfigureAwait(false);
223 this.twCon.AuthenticatedUserId = user.Id;
224 this.UpdateUserStats(user);
227 public void Initialize(string token, string tokenSecret, string username, long userId)
230 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
232 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
234 this.ResetApiStatus();
235 this.Api.Initialize(token, tokenSecret, userId, username);
236 twCon.Initialize(token, tokenSecret, username, userId);
237 _uname = username.ToLowerInvariant();
238 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
241 public string PreProcessUrl(string orgData)
245 //var IDNConveter = new IdnMapping();
246 var href = "<a href=\"";
250 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
254 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
255 posl1 += href.Length;
256 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
257 urlStr = orgData.Substring(posl1, posl2 - posl1);
259 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
260 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
261 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
266 var replacedUrl = MyCommon.IDNEncode(urlStr);
267 if (replacedUrl == null) continue;
268 if (replacedUrl == urlStr) continue;
270 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
281 private string GetPlainText(string orgData)
283 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
286 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
288 private string SanitizeHtml(string orgdata)
290 var retdata = orgdata;
292 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
293 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
295 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
300 private string AdjustHtml(string orgData)
302 var retStr = orgData;
303 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
308 // _hashList.Add("#" + m.Groups(1).Value);
312 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
313 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
314 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
316 //半角スペースを置換(Thanks @anis774)
320 ret = EscapeSpace(ref retStr);
323 return SanitizeHtml(retStr);
326 private bool EscapeSpace(ref string html)
328 //半角スペースを置換(Thanks @anis774)
330 for (int i = 0; i < html.Length; i++)
341 if ((!isTag) && (html[i] == ' '))
343 html = html.Remove(i, 1);
344 html = html.Insert(i, " ");
351 private struct PostInfo
353 public string CreatedAt;
356 public string UserId;
357 public PostInfo(string Created, string IdStr, string txt, string uid)
364 public bool Equals(PostInfo dst)
366 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
377 static private PostInfo _prev = new PostInfo("", "", "", "");
378 private bool IsPostRestricted(TwitterStatus status)
380 var _current = new PostInfo("", "", "", "");
382 _current.CreatedAt = status.CreatedAt;
383 _current.Id = status.IdStr;
384 if (status.Text == null)
390 _current.Text = status.Text;
392 _current.UserId = status.User.IdStr;
394 if (_current.Equals(_prev))
398 _prev.CreatedAt = _current.CreatedAt;
399 _prev.Id = _current.Id;
400 _prev.Text = _current.Text;
401 _prev.UserId = _current.UserId;
406 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
408 this.CheckAccountState();
410 if (mediaIds == null &&
411 Twitter.DMSendTextRegex.IsMatch(postStr))
413 await this.SendDirectMessage(postStr)
414 .ConfigureAwait(false);
418 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
419 .ConfigureAwait(false);
421 var status = await response.LoadJsonAsync()
422 .ConfigureAwait(false);
424 this.UpdateUserStats(status.User);
426 if (IsPostRestricted(status))
428 throw new WebApiException("OK:Delaying?");
432 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
434 this.CheckAccountState();
436 if (Twitter.DMSendTextRegex.IsMatch(postStr))
438 await this.SendDirectMessage(postStr)
439 .ConfigureAwait(false);
443 if (mediaItems.Length == 0)
444 throw new WebApiException("Err:Invalid Files!");
446 var uploadTasks = from m in mediaItems
447 select this.UploadMedia(m);
449 var mediaIds = await Task.WhenAll(uploadTasks)
450 .ConfigureAwait(false);
452 await this.PostStatus(postStr, reply_to, mediaIds)
453 .ConfigureAwait(false);
456 public async Task<long> UploadMedia(IMediaItem item)
458 this.CheckAccountState();
460 var response = await this.Api.MediaUpload(item)
461 .ConfigureAwait(false);
463 var media = await response.LoadJsonAsync()
464 .ConfigureAwait(false);
466 return media.MediaId;
469 public async Task SendDirectMessage(string postStr)
471 this.CheckAccountState();
472 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
474 var mc = Twitter.DMSendTextRegex.Match(postStr);
476 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
477 .ConfigureAwait(false);
479 var dm = await response.LoadJsonAsync()
480 .ConfigureAwait(false);
482 this.UpdateUserStats(dm.Sender);
485 public async Task PostRetweet(long id, bool read)
487 this.CheckAccountState();
491 var post = TabInformations.GetInstance()[id];
494 throw new WebApiException("Err:Target isn't found.");
496 if (TabInformations.GetInstance()[id].RetweetedId != null)
498 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
501 var response = await this.Api.StatusesRetweet(target)
502 .ConfigureAwait(false);
504 var status = await response.LoadJsonAsync()
505 .ConfigureAwait(false);
508 post = CreatePostsFromStatusData(status);
510 throw new WebApiException("Invalid Json!");
515 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
519 if (post.RetweetedId == null)
520 throw new WebApiException("Invalid Json!");
526 if (_readOwnPost) post.IsRead = true;
529 TabInformations.GetInstance().AddPost(post);
532 public string Username
536 return twCon.AuthenticatedUsername;
544 return twCon.AuthenticatedUserId;
548 public string Password
552 return twCon.Password;
556 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
557 public static MyCommon.ACCOUNT_STATE AccountState
561 return _accountState;
565 _accountState = value;
569 public bool RestrictFavCheck { get; set; }
572 public void GetTweenBinary(string strVer)
577 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
578 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
580 throw new WebApiException("Err:Download failed");
583 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
585 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
587 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
588 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
590 throw new WebApiException("Err:Download failed");
592 //その他言語圏のリソース。取得失敗しても継続
595 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
597 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
600 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
604 curCul = Thread.CurrentThread.CurrentUICulture.Name;
609 curCul = Thread.CurrentThread.CurrentUICulture.Name;
611 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
613 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
615 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
617 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
618 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
620 //return "Err:Download failed";
625 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
627 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
630 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
634 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
639 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
641 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
643 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
645 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
647 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
648 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
650 //return "Err:Download failed";
655 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
656 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
658 throw new WebApiException("Err:Download failed");
661 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
662 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
664 throw new WebApiException("Err:Download failed");
669 throw new WebApiException("Err:Download failed", ex);
674 public bool ReadOwnPost
682 _readOwnPost = value;
686 public int FollowersCount { get; private set; }
687 public int FriendsCount { get; private set; }
688 public int StatusesCount { get; private set; }
689 public string Location { get; private set; } = "";
690 public string Bio { get; private set; } = "";
692 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
693 private void UpdateUserStats(TwitterUser self)
695 this.FollowersCount = self.FollowersCount;
696 this.FriendsCount = self.FriendsCount;
697 this.StatusesCount = self.StatusesCount;
698 this.Location = self.Location;
699 this.Bio = self.Description;
703 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
705 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
707 return count >= 20 && count <= GetMaxApiResultCount(type);
711 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
713 public static bool VerifyMoreApiResultCount(int count)
715 return count >= 20 && count <= 200;
719 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
721 public static bool VerifyFirstApiResultCount(int count)
723 return count >= 20 && count <= 200;
727 /// WORKERTYPEに応じた取得可能な最大件数を取得する
729 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
731 // 参照: REST APIs - 各endpointのcountパラメータ
732 // https://dev.twitter.com/rest/public
735 case MyCommon.WORKERTYPE.Timeline:
736 case MyCommon.WORKERTYPE.Reply:
737 case MyCommon.WORKERTYPE.UserTimeline:
738 case MyCommon.WORKERTYPE.Favorites:
739 case MyCommon.WORKERTYPE.DirectMessegeRcv:
740 case MyCommon.WORKERTYPE.DirectMessegeSnt:
741 case MyCommon.WORKERTYPE.List: // 不明
744 case MyCommon.WORKERTYPE.PublicSearch:
748 throw new InvalidOperationException("Invalid type: " + type);
753 /// WORKERTYPEに応じた取得件数を取得する
755 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
757 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
758 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
763 if (SettingCommon.Instance.UseAdditionalCount)
767 case MyCommon.WORKERTYPE.Favorites:
768 if (SettingCommon.Instance.FavoritesCountApi != 0)
769 return SettingCommon.Instance.FavoritesCountApi;
771 case MyCommon.WORKERTYPE.List:
772 if (SettingCommon.Instance.ListCountApi != 0)
773 return SettingCommon.Instance.ListCountApi;
775 case MyCommon.WORKERTYPE.PublicSearch:
776 if (SettingCommon.Instance.SearchCountApi != 0)
777 return SettingCommon.Instance.SearchCountApi;
779 case MyCommon.WORKERTYPE.UserTimeline:
780 if (SettingCommon.Instance.UserTimelineCountApi != 0)
781 return SettingCommon.Instance.UserTimelineCountApi;
784 if (more && SettingCommon.Instance.MoreCountApi != 0)
786 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
788 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
790 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
795 var count = SettingCommon.Instance.CountApi;
797 if (type == MyCommon.WORKERTYPE.Reply)
798 count = SettingCommon.Instance.CountApiReply;
800 return Math.Min(count, GetMaxApiResultCount(type));
803 public async Task GetTimelineApi(bool read, MyCommon.WORKERTYPE gType, bool more, bool startup)
805 this.CheckAccountState();
807 var count = GetApiResultCount(gType, more, startup);
809 TwitterStatus[] statuses;
810 if (gType == MyCommon.WORKERTYPE.Timeline)
814 statuses = await this.Api.StatusesHomeTimeline(count, maxId: this.minHomeTimeline)
815 .ConfigureAwait(false);
819 statuses = await this.Api.StatusesHomeTimeline(count)
820 .ConfigureAwait(false);
827 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: this.minMentions)
828 .ConfigureAwait(false);
832 statuses = await this.Api.StatusesMentionsTimeline(count)
833 .ConfigureAwait(false);
837 var minimumId = CreatePostsFromJson(statuses, gType, null, read);
839 if (minimumId != null)
841 if (gType == MyCommon.WORKERTYPE.Timeline)
842 this.minHomeTimeline = minimumId.Value;
844 this.minMentions = minimumId.Value;
848 public async Task GetUserTimelineApi(bool read, string userName, TabClass tab, bool more)
850 this.CheckAccountState();
852 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
854 TwitterStatus[] statuses;
855 if (string.IsNullOrEmpty(userName))
857 var target = tab.User;
858 if (string.IsNullOrEmpty(target)) return;
860 statuses = await this.Api.StatusesUserTimeline(userName, count)
861 .ConfigureAwait(false);
867 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
868 .ConfigureAwait(false);
872 statuses = await this.Api.StatusesUserTimeline(userName, count)
873 .ConfigureAwait(false);
877 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
879 if (minimumId != null)
880 tab.OldestId = minimumId.Value;
883 public async Task<PostClass> GetStatusApi(bool read, long id)
885 this.CheckAccountState();
887 var status = await this.Api.StatusesShow(id)
888 .ConfigureAwait(false);
890 var item = CreatePostsFromStatusData(status);
892 throw new WebApiException("Err:Can't create post");
895 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
900 public async Task GetStatusApi(bool read, long id, TabClass tab)
902 var post = await this.GetStatusApi(read, id)
903 .ConfigureAwait(false);
905 //非同期アイコン取得&StatusDictionaryに追加
906 if (tab != null && tab.IsInnerStorageTabType)
907 tab.AddPostToInnerStorage(post);
909 TabInformations.GetInstance().AddPost(post);
912 private PostClass CreatePostsFromStatusData(TwitterStatus status)
914 return CreatePostsFromStatusData(status, false);
917 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
919 var post = new PostClass();
920 TwitterEntities entities;
923 post.StatusId = status.Id;
924 if (status.RetweetedStatus != null)
926 var retweeted = status.RetweetedStatus;
928 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
931 post.RetweetedId = retweeted.Id;
933 post.TextFromApi = retweeted.Text;
934 entities = retweeted.MergedEntities;
935 sourceHtml = retweeted.Source;
937 post.InReplyToStatusId = retweeted.InReplyToStatusId;
938 post.InReplyToUser = retweeted.InReplyToScreenName;
939 post.InReplyToUserId = status.InReplyToUserId;
948 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
949 post.IsFav = tc.Contains(retweeted.Id);
952 if (retweeted.Coordinates != null)
953 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
956 var user = retweeted.User;
958 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
960 post.UserId = user.Id;
961 post.ScreenName = user.ScreenName;
962 post.Nickname = user.Name.Trim();
963 post.ImageUrl = user.ProfileImageUrlHttps;
964 post.IsProtect = user.Protected;
967 post.RetweetedBy = status.User.ScreenName;
968 post.RetweetedByUserId = status.User.Id;
969 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
973 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
975 post.TextFromApi = status.Text;
976 entities = status.MergedEntities;
977 sourceHtml = status.Source;
978 post.InReplyToStatusId = status.InReplyToStatusId;
979 post.InReplyToUser = status.InReplyToScreenName;
980 post.InReplyToUserId = status.InReplyToUserId;
989 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
990 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
993 if (status.Coordinates != null)
994 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
997 var user = status.User;
999 if (user == null || user.ScreenName == null) return null;
1001 post.UserId = user.Id;
1002 post.ScreenName = user.ScreenName;
1003 post.Nickname = user.Name.Trim();
1004 post.ImageUrl = user.ProfileImageUrlHttps;
1005 post.IsProtect = user.Protected;
1006 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1009 string textFromApi = post.TextFromApi;
1010 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1011 post.TextFromApi = textFromApi;
1012 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1013 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1014 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1016 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1017 .Where(x => x != post.StatusId && x != post.RetweetedId)
1018 .Distinct().ToArray();
1020 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1021 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1025 var source = ParseSource(sourceHtml);
1026 post.Source = source.Item1;
1027 post.SourceUri = source.Item2;
1029 post.IsReply = post.ReplyToList.Contains(_uname);
1030 post.IsExcludeReply = false;
1038 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1046 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1048 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1050 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1052 return GetQuoteTweetStatusIds(urls);
1055 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1057 foreach (var url in urls)
1059 var match = Twitter.StatusUrlRegex.Match(url);
1063 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1064 yield return statusId;
1069 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1071 long? minimumId = null;
1073 foreach (var status in items)
1075 PostClass post = null;
1076 post = CreatePostsFromStatusData(status);
1077 if (post == null) continue;
1079 if (minimumId == null || minimumId.Value > post.StatusId)
1080 minimumId = post.StatusId;
1087 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1091 if (tab.Contains(post.StatusId)) continue;
1096 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1097 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1100 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1102 //非同期アイコン取得&StatusDictionaryに追加
1103 if (tab != null && tab.IsInnerStorageTabType)
1104 tab.AddPostToInnerStorage(post);
1106 TabInformations.GetInstance().AddPost(post);
1112 private long? CreatePostsFromSearchJson(TwitterSearchResult items, TabClass tab, bool read, int count, bool more)
1114 long? minimumId = null;
1116 foreach (var result in items.Statuses)
1118 var post = CreatePostsFromStatusData(result);
1122 if (minimumId == null || minimumId.Value > post.StatusId)
1123 minimumId = post.StatusId;
1125 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1131 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1135 if (tab.Contains(post.StatusId)) continue;
1140 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1142 //非同期アイコン取得&StatusDictionaryに追加
1143 if (tab != null && tab.IsInnerStorageTabType)
1144 tab.AddPostToInnerStorage(post);
1146 TabInformations.GetInstance().AddPost(post);
1152 private void CreateFavoritePostsFromJson(TwitterStatus[] item, bool read)
1154 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1156 foreach (var status in item)
1161 if (favTab.Contains(status.Id)) continue;
1164 var post = CreatePostsFromStatusData(status, true);
1165 if (post == null) continue;
1169 TabInformations.GetInstance().AddPost(post);
1173 public async Task GetListStatus(bool read, TabClass tab, bool more, bool startup)
1175 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1177 TwitterStatus[] statuses;
1180 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1181 .ConfigureAwait(false);
1185 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1186 .ConfigureAwait(false);
1189 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1191 if (minimumId != null)
1192 tab.OldestId = minimumId.Value;
1196 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1198 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1199 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1201 if (!posts.ContainsKey(startStatusId))
1202 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1204 var nextPost = posts[startStatusId];
1205 while (nextPost.InReplyToStatusId != null)
1207 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1209 nextPost = posts[nextPost.InReplyToStatusId.Value];
1215 public async Task GetRelatedResult(bool read, TabClass tab)
1217 var relPosts = new Dictionary<Int64, PostClass>();
1218 if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1221 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1222 if (p != null && p.InReplyToStatusId != null)
1224 tab.RelationTargetPost = p;
1228 p = await this.GetStatusApi(read, tab.RelationTargetPost.StatusId)
1229 .ConfigureAwait(false);
1230 tab.RelationTargetPost = p;
1233 relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1235 Exception lastException = null;
1237 // in_reply_to_status_id を使用してリプライチェインを辿る
1238 var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1240 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1242 var inReplyToId = nextPost.InReplyToStatusId.Value;
1244 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1245 if (inReplyToPost == null)
1249 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1250 .ConfigureAwait(false);
1252 catch (WebApiException ex)
1259 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1261 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1264 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1265 var text = tab.RelationTargetPost.Text;
1266 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1267 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1268 foreach (var _match in ma)
1271 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1273 if (relPosts.ContainsKey(_statusId))
1276 var p = TabInformations.GetInstance()[_statusId];
1281 p = await this.GetStatusApi(read, _statusId)
1282 .ConfigureAwait(false);
1284 catch (WebApiException ex)
1292 relPosts.Add(p.StatusId, p);
1296 relPosts.Values.ToList().ForEach(p =>
1298 if (p.IsMe && !read && this._readOwnPost)
1303 tab.AddPostToInnerStorage(p);
1306 if (lastException != null)
1307 throw new WebApiException(lastException.Message, lastException);
1310 public async Task GetSearch(bool read, TabClass tab, bool more)
1312 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1315 long? sinceId = null;
1318 maxId = tab.OldestId - 1;
1322 sinceId = tab.SinceId;
1325 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1326 .ConfigureAwait(false);
1328 if (!TabInformations.GetInstance().ContainsTab(tab))
1331 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, count, more);
1333 if (minimumId != null)
1334 tab.OldestId = minimumId.Value;
1337 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1339 foreach (var message in item)
1341 var post = new PostClass();
1344 post.StatusId = message.Id;
1345 if (gType != MyCommon.WORKERTYPE.UserStream)
1347 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1349 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1353 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1360 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1364 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1366 var textFromApi = message.Text;
1368 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1369 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1370 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1371 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1374 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1376 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1377 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1382 if (gType == MyCommon.WORKERTYPE.UserStream)
1384 if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
1386 user = message.Sender;
1392 user = message.Recipient;
1399 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1401 user = message.Sender;
1407 user = message.Recipient;
1413 post.UserId = user.Id;
1414 post.ScreenName = user.ScreenName;
1415 post.Nickname = user.Name.Trim();
1416 post.ImageUrl = user.ProfileImageUrlHttps;
1417 post.IsProtect = user.Protected;
1421 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1422 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1427 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1428 post.IsReply = false;
1429 post.IsExcludeReply = false;
1432 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1433 dmTab.AddPostToInnerStorage(post);
1437 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1439 this.CheckAccountState();
1440 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1442 var count = GetApiResultCount(gType, more, false);
1444 TwitterDirectMessage[] messages;
1445 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1449 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1450 .ConfigureAwait(false);
1454 messages = await this.Api.DirectMessagesRecv(count)
1455 .ConfigureAwait(false);
1462 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1463 .ConfigureAwait(false);
1467 messages = await this.Api.DirectMessagesSent(count)
1468 .ConfigureAwait(false);
1472 CreateDirectMessagesFromJson(messages, gType, read);
1475 public async Task GetFavoritesApi(bool read, bool more)
1477 this.CheckAccountState();
1479 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1481 var statuses = await this.Api.FavoritesList(count)
1482 .ConfigureAwait(false);
1484 CreateFavoritePostsFromJson(statuses, read);
1487 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1489 if (entities != null)
1491 if (entities.Urls != null)
1493 foreach (var m in entities.Urls)
1495 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1498 if (entities.Media != null)
1500 foreach (var m in entities.Media)
1502 if (m.AltText != null)
1504 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1508 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1519 /// <exception cref="WebApiException"/>
1520 public async Task RefreshFollowerIds()
1522 if (MyCommon._endingFlag) return;
1525 var newFollowerIds = new HashSet<long>();
1528 var ret = await this.Api.FollowersIds(cursor)
1529 .ConfigureAwait(false);
1531 if (ret.Ids == null)
1532 throw new WebApiException("ret.ids == null");
1534 newFollowerIds.UnionWith(ret.Ids);
1535 cursor = ret.NextCursor;
1536 } while (cursor != 0);
1538 this.followerId = newFollowerIds;
1539 TabInformations.GetInstance().RefreshOwl(this.followerId);
1541 this._GetFollowerResult = true;
1544 public bool GetFollowersSuccess
1548 return _GetFollowerResult;
1553 /// RT 非表示ユーザーを更新します
1555 /// <exception cref="WebApiException"/>
1556 public async Task RefreshNoRetweetIds()
1558 if (MyCommon._endingFlag) return;
1560 this.noRTId = await this.Api.NoRetweetIds()
1561 .ConfigureAwait(false);
1563 this._GetNoRetweetResult = true;
1566 public bool GetNoRetweetSuccess
1570 return _GetNoRetweetResult;
1575 /// t.co の文字列長などの設定情報を更新します
1577 /// <exception cref="WebApiException"/>
1578 public async Task RefreshConfiguration()
1580 this.Configuration = await this.Api.Configuration()
1581 .ConfigureAwait(false);
1584 public async Task GetListsApi()
1586 this.CheckAccountState();
1588 var ownedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsOwnerships(this.Username, cursor: x))
1589 .ConfigureAwait(false);
1591 var subscribedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsSubscriptions(this.Username, cursor: x))
1592 .ConfigureAwait(false);
1594 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1595 .Select(x => new ListElement(x, this))
1599 public async Task DeleteList(long listId)
1601 await this.Api.ListsDestroy(listId)
1603 .ConfigureAwait(false);
1605 var tabinfo = TabInformations.GetInstance();
1607 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1608 .Where(x => x.Id != listId)
1612 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1614 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1615 .ConfigureAwait(false);
1617 var list = await response.LoadJsonAsync()
1618 .ConfigureAwait(false);
1620 return new ListElement(list, this);
1623 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1625 this.CheckAccountState();
1627 var users = await this.Api.ListsMembers(listId, cursor)
1628 .ConfigureAwait(false);
1630 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1632 return users.NextCursor;
1635 public async Task CreateListApi(string listName, bool isPrivate, string description)
1637 this.CheckAccountState();
1639 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1640 .ConfigureAwait(false);
1642 var list = await response.LoadJsonAsync()
1643 .ConfigureAwait(false);
1645 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1648 public async Task<bool> ContainsUserAtList(long listId, string user)
1650 this.CheckAccountState();
1654 await this.Api.ListsMembersShow(listId, user)
1655 .ConfigureAwait(false);
1659 catch (TwitterApiException ex)
1660 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1666 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1668 if (entities != null)
1670 if (entities.Hashtags != null)
1674 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1677 if (entities.UserMentions != null)
1679 foreach (var ent in entities.UserMentions)
1681 var screenName = ent.ScreenName.ToLowerInvariant();
1682 if (!AtList.Contains(screenName))
1683 AtList.Add(screenName);
1686 if (entities.Media != null)
1690 foreach (var ent in entities.Media)
1692 if (!media.Any(x => x.Url == ent.MediaUrl))
1694 if (ent.VideoInfo != null &&
1695 ent.Type == "animated_gif" || ent.Type == "video")
1697 //var videoUrl = ent.VideoInfo.Variants
1698 // .Where(v => v.ContentType == "video/mp4")
1699 // .OrderByDescending(v => v.Bitrate)
1700 // .Select(v => v.Url).FirstOrDefault();
1701 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1704 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1711 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1712 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1714 text = Regex.Replace(text, "(^|[^a-zA-Z0-9_/&##@@>=.~])(sm|nm)([0-9]{1,10})", "$1<a href=\"http://www.nicovideo.jp/watch/$2$3\">$2$3</a>");
1715 text = PreProcessUrl(text); //IDN置換
1720 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1723 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1725 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1727 if (string.IsNullOrEmpty(sourceHtml))
1728 return Tuple.Create<string, Uri>("", null);
1733 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1735 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1738 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1741 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1742 sourceUri = new Uri(SourceUriBase, uriStr);
1744 catch (UriFormatException)
1751 sourceText = WebUtility.HtmlDecode(sourceHtml);
1755 return Tuple.Create(sourceText, sourceUri);
1758 public async Task<TwitterApiStatus> GetInfoApi()
1760 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1762 if (MyCommon._endingFlag) return null;
1764 var limits = await this.Api.ApplicationRateLimitStatus()
1765 .ConfigureAwait(false);
1767 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1769 return MyCommon.TwitterApiInfo;
1773 /// ブロック中のユーザーを更新します
1775 /// <exception cref="WebApiException"/>
1776 public async Task RefreshBlockIds()
1778 if (MyCommon._endingFlag) return;
1781 var newBlockIds = new HashSet<long>();
1784 var ret = await this.Api.BlocksIds(cursor)
1785 .ConfigureAwait(false);
1787 newBlockIds.UnionWith(ret.Ids);
1788 cursor = ret.NextCursor;
1789 } while (cursor != 0);
1791 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1793 TabInformations.GetInstance().BlockIds = newBlockIds;
1797 /// ミュート中のユーザーIDを更新します
1799 /// <exception cref="WebApiException"/>
1800 public async Task RefreshMuteUserIdsAsync()
1802 if (MyCommon._endingFlag) return;
1804 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1805 .ConfigureAwait(false);
1807 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1810 public string[] GetHashList()
1815 hashArray = _hashList.ToArray();
1821 public string AccessToken
1825 return twCon.AccessToken;
1829 public string AccessTokenSecret
1833 return twCon.AccessTokenSecret;
1837 private void CheckAccountState()
1839 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1840 throw new WebApiException("Auth error. Check your account");
1843 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1845 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1846 throw new WebApiException("Auth Err:try to re-authorization.");
1849 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
1850 [CallerMemberName] string callerMethodName = "")
1852 if (httpStatus == HttpStatusCode.OK)
1854 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1858 if (string.IsNullOrWhiteSpace(responseText))
1860 if (httpStatus == HttpStatusCode.Unauthorized)
1861 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1863 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
1868 var errors = TwitterError.ParseJson(responseText).Errors;
1869 if (errors == null || !errors.Any())
1871 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1874 foreach (var error in errors)
1876 if (error.Code == TwitterErrorCode.InvalidToken ||
1877 error.Code == TwitterErrorCode.SuspendedAccount)
1879 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1883 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
1885 catch (SerializationException) { }
1887 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1890 public int GetTextLengthRemain(string postText)
1892 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1893 if (matchDm.Success)
1894 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1896 return this.GetTextLengthRemainInternal(postText, isDm: false);
1899 private int GetTextLengthRemainInternal(string postText, bool isDm)
1904 while (pos < postText.Length)
1908 if (char.IsSurrogatePair(postText, pos))
1909 pos += 2; // サロゲートペアの場合は2文字分進める
1914 var urls = TweetExtractor.ExtractUrls(postText);
1915 foreach (var url in urls)
1917 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1918 ? this.Configuration.ShortUrlLengthHttps
1919 : this.Configuration.ShortUrlLength;
1921 textLength += shortUrlLength - url.Length;
1925 return this.Configuration.DmTextCharacterLimit - textLength;
1927 return 140 - textLength;
1931 #region "UserStream"
1932 private string trackWord_ = "";
1933 public string TrackWord
1944 private bool allAtReply_ = false;
1945 public bool AllAtReply
1953 allAtReply_ = value;
1957 public event EventHandler NewPostFromStream;
1958 public event EventHandler UserStreamStarted;
1959 public event EventHandler UserStreamStopped;
1960 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1961 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1962 private DateTime _lastUserstreamDataReceived;
1963 private TwitterUserstream userStream;
1965 public class FormattedEvent
1967 public MyCommon.EVENTTYPE Eventtype { get; set; }
1968 public DateTime CreatedAt { get; set; }
1969 public string Event { get; set; }
1970 public string Username { get; set; }
1971 public string Target { get; set; }
1972 public Int64 Id { get; set; }
1973 public bool IsMe { get; set; }
1976 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1977 public List<FormattedEvent> StoredEvent
1981 return storedEvent_;
1985 storedEvent_ = value;
1989 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1991 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1992 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1993 ["follow"] = MyCommon.EVENTTYPE.Follow,
1994 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1995 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1996 ["block"] = MyCommon.EVENTTYPE.Block,
1997 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1998 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1999 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2000 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2001 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2002 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2003 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2004 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2005 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2006 ["mute"] = MyCommon.EVENTTYPE.Mute,
2007 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2008 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2011 public bool IsUserstreamDataReceived
2015 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2019 private void userStream_StatusArrived(string line)
2021 this._lastUserstreamDataReceived = DateTime.Now;
2022 if (string.IsNullOrEmpty(line)) return;
2024 if (line.First() != '{' || line.Last() != '}')
2026 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2034 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2036 var xElm = XElement.Load(jsonReader);
2037 if (xElm.Element("friends") != null)
2039 Debug.WriteLine("friends");
2042 else if (xElm.Element("delete") != null)
2044 Debug.WriteLine("delete");
2047 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2050 long.TryParse(idElm.Value, out id);
2052 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2054 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2057 long.TryParse(idElm.Value, out id);
2059 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2063 MyCommon.TraceOut("delete:" + line);
2066 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2068 var sEvt = this.StoredEvent[i];
2069 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2071 this.StoredEvent.RemoveAt(i);
2076 else if (xElm.Element("limit") != null)
2078 Debug.WriteLine(line);
2081 else if (xElm.Element("event") != null)
2083 Debug.WriteLine("event: " + xElm.Element("event").Value);
2084 CreateEventFromJson(line);
2087 else if (xElm.Element("direct_message") != null)
2089 Debug.WriteLine("direct_message");
2092 else if (xElm.Element("retweeted_status") != null)
2094 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2095 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2097 // 自分に関係しないリツイートの場合は無視する
2098 var selfUserId = this.UserId.ToString();
2099 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2101 // 公式 RT をイベントとしても扱う
2102 var evt = CreateEventFromRetweet(xElm);
2105 this.StoredEvent.Insert(0, evt);
2107 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2111 // 従来通り公式 RT の表示も行うため return しない
2113 else if (xElm.Element("scrub_geo") != null)
2117 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2118 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2122 MyCommon.TraceOut("scrub_geo:" + line);
2132 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2133 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2135 catch (SerializationException ex)
2137 throw TwitterApiException.CreateFromException(ex, line);
2144 var status = TwitterStatus.ParseJson(line);
2145 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2147 catch (SerializationException ex)
2149 throw TwitterApiException.CreateFromException(ex, line);
2153 catch (WebApiException ex)
2155 MyCommon.TraceOut(ex);
2158 catch(NullReferenceException)
2160 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2163 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2167 /// UserStreamsから受信した公式RTをイベントに変換します
2169 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2171 return new FormattedEvent
2173 Eventtype = MyCommon.EVENTTYPE.Retweet,
2175 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2176 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2177 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2178 Target = string.Format("@{0}:{1}", new[]
2180 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2181 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2183 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2187 private void CreateEventFromJson(string content)
2189 TwitterStreamEvent eventData = null;
2192 eventData = TwitterStreamEvent.ParseJson(content);
2194 catch(SerializationException ex)
2196 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2200 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2203 var evt = new FormattedEvent();
2204 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2205 evt.Event = eventData.Event;
2206 evt.Username = eventData.Source.ScreenName;
2207 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2209 MyCommon.EVENTTYPE eventType;
2210 eventTable.TryGetValue(eventData.Event, out eventType);
2211 evt.Eventtype = eventType;
2213 TwitterStreamEvent<TwitterStatus> tweetEvent;
2215 switch (eventData.Event)
2217 case "access_revoked":
2218 case "access_unrevoked":
2220 case "user_suspend":
2223 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2225 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2229 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2234 evt.Target = "@" + eventData.Target.ScreenName;
2236 case "favorited_retweet":
2237 case "retweeted_retweet":
2241 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2242 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2243 evt.Id = tweetEvent.TargetObject.Id;
2245 if (SettingCommon.Instance.IsRemoveSameEvent)
2247 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2251 var tabinfo = TabInformations.GetInstance();
2254 var statusId = tweetEvent.TargetObject.Id;
2255 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2258 if (eventData.Event == "favorite")
2260 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2261 if (!favTab.Contains(post.StatusId))
2262 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2264 if (tweetEvent.Source.Id == this.UserId)
2268 else if (tweetEvent.Target.Id == this.UserId)
2270 post.FavoritedCount++;
2272 if (SettingCommon.Instance.FavEventUnread)
2273 tabinfo.SetReadAllTab(post.StatusId, read: false);
2278 if (tweetEvent.Source.Id == this.UserId)
2282 else if (tweetEvent.Target.Id == this.UserId)
2284 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2288 case "quoted_tweet":
2289 if (evt.IsMe) return;
2291 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2292 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2293 evt.Id = tweetEvent.TargetObject.Id;
2295 if (SettingCommon.Instance.IsRemoveSameEvent)
2297 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2301 case "list_member_added":
2302 case "list_member_removed":
2303 case "list_created":
2304 case "list_destroyed":
2305 case "list_updated":
2306 case "list_user_subscribed":
2307 case "list_user_unsubscribed":
2308 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2309 evt.Target = listEvent.TargetObject.FullName;
2312 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2316 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2325 evt.Target = "@" + eventData.Target.ScreenName;
2326 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2328 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2332 evt.Target = "@" + eventData.Target.ScreenName;
2333 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2335 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2340 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2343 this.StoredEvent.Insert(0, evt);
2345 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2348 private void userStream_Started()
2350 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2353 private void userStream_Stopped()
2355 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2358 public bool UserStreamActive
2359 => this.userStream == null ? false : this.userStream.IsStreamActive;
2361 public void StartUserStream()
2363 var newStream = new TwitterUserstream(this.Api);
2365 newStream.StatusArrived += userStream_StatusArrived;
2366 newStream.Started += userStream_Started;
2367 newStream.Stopped += userStream_Stopped;
2369 newStream.Start(this.AllAtReply, this.TrackWord);
2371 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2372 oldStream?.Dispose();
2375 public void StopUserStream()
2377 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2378 oldStream?.Dispose();
2381 public void ReconnectUserStream()
2383 this.StartUserStream();
2386 private class TwitterUserstream : IDisposable
2388 public bool AllAtReplies { get; private set; }
2389 public string TrackWords { get; private set; }
2391 public bool IsStreamActive { get; private set; }
2393 public event Action<string> StatusArrived;
2394 public event Action Stopped;
2395 public event Action Started;
2397 private TwitterApi twitterApi;
2399 private Task streamTask;
2400 private CancellationTokenSource streamCts;
2402 public TwitterUserstream(TwitterApi twitterApi)
2404 this.twitterApi = twitterApi;
2407 public void Start(bool allAtReplies, string trackwords)
2409 this.AllAtReplies = allAtReplies;
2410 this.TrackWords = trackwords;
2412 var cts = new CancellationTokenSource();
2414 this.streamCts = cts;
2415 this.streamTask = Task.Run(async () =>
2419 await this.UserStreamLoop(cts.Token)
2420 .ConfigureAwait(false);
2422 catch (OperationCanceledException) { }
2428 this.streamCts?.Cancel();
2430 // streamTask の完了を待たずに IsStreamActive を false にセットする
2431 this.IsStreamActive = false;
2432 this.Stopped?.Invoke();
2435 private async Task UserStreamLoop(CancellationToken cancellationToken)
2437 TimeSpan? sleep = null;
2442 await Task.Delay(sleep.Value, cancellationToken)
2443 .ConfigureAwait(false);
2447 if (!MyCommon.IsNetworkAvailable())
2449 sleep = TimeSpan.FromSeconds(30);
2453 this.IsStreamActive = true;
2454 this.Started?.Invoke();
2458 var replies = this.AllAtReplies ? "all" : null;
2460 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2461 .ConfigureAwait(false))
2462 using (var reader = new StreamReader(stream))
2464 while (!reader.EndOfStream)
2466 var line = await reader.ReadLineAsync()
2467 .ConfigureAwait(false);
2469 cancellationToken.ThrowIfCancellationRequested();
2471 this.StatusArrived?.Invoke(line);
2475 // キャンセルされていないのにストリームが終了した場合
2476 sleep = TimeSpan.FromSeconds(30);
2478 catch (HttpRequestException) { sleep = TimeSpan.FromSeconds(30); }
2479 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2480 catch (OperationCanceledException)
2482 if (cancellationToken.IsCancellationRequested)
2485 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2486 sleep = TimeSpan.FromSeconds(30);
2488 catch (Exception ex)
2490 MyCommon.ExceptionOut(ex);
2491 sleep = TimeSpan.FromSeconds(30);
2495 this.IsStreamActive = false;
2496 this.Stopped?.Invoke();
2501 private bool disposed = false;
2503 public void Dispose()
2508 this.disposed = true;
2512 this.Started = null;
2513 this.Stopped = null;
2514 this.StatusArrived = null;
2519 #region "IDisposable Support"
2520 private bool disposedValue; // 重複する呼び出しを検出するには
2523 protected virtual void Dispose(bool disposing)
2525 if (!this.disposedValue)
2529 this.StopUserStream();
2532 this.disposedValue = true;
2535 //protected Overrides void Finalize()
2537 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2539 // MyBase.Finalize()
2542 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2543 public void Dispose()
2545 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2547 GC.SuppressFinalize(this);
2552 public class PostDeletedEventArgs : EventArgs
2554 public long StatusId { get; }
2556 public PostDeletedEventArgs(long statusId)
2558 this.StatusId = statusId;
2562 public class UserStreamEventReceivedEventArgs : EventArgs
2564 public Twitter.FormattedEvent EventData { get; }
2566 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2568 this.EventData = eventData;