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 /// attachment_url に指定可能な URL を判定する正規表現
138 public static readonly Regex AttachmentUrlRegex = new Regex(@"https?://(
139 twitter\.com/[0-9A-Za-z_]+/status/[0-9]+
140 | mobile\.twitter\.com/[0-9A-Za-z_]+/status/[0-9]+
141 | twitter\.com/messages/compose\?recipient_id=[0-9]+(&.+)?
142 )$", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
145 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
147 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
148 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
149 | favstar\.fm/t/ # Favstar (short)
150 | aclog\.koba789\.com/i/ # aclog
151 | frtrt\.net/solo_status\.php\?status= # RtRT
152 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
155 /// DM送信かどうかを判定する正規表現
157 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
159 public TwitterApi Api { get; }
160 public TwitterConfiguration Configuration { get; private set; }
161 public TwitterTextConfiguration TextConfiguration { get; private set; }
163 delegate void GetIconImageDelegate(PostClass post);
164 private readonly object LockObj = new object();
165 private ISet<long> followerId = new HashSet<long>();
166 private bool _GetFollowerResult = false;
167 private long[] noRTId = new long[0];
168 private bool _GetNoRetweetResult = false;
171 private string _uname;
173 private bool _readOwnPost;
174 private List<string> _hashList = new List<string>();
176 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
177 private long minDirectmessage = long.MaxValue;
178 private long minDirectmessageSent = long.MaxValue;
180 private long previousStatusId = -1L;
182 //private FavoriteQueue favQueue;
184 //private List<PostClass> _deletemessages = new List<PostClass>();
186 public Twitter() : this(new TwitterApi())
190 public Twitter(TwitterApi api)
193 this.Configuration = TwitterConfiguration.DefaultConfiguration();
194 this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
197 public TwitterApiAccessLevel AccessLevel
201 return MyCommon.TwitterApiInfo.AccessLevel;
205 protected void ResetApiStatus()
207 MyCommon.TwitterApiInfo.Reset();
210 public void ClearAuthInfo()
212 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
213 this.ResetApiStatus();
217 public void VerifyCredentials()
221 this.VerifyCredentialsAsync().Wait();
223 catch (AggregateException ex) when (ex.InnerException is WebApiException)
225 throw new WebApiException(ex.InnerException.Message, ex);
229 public async Task VerifyCredentialsAsync()
231 var user = await this.Api.AccountVerifyCredentials()
232 .ConfigureAwait(false);
234 this.UpdateUserStats(user);
237 public void Initialize(string token, string tokenSecret, string username, long userId)
240 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
242 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
244 this.ResetApiStatus();
245 this.Api.Initialize(token, tokenSecret, userId, username);
246 _uname = username.ToLowerInvariant();
247 if (SettingManager.Common.UserstreamStartup) this.ReconnectUserStream();
250 internal static string PreProcessUrl(string orgData)
254 //var IDNConveter = new IdnMapping();
255 var href = "<a href=\"";
259 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
263 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
264 posl1 += href.Length;
265 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
266 urlStr = orgData.Substring(posl1, posl2 - posl1);
268 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
269 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
270 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
275 var replacedUrl = MyCommon.IDNEncode(urlStr);
276 if (replacedUrl == null) continue;
277 if (replacedUrl == urlStr) continue;
279 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
290 public async Task PostStatus(PostStatusParams param)
292 this.CheckAccountState();
294 if (Twitter.DMSendTextRegex.IsMatch(param.Text))
296 await this.SendDirectMessage(param.Text)
297 .ConfigureAwait(false);
301 var response = await this.Api.StatusesUpdate(param.Text, param.InReplyToStatusId, param.MediaIds,
302 param.AutoPopulateReplyMetadata, param.ExcludeReplyUserIds, param.AttachmentUrl)
303 .ConfigureAwait(false);
305 var status = await response.LoadJsonAsync()
306 .ConfigureAwait(false);
308 this.UpdateUserStats(status.User);
310 if (status.Id == this.previousStatusId)
311 throw new WebApiException("OK:Delaying?");
313 this.previousStatusId = status.Id;
316 public Task<long> UploadMedia(IMediaItem item)
317 => this.UploadMedia(item, SettingManager.Common.AlphaPNGWorkaround);
319 public async Task<long> UploadMedia(IMediaItem item, bool alphaPNGWorkaround)
321 this.CheckAccountState();
323 LazyJson<TwitterUploadMediaResult> response;
325 using (var origImage = item.CreateImage())
327 if (alphaPNGWorkaround && this.AddAlphaChannelIfNeeded(origImage.Image, out var newImage))
329 using (var newMediaItem = new MemoryImageMediaItem(newImage))
331 response = await this.Api.MediaUpload(newMediaItem)
332 .ConfigureAwait(false);
337 response = await this.Api.MediaUpload(item)
338 .ConfigureAwait(false);
342 var media = await response.LoadJsonAsync()
343 .ConfigureAwait(false);
345 return media.MediaId;
349 /// pic.twitter.com アップロード時に JPEG への変換を回避するための加工を行う
352 /// pic.twitter.com へのアップロード時に、アルファチャンネルを持たない PNG 画像が
353 /// JPEG 形式に変換され画質が低下する問題を回避します。
354 /// PNG 以外の画像や、すでにアルファチャンネルを持つ PNG 画像に対しては何もしません。
356 /// <returns>加工が行われた場合は true、そうでない場合は false</returns>
357 private bool AddAlphaChannelIfNeeded(Image origImage, out MemoryImage newImage)
361 // PNG 画像以外に対しては何もしない
362 if (origImage.RawFormat.Guid != ImageFormat.Png.Guid)
365 using (var bitmap = new Bitmap(origImage))
367 // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
368 foreach (var x in Enumerable.Range(0, bitmap.Width))
370 foreach (var y in Enumerable.Range(0, bitmap.Height))
372 if (bitmap.GetPixel(x, y).A != 255)
377 // 左上の 1px だけアルファ値を 254 にする
378 var pixel = bitmap.GetPixel(0, 0);
379 var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
380 bitmap.SetPixel(0, 0, newPixel);
382 // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
383 newImage = MemoryImage.CopyFromImage(bitmap);
389 public async Task SendDirectMessage(string postStr)
391 this.CheckAccountState();
392 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
394 var mc = Twitter.DMSendTextRegex.Match(postStr);
396 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
397 .ConfigureAwait(false);
399 var dm = await response.LoadJsonAsync()
400 .ConfigureAwait(false);
402 this.UpdateUserStats(dm.Sender);
405 public async Task PostRetweet(long id, bool read)
407 this.CheckAccountState();
410 var post = TabInformations.GetInstance()[id];
412 throw new WebApiException("Err:Target isn't found.");
414 var target = post.RetweetedId ?? id; //再RTの場合は元発言をRT
416 var response = await this.Api.StatusesRetweet(target)
417 .ConfigureAwait(false);
419 var status = await response.LoadJsonAsync()
420 .ConfigureAwait(false);
425 if (TabInformations.GetInstance().ContainsKey(status.Id))
430 if (status.RetweetedStatus == null)
431 throw new WebApiException("Invalid Json!");
434 post = CreatePostsFromStatusData(status);
441 if (_readOwnPost) post.IsRead = true;
444 TabInformations.GetInstance().AddPost(post);
447 public string Username
448 => this.Api.CurrentScreenName;
451 => this.Api.CurrentUserId;
453 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
454 public static MyCommon.ACCOUNT_STATE AccountState
458 return _accountState;
462 _accountState = value;
466 public bool RestrictFavCheck { get; set; }
468 public bool ReadOwnPost
476 _readOwnPost = value;
480 public int FollowersCount { get; private set; }
481 public int FriendsCount { get; private set; }
482 public int StatusesCount { get; private set; }
483 public string Location { get; private set; } = "";
484 public string Bio { get; private set; } = "";
486 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
487 private void UpdateUserStats(TwitterUser self)
489 this.FollowersCount = self.FollowersCount;
490 this.FriendsCount = self.FriendsCount;
491 this.StatusesCount = self.StatusesCount;
492 this.Location = self.Location;
493 this.Bio = self.Description;
497 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
499 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
501 return count >= 20 && count <= GetMaxApiResultCount(type);
505 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
507 public static bool VerifyMoreApiResultCount(int count)
509 return count >= 20 && count <= 200;
513 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
515 public static bool VerifyFirstApiResultCount(int count)
517 return count >= 20 && count <= 200;
521 /// WORKERTYPEに応じた取得可能な最大件数を取得する
523 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
525 // 参照: REST APIs - 各endpointのcountパラメータ
526 // https://dev.twitter.com/rest/public
529 case MyCommon.WORKERTYPE.Timeline:
530 case MyCommon.WORKERTYPE.Reply:
531 case MyCommon.WORKERTYPE.UserTimeline:
532 case MyCommon.WORKERTYPE.Favorites:
533 case MyCommon.WORKERTYPE.DirectMessegeRcv:
534 case MyCommon.WORKERTYPE.DirectMessegeSnt:
535 case MyCommon.WORKERTYPE.List: // 不明
538 case MyCommon.WORKERTYPE.PublicSearch:
542 throw new InvalidOperationException("Invalid type: " + type);
547 /// WORKERTYPEに応じた取得件数を取得する
549 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
551 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
552 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
557 if (SettingManager.Common.UseAdditionalCount)
561 case MyCommon.WORKERTYPE.Favorites:
562 if (SettingManager.Common.FavoritesCountApi != 0)
563 return SettingManager.Common.FavoritesCountApi;
565 case MyCommon.WORKERTYPE.List:
566 if (SettingManager.Common.ListCountApi != 0)
567 return SettingManager.Common.ListCountApi;
569 case MyCommon.WORKERTYPE.PublicSearch:
570 if (SettingManager.Common.SearchCountApi != 0)
571 return SettingManager.Common.SearchCountApi;
573 case MyCommon.WORKERTYPE.UserTimeline:
574 if (SettingManager.Common.UserTimelineCountApi != 0)
575 return SettingManager.Common.UserTimelineCountApi;
578 if (more && SettingManager.Common.MoreCountApi != 0)
580 return Math.Min(SettingManager.Common.MoreCountApi, GetMaxApiResultCount(type));
582 if (startup && SettingManager.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
584 return Math.Min(SettingManager.Common.FirstCountApi, GetMaxApiResultCount(type));
589 var count = SettingManager.Common.CountApi;
591 if (type == MyCommon.WORKERTYPE.Reply)
592 count = SettingManager.Common.CountApiReply;
594 return Math.Min(count, GetMaxApiResultCount(type));
597 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
599 this.CheckAccountState();
601 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
603 TwitterStatus[] statuses;
606 statuses = await this.Api.StatusesHomeTimeline(count, maxId: tab.OldestId)
607 .ConfigureAwait(false);
611 statuses = await this.Api.StatusesHomeTimeline(count)
612 .ConfigureAwait(false);
615 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
616 if (minimumId != null)
617 tab.OldestId = minimumId.Value;
620 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
622 this.CheckAccountState();
624 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
626 TwitterStatus[] statuses;
629 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
630 .ConfigureAwait(false);
634 statuses = await this.Api.StatusesMentionsTimeline(count)
635 .ConfigureAwait(false);
638 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
639 if (minimumId != null)
640 tab.OldestId = minimumId.Value;
643 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
645 this.CheckAccountState();
647 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
649 TwitterStatus[] statuses;
650 if (string.IsNullOrEmpty(userName))
652 var target = tab.ScreenName;
653 if (string.IsNullOrEmpty(target)) return;
655 statuses = await this.Api.StatusesUserTimeline(userName, count)
656 .ConfigureAwait(false);
662 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
663 .ConfigureAwait(false);
667 statuses = await this.Api.StatusesUserTimeline(userName, count)
668 .ConfigureAwait(false);
672 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
674 if (minimumId != null)
675 tab.OldestId = minimumId.Value;
678 public async Task<PostClass> GetStatusApi(bool read, long id)
680 this.CheckAccountState();
682 var status = await this.Api.StatusesShow(id)
683 .ConfigureAwait(false);
685 var item = CreatePostsFromStatusData(status);
688 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
693 public async Task GetStatusApi(bool read, long id, TabModel tab)
695 var post = await this.GetStatusApi(read, id)
696 .ConfigureAwait(false);
698 //非同期アイコン取得&StatusDictionaryに追加
699 if (tab != null && tab.IsInnerStorageTabType)
700 tab.AddPostQueue(post);
702 TabInformations.GetInstance().AddPost(post);
705 private PostClass CreatePostsFromStatusData(TwitterStatus status)
707 return CreatePostsFromStatusData(status, false);
710 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
712 var post = new PostClass();
713 TwitterEntities entities;
716 post.StatusId = status.Id;
717 if (status.RetweetedStatus != null)
719 var retweeted = status.RetweetedStatus;
721 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
724 post.RetweetedId = retweeted.Id;
726 post.TextFromApi = retweeted.FullText;
727 entities = retweeted.MergedEntities;
728 sourceHtml = retweeted.Source;
730 post.InReplyToStatusId = retweeted.InReplyToStatusId;
731 post.InReplyToUser = retweeted.InReplyToScreenName;
732 post.InReplyToUserId = status.InReplyToUserId;
741 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
742 post.IsFav = tc.Contains(retweeted.Id);
745 if (retweeted.Coordinates != null)
746 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
749 var user = retweeted.User;
752 post.UserId = user.Id;
753 post.ScreenName = user.ScreenName;
754 post.Nickname = user.Name.Trim();
755 post.ImageUrl = user.ProfileImageUrlHttps;
756 post.IsProtect = user.Protected;
761 post.ScreenName = "?????";
762 post.Nickname = "Unknown User";
766 if (status.User != null)
768 post.RetweetedBy = status.User.ScreenName;
769 post.RetweetedByUserId = status.User.Id;
770 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
774 post.RetweetedBy = "?????";
775 post.RetweetedByUserId = 0L;
780 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
782 post.TextFromApi = status.FullText;
783 entities = status.MergedEntities;
784 sourceHtml = status.Source;
785 post.InReplyToStatusId = status.InReplyToStatusId;
786 post.InReplyToUser = status.InReplyToScreenName;
787 post.InReplyToUserId = status.InReplyToUserId;
796 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
797 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
800 if (status.Coordinates != null)
801 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
804 var user = status.User;
807 post.UserId = user.Id;
808 post.ScreenName = user.ScreenName;
809 post.Nickname = user.Name.Trim();
810 post.ImageUrl = user.ProfileImageUrlHttps;
811 post.IsProtect = user.Protected;
812 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
817 post.ScreenName = "?????";
818 post.Nickname = "Unknown User";
822 string textFromApi = post.TextFromApi;
823 var quotedStatusLink = (status.RetweetedStatus ?? status).QuotedStatusPermalink;
825 post.Text = CreateHtmlAnchor(textFromApi, entities, quotedStatusLink);
826 post.TextFromApi = textFromApi;
827 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities, quotedStatusLink);
828 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
829 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
830 post.AccessibleText = CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus, quotedStatusLink);
831 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
832 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
834 this.ExtractEntities(entities, post.ReplyToList, post.Media);
836 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities, quotedStatusLink)
837 .Where(x => x != post.StatusId && x != post.RetweetedId)
838 .Distinct().ToArray();
840 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
841 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
844 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
845 if (post.Text == post.TextFromApi)
846 post.Text = post.TextFromApi;
847 if (post.AccessibleText == post.TextFromApi)
848 post.AccessibleText = post.TextFromApi;
850 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
851 post.ScreenName = string.Intern(post.ScreenName);
852 post.Nickname = string.Intern(post.Nickname);
853 post.ImageUrl = string.Intern(post.ImageUrl);
854 post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
857 var (sourceText, sourceUri) = ParseSource(sourceHtml);
858 post.Source = string.Intern(sourceText);
859 post.SourceUri = sourceUri;
861 post.IsReply = post.RetweetedId == null && post.ReplyToList.Any(x => x.Item1 == this.UserId);
862 post.IsExcludeReply = false;
870 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
878 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
880 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities, TwitterQuotedStatusPermalink quotedStatusLink)
882 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
884 if (quotedStatusLink != null)
885 urls = urls.Concat(new[] { quotedStatusLink.Expanded });
887 return GetQuoteTweetStatusIds(urls);
890 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
892 foreach (var url in urls)
894 var match = Twitter.StatusUrlRegex.Match(url);
897 if (long.TryParse(match.Groups["StatusId"].Value, out var statusId))
898 yield return statusId;
903 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
905 long? minimumId = null;
907 foreach (var status in items)
909 if (minimumId == null || minimumId.Value > status.Id)
910 minimumId = status.Id;
917 if (TabInformations.GetInstance().ContainsKey(status.Id)) continue;
921 if (tab.Contains(status.Id)) continue;
926 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
927 status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
929 var post = CreatePostsFromStatusData(status);
932 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
934 if (tab != null && tab.IsInnerStorageTabType)
935 tab.AddPostQueue(post);
937 TabInformations.GetInstance().AddPost(post);
943 private long? CreatePostsFromSearchJson(TwitterSearchResult items, PublicSearchTabModel tab, bool read, bool more)
945 long? minimumId = null;
947 foreach (var status in items.Statuses)
949 if (minimumId == null || minimumId.Value > status.Id)
950 minimumId = status.Id;
952 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
956 if (tab.Contains(status.Id)) continue;
959 var post = CreatePostsFromStatusData(status);
962 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
964 tab.AddPostQueue(post);
970 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
972 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
973 long? minimumId = null;
975 foreach (var status in items)
977 if (minimumId == null || minimumId.Value > status.Id)
978 minimumId = status.Id;
983 if (favTab.Contains(status.Id)) continue;
986 var post = CreatePostsFromStatusData(status, true);
990 TabInformations.GetInstance().AddPost(post);
996 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
998 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1000 TwitterStatus[] statuses;
1003 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingManager.Common.IsListsIncludeRts)
1004 .ConfigureAwait(false);
1008 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Common.IsListsIncludeRts)
1009 .ConfigureAwait(false);
1012 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1014 if (minimumId != null)
1015 tab.OldestId = minimumId.Value;
1019 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1021 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1022 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1024 if (!posts.ContainsKey(startStatusId))
1025 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1027 var nextPost = posts[startStatusId];
1028 while (nextPost.InReplyToStatusId != null)
1030 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1032 nextPost = posts[nextPost.InReplyToStatusId.Value];
1038 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
1040 var targetPost = tab.TargetPost;
1041 var relPosts = new Dictionary<Int64, PostClass>();
1042 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1045 var p = TabInformations.GetInstance()[targetPost.StatusId];
1046 if (p != null && p.InReplyToStatusId != null)
1052 p = await this.GetStatusApi(read, targetPost.StatusId)
1053 .ConfigureAwait(false);
1057 relPosts.Add(targetPost.StatusId, targetPost);
1059 Exception lastException = null;
1061 // in_reply_to_status_id を使用してリプライチェインを辿る
1062 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1064 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1066 var inReplyToId = nextPost.InReplyToStatusId.Value;
1068 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1069 if (inReplyToPost == null)
1073 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1074 .ConfigureAwait(false);
1076 catch (WebApiException ex)
1083 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1085 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1088 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1089 var text = targetPost.Text;
1090 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1091 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1092 foreach (var _match in ma)
1094 if (Int64.TryParse(_match.Groups["StatusId"].Value, out var _statusId))
1096 if (relPosts.ContainsKey(_statusId))
1099 var p = TabInformations.GetInstance()[_statusId];
1104 p = await this.GetStatusApi(read, _statusId)
1105 .ConfigureAwait(false);
1107 catch (WebApiException ex)
1115 relPosts.Add(p.StatusId, p);
1119 relPosts.Values.ToList().ForEach(p =>
1121 if (p.IsMe && !read && this._readOwnPost)
1126 tab.AddPostQueue(p);
1129 if (lastException != null)
1130 throw new WebApiException(lastException.Message, lastException);
1133 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1135 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1138 long? sinceId = null;
1141 maxId = tab.OldestId - 1;
1145 sinceId = tab.SinceId;
1148 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1149 .ConfigureAwait(false);
1151 if (!TabInformations.GetInstance().ContainsTab(tab))
1154 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, more);
1156 if (minimumId != null)
1157 tab.OldestId = minimumId.Value;
1160 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1162 foreach (var message in item)
1164 var post = new PostClass();
1167 post.StatusId = message.Id;
1168 if (gType != MyCommon.WORKERTYPE.UserStream)
1170 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1172 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1176 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1183 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1187 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1189 var textFromApi = message.Text;
1191 post.Text = CreateHtmlAnchor(textFromApi, message.Entities, quotedStatusLink: null);
1192 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities, quotedStatusLink: null);
1193 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1194 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1195 post.AccessibleText = CreateAccessibleText(textFromApi, message.Entities, quotedStatus: null, quotedStatusLink: null);
1196 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1197 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1200 this.ExtractEntities(message.Entities, post.ReplyToList, post.Media);
1202 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities, quotedStatusLink: null)
1203 .Distinct().ToArray();
1205 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1206 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1211 if (gType == MyCommon.WORKERTYPE.UserStream)
1213 if (this.Api.CurrentUserId == message.Recipient.Id)
1215 user = message.Sender;
1221 user = message.Recipient;
1228 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1230 user = message.Sender;
1236 user = message.Recipient;
1242 post.UserId = user.Id;
1243 post.ScreenName = user.ScreenName;
1244 post.Nickname = user.Name.Trim();
1245 post.ImageUrl = user.ProfileImageUrlHttps;
1246 post.IsProtect = user.Protected;
1248 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1249 if (post.Text == post.TextFromApi)
1250 post.Text = post.TextFromApi;
1251 if (post.AccessibleText == post.TextFromApi)
1252 post.AccessibleText = post.TextFromApi;
1254 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1255 post.ScreenName = string.Intern(post.ScreenName);
1256 post.Nickname = string.Intern(post.Nickname);
1257 post.ImageUrl = string.Intern(post.ImageUrl);
1261 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1262 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1267 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1268 post.IsReply = false;
1269 post.IsExcludeReply = false;
1272 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1273 dmTab.AddPostQueue(post);
1277 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1279 this.CheckAccountState();
1280 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1282 var count = GetApiResultCount(gType, more, false);
1284 TwitterDirectMessage[] messages;
1285 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1289 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1290 .ConfigureAwait(false);
1294 messages = await this.Api.DirectMessagesRecv(count)
1295 .ConfigureAwait(false);
1302 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1303 .ConfigureAwait(false);
1307 messages = await this.Api.DirectMessagesSent(count)
1308 .ConfigureAwait(false);
1312 CreateDirectMessagesFromJson(messages, gType, read);
1315 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1317 this.CheckAccountState();
1319 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1321 TwitterStatus[] statuses;
1324 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1325 .ConfigureAwait(false);
1329 statuses = await this.Api.FavoritesList(count)
1330 .ConfigureAwait(false);
1333 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1335 if (minimumId != null)
1336 tab.OldestId = minimumId.Value;
1339 private string ReplaceTextFromApi(string text, TwitterEntities entities, TwitterQuotedStatusPermalink quotedStatusLink)
1341 if (entities != null)
1343 if (entities.Urls != null)
1345 foreach (var m in entities.Urls)
1347 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1350 if (entities.Media != null)
1352 foreach (var m in entities.Media)
1354 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1359 if (quotedStatusLink != null)
1360 text += " " + quotedStatusLink.Display;
1365 internal static string CreateAccessibleText(string text, TwitterEntities entities, TwitterStatus quotedStatus, TwitterQuotedStatusPermalink quotedStatusLink)
1367 if (entities == null)
1370 if (entities.Urls != null)
1372 foreach (var entity in entities.Urls)
1374 if (quotedStatus != null)
1376 var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1377 if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quotedStatus.IdStr)
1379 var quotedText = CreateAccessibleText(quotedStatus.FullText, quotedStatus.MergedEntities, quotedStatus: null, quotedStatusLink: null);
1380 text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quotedStatus.User.ScreenName, quotedText));
1385 if (!string.IsNullOrEmpty(entity.DisplayUrl))
1386 text = text.Replace(entity.Url, entity.DisplayUrl);
1390 if (entities.Media != null)
1392 foreach (var entity in entities.Media)
1394 if (!string.IsNullOrEmpty(entity.AltText))
1396 text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1398 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1400 text = text.Replace(entity.Url, entity.DisplayUrl);
1405 if (quotedStatusLink != null)
1407 var quoteText = CreateAccessibleText(quotedStatus.FullText, quotedStatus.MergedEntities, quotedStatus: null, quotedStatusLink: null);
1408 text += " " + string.Format(Properties.Resources.QuoteStatus_AccessibleText, quotedStatus.User.ScreenName, quoteText);
1417 /// <exception cref="WebApiException"/>
1418 public async Task RefreshFollowerIds()
1420 if (MyCommon._endingFlag) return;
1423 var newFollowerIds = new HashSet<long>();
1426 var ret = await this.Api.FollowersIds(cursor)
1427 .ConfigureAwait(false);
1429 if (ret.Ids == null)
1430 throw new WebApiException("ret.ids == null");
1432 newFollowerIds.UnionWith(ret.Ids);
1433 cursor = ret.NextCursor;
1434 } while (cursor != 0);
1436 this.followerId = newFollowerIds;
1437 TabInformations.GetInstance().RefreshOwl(this.followerId);
1439 this._GetFollowerResult = true;
1442 public bool GetFollowersSuccess
1446 return _GetFollowerResult;
1451 /// RT 非表示ユーザーを更新します
1453 /// <exception cref="WebApiException"/>
1454 public async Task RefreshNoRetweetIds()
1456 if (MyCommon._endingFlag) return;
1458 this.noRTId = await this.Api.NoRetweetIds()
1459 .ConfigureAwait(false);
1461 this._GetNoRetweetResult = true;
1464 public bool GetNoRetweetSuccess
1468 return _GetNoRetweetResult;
1473 /// t.co の文字列長などの設定情報を更新します
1475 /// <exception cref="WebApiException"/>
1476 public async Task RefreshConfiguration()
1478 this.Configuration = await this.Api.Configuration()
1479 .ConfigureAwait(false);
1481 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1482 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1485 public async Task GetListsApi()
1487 this.CheckAccountState();
1489 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1490 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1491 .ConfigureAwait(false);
1493 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1494 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1495 .ConfigureAwait(false);
1497 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1498 .Select(x => new ListElement(x, this))
1502 public async Task DeleteList(long listId)
1504 await this.Api.ListsDestroy(listId)
1506 .ConfigureAwait(false);
1508 var tabinfo = TabInformations.GetInstance();
1510 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1511 .Where(x => x.Id != listId)
1515 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1517 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1518 .ConfigureAwait(false);
1520 var list = await response.LoadJsonAsync()
1521 .ConfigureAwait(false);
1523 return new ListElement(list, this);
1526 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1528 this.CheckAccountState();
1530 var users = await this.Api.ListsMembers(listId, cursor)
1531 .ConfigureAwait(false);
1533 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1535 return users.NextCursor;
1538 public async Task CreateListApi(string listName, bool isPrivate, string description)
1540 this.CheckAccountState();
1542 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1543 .ConfigureAwait(false);
1545 var list = await response.LoadJsonAsync()
1546 .ConfigureAwait(false);
1548 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1551 public async Task<bool> ContainsUserAtList(long listId, string user)
1553 this.CheckAccountState();
1557 await this.Api.ListsMembersShow(listId, user)
1558 .ConfigureAwait(false);
1562 catch (TwitterApiException ex)
1563 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1569 private void ExtractEntities(TwitterEntities entities, List<Tuple<long, string>> AtList, List<MediaInfo> media)
1571 if (entities != null)
1573 if (entities.Hashtags != null)
1577 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1580 if (entities.UserMentions != null)
1582 foreach (var ent in entities.UserMentions)
1584 AtList.Add(Tuple.Create(ent.Id, ent.ScreenName));
1587 if (entities.Media != null)
1591 foreach (var ent in entities.Media)
1593 if (!media.Any(x => x.Url == ent.MediaUrlHttps))
1595 if (ent.VideoInfo != null &&
1596 ent.Type == "animated_gif" || ent.Type == "video")
1598 //var videoUrl = ent.VideoInfo.Variants
1599 // .Where(v => v.ContentType == "video/mp4")
1600 // .OrderByDescending(v => v.Bitrate)
1601 // .Select(v => v.Url).FirstOrDefault();
1602 media.Add(new MediaInfo(ent.MediaUrlHttps, ent.AltText, ent.ExpandedUrl));
1605 media.Add(new MediaInfo(ent.MediaUrlHttps, ent.AltText, videoUrl: null));
1613 internal static string CreateHtmlAnchor(string text, TwitterEntities entities, TwitterQuotedStatusPermalink quotedStatusLink)
1615 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1616 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1618 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>");
1619 text = PreProcessUrl(text); //IDN置換
1621 if (quotedStatusLink != null)
1623 text += string.Format(" <a href=\"{0}\" title=\"{0}\">{1}</a>",
1624 WebUtility.HtmlEncode(quotedStatusLink.Url),
1625 WebUtility.HtmlEncode(quotedStatusLink.Display));
1631 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1634 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1636 internal static (string SourceText, Uri SourceUri) ParseSource(string sourceHtml)
1638 if (string.IsNullOrEmpty(sourceHtml))
1644 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1646 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1649 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1652 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1653 sourceUri = new Uri(SourceUriBase, uriStr);
1655 catch (UriFormatException)
1662 sourceText = WebUtility.HtmlDecode(sourceHtml);
1666 return (sourceText, sourceUri);
1669 public async Task<TwitterApiStatus> GetInfoApi()
1671 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1673 if (MyCommon._endingFlag) return null;
1675 var limits = await this.Api.ApplicationRateLimitStatus()
1676 .ConfigureAwait(false);
1678 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1680 return MyCommon.TwitterApiInfo;
1684 /// ブロック中のユーザーを更新します
1686 /// <exception cref="WebApiException"/>
1687 public async Task RefreshBlockIds()
1689 if (MyCommon._endingFlag) return;
1692 var newBlockIds = new HashSet<long>();
1695 var ret = await this.Api.BlocksIds(cursor)
1696 .ConfigureAwait(false);
1698 newBlockIds.UnionWith(ret.Ids);
1699 cursor = ret.NextCursor;
1700 } while (cursor != 0);
1702 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1704 TabInformations.GetInstance().BlockIds = newBlockIds;
1708 /// ミュート中のユーザーIDを更新します
1710 /// <exception cref="WebApiException"/>
1711 public async Task RefreshMuteUserIdsAsync()
1713 if (MyCommon._endingFlag) return;
1715 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1716 .ConfigureAwait(false);
1718 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1721 public string[] GetHashList()
1726 hashArray = _hashList.ToArray();
1732 public string AccessToken
1733 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1735 public string AccessTokenSecret
1736 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1738 private void CheckAccountState()
1740 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1741 throw new WebApiException("Auth error. Check your account");
1744 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1746 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1747 throw new WebApiException("Auth Err:try to re-authorization.");
1750 public int GetTextLengthRemain(string postText)
1752 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1753 if (matchDm.Success)
1754 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1756 return this.GetTextLengthRemainWeighted(postText);
1759 private int GetTextLengthRemainDM(string postText)
1764 while (pos < postText.Length)
1768 if (char.IsSurrogatePair(postText, pos))
1769 pos += 2; // サロゲートペアの場合は2文字分進める
1774 var urls = TweetExtractor.ExtractUrls(postText);
1775 foreach (var url in urls)
1777 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1778 ? this.Configuration.ShortUrlLengthHttps
1779 : this.Configuration.ShortUrlLength;
1781 textLength += shortUrlLength - url.Length;
1784 return this.Configuration.DmTextCharacterLimit - textLength;
1787 private int GetTextLengthRemainWeighted(string postText)
1789 var config = this.TextConfiguration;
1790 var totalWeight = 0;
1792 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1795 while (pos < postText.Length)
1797 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == pos);
1798 if (urlEntity != null)
1800 totalWeight += config.TransformedURLLength * config.Scale;
1802 var urlLength = urlEntity.Indices[1] - urlEntity.Indices[0];
1808 var codepoint = postText.GetCodepointAtSafe(pos);
1809 var weight = config.DefaultWeight;
1811 foreach (var weightRange in config.Ranges)
1813 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1815 weight = weightRange.Weight;
1820 totalWeight += weight;
1822 var isSurrogatePair = codepoint > 0xffff;
1823 if (isSurrogatePair)
1824 pos += 2; // サロゲートペアの場合は2文字分進める
1829 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1831 return remainWeight / config.Scale;
1835 #region "UserStream"
1836 private string trackWord_ = "";
1837 public string TrackWord
1848 private bool allAtReply_ = false;
1849 public bool AllAtReply
1857 allAtReply_ = value;
1861 public event EventHandler NewPostFromStream;
1862 public event EventHandler UserStreamStarted;
1863 public event EventHandler UserStreamStopped;
1864 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1865 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1866 private DateTimeUtc _lastUserstreamDataReceived;
1867 private TwitterUserstream userStream;
1869 public class FormattedEvent
1871 public MyCommon.EVENTTYPE Eventtype { get; set; }
1872 public DateTimeUtc CreatedAt { get; set; }
1873 public string Event { get; set; }
1874 public string Username { get; set; }
1875 public string Target { get; set; }
1876 public Int64 Id { get; set; }
1877 public bool IsMe { get; set; }
1880 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1881 public List<FormattedEvent> StoredEvent
1885 return storedEvent_;
1889 storedEvent_ = value;
1893 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1895 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1896 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1897 ["follow"] = MyCommon.EVENTTYPE.Follow,
1898 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1899 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1900 ["block"] = MyCommon.EVENTTYPE.Block,
1901 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1902 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1903 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1904 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1905 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1906 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1907 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1908 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1909 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1910 ["mute"] = MyCommon.EVENTTYPE.Mute,
1911 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1912 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1915 public bool IsUserstreamDataReceived
1916 => (DateTimeUtc.Now - this._lastUserstreamDataReceived).TotalSeconds < 31;
1918 private void userStream_StatusArrived(string line)
1920 this._lastUserstreamDataReceived = DateTimeUtc.Now;
1921 if (string.IsNullOrEmpty(line)) return;
1923 if (line.First() != '{' || line.Last() != '}')
1925 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
1933 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
1935 var xElm = XElement.Load(jsonReader);
1936 if (xElm.Element("friends") != null)
1938 Debug.WriteLine("friends");
1941 else if (xElm.Element("delete") != null)
1943 Debug.WriteLine("delete");
1946 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
1949 long.TryParse(idElm.Value, out id);
1951 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1953 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
1956 long.TryParse(idElm.Value, out id);
1958 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1962 MyCommon.TraceOut("delete:" + line);
1965 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
1967 var sEvt = this.StoredEvent[i];
1968 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
1970 this.StoredEvent.RemoveAt(i);
1975 else if (xElm.Element("limit") != null)
1977 Debug.WriteLine(line);
1980 else if (xElm.Element("event") != null)
1982 Debug.WriteLine("event: " + xElm.Element("event").Value);
1983 CreateEventFromJson(line);
1986 else if (xElm.Element("direct_message") != null)
1988 Debug.WriteLine("direct_message");
1991 else if (xElm.Element("retweeted_status") != null)
1993 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
1994 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
1996 // 自分に関係しないリツイートの場合は無視する
1997 var selfUserId = this.UserId.ToString();
1998 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2000 // 公式 RT をイベントとしても扱う
2001 var evt = CreateEventFromRetweet(xElm);
2004 this.StoredEvent.Insert(0, evt);
2006 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2010 // 従来通り公式 RT の表示も行うため return しない
2012 else if (xElm.Element("scrub_geo") != null)
2016 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2017 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2021 MyCommon.TraceOut("scrub_geo:" + line);
2031 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2032 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2034 catch (SerializationException ex)
2036 throw TwitterApiException.CreateFromException(ex, line);
2043 var status = TwitterStatusCompat.ParseJson(line);
2044 this.CreatePostsFromJson(new[] { status.Normalize() }, MyCommon.WORKERTYPE.UserStream, null, false);
2046 catch (SerializationException ex)
2048 throw TwitterApiException.CreateFromException(ex, line);
2052 catch (WebApiException ex)
2054 MyCommon.TraceOut(ex);
2057 catch (XmlException)
2059 MyCommon.TraceOut("XmlException (StatusArrived): " + line);
2061 catch(NullReferenceException)
2063 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2066 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2070 /// UserStreamsから受信した公式RTをイベントに変換します
2072 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2074 return new FormattedEvent
2076 Eventtype = MyCommon.EVENTTYPE.Retweet,
2078 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2079 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2080 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2081 Target = string.Format("@{0}:{1}", new[]
2083 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2084 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2086 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2090 private void CreateEventFromJson(string content)
2092 TwitterStreamEvent eventData = null;
2095 eventData = TwitterStreamEvent.ParseJson(content);
2097 catch(SerializationException ex)
2099 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2103 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2106 var evt = new FormattedEvent();
2107 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2108 evt.Event = eventData.Event;
2109 evt.Username = eventData.Source.ScreenName;
2110 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2112 eventTable.TryGetValue(eventData.Event, out var eventType);
2113 evt.Eventtype = eventType;
2115 TwitterStreamEvent<TwitterStatusCompat> tweetEvent;
2116 TwitterStatus tweet;
2118 switch (eventData.Event)
2120 case "access_revoked":
2121 case "access_unrevoked":
2123 case "user_suspend":
2126 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2128 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2132 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2137 evt.Target = "@" + eventData.Target.ScreenName;
2139 case "favorited_retweet":
2140 case "retweeted_retweet":
2144 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2145 tweet = tweetEvent.TargetObject.Normalize();
2146 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2149 if (SettingManager.Common.IsRemoveSameEvent)
2151 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2155 var tabinfo = TabInformations.GetInstance();
2157 var statusId = tweet.Id;
2158 if (!tabinfo.Posts.TryGetValue(statusId, out var post))
2161 if (eventData.Event == "favorite")
2163 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2164 favTab.AddPostQueue(post);
2166 if (tweetEvent.Source.Id == this.UserId)
2170 else if (tweetEvent.Target.Id == this.UserId)
2172 post.FavoritedCount++;
2174 if (SettingManager.Common.FavEventUnread)
2175 tabinfo.SetReadAllTab(post.StatusId, read: false);
2180 if (tweetEvent.Source.Id == this.UserId)
2184 else if (tweetEvent.Target.Id == this.UserId)
2186 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2190 case "quoted_tweet":
2191 if (evt.IsMe) return;
2193 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2194 tweet = tweetEvent.TargetObject.Normalize();
2195 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2198 if (SettingManager.Common.IsRemoveSameEvent)
2200 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2204 case "list_member_added":
2205 case "list_member_removed":
2206 case "list_created":
2207 case "list_destroyed":
2208 case "list_updated":
2209 case "list_user_subscribed":
2210 case "list_user_unsubscribed":
2211 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2212 evt.Target = listEvent.TargetObject.FullName;
2215 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2219 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2228 evt.Target = "@" + eventData.Target.ScreenName;
2229 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2231 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2235 evt.Target = "@" + eventData.Target.ScreenName;
2236 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2238 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2243 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2246 this.StoredEvent.Insert(0, evt);
2248 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2251 private void userStream_Started()
2253 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2256 private void userStream_Stopped()
2258 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2261 public bool UserStreamActive
2262 => this.userStream != null && this.userStream.IsStreamActive;
2264 public void StartUserStream()
2266 var newStream = new TwitterUserstream(this.Api);
2268 newStream.StatusArrived += userStream_StatusArrived;
2269 newStream.Started += userStream_Started;
2270 newStream.Stopped += userStream_Stopped;
2272 newStream.Start(this.AllAtReply, this.TrackWord);
2274 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2275 oldStream?.Dispose();
2278 public void StopUserStream()
2280 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2281 oldStream?.Dispose();
2284 public void ReconnectUserStream()
2286 if (this.userStream != null)
2288 this.StartUserStream();
2292 private class TwitterUserstream : IDisposable
2294 public bool AllAtReplies { get; private set; }
2295 public string TrackWords { get; private set; }
2297 public bool IsStreamActive { get; private set; }
2299 public event Action<string> StatusArrived;
2300 public event Action Stopped;
2301 public event Action Started;
2303 private TwitterApi twitterApi;
2305 private Task streamTask;
2306 private CancellationTokenSource streamCts;
2308 public TwitterUserstream(TwitterApi twitterApi)
2310 this.twitterApi = twitterApi;
2313 public void Start(bool allAtReplies, string trackwords)
2315 this.AllAtReplies = allAtReplies;
2316 this.TrackWords = trackwords;
2318 var cts = new CancellationTokenSource();
2320 this.streamCts = cts;
2321 this.streamTask = Task.Run(async () =>
2325 await this.UserStreamLoop(cts.Token)
2326 .ConfigureAwait(false);
2328 catch (OperationCanceledException) { }
2334 this.streamCts?.Cancel();
2336 // streamTask の完了を待たずに IsStreamActive を false にセットする
2337 this.IsStreamActive = false;
2338 this.Stopped?.Invoke();
2341 private async Task UserStreamLoop(CancellationToken cancellationToken)
2343 TimeSpan sleep = TimeSpan.Zero;
2346 if (sleep != TimeSpan.Zero)
2348 await Task.Delay(sleep, cancellationToken)
2349 .ConfigureAwait(false);
2350 sleep = TimeSpan.Zero;
2353 if (!MyCommon.IsNetworkAvailable())
2355 sleep = TimeSpan.FromSeconds(30);
2359 this.IsStreamActive = true;
2360 this.Started?.Invoke();
2364 var replies = this.AllAtReplies ? "all" : null;
2366 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2367 .ConfigureAwait(false))
2368 using (var reader = new StreamReader(stream))
2370 while (!reader.EndOfStream)
2372 var line = await reader.ReadLineAsync()
2373 .ConfigureAwait(false);
2375 cancellationToken.ThrowIfCancellationRequested();
2377 this.StatusArrived?.Invoke(line);
2381 // キャンセルされていないのにストリームが終了した場合
2382 sleep = TimeSpan.FromSeconds(30);
2384 catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2385 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2386 catch (OperationCanceledException)
2388 if (cancellationToken.IsCancellationRequested)
2391 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2392 sleep = TimeSpan.FromSeconds(30);
2394 catch (Exception ex)
2396 MyCommon.ExceptionOut(ex);
2397 sleep = TimeSpan.FromSeconds(30);
2401 this.IsStreamActive = false;
2402 this.Stopped?.Invoke();
2407 private bool disposed = false;
2409 public void Dispose()
2414 this.disposed = true;
2418 this.Started = null;
2419 this.Stopped = null;
2420 this.StatusArrived = null;
2425 #region "IDisposable Support"
2426 private bool disposedValue; // 重複する呼び出しを検出するには
2429 protected virtual void Dispose(bool disposing)
2431 if (!this.disposedValue)
2435 this.StopUserStream();
2438 this.disposedValue = true;
2441 //protected Overrides void Finalize()
2443 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2445 // MyBase.Finalize()
2448 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2449 public void Dispose()
2451 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2453 GC.SuppressFinalize(this);
2458 public class PostDeletedEventArgs : EventArgs
2460 public long StatusId { get; }
2462 public PostDeletedEventArgs(long statusId)
2464 this.StatusId = statusId;
2468 public class UserStreamEventReceivedEventArgs : EventArgs
2470 public Twitter.FormattedEvent EventData { get; }
2472 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2474 this.EventData = eventData;