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;
52 using OpenTween.Models;
53 using System.Drawing.Imaging;
54 using OpenTween.Setting;
58 public class Twitter : IDisposable
60 #region Regexp from twitter-text-js
62 // The code in this region code block incorporates works covered by
63 // the following copyright and permission notices:
65 // Copyright 2011 Twitter, Inc.
67 // Licensed under the Apache License, Version 2.0 (the "License"); you
68 // may not use this work except in compliance with the License. You
69 // may obtain a copy of the License in the LICENSE file, or at:
71 // http://www.apache.org/licenses/LICENSE-2.0
73 // Unless required by applicable law or agreed to in writing, software
74 // distributed under the License is distributed on an "AS IS" BASIS,
75 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
76 // implied. See the License for the specific language governing
77 // permissions and limitations under the License.
80 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";
81 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
82 //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";
83 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
84 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
85 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
86 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
87 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
88 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
90 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
91 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
92 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";
93 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
94 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
95 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
96 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]|$))";
97 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]|$))";
98 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
99 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
100 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
101 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
102 private const string url_valid_port_number = @"[0-9]+";
104 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
105 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
106 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
107 private const string pth = "(?:" +
109 url_valid_general_path_chars + "*" +
110 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
111 url_valid_path_ending_chars +
112 ")|(?:@" + url_valid_general_path_chars + "+/)" +
114 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
115 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
116 "(?<url>(?<protocol>https?://)?" +
117 "(?<domain>" + url_valid_domain + ")" +
118 "(?::" + url_valid_port_number + ")?" +
119 "(?<path>/" + pth + "*)?" +
126 /// Twitter API のステータスページのURL
128 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
131 /// ツイートへのパーマリンクURLを判定する正規表現
133 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
136 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
138 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
139 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
140 | favstar\.fm/t/ # Favstar (short)
141 | aclog\.koba789\.com/i/ # aclog
142 | frtrt\.net/solo_status\.php\?status= # RtRT
143 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
146 /// DM送信かどうかを判定する正規表現
148 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
150 public TwitterApi Api { get; }
151 public TwitterConfiguration Configuration { get; private set; }
152 public TwitterTextConfiguration TextConfiguration { get; private set; }
154 delegate void GetIconImageDelegate(PostClass post);
155 private readonly object LockObj = new object();
156 private ISet<long> followerId = new HashSet<long>();
157 private bool _GetFollowerResult = false;
158 private long[] noRTId = new long[0];
159 private bool _GetNoRetweetResult = false;
162 private string _uname;
164 private bool _readOwnPost;
165 private List<string> _hashList = new List<string>();
167 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
168 private long minDirectmessage = long.MaxValue;
169 private long minDirectmessageSent = long.MaxValue;
171 private long previousStatusId = -1L;
173 //private FavoriteQueue favQueue;
175 //private List<PostClass> _deletemessages = new List<PostClass>();
177 public Twitter() : this(new TwitterApi())
181 public Twitter(TwitterApi api)
184 this.Configuration = TwitterConfiguration.DefaultConfiguration();
185 this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
188 public TwitterApiAccessLevel AccessLevel
192 return MyCommon.TwitterApiInfo.AccessLevel;
196 protected void ResetApiStatus()
198 MyCommon.TwitterApiInfo.Reset();
201 public void ClearAuthInfo()
203 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
204 this.ResetApiStatus();
208 public void VerifyCredentials()
212 this.VerifyCredentialsAsync().Wait();
214 catch (AggregateException ex) when (ex.InnerException is WebApiException)
216 throw new WebApiException(ex.InnerException.Message, ex);
220 public async Task VerifyCredentialsAsync()
222 var user = await this.Api.AccountVerifyCredentials()
223 .ConfigureAwait(false);
225 this.UpdateUserStats(user);
228 public void Initialize(string token, string tokenSecret, string username, long userId)
231 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
233 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
235 this.ResetApiStatus();
236 this.Api.Initialize(token, tokenSecret, userId, username);
237 _uname = username.ToLowerInvariant();
238 if (SettingManager.Common.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 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
283 this.CheckAccountState();
285 if (Twitter.DMSendTextRegex.IsMatch(postStr))
287 await this.SendDirectMessage(postStr)
288 .ConfigureAwait(false);
292 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
293 .ConfigureAwait(false);
295 var status = await response.LoadJsonAsync()
296 .ConfigureAwait(false);
298 this.UpdateUserStats(status.User);
300 if (status.Id == this.previousStatusId)
301 throw new WebApiException("OK:Delaying?");
303 this.previousStatusId = status.Id;
306 public Task<long> UploadMedia(IMediaItem item)
307 => this.UploadMedia(item, SettingManager.Common.AlphaPNGWorkaround);
309 public async Task<long> UploadMedia(IMediaItem item, bool alphaPNGWorkaround)
311 this.CheckAccountState();
313 LazyJson<TwitterUploadMediaResult> response;
315 using (var origImage = item.CreateImage())
317 if (alphaPNGWorkaround && this.AddAlphaChannelIfNeeded(origImage.Image, out var newImage))
319 using (var newMediaItem = new MemoryImageMediaItem(newImage))
321 response = await this.Api.MediaUpload(newMediaItem)
322 .ConfigureAwait(false);
327 response = await this.Api.MediaUpload(item)
328 .ConfigureAwait(false);
332 var media = await response.LoadJsonAsync()
333 .ConfigureAwait(false);
335 return media.MediaId;
339 /// pic.twitter.com アップロード時に JPEG への変換を回避するための加工を行う
342 /// pic.twitter.com へのアップロード時に、アルファチャンネルを持たない PNG 画像が
343 /// JPEG 形式に変換され画質が低下する問題を回避します。
344 /// PNG 以外の画像や、すでにアルファチャンネルを持つ PNG 画像に対しては何もしません。
346 /// <returns>加工が行われた場合は true、そうでない場合は false</returns>
347 private bool AddAlphaChannelIfNeeded(Image origImage, out MemoryImage newImage)
351 // PNG 画像以外に対しては何もしない
352 if (origImage.RawFormat.Guid != ImageFormat.Png.Guid)
355 using (var bitmap = new Bitmap(origImage))
357 // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
358 foreach (var x in Enumerable.Range(0, bitmap.Width))
360 foreach (var y in Enumerable.Range(0, bitmap.Height))
362 if (bitmap.GetPixel(x, y).A != 255)
367 // 左上の 1px だけアルファ値を 254 にする
368 var pixel = bitmap.GetPixel(0, 0);
369 var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
370 bitmap.SetPixel(0, 0, newPixel);
372 // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
373 newImage = MemoryImage.CopyFromImage(bitmap);
379 public async Task SendDirectMessage(string postStr)
381 this.CheckAccountState();
382 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
384 var mc = Twitter.DMSendTextRegex.Match(postStr);
386 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
387 .ConfigureAwait(false);
389 var dm = await response.LoadJsonAsync()
390 .ConfigureAwait(false);
392 this.UpdateUserStats(dm.Sender);
395 public async Task PostRetweet(long id, bool read)
397 this.CheckAccountState();
400 var post = TabInformations.GetInstance()[id];
402 throw new WebApiException("Err:Target isn't found.");
404 var target = post.RetweetedId ?? id; //再RTの場合は元発言をRT
406 var response = await this.Api.StatusesRetweet(target)
407 .ConfigureAwait(false);
409 var status = await response.LoadJsonAsync()
410 .ConfigureAwait(false);
415 if (TabInformations.GetInstance().ContainsKey(status.Id))
420 if (status.RetweetedStatus == null)
421 throw new WebApiException("Invalid Json!");
424 post = CreatePostsFromStatusData(status);
431 if (_readOwnPost) post.IsRead = true;
434 TabInformations.GetInstance().AddPost(post);
437 public string Username
438 => this.Api.CurrentScreenName;
441 => this.Api.CurrentUserId;
443 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
444 public static MyCommon.ACCOUNT_STATE AccountState
448 return _accountState;
452 _accountState = value;
456 public bool RestrictFavCheck { get; set; }
458 public bool ReadOwnPost
466 _readOwnPost = value;
470 public int FollowersCount { get; private set; }
471 public int FriendsCount { get; private set; }
472 public int StatusesCount { get; private set; }
473 public string Location { get; private set; } = "";
474 public string Bio { get; private set; } = "";
476 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
477 private void UpdateUserStats(TwitterUser self)
479 this.FollowersCount = self.FollowersCount;
480 this.FriendsCount = self.FriendsCount;
481 this.StatusesCount = self.StatusesCount;
482 this.Location = self.Location;
483 this.Bio = self.Description;
487 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
489 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
491 return count >= 20 && count <= GetMaxApiResultCount(type);
495 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
497 public static bool VerifyMoreApiResultCount(int count)
499 return count >= 20 && count <= 200;
503 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
505 public static bool VerifyFirstApiResultCount(int count)
507 return count >= 20 && count <= 200;
511 /// WORKERTYPEに応じた取得可能な最大件数を取得する
513 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
515 // 参照: REST APIs - 各endpointのcountパラメータ
516 // https://dev.twitter.com/rest/public
519 case MyCommon.WORKERTYPE.Timeline:
520 case MyCommon.WORKERTYPE.Reply:
521 case MyCommon.WORKERTYPE.UserTimeline:
522 case MyCommon.WORKERTYPE.Favorites:
523 case MyCommon.WORKERTYPE.DirectMessegeRcv:
524 case MyCommon.WORKERTYPE.DirectMessegeSnt:
525 case MyCommon.WORKERTYPE.List: // 不明
528 case MyCommon.WORKERTYPE.PublicSearch:
532 throw new InvalidOperationException("Invalid type: " + type);
537 /// WORKERTYPEに応じた取得件数を取得する
539 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
541 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
542 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
547 if (SettingManager.Common.UseAdditionalCount)
551 case MyCommon.WORKERTYPE.Favorites:
552 if (SettingManager.Common.FavoritesCountApi != 0)
553 return SettingManager.Common.FavoritesCountApi;
555 case MyCommon.WORKERTYPE.List:
556 if (SettingManager.Common.ListCountApi != 0)
557 return SettingManager.Common.ListCountApi;
559 case MyCommon.WORKERTYPE.PublicSearch:
560 if (SettingManager.Common.SearchCountApi != 0)
561 return SettingManager.Common.SearchCountApi;
563 case MyCommon.WORKERTYPE.UserTimeline:
564 if (SettingManager.Common.UserTimelineCountApi != 0)
565 return SettingManager.Common.UserTimelineCountApi;
568 if (more && SettingManager.Common.MoreCountApi != 0)
570 return Math.Min(SettingManager.Common.MoreCountApi, GetMaxApiResultCount(type));
572 if (startup && SettingManager.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
574 return Math.Min(SettingManager.Common.FirstCountApi, GetMaxApiResultCount(type));
579 var count = SettingManager.Common.CountApi;
581 if (type == MyCommon.WORKERTYPE.Reply)
582 count = SettingManager.Common.CountApiReply;
584 return Math.Min(count, GetMaxApiResultCount(type));
587 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
589 this.CheckAccountState();
591 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
593 TwitterStatus[] statuses;
596 statuses = await this.Api.StatusesHomeTimeline(count, maxId: tab.OldestId)
597 .ConfigureAwait(false);
601 statuses = await this.Api.StatusesHomeTimeline(count)
602 .ConfigureAwait(false);
605 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
606 if (minimumId != null)
607 tab.OldestId = minimumId.Value;
610 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
612 this.CheckAccountState();
614 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
616 TwitterStatus[] statuses;
619 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
620 .ConfigureAwait(false);
624 statuses = await this.Api.StatusesMentionsTimeline(count)
625 .ConfigureAwait(false);
628 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
629 if (minimumId != null)
630 tab.OldestId = minimumId.Value;
633 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
635 this.CheckAccountState();
637 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
639 TwitterStatus[] statuses;
640 if (string.IsNullOrEmpty(userName))
642 var target = tab.ScreenName;
643 if (string.IsNullOrEmpty(target)) return;
645 statuses = await this.Api.StatusesUserTimeline(userName, count)
646 .ConfigureAwait(false);
652 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
653 .ConfigureAwait(false);
657 statuses = await this.Api.StatusesUserTimeline(userName, count)
658 .ConfigureAwait(false);
662 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
664 if (minimumId != null)
665 tab.OldestId = minimumId.Value;
668 public async Task<PostClass> GetStatusApi(bool read, long id)
670 this.CheckAccountState();
672 var status = await this.Api.StatusesShow(id)
673 .ConfigureAwait(false);
675 var item = CreatePostsFromStatusData(status);
678 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
683 public async Task GetStatusApi(bool read, long id, TabModel tab)
685 var post = await this.GetStatusApi(read, id)
686 .ConfigureAwait(false);
688 //非同期アイコン取得&StatusDictionaryに追加
689 if (tab != null && tab.IsInnerStorageTabType)
690 tab.AddPostQueue(post);
692 TabInformations.GetInstance().AddPost(post);
695 private PostClass CreatePostsFromStatusData(TwitterStatus status)
697 return CreatePostsFromStatusData(status, false);
700 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
702 var post = new PostClass();
703 TwitterEntities entities;
706 post.StatusId = status.Id;
707 if (status.RetweetedStatus != null)
709 var retweeted = status.RetweetedStatus;
711 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
714 post.RetweetedId = retweeted.Id;
716 post.TextFromApi = retweeted.FullText;
717 entities = retweeted.MergedEntities;
718 sourceHtml = retweeted.Source;
720 post.InReplyToStatusId = retweeted.InReplyToStatusId;
721 post.InReplyToUser = retweeted.InReplyToScreenName;
722 post.InReplyToUserId = status.InReplyToUserId;
731 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
732 post.IsFav = tc.Contains(retweeted.Id);
735 if (retweeted.Coordinates != null)
736 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
739 var user = retweeted.User;
742 post.UserId = user.Id;
743 post.ScreenName = user.ScreenName;
744 post.Nickname = user.Name.Trim();
745 post.ImageUrl = user.ProfileImageUrlHttps;
746 post.IsProtect = user.Protected;
751 post.ScreenName = "?????";
752 post.Nickname = "Unknown User";
756 if (status.User != null)
758 post.RetweetedBy = status.User.ScreenName;
759 post.RetweetedByUserId = status.User.Id;
760 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
764 post.RetweetedBy = "?????";
765 post.RetweetedByUserId = 0L;
770 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
772 post.TextFromApi = status.FullText;
773 entities = status.MergedEntities;
774 sourceHtml = status.Source;
775 post.InReplyToStatusId = status.InReplyToStatusId;
776 post.InReplyToUser = status.InReplyToScreenName;
777 post.InReplyToUserId = status.InReplyToUserId;
786 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
787 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
790 if (status.Coordinates != null)
791 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
794 var user = status.User;
797 post.UserId = user.Id;
798 post.ScreenName = user.ScreenName;
799 post.Nickname = user.Name.Trim();
800 post.ImageUrl = user.ProfileImageUrlHttps;
801 post.IsProtect = user.Protected;
802 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
807 post.ScreenName = "?????";
808 post.Nickname = "Unknown User";
812 string textFromApi = post.TextFromApi;
813 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
814 post.TextFromApi = textFromApi;
815 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
816 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
817 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
818 post.AccessibleText = this.CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus);
819 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
820 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
822 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
823 .Where(x => x != post.StatusId && x != post.RetweetedId)
824 .Distinct().ToArray();
826 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
827 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
830 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
831 if (post.Text == post.TextFromApi)
832 post.Text = post.TextFromApi;
833 if (post.AccessibleText == post.TextFromApi)
834 post.AccessibleText = post.TextFromApi;
836 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
837 post.ScreenName = string.Intern(post.ScreenName);
838 post.Nickname = string.Intern(post.Nickname);
839 post.ImageUrl = string.Intern(post.ImageUrl);
840 post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
843 var (sourceText, sourceUri) = ParseSource(sourceHtml);
844 post.Source = string.Intern(sourceText);
845 post.SourceUri = sourceUri;
847 post.IsReply = post.RetweetedId == null && post.ReplyToList.Any(x => x.Item1 == this.UserId);
848 post.IsExcludeReply = false;
856 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
864 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
866 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
868 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
870 return GetQuoteTweetStatusIds(urls);
873 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
875 foreach (var url in urls)
877 var match = Twitter.StatusUrlRegex.Match(url);
880 if (long.TryParse(match.Groups["StatusId"].Value, out var statusId))
881 yield return statusId;
886 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
888 long? minimumId = null;
890 foreach (var status in items)
892 if (minimumId == null || minimumId.Value > status.Id)
893 minimumId = status.Id;
900 if (TabInformations.GetInstance().ContainsKey(status.Id)) continue;
904 if (tab.Contains(status.Id)) continue;
909 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
910 status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
912 var post = CreatePostsFromStatusData(status);
915 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
917 if (tab != null && tab.IsInnerStorageTabType)
918 tab.AddPostQueue(post);
920 TabInformations.GetInstance().AddPost(post);
926 private long? CreatePostsFromSearchJson(TwitterSearchResult items, PublicSearchTabModel tab, bool read, bool more)
928 long? minimumId = null;
930 foreach (var status in items.Statuses)
932 if (minimumId == null || minimumId.Value > status.Id)
933 minimumId = status.Id;
935 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
939 if (tab.Contains(status.Id)) continue;
942 var post = CreatePostsFromStatusData(status);
945 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
947 tab.AddPostQueue(post);
953 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
955 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
956 long? minimumId = null;
958 foreach (var status in items)
960 if (minimumId == null || minimumId.Value > status.Id)
961 minimumId = status.Id;
966 if (favTab.Contains(status.Id)) continue;
969 var post = CreatePostsFromStatusData(status, true);
973 TabInformations.GetInstance().AddPost(post);
979 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
981 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
983 TwitterStatus[] statuses;
986 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingManager.Common.IsListsIncludeRts)
987 .ConfigureAwait(false);
991 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Common.IsListsIncludeRts)
992 .ConfigureAwait(false);
995 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
997 if (minimumId != null)
998 tab.OldestId = minimumId.Value;
1002 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1004 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1005 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1007 if (!posts.ContainsKey(startStatusId))
1008 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1010 var nextPost = posts[startStatusId];
1011 while (nextPost.InReplyToStatusId != null)
1013 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1015 nextPost = posts[nextPost.InReplyToStatusId.Value];
1021 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
1023 var targetPost = tab.TargetPost;
1024 var relPosts = new Dictionary<Int64, PostClass>();
1025 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1028 var p = TabInformations.GetInstance()[targetPost.StatusId];
1029 if (p != null && p.InReplyToStatusId != null)
1035 p = await this.GetStatusApi(read, targetPost.StatusId)
1036 .ConfigureAwait(false);
1040 relPosts.Add(targetPost.StatusId, targetPost);
1042 Exception lastException = null;
1044 // in_reply_to_status_id を使用してリプライチェインを辿る
1045 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1047 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1049 var inReplyToId = nextPost.InReplyToStatusId.Value;
1051 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1052 if (inReplyToPost == null)
1056 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1057 .ConfigureAwait(false);
1059 catch (WebApiException ex)
1066 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1068 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1071 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1072 var text = targetPost.Text;
1073 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1074 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1075 foreach (var _match in ma)
1077 if (Int64.TryParse(_match.Groups["StatusId"].Value, out var _statusId))
1079 if (relPosts.ContainsKey(_statusId))
1082 var p = TabInformations.GetInstance()[_statusId];
1087 p = await this.GetStatusApi(read, _statusId)
1088 .ConfigureAwait(false);
1090 catch (WebApiException ex)
1098 relPosts.Add(p.StatusId, p);
1102 relPosts.Values.ToList().ForEach(p =>
1104 if (p.IsMe && !read && this._readOwnPost)
1109 tab.AddPostQueue(p);
1112 if (lastException != null)
1113 throw new WebApiException(lastException.Message, lastException);
1116 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1118 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1121 long? sinceId = null;
1124 maxId = tab.OldestId - 1;
1128 sinceId = tab.SinceId;
1131 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1132 .ConfigureAwait(false);
1134 if (!TabInformations.GetInstance().ContainsTab(tab))
1137 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, more);
1139 if (minimumId != null)
1140 tab.OldestId = minimumId.Value;
1143 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1145 foreach (var message in item)
1147 var post = new PostClass();
1150 post.StatusId = message.Id;
1151 if (gType != MyCommon.WORKERTYPE.UserStream)
1153 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1155 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1159 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1166 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1170 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1172 var textFromApi = message.Text;
1174 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1175 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1176 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1177 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1178 post.AccessibleText = this.CreateAccessibleText(textFromApi, message.Entities, quoteStatus: null);
1179 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1180 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1183 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1185 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1186 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1191 if (gType == MyCommon.WORKERTYPE.UserStream)
1193 if (this.Api.CurrentUserId == message.Recipient.Id)
1195 user = message.Sender;
1201 user = message.Recipient;
1208 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1210 user = message.Sender;
1216 user = message.Recipient;
1222 post.UserId = user.Id;
1223 post.ScreenName = user.ScreenName;
1224 post.Nickname = user.Name.Trim();
1225 post.ImageUrl = user.ProfileImageUrlHttps;
1226 post.IsProtect = user.Protected;
1228 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1229 if (post.Text == post.TextFromApi)
1230 post.Text = post.TextFromApi;
1231 if (post.AccessibleText == post.TextFromApi)
1232 post.AccessibleText = post.TextFromApi;
1234 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1235 post.ScreenName = string.Intern(post.ScreenName);
1236 post.Nickname = string.Intern(post.Nickname);
1237 post.ImageUrl = string.Intern(post.ImageUrl);
1241 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1242 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1247 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1248 post.IsReply = false;
1249 post.IsExcludeReply = false;
1252 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1253 dmTab.AddPostQueue(post);
1257 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1259 this.CheckAccountState();
1260 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1262 var count = GetApiResultCount(gType, more, false);
1264 TwitterDirectMessage[] messages;
1265 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1269 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1270 .ConfigureAwait(false);
1274 messages = await this.Api.DirectMessagesRecv(count)
1275 .ConfigureAwait(false);
1282 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1283 .ConfigureAwait(false);
1287 messages = await this.Api.DirectMessagesSent(count)
1288 .ConfigureAwait(false);
1292 CreateDirectMessagesFromJson(messages, gType, read);
1295 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1297 this.CheckAccountState();
1299 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1301 TwitterStatus[] statuses;
1304 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1305 .ConfigureAwait(false);
1309 statuses = await this.Api.FavoritesList(count)
1310 .ConfigureAwait(false);
1313 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1315 if (minimumId != null)
1316 tab.OldestId = minimumId.Value;
1319 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1321 if (entities != null)
1323 if (entities.Urls != null)
1325 foreach (var m in entities.Urls)
1327 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1330 if (entities.Media != null)
1332 foreach (var m in entities.Media)
1334 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1341 private string CreateAccessibleText(string text, TwitterEntities entities, TwitterStatus quoteStatus)
1343 if (entities == null)
1346 if (entities.Urls != null)
1348 foreach (var entity in entities.Urls)
1350 if (quoteStatus != null)
1352 var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1353 if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quoteStatus.IdStr)
1355 var quoteText = this.CreateAccessibleText(quoteStatus.FullText, quoteStatus.MergedEntities, quoteStatus: null);
1356 text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quoteStatus.User.ScreenName, quoteText));
1359 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1361 text = text.Replace(entity.Url, entity.DisplayUrl);
1366 if (entities.Media != null)
1368 foreach (var entity in entities.Media)
1370 if (!string.IsNullOrEmpty(entity.AltText))
1372 text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1374 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1376 text = text.Replace(entity.Url, entity.DisplayUrl);
1387 /// <exception cref="WebApiException"/>
1388 public async Task RefreshFollowerIds()
1390 if (MyCommon._endingFlag) return;
1393 var newFollowerIds = new HashSet<long>();
1396 var ret = await this.Api.FollowersIds(cursor)
1397 .ConfigureAwait(false);
1399 if (ret.Ids == null)
1400 throw new WebApiException("ret.ids == null");
1402 newFollowerIds.UnionWith(ret.Ids);
1403 cursor = ret.NextCursor;
1404 } while (cursor != 0);
1406 this.followerId = newFollowerIds;
1407 TabInformations.GetInstance().RefreshOwl(this.followerId);
1409 this._GetFollowerResult = true;
1412 public bool GetFollowersSuccess
1416 return _GetFollowerResult;
1421 /// RT 非表示ユーザーを更新します
1423 /// <exception cref="WebApiException"/>
1424 public async Task RefreshNoRetweetIds()
1426 if (MyCommon._endingFlag) return;
1428 this.noRTId = await this.Api.NoRetweetIds()
1429 .ConfigureAwait(false);
1431 this._GetNoRetweetResult = true;
1434 public bool GetNoRetweetSuccess
1438 return _GetNoRetweetResult;
1443 /// t.co の文字列長などの設定情報を更新します
1445 /// <exception cref="WebApiException"/>
1446 public async Task RefreshConfiguration()
1448 this.Configuration = await this.Api.Configuration()
1449 .ConfigureAwait(false);
1451 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1452 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1455 public async Task GetListsApi()
1457 this.CheckAccountState();
1459 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1460 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1461 .ConfigureAwait(false);
1463 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1464 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1465 .ConfigureAwait(false);
1467 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1468 .Select(x => new ListElement(x, this))
1472 public async Task DeleteList(long listId)
1474 await this.Api.ListsDestroy(listId)
1476 .ConfigureAwait(false);
1478 var tabinfo = TabInformations.GetInstance();
1480 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1481 .Where(x => x.Id != listId)
1485 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1487 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1488 .ConfigureAwait(false);
1490 var list = await response.LoadJsonAsync()
1491 .ConfigureAwait(false);
1493 return new ListElement(list, this);
1496 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1498 this.CheckAccountState();
1500 var users = await this.Api.ListsMembers(listId, cursor)
1501 .ConfigureAwait(false);
1503 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1505 return users.NextCursor;
1508 public async Task CreateListApi(string listName, bool isPrivate, string description)
1510 this.CheckAccountState();
1512 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1513 .ConfigureAwait(false);
1515 var list = await response.LoadJsonAsync()
1516 .ConfigureAwait(false);
1518 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1521 public async Task<bool> ContainsUserAtList(long listId, string user)
1523 this.CheckAccountState();
1527 await this.Api.ListsMembersShow(listId, user)
1528 .ConfigureAwait(false);
1532 catch (TwitterApiException ex)
1533 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1539 public string CreateHtmlAnchor(string text, List<Tuple<long, string>> AtList, TwitterEntities entities, List<MediaInfo> media)
1541 if (entities != null)
1543 if (entities.Hashtags != null)
1547 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1550 if (entities.UserMentions != null)
1552 foreach (var ent in entities.UserMentions)
1554 AtList.Add(Tuple.Create(ent.Id, ent.ScreenName));
1557 if (entities.Media != null)
1561 foreach (var ent in entities.Media)
1563 if (!media.Any(x => x.Url == ent.MediaUrl))
1565 if (ent.VideoInfo != null &&
1566 ent.Type == "animated_gif" || ent.Type == "video")
1568 //var videoUrl = ent.VideoInfo.Variants
1569 // .Where(v => v.ContentType == "video/mp4")
1570 // .OrderByDescending(v => v.Bitrate)
1571 // .Select(v => v.Url).FirstOrDefault();
1572 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1575 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1582 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1583 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1585 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>");
1586 text = PreProcessUrl(text); //IDN置換
1591 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1594 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1596 internal static (string SourceText, Uri SourceUri) ParseSource(string sourceHtml)
1598 if (string.IsNullOrEmpty(sourceHtml))
1604 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1606 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1609 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1612 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1613 sourceUri = new Uri(SourceUriBase, uriStr);
1615 catch (UriFormatException)
1622 sourceText = WebUtility.HtmlDecode(sourceHtml);
1626 return (sourceText, sourceUri);
1629 public async Task<TwitterApiStatus> GetInfoApi()
1631 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1633 if (MyCommon._endingFlag) return null;
1635 var limits = await this.Api.ApplicationRateLimitStatus()
1636 .ConfigureAwait(false);
1638 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1640 return MyCommon.TwitterApiInfo;
1644 /// ブロック中のユーザーを更新します
1646 /// <exception cref="WebApiException"/>
1647 public async Task RefreshBlockIds()
1649 if (MyCommon._endingFlag) return;
1652 var newBlockIds = new HashSet<long>();
1655 var ret = await this.Api.BlocksIds(cursor)
1656 .ConfigureAwait(false);
1658 newBlockIds.UnionWith(ret.Ids);
1659 cursor = ret.NextCursor;
1660 } while (cursor != 0);
1662 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1664 TabInformations.GetInstance().BlockIds = newBlockIds;
1668 /// ミュート中のユーザーIDを更新します
1670 /// <exception cref="WebApiException"/>
1671 public async Task RefreshMuteUserIdsAsync()
1673 if (MyCommon._endingFlag) return;
1675 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1676 .ConfigureAwait(false);
1678 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1681 public string[] GetHashList()
1686 hashArray = _hashList.ToArray();
1692 public string AccessToken
1693 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1695 public string AccessTokenSecret
1696 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1698 private void CheckAccountState()
1700 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1701 throw new WebApiException("Auth error. Check your account");
1704 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1706 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1707 throw new WebApiException("Auth Err:try to re-authorization.");
1710 public int GetTextLengthRemain(string postText)
1712 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1713 if (matchDm.Success)
1714 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1716 return this.GetTextLengthRemainWeighted(postText);
1719 private int GetTextLengthRemainDM(string postText)
1724 while (pos < postText.Length)
1728 if (char.IsSurrogatePair(postText, pos))
1729 pos += 2; // サロゲートペアの場合は2文字分進める
1734 var urls = TweetExtractor.ExtractUrls(postText);
1735 foreach (var url in urls)
1737 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1738 ? this.Configuration.ShortUrlLengthHttps
1739 : this.Configuration.ShortUrlLength;
1741 textLength += shortUrlLength - url.Length;
1744 return this.Configuration.DmTextCharacterLimit - textLength;
1747 private int GetTextLengthRemainWeighted(string postText)
1749 var config = this.TextConfiguration;
1750 var totalWeight = 0;
1752 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1755 while (pos < postText.Length)
1757 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == pos);
1758 if (urlEntity != null)
1760 totalWeight += config.TransformedURLLength * config.Scale;
1762 var urlLength = urlEntity.Indices[1] - urlEntity.Indices[0];
1768 var codepoint = postText.GetCodepointAtSafe(pos);
1769 var weight = config.DefaultWeight;
1771 foreach (var weightRange in config.Ranges)
1773 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1775 weight = weightRange.Weight;
1780 totalWeight += weight;
1782 var isSurrogatePair = codepoint > 0xffff;
1783 if (isSurrogatePair)
1784 pos += 2; // サロゲートペアの場合は2文字分進める
1789 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1791 return remainWeight / config.Scale;
1795 #region "UserStream"
1796 private string trackWord_ = "";
1797 public string TrackWord
1808 private bool allAtReply_ = false;
1809 public bool AllAtReply
1817 allAtReply_ = value;
1821 public event EventHandler NewPostFromStream;
1822 public event EventHandler UserStreamStarted;
1823 public event EventHandler UserStreamStopped;
1824 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1825 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1826 private DateTime _lastUserstreamDataReceived;
1827 private TwitterUserstream userStream;
1829 public class FormattedEvent
1831 public MyCommon.EVENTTYPE Eventtype { get; set; }
1832 public DateTime CreatedAt { get; set; }
1833 public string Event { get; set; }
1834 public string Username { get; set; }
1835 public string Target { get; set; }
1836 public Int64 Id { get; set; }
1837 public bool IsMe { get; set; }
1840 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1841 public List<FormattedEvent> StoredEvent
1845 return storedEvent_;
1849 storedEvent_ = value;
1853 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1855 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1856 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1857 ["follow"] = MyCommon.EVENTTYPE.Follow,
1858 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1859 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1860 ["block"] = MyCommon.EVENTTYPE.Block,
1861 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1862 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1863 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1864 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1865 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1866 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1867 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1868 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1869 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1870 ["mute"] = MyCommon.EVENTTYPE.Mute,
1871 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1872 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1875 public bool IsUserstreamDataReceived
1879 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
1883 private void userStream_StatusArrived(string line)
1885 this._lastUserstreamDataReceived = DateTime.Now;
1886 if (string.IsNullOrEmpty(line)) return;
1888 if (line.First() != '{' || line.Last() != '}')
1890 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
1898 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
1900 var xElm = XElement.Load(jsonReader);
1901 if (xElm.Element("friends") != null)
1903 Debug.WriteLine("friends");
1906 else if (xElm.Element("delete") != null)
1908 Debug.WriteLine("delete");
1911 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
1914 long.TryParse(idElm.Value, out id);
1916 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1918 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
1921 long.TryParse(idElm.Value, out id);
1923 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1927 MyCommon.TraceOut("delete:" + line);
1930 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
1932 var sEvt = this.StoredEvent[i];
1933 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
1935 this.StoredEvent.RemoveAt(i);
1940 else if (xElm.Element("limit") != null)
1942 Debug.WriteLine(line);
1945 else if (xElm.Element("event") != null)
1947 Debug.WriteLine("event: " + xElm.Element("event").Value);
1948 CreateEventFromJson(line);
1951 else if (xElm.Element("direct_message") != null)
1953 Debug.WriteLine("direct_message");
1956 else if (xElm.Element("retweeted_status") != null)
1958 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
1959 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
1961 // 自分に関係しないリツイートの場合は無視する
1962 var selfUserId = this.UserId.ToString();
1963 if (sourceUserId == selfUserId || targetUserId == selfUserId)
1965 // 公式 RT をイベントとしても扱う
1966 var evt = CreateEventFromRetweet(xElm);
1969 this.StoredEvent.Insert(0, evt);
1971 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
1975 // 従来通り公式 RT の表示も行うため return しない
1977 else if (xElm.Element("scrub_geo") != null)
1981 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
1982 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
1986 MyCommon.TraceOut("scrub_geo:" + line);
1996 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
1997 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
1999 catch (SerializationException ex)
2001 throw TwitterApiException.CreateFromException(ex, line);
2008 var status = TwitterStatusCompat.ParseJson(line);
2009 this.CreatePostsFromJson(new[] { status.Normalize() }, MyCommon.WORKERTYPE.UserStream, null, false);
2011 catch (SerializationException ex)
2013 throw TwitterApiException.CreateFromException(ex, line);
2017 catch (WebApiException ex)
2019 MyCommon.TraceOut(ex);
2022 catch (XmlException)
2024 MyCommon.TraceOut("XmlException (StatusArrived): " + line);
2026 catch(NullReferenceException)
2028 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2031 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2035 /// UserStreamsから受信した公式RTをイベントに変換します
2037 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2039 return new FormattedEvent
2041 Eventtype = MyCommon.EVENTTYPE.Retweet,
2043 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2044 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2045 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2046 Target = string.Format("@{0}:{1}", new[]
2048 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2049 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2051 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2055 private void CreateEventFromJson(string content)
2057 TwitterStreamEvent eventData = null;
2060 eventData = TwitterStreamEvent.ParseJson(content);
2062 catch(SerializationException ex)
2064 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2068 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2071 var evt = new FormattedEvent();
2072 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2073 evt.Event = eventData.Event;
2074 evt.Username = eventData.Source.ScreenName;
2075 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2077 eventTable.TryGetValue(eventData.Event, out var eventType);
2078 evt.Eventtype = eventType;
2080 TwitterStreamEvent<TwitterStatusCompat> tweetEvent;
2081 TwitterStatus tweet;
2083 switch (eventData.Event)
2085 case "access_revoked":
2086 case "access_unrevoked":
2088 case "user_suspend":
2091 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2093 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2097 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2102 evt.Target = "@" + eventData.Target.ScreenName;
2104 case "favorited_retweet":
2105 case "retweeted_retweet":
2109 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2110 tweet = tweetEvent.TargetObject.Normalize();
2111 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2114 if (SettingManager.Common.IsRemoveSameEvent)
2116 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2120 var tabinfo = TabInformations.GetInstance();
2122 var statusId = tweet.Id;
2123 if (!tabinfo.Posts.TryGetValue(statusId, out var post))
2126 if (eventData.Event == "favorite")
2128 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2129 favTab.AddPostQueue(post);
2131 if (tweetEvent.Source.Id == this.UserId)
2135 else if (tweetEvent.Target.Id == this.UserId)
2137 post.FavoritedCount++;
2139 if (SettingManager.Common.FavEventUnread)
2140 tabinfo.SetReadAllTab(post.StatusId, read: false);
2145 if (tweetEvent.Source.Id == this.UserId)
2149 else if (tweetEvent.Target.Id == this.UserId)
2151 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2155 case "quoted_tweet":
2156 if (evt.IsMe) return;
2158 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2159 tweet = tweetEvent.TargetObject.Normalize();
2160 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2163 if (SettingManager.Common.IsRemoveSameEvent)
2165 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2169 case "list_member_added":
2170 case "list_member_removed":
2171 case "list_created":
2172 case "list_destroyed":
2173 case "list_updated":
2174 case "list_user_subscribed":
2175 case "list_user_unsubscribed":
2176 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2177 evt.Target = listEvent.TargetObject.FullName;
2180 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2184 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2193 evt.Target = "@" + eventData.Target.ScreenName;
2194 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2196 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2200 evt.Target = "@" + eventData.Target.ScreenName;
2201 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2203 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2208 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2211 this.StoredEvent.Insert(0, evt);
2213 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2216 private void userStream_Started()
2218 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2221 private void userStream_Stopped()
2223 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2226 public bool UserStreamActive
2227 => this.userStream != null && this.userStream.IsStreamActive;
2229 public void StartUserStream()
2231 var newStream = new TwitterUserstream(this.Api);
2233 newStream.StatusArrived += userStream_StatusArrived;
2234 newStream.Started += userStream_Started;
2235 newStream.Stopped += userStream_Stopped;
2237 newStream.Start(this.AllAtReply, this.TrackWord);
2239 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2240 oldStream?.Dispose();
2243 public void StopUserStream()
2245 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2246 oldStream?.Dispose();
2249 public void ReconnectUserStream()
2251 if (this.userStream != null)
2253 this.StartUserStream();
2257 private class TwitterUserstream : IDisposable
2259 public bool AllAtReplies { get; private set; }
2260 public string TrackWords { get; private set; }
2262 public bool IsStreamActive { get; private set; }
2264 public event Action<string> StatusArrived;
2265 public event Action Stopped;
2266 public event Action Started;
2268 private TwitterApi twitterApi;
2270 private Task streamTask;
2271 private CancellationTokenSource streamCts;
2273 public TwitterUserstream(TwitterApi twitterApi)
2275 this.twitterApi = twitterApi;
2278 public void Start(bool allAtReplies, string trackwords)
2280 this.AllAtReplies = allAtReplies;
2281 this.TrackWords = trackwords;
2283 var cts = new CancellationTokenSource();
2285 this.streamCts = cts;
2286 this.streamTask = Task.Run(async () =>
2290 await this.UserStreamLoop(cts.Token)
2291 .ConfigureAwait(false);
2293 catch (OperationCanceledException) { }
2299 this.streamCts?.Cancel();
2301 // streamTask の完了を待たずに IsStreamActive を false にセットする
2302 this.IsStreamActive = false;
2303 this.Stopped?.Invoke();
2306 private async Task UserStreamLoop(CancellationToken cancellationToken)
2308 TimeSpan sleep = TimeSpan.Zero;
2311 if (sleep != TimeSpan.Zero)
2313 await Task.Delay(sleep, cancellationToken)
2314 .ConfigureAwait(false);
2315 sleep = TimeSpan.Zero;
2318 if (!MyCommon.IsNetworkAvailable())
2320 sleep = TimeSpan.FromSeconds(30);
2324 this.IsStreamActive = true;
2325 this.Started?.Invoke();
2329 var replies = this.AllAtReplies ? "all" : null;
2331 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2332 .ConfigureAwait(false))
2333 using (var reader = new StreamReader(stream))
2335 while (!reader.EndOfStream)
2337 var line = await reader.ReadLineAsync()
2338 .ConfigureAwait(false);
2340 cancellationToken.ThrowIfCancellationRequested();
2342 this.StatusArrived?.Invoke(line);
2346 // キャンセルされていないのにストリームが終了した場合
2347 sleep = TimeSpan.FromSeconds(30);
2349 catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2350 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2351 catch (OperationCanceledException)
2353 if (cancellationToken.IsCancellationRequested)
2356 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2357 sleep = TimeSpan.FromSeconds(30);
2359 catch (Exception ex)
2361 MyCommon.ExceptionOut(ex);
2362 sleep = TimeSpan.FromSeconds(30);
2366 this.IsStreamActive = false;
2367 this.Stopped?.Invoke();
2372 private bool disposed = false;
2374 public void Dispose()
2379 this.disposed = true;
2383 this.Started = null;
2384 this.Stopped = null;
2385 this.StatusArrived = null;
2390 #region "IDisposable Support"
2391 private bool disposedValue; // 重複する呼び出しを検出するには
2394 protected virtual void Dispose(bool disposing)
2396 if (!this.disposedValue)
2400 this.StopUserStream();
2403 this.disposedValue = true;
2406 //protected Overrides void Finalize()
2408 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2410 // MyBase.Finalize()
2413 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2414 public void Dispose()
2416 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2418 GC.SuppressFinalize(this);
2423 public class PostDeletedEventArgs : EventArgs
2425 public long StatusId { get; }
2427 public PostDeletedEventArgs(long statusId)
2429 this.StatusId = statusId;
2433 public class UserStreamEventReceivedEventArgs : EventArgs
2435 public Twitter.FormattedEvent EventData { get; }
2437 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2439 this.EventData = eventData;