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();
205 public void VerifyCredentials()
211 res = twCon.VerifyCredentials(ref content);
215 throw new WebApiException("Err:" + ex.Message, ex);
218 this.CheckStatusCode(res, content);
222 var user = TwitterUser.ParseJson(content);
224 this.twCon.AuthenticatedUserId = user.Id;
225 this.UpdateUserStats(user);
227 catch (SerializationException ex)
229 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
230 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
234 public void Initialize(string token, string tokenSecret, string username, long userId)
237 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
239 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
241 this.ResetApiStatus();
242 this.Api.Initialize(token, tokenSecret, userId, username);
243 twCon.Initialize(token, tokenSecret, username, userId);
244 _uname = username.ToLowerInvariant();
245 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
248 public string PreProcessUrl(string orgData)
252 //var IDNConveter = new IdnMapping();
253 var href = "<a href=\"";
257 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
261 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
262 posl1 += href.Length;
263 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
264 urlStr = orgData.Substring(posl1, posl2 - posl1);
266 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
267 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
268 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
273 var replacedUrl = MyCommon.IDNEncode(urlStr);
274 if (replacedUrl == null) continue;
275 if (replacedUrl == urlStr) continue;
277 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
288 private string GetPlainText(string orgData)
290 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
293 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
295 private string SanitizeHtml(string orgdata)
297 var retdata = orgdata;
299 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
300 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
302 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
307 private string AdjustHtml(string orgData)
309 var retStr = orgData;
310 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
315 // _hashList.Add("#" + m.Groups(1).Value);
319 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
320 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
321 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
323 //半角スペースを置換(Thanks @anis774)
327 ret = EscapeSpace(ref retStr);
330 return SanitizeHtml(retStr);
333 private bool EscapeSpace(ref string html)
335 //半角スペースを置換(Thanks @anis774)
337 for (int i = 0; i < html.Length; i++)
348 if ((!isTag) && (html[i] == ' '))
350 html = html.Remove(i, 1);
351 html = html.Insert(i, " ");
358 private struct PostInfo
360 public string CreatedAt;
363 public string UserId;
364 public PostInfo(string Created, string IdStr, string txt, string uid)
371 public bool Equals(PostInfo dst)
373 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
384 static private PostInfo _prev = new PostInfo("", "", "", "");
385 private bool IsPostRestricted(TwitterStatus status)
387 var _current = new PostInfo("", "", "", "");
389 _current.CreatedAt = status.CreatedAt;
390 _current.Id = status.IdStr;
391 if (status.Text == null)
397 _current.Text = status.Text;
399 _current.UserId = status.User.IdStr;
401 if (_current.Equals(_prev))
405 _prev.CreatedAt = _current.CreatedAt;
406 _prev.Id = _current.Id;
407 _prev.Text = _current.Text;
408 _prev.UserId = _current.UserId;
413 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
415 this.CheckAccountState();
417 if (mediaIds == null &&
418 Twitter.DMSendTextRegex.IsMatch(postStr))
420 await this.SendDirectMessage(postStr)
421 .ConfigureAwait(false);
425 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
426 .ConfigureAwait(false);
428 var status = await response.LoadJsonAsync()
429 .ConfigureAwait(false);
431 this.UpdateUserStats(status.User);
433 if (IsPostRestricted(status))
435 throw new WebApiException("OK:Delaying?");
439 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
441 this.CheckAccountState();
443 if (Twitter.DMSendTextRegex.IsMatch(postStr))
445 await this.SendDirectMessage(postStr)
446 .ConfigureAwait(false);
450 if (mediaItems.Length == 0)
451 throw new WebApiException("Err:Invalid Files!");
453 var uploadTasks = from m in mediaItems
454 select this.UploadMedia(m);
456 var mediaIds = await Task.WhenAll(uploadTasks)
457 .ConfigureAwait(false);
459 await this.PostStatus(postStr, reply_to, mediaIds)
460 .ConfigureAwait(false);
463 public async Task<long> UploadMedia(IMediaItem item)
465 this.CheckAccountState();
467 var response = await this.Api.MediaUpload(item)
468 .ConfigureAwait(false);
470 var media = await response.LoadJsonAsync()
471 .ConfigureAwait(false);
473 return media.MediaId;
476 public async Task SendDirectMessage(string postStr)
478 this.CheckAccountState();
479 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
481 var mc = Twitter.DMSendTextRegex.Match(postStr);
483 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
484 .ConfigureAwait(false);
486 var dm = await response.LoadJsonAsync()
487 .ConfigureAwait(false);
489 this.UpdateUserStats(dm.Sender);
492 public async Task PostRetweet(long id, bool read)
494 this.CheckAccountState();
498 var post = TabInformations.GetInstance()[id];
501 throw new WebApiException("Err:Target isn't found.");
503 if (TabInformations.GetInstance()[id].RetweetedId != null)
505 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
508 var response = await this.Api.StatusesRetweet(target)
509 .ConfigureAwait(false);
511 var status = await response.LoadJsonAsync()
512 .ConfigureAwait(false);
515 post = CreatePostsFromStatusData(status);
517 throw new WebApiException("Invalid Json!");
522 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
526 if (post.RetweetedId == null)
527 throw new WebApiException("Invalid Json!");
533 if (_readOwnPost) post.IsRead = true;
536 TabInformations.GetInstance().AddPost(post);
539 public string Username
543 return twCon.AuthenticatedUsername;
551 return twCon.AuthenticatedUserId;
555 public string Password
559 return twCon.Password;
563 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
564 public static MyCommon.ACCOUNT_STATE AccountState
568 return _accountState;
572 _accountState = value;
576 public bool RestrictFavCheck { get; set; }
579 public void GetTweenBinary(string strVer)
584 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
585 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
587 throw new WebApiException("Err:Download failed");
590 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
592 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
594 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
595 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
597 throw new WebApiException("Err:Download failed");
599 //その他言語圏のリソース。取得失敗しても継続
602 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
604 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
607 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
611 curCul = Thread.CurrentThread.CurrentUICulture.Name;
616 curCul = Thread.CurrentThread.CurrentUICulture.Name;
618 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
620 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
622 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
624 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
625 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
627 //return "Err:Download failed";
632 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
634 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
637 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
641 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
646 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
648 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
650 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
652 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
654 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
655 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
657 //return "Err:Download failed";
662 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
663 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
665 throw new WebApiException("Err:Download failed");
668 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
669 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
671 throw new WebApiException("Err:Download failed");
676 throw new WebApiException("Err:Download failed", ex);
681 public bool ReadOwnPost
689 _readOwnPost = value;
693 public int FollowersCount { get; private set; }
694 public int FriendsCount { get; private set; }
695 public int StatusesCount { get; private set; }
696 public string Location { get; private set; } = "";
697 public string Bio { get; private set; } = "";
699 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
700 private void UpdateUserStats(TwitterUser self)
702 this.FollowersCount = self.FollowersCount;
703 this.FriendsCount = self.FriendsCount;
704 this.StatusesCount = self.StatusesCount;
705 this.Location = self.Location;
706 this.Bio = self.Description;
710 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
712 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
714 return count >= 20 && count <= GetMaxApiResultCount(type);
718 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
720 public static bool VerifyMoreApiResultCount(int count)
722 return count >= 20 && count <= 200;
726 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
728 public static bool VerifyFirstApiResultCount(int count)
730 return count >= 20 && count <= 200;
734 /// WORKERTYPEに応じた取得可能な最大件数を取得する
736 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
738 // 参照: REST APIs - 各endpointのcountパラメータ
739 // https://dev.twitter.com/rest/public
742 case MyCommon.WORKERTYPE.Timeline:
743 case MyCommon.WORKERTYPE.Reply:
744 case MyCommon.WORKERTYPE.UserTimeline:
745 case MyCommon.WORKERTYPE.Favorites:
746 case MyCommon.WORKERTYPE.DirectMessegeRcv:
747 case MyCommon.WORKERTYPE.DirectMessegeSnt:
748 case MyCommon.WORKERTYPE.List: // 不明
751 case MyCommon.WORKERTYPE.PublicSearch:
755 throw new InvalidOperationException("Invalid type: " + type);
760 /// WORKERTYPEに応じた取得件数を取得する
762 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
764 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
765 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
770 if (SettingCommon.Instance.UseAdditionalCount)
774 case MyCommon.WORKERTYPE.Favorites:
775 if (SettingCommon.Instance.FavoritesCountApi != 0)
776 return SettingCommon.Instance.FavoritesCountApi;
778 case MyCommon.WORKERTYPE.List:
779 if (SettingCommon.Instance.ListCountApi != 0)
780 return SettingCommon.Instance.ListCountApi;
782 case MyCommon.WORKERTYPE.PublicSearch:
783 if (SettingCommon.Instance.SearchCountApi != 0)
784 return SettingCommon.Instance.SearchCountApi;
786 case MyCommon.WORKERTYPE.UserTimeline:
787 if (SettingCommon.Instance.UserTimelineCountApi != 0)
788 return SettingCommon.Instance.UserTimelineCountApi;
791 if (more && SettingCommon.Instance.MoreCountApi != 0)
793 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
795 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
797 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
802 var count = SettingCommon.Instance.CountApi;
804 if (type == MyCommon.WORKERTYPE.Reply)
805 count = SettingCommon.Instance.CountApiReply;
807 return Math.Min(count, GetMaxApiResultCount(type));
810 public async Task GetTimelineApi(bool read, MyCommon.WORKERTYPE gType, bool more, bool startup)
812 this.CheckAccountState();
814 var count = GetApiResultCount(gType, more, startup);
816 TwitterStatus[] statuses;
817 if (gType == MyCommon.WORKERTYPE.Timeline)
821 statuses = await this.Api.StatusesHomeTimeline(count, maxId: this.minHomeTimeline)
822 .ConfigureAwait(false);
826 statuses = await this.Api.StatusesHomeTimeline(count)
827 .ConfigureAwait(false);
834 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: this.minMentions)
835 .ConfigureAwait(false);
839 statuses = await this.Api.StatusesMentionsTimeline(count)
840 .ConfigureAwait(false);
844 var minimumId = CreatePostsFromJson(statuses, gType, null, read);
846 if (minimumId != null)
848 if (gType == MyCommon.WORKERTYPE.Timeline)
849 this.minHomeTimeline = minimumId.Value;
851 this.minMentions = minimumId.Value;
855 public async Task GetUserTimelineApi(bool read, string userName, TabClass tab, bool more)
857 this.CheckAccountState();
859 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
861 TwitterStatus[] statuses;
862 if (string.IsNullOrEmpty(userName))
864 var target = tab.User;
865 if (string.IsNullOrEmpty(target)) return;
867 statuses = await this.Api.StatusesUserTimeline(userName, count)
868 .ConfigureAwait(false);
874 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
875 .ConfigureAwait(false);
879 statuses = await this.Api.StatusesUserTimeline(userName, count)
880 .ConfigureAwait(false);
884 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
886 if (minimumId != null)
887 tab.OldestId = minimumId.Value;
890 public async Task<PostClass> GetStatusApi(bool read, long id)
892 this.CheckAccountState();
894 var status = await this.Api.StatusesShow(id)
895 .ConfigureAwait(false);
897 var item = CreatePostsFromStatusData(status);
899 throw new WebApiException("Err:Can't create post");
902 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
907 public async Task GetStatusApi(bool read, long id, TabClass tab)
909 var post = await this.GetStatusApi(read, id)
910 .ConfigureAwait(false);
912 //非同期アイコン取得&StatusDictionaryに追加
913 if (tab != null && tab.IsInnerStorageTabType)
914 tab.AddPostToInnerStorage(post);
916 TabInformations.GetInstance().AddPost(post);
919 private PostClass CreatePostsFromStatusData(TwitterStatus status)
921 return CreatePostsFromStatusData(status, false);
924 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
926 var post = new PostClass();
927 TwitterEntities entities;
930 post.StatusId = status.Id;
931 if (status.RetweetedStatus != null)
933 var retweeted = status.RetweetedStatus;
935 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
938 post.RetweetedId = retweeted.Id;
940 post.TextFromApi = retweeted.Text;
941 entities = retweeted.MergedEntities;
942 sourceHtml = retweeted.Source;
944 post.InReplyToStatusId = retweeted.InReplyToStatusId;
945 post.InReplyToUser = retweeted.InReplyToScreenName;
946 post.InReplyToUserId = status.InReplyToUserId;
955 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
956 post.IsFav = tc.Contains(retweeted.Id);
959 if (retweeted.Coordinates != null)
960 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
963 var user = retweeted.User;
965 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
967 post.UserId = user.Id;
968 post.ScreenName = user.ScreenName;
969 post.Nickname = user.Name.Trim();
970 post.ImageUrl = user.ProfileImageUrlHttps;
971 post.IsProtect = user.Protected;
974 post.RetweetedBy = status.User.ScreenName;
975 post.RetweetedByUserId = status.User.Id;
976 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
980 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
982 post.TextFromApi = status.Text;
983 entities = status.MergedEntities;
984 sourceHtml = status.Source;
985 post.InReplyToStatusId = status.InReplyToStatusId;
986 post.InReplyToUser = status.InReplyToScreenName;
987 post.InReplyToUserId = status.InReplyToUserId;
996 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
997 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1000 if (status.Coordinates != null)
1001 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1004 var user = status.User;
1006 if (user == null || user.ScreenName == null) return null;
1008 post.UserId = user.Id;
1009 post.ScreenName = user.ScreenName;
1010 post.Nickname = user.Name.Trim();
1011 post.ImageUrl = user.ProfileImageUrlHttps;
1012 post.IsProtect = user.Protected;
1013 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1016 string textFromApi = post.TextFromApi;
1017 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1018 post.TextFromApi = textFromApi;
1019 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1020 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1021 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1023 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1024 .Where(x => x != post.StatusId && x != post.RetweetedId)
1025 .Distinct().ToArray();
1027 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1028 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1032 var source = ParseSource(sourceHtml);
1033 post.Source = source.Item1;
1034 post.SourceUri = source.Item2;
1036 post.IsReply = post.ReplyToList.Contains(_uname);
1037 post.IsExcludeReply = false;
1045 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1053 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1055 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1057 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1059 return GetQuoteTweetStatusIds(urls);
1062 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1064 foreach (var url in urls)
1066 var match = Twitter.StatusUrlRegex.Match(url);
1070 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1071 yield return statusId;
1076 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1078 long? minimumId = null;
1080 foreach (var status in items)
1082 PostClass post = null;
1083 post = CreatePostsFromStatusData(status);
1084 if (post == null) continue;
1086 if (minimumId == null || minimumId.Value > post.StatusId)
1087 minimumId = post.StatusId;
1094 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1098 if (tab.Contains(post.StatusId)) continue;
1103 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1104 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1107 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1109 //非同期アイコン取得&StatusDictionaryに追加
1110 if (tab != null && tab.IsInnerStorageTabType)
1111 tab.AddPostToInnerStorage(post);
1113 TabInformations.GetInstance().AddPost(post);
1119 private long? CreatePostsFromSearchJson(TwitterSearchResult items, TabClass tab, bool read, int count, bool more)
1121 long? minimumId = null;
1123 foreach (var result in items.Statuses)
1125 var post = CreatePostsFromStatusData(result);
1129 if (minimumId == null || minimumId.Value > post.StatusId)
1130 minimumId = post.StatusId;
1132 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1138 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1142 if (tab.Contains(post.StatusId)) continue;
1147 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1149 //非同期アイコン取得&StatusDictionaryに追加
1150 if (tab != null && tab.IsInnerStorageTabType)
1151 tab.AddPostToInnerStorage(post);
1153 TabInformations.GetInstance().AddPost(post);
1159 private void CreateFavoritePostsFromJson(TwitterStatus[] item, bool read)
1161 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1163 foreach (var status in item)
1168 if (favTab.Contains(status.Id)) continue;
1171 var post = CreatePostsFromStatusData(status, true);
1172 if (post == null) continue;
1176 TabInformations.GetInstance().AddPost(post);
1180 public async Task GetListStatus(bool read, TabClass tab, bool more, bool startup)
1182 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1184 TwitterStatus[] statuses;
1187 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1188 .ConfigureAwait(false);
1192 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1193 .ConfigureAwait(false);
1196 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1198 if (minimumId != null)
1199 tab.OldestId = minimumId.Value;
1203 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1205 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1206 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1208 if (!posts.ContainsKey(startStatusId))
1209 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1211 var nextPost = posts[startStatusId];
1212 while (nextPost.InReplyToStatusId != null)
1214 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1216 nextPost = posts[nextPost.InReplyToStatusId.Value];
1222 public async Task GetRelatedResult(bool read, TabClass tab)
1224 var relPosts = new Dictionary<Int64, PostClass>();
1225 if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1228 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1229 if (p != null && p.InReplyToStatusId != null)
1231 tab.RelationTargetPost = p;
1235 p = await this.GetStatusApi(read, tab.RelationTargetPost.StatusId)
1236 .ConfigureAwait(false);
1237 tab.RelationTargetPost = p;
1240 relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1242 Exception lastException = null;
1244 // in_reply_to_status_id を使用してリプライチェインを辿る
1245 var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1247 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1249 var inReplyToId = nextPost.InReplyToStatusId.Value;
1251 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1252 if (inReplyToPost == null)
1256 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1257 .ConfigureAwait(false);
1259 catch (WebApiException ex)
1266 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1268 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1271 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1272 var text = tab.RelationTargetPost.Text;
1273 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1274 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1275 foreach (var _match in ma)
1278 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1280 if (relPosts.ContainsKey(_statusId))
1283 var p = TabInformations.GetInstance()[_statusId];
1288 p = await this.GetStatusApi(read, _statusId)
1289 .ConfigureAwait(false);
1291 catch (WebApiException ex)
1299 relPosts.Add(p.StatusId, p);
1303 relPosts.Values.ToList().ForEach(p =>
1305 if (p.IsMe && !read && this._readOwnPost)
1310 tab.AddPostToInnerStorage(p);
1313 if (lastException != null)
1314 throw new WebApiException(lastException.Message, lastException);
1317 public async Task GetSearch(bool read, TabClass tab, bool more)
1319 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1322 long? sinceId = null;
1325 maxId = tab.OldestId - 1;
1329 sinceId = tab.SinceId;
1332 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1333 .ConfigureAwait(false);
1335 if (!TabInformations.GetInstance().ContainsTab(tab))
1338 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, count, more);
1340 if (minimumId != null)
1341 tab.OldestId = minimumId.Value;
1344 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1346 foreach (var message in item)
1348 var post = new PostClass();
1351 post.StatusId = message.Id;
1352 if (gType != MyCommon.WORKERTYPE.UserStream)
1354 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1356 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1360 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1367 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1371 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1373 var textFromApi = message.Text;
1375 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1376 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1377 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1378 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1381 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1383 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1384 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1389 if (gType == MyCommon.WORKERTYPE.UserStream)
1391 if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
1393 user = message.Sender;
1399 user = message.Recipient;
1406 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1408 user = message.Sender;
1414 user = message.Recipient;
1420 post.UserId = user.Id;
1421 post.ScreenName = user.ScreenName;
1422 post.Nickname = user.Name.Trim();
1423 post.ImageUrl = user.ProfileImageUrlHttps;
1424 post.IsProtect = user.Protected;
1428 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1429 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1434 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1435 post.IsReply = false;
1436 post.IsExcludeReply = false;
1439 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1440 dmTab.AddPostToInnerStorage(post);
1444 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1446 this.CheckAccountState();
1447 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1449 var count = GetApiResultCount(gType, more, false);
1451 TwitterDirectMessage[] messages;
1452 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1456 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1457 .ConfigureAwait(false);
1461 messages = await this.Api.DirectMessagesRecv(count)
1462 .ConfigureAwait(false);
1469 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1470 .ConfigureAwait(false);
1474 messages = await this.Api.DirectMessagesSent(count)
1475 .ConfigureAwait(false);
1479 CreateDirectMessagesFromJson(messages, gType, read);
1482 public async Task GetFavoritesApi(bool read, bool more)
1484 this.CheckAccountState();
1486 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1488 var statuses = await this.Api.FavoritesList(count)
1489 .ConfigureAwait(false);
1491 CreateFavoritePostsFromJson(statuses, read);
1494 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1496 if (entities != null)
1498 if (entities.Urls != null)
1500 foreach (var m in entities.Urls)
1502 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1505 if (entities.Media != null)
1507 foreach (var m in entities.Media)
1509 if (m.AltText != null)
1511 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1515 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1526 /// <exception cref="WebApiException"/>
1527 public async Task RefreshFollowerIds()
1529 if (MyCommon._endingFlag) return;
1532 var newFollowerIds = new HashSet<long>();
1535 var ret = await this.Api.FollowersIds(cursor)
1536 .ConfigureAwait(false);
1538 if (ret.Ids == null)
1539 throw new WebApiException("ret.ids == null");
1541 newFollowerIds.UnionWith(ret.Ids);
1542 cursor = ret.NextCursor;
1543 } while (cursor != 0);
1545 this.followerId = newFollowerIds;
1546 TabInformations.GetInstance().RefreshOwl(this.followerId);
1548 this._GetFollowerResult = true;
1551 public bool GetFollowersSuccess
1555 return _GetFollowerResult;
1560 /// RT 非表示ユーザーを更新します
1562 /// <exception cref="WebApiException"/>
1563 public async Task RefreshNoRetweetIds()
1565 if (MyCommon._endingFlag) return;
1567 this.noRTId = await this.Api.NoRetweetIds()
1568 .ConfigureAwait(false);
1570 this._GetNoRetweetResult = true;
1573 public bool GetNoRetweetSuccess
1577 return _GetNoRetweetResult;
1582 /// t.co の文字列長などの設定情報を更新します
1584 /// <exception cref="WebApiException"/>
1585 public async Task RefreshConfiguration()
1587 this.Configuration = await this.Api.Configuration()
1588 .ConfigureAwait(false);
1591 public async Task GetListsApi()
1593 this.CheckAccountState();
1595 var ownedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsOwnerships(this.Username, cursor: x))
1596 .ConfigureAwait(false);
1598 var subscribedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsSubscriptions(this.Username, cursor: x))
1599 .ConfigureAwait(false);
1601 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1602 .Select(x => new ListElement(x, this))
1606 public async Task DeleteList(long listId)
1608 await this.Api.ListsDestroy(listId)
1610 .ConfigureAwait(false);
1612 var tabinfo = TabInformations.GetInstance();
1614 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1615 .Where(x => x.Id != listId)
1619 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1621 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1622 .ConfigureAwait(false);
1624 var list = await response.LoadJsonAsync()
1625 .ConfigureAwait(false);
1627 return new ListElement(list, this);
1630 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1632 this.CheckAccountState();
1634 var users = await this.Api.ListsMembers(listId, cursor)
1635 .ConfigureAwait(false);
1637 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1639 return users.NextCursor;
1642 public async Task CreateListApi(string listName, bool isPrivate, string description)
1644 this.CheckAccountState();
1646 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1647 .ConfigureAwait(false);
1649 var list = await response.LoadJsonAsync()
1650 .ConfigureAwait(false);
1652 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1655 public async Task<bool> ContainsUserAtList(long listId, string user)
1657 this.CheckAccountState();
1661 await this.Api.ListsMembersShow(listId, user)
1662 .ConfigureAwait(false);
1666 catch (TwitterApiException ex)
1667 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1673 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1675 if (entities != null)
1677 if (entities.Hashtags != null)
1681 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1684 if (entities.UserMentions != null)
1686 foreach (var ent in entities.UserMentions)
1688 var screenName = ent.ScreenName.ToLowerInvariant();
1689 if (!AtList.Contains(screenName))
1690 AtList.Add(screenName);
1693 if (entities.Media != null)
1697 foreach (var ent in entities.Media)
1699 if (!media.Any(x => x.Url == ent.MediaUrl))
1701 if (ent.VideoInfo != null &&
1702 ent.Type == "animated_gif" || ent.Type == "video")
1704 //var videoUrl = ent.VideoInfo.Variants
1705 // .Where(v => v.ContentType == "video/mp4")
1706 // .OrderByDescending(v => v.Bitrate)
1707 // .Select(v => v.Url).FirstOrDefault();
1708 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1711 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1718 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1719 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1721 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>");
1722 text = PreProcessUrl(text); //IDN置換
1727 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1730 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1732 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1734 if (string.IsNullOrEmpty(sourceHtml))
1735 return Tuple.Create<string, Uri>("", null);
1740 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1742 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1745 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1748 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1749 sourceUri = new Uri(SourceUriBase, uriStr);
1751 catch (UriFormatException)
1758 sourceText = WebUtility.HtmlDecode(sourceHtml);
1762 return Tuple.Create(sourceText, sourceUri);
1765 public async Task<TwitterApiStatus> GetInfoApi()
1767 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1769 if (MyCommon._endingFlag) return null;
1771 var limits = await this.Api.ApplicationRateLimitStatus()
1772 .ConfigureAwait(false);
1774 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1776 return MyCommon.TwitterApiInfo;
1780 /// ブロック中のユーザーを更新します
1782 /// <exception cref="WebApiException"/>
1783 public async Task RefreshBlockIds()
1785 if (MyCommon._endingFlag) return;
1788 var newBlockIds = new HashSet<long>();
1791 var ret = await this.Api.BlocksIds(cursor)
1792 .ConfigureAwait(false);
1794 newBlockIds.UnionWith(ret.Ids);
1795 cursor = ret.NextCursor;
1796 } while (cursor != 0);
1798 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1800 TabInformations.GetInstance().BlockIds = newBlockIds;
1804 /// ミュート中のユーザーIDを更新します
1806 /// <exception cref="WebApiException"/>
1807 public async Task RefreshMuteUserIdsAsync()
1809 if (MyCommon._endingFlag) return;
1811 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1812 .ConfigureAwait(false);
1814 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1817 public string[] GetHashList()
1822 hashArray = _hashList.ToArray();
1828 public string AccessToken
1832 return twCon.AccessToken;
1836 public string AccessTokenSecret
1840 return twCon.AccessTokenSecret;
1844 private void CheckAccountState()
1846 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1847 throw new WebApiException("Auth error. Check your account");
1850 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1852 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1853 throw new WebApiException("Auth Err:try to re-authorization.");
1856 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
1857 [CallerMemberName] string callerMethodName = "")
1859 if (httpStatus == HttpStatusCode.OK)
1861 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1865 if (string.IsNullOrWhiteSpace(responseText))
1867 if (httpStatus == HttpStatusCode.Unauthorized)
1868 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1870 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
1875 var errors = TwitterError.ParseJson(responseText).Errors;
1876 if (errors == null || !errors.Any())
1878 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1881 foreach (var error in errors)
1883 if (error.Code == TwitterErrorCode.InvalidToken ||
1884 error.Code == TwitterErrorCode.SuspendedAccount)
1886 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1890 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
1892 catch (SerializationException) { }
1894 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1897 public int GetTextLengthRemain(string postText)
1899 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1900 if (matchDm.Success)
1901 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1903 return this.GetTextLengthRemainInternal(postText, isDm: false);
1906 private int GetTextLengthRemainInternal(string postText, bool isDm)
1911 while (pos < postText.Length)
1915 if (char.IsSurrogatePair(postText, pos))
1916 pos += 2; // サロゲートペアの場合は2文字分進める
1921 var urls = TweetExtractor.ExtractUrls(postText);
1922 foreach (var url in urls)
1924 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1925 ? this.Configuration.ShortUrlLengthHttps
1926 : this.Configuration.ShortUrlLength;
1928 textLength += shortUrlLength - url.Length;
1932 return this.Configuration.DmTextCharacterLimit - textLength;
1934 return 140 - textLength;
1938 #region "UserStream"
1939 private string trackWord_ = "";
1940 public string TrackWord
1951 private bool allAtReply_ = false;
1952 public bool AllAtReply
1960 allAtReply_ = value;
1964 public event EventHandler NewPostFromStream;
1965 public event EventHandler UserStreamStarted;
1966 public event EventHandler UserStreamStopped;
1967 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1968 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1969 private DateTime _lastUserstreamDataReceived;
1970 private TwitterUserstream userStream;
1972 public class FormattedEvent
1974 public MyCommon.EVENTTYPE Eventtype { get; set; }
1975 public DateTime CreatedAt { get; set; }
1976 public string Event { get; set; }
1977 public string Username { get; set; }
1978 public string Target { get; set; }
1979 public Int64 Id { get; set; }
1980 public bool IsMe { get; set; }
1983 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1984 public List<FormattedEvent> StoredEvent
1988 return storedEvent_;
1992 storedEvent_ = value;
1996 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1998 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1999 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
2000 ["follow"] = MyCommon.EVENTTYPE.Follow,
2001 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
2002 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
2003 ["block"] = MyCommon.EVENTTYPE.Block,
2004 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
2005 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
2006 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2007 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2008 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2009 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2010 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2011 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2012 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2013 ["mute"] = MyCommon.EVENTTYPE.Mute,
2014 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2015 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2018 public bool IsUserstreamDataReceived
2022 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2026 private void userStream_StatusArrived(string line)
2028 this._lastUserstreamDataReceived = DateTime.Now;
2029 if (string.IsNullOrEmpty(line)) return;
2031 if (line.First() != '{' || line.Last() != '}')
2033 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2041 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2043 var xElm = XElement.Load(jsonReader);
2044 if (xElm.Element("friends") != null)
2046 Debug.WriteLine("friends");
2049 else if (xElm.Element("delete") != null)
2051 Debug.WriteLine("delete");
2054 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2057 long.TryParse(idElm.Value, out id);
2059 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2061 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2064 long.TryParse(idElm.Value, out id);
2066 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2070 MyCommon.TraceOut("delete:" + line);
2073 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2075 var sEvt = this.StoredEvent[i];
2076 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2078 this.StoredEvent.RemoveAt(i);
2083 else if (xElm.Element("limit") != null)
2085 Debug.WriteLine(line);
2088 else if (xElm.Element("event") != null)
2090 Debug.WriteLine("event: " + xElm.Element("event").Value);
2091 CreateEventFromJson(line);
2094 else if (xElm.Element("direct_message") != null)
2096 Debug.WriteLine("direct_message");
2099 else if (xElm.Element("retweeted_status") != null)
2101 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2102 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2104 // 自分に関係しないリツイートの場合は無視する
2105 var selfUserId = this.UserId.ToString();
2106 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2108 // 公式 RT をイベントとしても扱う
2109 var evt = CreateEventFromRetweet(xElm);
2112 this.StoredEvent.Insert(0, evt);
2114 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2118 // 従来通り公式 RT の表示も行うため return しない
2120 else if (xElm.Element("scrub_geo") != null)
2124 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2125 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2129 MyCommon.TraceOut("scrub_geo:" + line);
2139 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2140 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2142 catch (SerializationException ex)
2144 throw TwitterApiException.CreateFromException(ex, line);
2151 var status = TwitterStatus.ParseJson(line);
2152 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2154 catch (SerializationException ex)
2156 throw TwitterApiException.CreateFromException(ex, line);
2160 catch (WebApiException ex)
2162 MyCommon.TraceOut(ex);
2165 catch(NullReferenceException)
2167 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2170 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2174 /// UserStreamsから受信した公式RTをイベントに変換します
2176 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2178 return new FormattedEvent
2180 Eventtype = MyCommon.EVENTTYPE.Retweet,
2182 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2183 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2184 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2185 Target = string.Format("@{0}:{1}", new[]
2187 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2188 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2190 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2194 private void CreateEventFromJson(string content)
2196 TwitterStreamEvent eventData = null;
2199 eventData = TwitterStreamEvent.ParseJson(content);
2201 catch(SerializationException ex)
2203 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2207 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2210 var evt = new FormattedEvent();
2211 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2212 evt.Event = eventData.Event;
2213 evt.Username = eventData.Source.ScreenName;
2214 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2216 MyCommon.EVENTTYPE eventType;
2217 eventTable.TryGetValue(eventData.Event, out eventType);
2218 evt.Eventtype = eventType;
2220 TwitterStreamEvent<TwitterStatus> tweetEvent;
2222 switch (eventData.Event)
2224 case "access_revoked":
2225 case "access_unrevoked":
2227 case "user_suspend":
2230 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2232 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2236 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2241 evt.Target = "@" + eventData.Target.ScreenName;
2243 case "favorited_retweet":
2244 case "retweeted_retweet":
2248 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2249 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2250 evt.Id = tweetEvent.TargetObject.Id;
2252 if (SettingCommon.Instance.IsRemoveSameEvent)
2254 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2258 var tabinfo = TabInformations.GetInstance();
2261 var statusId = tweetEvent.TargetObject.Id;
2262 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2265 if (eventData.Event == "favorite")
2267 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2268 if (!favTab.Contains(post.StatusId))
2269 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2271 if (tweetEvent.Source.Id == this.UserId)
2275 else if (tweetEvent.Target.Id == this.UserId)
2277 post.FavoritedCount++;
2279 if (SettingCommon.Instance.FavEventUnread)
2280 tabinfo.SetReadAllTab(post.StatusId, read: false);
2285 if (tweetEvent.Source.Id == this.UserId)
2289 else if (tweetEvent.Target.Id == this.UserId)
2291 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2295 case "quoted_tweet":
2296 if (evt.IsMe) return;
2298 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2299 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2300 evt.Id = tweetEvent.TargetObject.Id;
2302 if (SettingCommon.Instance.IsRemoveSameEvent)
2304 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2308 case "list_member_added":
2309 case "list_member_removed":
2310 case "list_created":
2311 case "list_destroyed":
2312 case "list_updated":
2313 case "list_user_subscribed":
2314 case "list_user_unsubscribed":
2315 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2316 evt.Target = listEvent.TargetObject.FullName;
2319 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2323 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2332 evt.Target = "@" + eventData.Target.ScreenName;
2333 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2335 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2339 evt.Target = "@" + eventData.Target.ScreenName;
2340 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2342 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2347 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2350 this.StoredEvent.Insert(0, evt);
2352 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2355 private void userStream_Started()
2357 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2360 private void userStream_Stopped()
2362 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2365 public bool UserStreamActive
2366 => this.userStream == null ? false : this.userStream.IsStreamActive;
2368 public void StartUserStream()
2370 var newStream = new TwitterUserstream(this.Api);
2372 newStream.StatusArrived += userStream_StatusArrived;
2373 newStream.Started += userStream_Started;
2374 newStream.Stopped += userStream_Stopped;
2376 newStream.Start(this.AllAtReply, this.TrackWord);
2378 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2379 oldStream?.Dispose();
2382 public void StopUserStream()
2384 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2385 oldStream?.Dispose();
2388 public void ReconnectUserStream()
2390 this.StartUserStream();
2393 private class TwitterUserstream : IDisposable
2395 public bool AllAtReplies { get; private set; }
2396 public string TrackWords { get; private set; }
2398 public bool IsStreamActive { get; private set; }
2400 public event Action<string> StatusArrived;
2401 public event Action Stopped;
2402 public event Action Started;
2404 private TwitterApi twitterApi;
2406 private Task streamTask;
2407 private CancellationTokenSource streamCts;
2409 public TwitterUserstream(TwitterApi twitterApi)
2411 this.twitterApi = twitterApi;
2414 public void Start(bool allAtReplies, string trackwords)
2416 this.AllAtReplies = allAtReplies;
2417 this.TrackWords = trackwords;
2419 var cts = new CancellationTokenSource();
2421 this.streamCts = cts;
2422 this.streamTask = Task.Run(async () =>
2426 await this.UserStreamLoop(cts.Token)
2427 .ConfigureAwait(false);
2429 catch (OperationCanceledException) { }
2435 this.streamCts?.Cancel();
2437 // streamTask の完了を待たずに IsStreamActive を false にセットする
2438 this.IsStreamActive = false;
2439 this.Stopped?.Invoke();
2442 private async Task UserStreamLoop(CancellationToken cancellationToken)
2444 TimeSpan? sleep = null;
2449 await Task.Delay(sleep.Value, cancellationToken)
2450 .ConfigureAwait(false);
2454 if (!MyCommon.IsNetworkAvailable())
2456 sleep = TimeSpan.FromSeconds(30);
2460 this.IsStreamActive = true;
2461 this.Started?.Invoke();
2465 var replies = this.AllAtReplies ? "all" : null;
2467 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2468 .ConfigureAwait(false))
2469 using (var reader = new StreamReader(stream))
2471 while (!reader.EndOfStream)
2473 var line = await reader.ReadLineAsync()
2474 .ConfigureAwait(false);
2476 cancellationToken.ThrowIfCancellationRequested();
2478 this.StatusArrived?.Invoke(line);
2482 // キャンセルされていないのにストリームが終了した場合
2483 sleep = TimeSpan.FromSeconds(30);
2485 catch (HttpRequestException) { sleep = TimeSpan.FromSeconds(30); }
2486 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2487 catch (OperationCanceledException)
2489 if (cancellationToken.IsCancellationRequested)
2492 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2493 sleep = TimeSpan.FromSeconds(30);
2495 catch (Exception ex)
2497 MyCommon.ExceptionOut(ex);
2498 sleep = TimeSpan.FromSeconds(30);
2502 this.IsStreamActive = false;
2503 this.Stopped?.Invoke();
2508 private bool disposed = false;
2510 public void Dispose()
2515 this.disposed = true;
2519 this.Started = null;
2520 this.Stopped = null;
2521 this.StatusArrived = null;
2526 #region "IDisposable Support"
2527 private bool disposedValue; // 重複する呼び出しを検出するには
2530 protected virtual void Dispose(bool disposing)
2532 if (!this.disposedValue)
2536 this.StopUserStream();
2539 this.disposedValue = true;
2542 //protected Overrides void Finalize()
2544 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2546 // MyBase.Finalize()
2549 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2550 public void Dispose()
2552 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2554 GC.SuppressFinalize(this);
2559 public class PostDeletedEventArgs : EventArgs
2561 public long StatusId { get; }
2563 public PostDeletedEventArgs(long statusId)
2565 this.StatusId = statusId;
2569 public class UserStreamEventReceivedEventArgs : EventArgs
2571 public Twitter.FormattedEvent EventData { get; }
2573 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2575 this.EventData = eventData;