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; }
153 delegate void GetIconImageDelegate(PostClass post);
154 private readonly object LockObj = new object();
155 private ISet<long> followerId = new HashSet<long>();
156 private bool _GetFollowerResult = false;
157 private long[] noRTId = new long[0];
158 private bool _GetNoRetweetResult = false;
161 private string _uname;
163 private bool _readOwnPost;
164 private List<string> _hashList = new List<string>();
166 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
167 private long minDirectmessage = long.MaxValue;
168 private long minDirectmessageSent = long.MaxValue;
170 private long previousStatusId = -1L;
172 //private FavoriteQueue favQueue;
174 //private List<PostClass> _deletemessages = new List<PostClass>();
176 public Twitter() : this(new TwitterApi())
180 public Twitter(TwitterApi api)
183 this.Configuration = TwitterConfiguration.DefaultConfiguration();
186 public TwitterApiAccessLevel AccessLevel
190 return MyCommon.TwitterApiInfo.AccessLevel;
194 protected void ResetApiStatus()
196 MyCommon.TwitterApiInfo.Reset();
199 public void ClearAuthInfo()
201 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
202 this.ResetApiStatus();
206 public void VerifyCredentials()
210 this.VerifyCredentialsAsync().Wait();
212 catch (AggregateException ex) when (ex.InnerException is WebApiException)
214 throw new WebApiException(ex.InnerException.Message, ex);
218 public async Task VerifyCredentialsAsync()
220 var user = await this.Api.AccountVerifyCredentials()
221 .ConfigureAwait(false);
223 this.UpdateUserStats(user);
226 public void Initialize(string token, string tokenSecret, string username, long userId)
229 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
231 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
233 this.ResetApiStatus();
234 this.Api.Initialize(token, tokenSecret, userId, username);
235 _uname = username.ToLowerInvariant();
236 if (SettingManager.Common.UserstreamStartup) this.ReconnectUserStream();
239 public string PreProcessUrl(string orgData)
243 //var IDNConveter = new IdnMapping();
244 var href = "<a href=\"";
248 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
252 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
253 posl1 += href.Length;
254 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
255 urlStr = orgData.Substring(posl1, posl2 - posl1);
257 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
258 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
259 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
264 var replacedUrl = MyCommon.IDNEncode(urlStr);
265 if (replacedUrl == null) continue;
266 if (replacedUrl == urlStr) continue;
268 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
279 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
281 this.CheckAccountState();
283 if (mediaIds == null &&
284 Twitter.DMSendTextRegex.IsMatch(postStr))
286 await this.SendDirectMessage(postStr)
287 .ConfigureAwait(false);
291 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
292 .ConfigureAwait(false);
294 var status = await response.LoadJsonAsync()
295 .ConfigureAwait(false);
297 this.UpdateUserStats(status.User);
299 if (status.Id == this.previousStatusId)
300 throw new WebApiException("OK:Delaying?");
302 this.previousStatusId = status.Id;
305 public Task<long> UploadMedia(IMediaItem item)
306 => this.UploadMedia(item, SettingManager.Common.AlphaPNGWorkaround);
308 public async Task<long> UploadMedia(IMediaItem item, bool alphaPNGWorkaround)
310 this.CheckAccountState();
312 LazyJson<TwitterUploadMediaResult> response;
314 using (var origImage = item.CreateImage())
316 if (alphaPNGWorkaround && this.AddAlphaChannelIfNeeded(origImage.Image, out var newImage))
318 using (var newMediaItem = new MemoryImageMediaItem(newImage))
320 response = await this.Api.MediaUpload(newMediaItem)
321 .ConfigureAwait(false);
326 response = await this.Api.MediaUpload(item)
327 .ConfigureAwait(false);
331 var media = await response.LoadJsonAsync()
332 .ConfigureAwait(false);
334 return media.MediaId;
338 /// pic.twitter.com アップロード時に JPEG への変換を回避するための加工を行う
341 /// pic.twitter.com へのアップロード時に、アルファチャンネルを持たない PNG 画像が
342 /// JPEG 形式に変換され画質が低下する問題を回避します。
343 /// PNG 以外の画像や、すでにアルファチャンネルを持つ PNG 画像に対しては何もしません。
345 /// <returns>加工が行われた場合は true、そうでない場合は false</returns>
346 private bool AddAlphaChannelIfNeeded(Image origImage, out MemoryImage newImage)
350 // PNG 画像以外に対しては何もしない
351 if (origImage.RawFormat.Guid != ImageFormat.Png.Guid)
354 using (var bitmap = new Bitmap(origImage))
356 // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
357 foreach (var x in Enumerable.Range(0, bitmap.Width))
359 foreach (var y in Enumerable.Range(0, bitmap.Height))
361 if (bitmap.GetPixel(x, y).A != 255)
366 // 左上の 1px だけアルファ値を 254 にする
367 var pixel = bitmap.GetPixel(0, 0);
368 var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
369 bitmap.SetPixel(0, 0, newPixel);
371 // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
372 newImage = MemoryImage.CopyFromImage(bitmap);
378 public async Task SendDirectMessage(string postStr)
380 this.CheckAccountState();
381 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
383 var mc = Twitter.DMSendTextRegex.Match(postStr);
385 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
386 .ConfigureAwait(false);
388 var dm = await response.LoadJsonAsync()
389 .ConfigureAwait(false);
391 this.UpdateUserStats(dm.Sender);
394 public async Task PostRetweet(long id, bool read)
396 this.CheckAccountState();
399 var post = TabInformations.GetInstance()[id];
401 throw new WebApiException("Err:Target isn't found.");
403 var target = post.RetweetedId ?? id; //再RTの場合は元発言をRT
405 var response = await this.Api.StatusesRetweet(target)
406 .ConfigureAwait(false);
408 var status = await response.LoadJsonAsync()
409 .ConfigureAwait(false);
414 if (TabInformations.GetInstance().ContainsKey(status.Id))
419 if (status.RetweetedStatus == null)
420 throw new WebApiException("Invalid Json!");
423 post = CreatePostsFromStatusData(status);
430 if (_readOwnPost) post.IsRead = true;
433 TabInformations.GetInstance().AddPost(post);
436 public string Username
437 => this.Api.CurrentScreenName;
440 => this.Api.CurrentUserId;
442 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
443 public static MyCommon.ACCOUNT_STATE AccountState
447 return _accountState;
451 _accountState = value;
455 public bool RestrictFavCheck { get; set; }
457 public bool ReadOwnPost
465 _readOwnPost = value;
469 public int FollowersCount { get; private set; }
470 public int FriendsCount { get; private set; }
471 public int StatusesCount { get; private set; }
472 public string Location { get; private set; } = "";
473 public string Bio { get; private set; } = "";
475 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
476 private void UpdateUserStats(TwitterUser self)
478 this.FollowersCount = self.FollowersCount;
479 this.FriendsCount = self.FriendsCount;
480 this.StatusesCount = self.StatusesCount;
481 this.Location = self.Location;
482 this.Bio = self.Description;
486 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
488 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
490 return count >= 20 && count <= GetMaxApiResultCount(type);
494 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
496 public static bool VerifyMoreApiResultCount(int count)
498 return count >= 20 && count <= 200;
502 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
504 public static bool VerifyFirstApiResultCount(int count)
506 return count >= 20 && count <= 200;
510 /// WORKERTYPEに応じた取得可能な最大件数を取得する
512 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
514 // 参照: REST APIs - 各endpointのcountパラメータ
515 // https://dev.twitter.com/rest/public
518 case MyCommon.WORKERTYPE.Timeline:
519 case MyCommon.WORKERTYPE.Reply:
520 case MyCommon.WORKERTYPE.UserTimeline:
521 case MyCommon.WORKERTYPE.Favorites:
522 case MyCommon.WORKERTYPE.DirectMessegeRcv:
523 case MyCommon.WORKERTYPE.DirectMessegeSnt:
524 case MyCommon.WORKERTYPE.List: // 不明
527 case MyCommon.WORKERTYPE.PublicSearch:
531 throw new InvalidOperationException("Invalid type: " + type);
536 /// WORKERTYPEに応じた取得件数を取得する
538 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
540 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
541 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
546 if (SettingManager.Common.UseAdditionalCount)
550 case MyCommon.WORKERTYPE.Favorites:
551 if (SettingManager.Common.FavoritesCountApi != 0)
552 return SettingManager.Common.FavoritesCountApi;
554 case MyCommon.WORKERTYPE.List:
555 if (SettingManager.Common.ListCountApi != 0)
556 return SettingManager.Common.ListCountApi;
558 case MyCommon.WORKERTYPE.PublicSearch:
559 if (SettingManager.Common.SearchCountApi != 0)
560 return SettingManager.Common.SearchCountApi;
562 case MyCommon.WORKERTYPE.UserTimeline:
563 if (SettingManager.Common.UserTimelineCountApi != 0)
564 return SettingManager.Common.UserTimelineCountApi;
567 if (more && SettingManager.Common.MoreCountApi != 0)
569 return Math.Min(SettingManager.Common.MoreCountApi, GetMaxApiResultCount(type));
571 if (startup && SettingManager.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
573 return Math.Min(SettingManager.Common.FirstCountApi, GetMaxApiResultCount(type));
578 var count = SettingManager.Common.CountApi;
580 if (type == MyCommon.WORKERTYPE.Reply)
581 count = SettingManager.Common.CountApiReply;
583 return Math.Min(count, GetMaxApiResultCount(type));
586 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
588 this.CheckAccountState();
590 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
592 TwitterStatus[] statuses;
595 statuses = await this.Api.StatusesHomeTimeline(count, maxId: tab.OldestId)
596 .ConfigureAwait(false);
600 statuses = await this.Api.StatusesHomeTimeline(count)
601 .ConfigureAwait(false);
604 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
606 if (minimumId != null && minimumId.Value < tab.OldestId)
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);
630 if (minimumId != null && minimumId.Value < tab.OldestId)
631 tab.OldestId = minimumId.Value;
634 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
636 this.CheckAccountState();
638 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
640 TwitterStatus[] statuses;
641 if (string.IsNullOrEmpty(userName))
643 var target = tab.ScreenName;
644 if (string.IsNullOrEmpty(target)) return;
646 statuses = await this.Api.StatusesUserTimeline(userName, count)
647 .ConfigureAwait(false);
653 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
654 .ConfigureAwait(false);
658 statuses = await this.Api.StatusesUserTimeline(userName, count)
659 .ConfigureAwait(false);
663 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
665 if (minimumId != null && minimumId.Value < tab.OldestId)
666 tab.OldestId = minimumId.Value;
669 public async Task<PostClass> GetStatusApi(bool read, long id)
671 this.CheckAccountState();
673 var status = await this.Api.StatusesShow(id)
674 .ConfigureAwait(false);
676 var item = CreatePostsFromStatusData(status);
679 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
684 public async Task GetStatusApi(bool read, long id, TabModel tab)
686 var post = await this.GetStatusApi(read, id)
687 .ConfigureAwait(false);
689 //非同期アイコン取得&StatusDictionaryに追加
690 if (tab != null && tab.IsInnerStorageTabType)
691 tab.AddPostQueue(post);
693 TabInformations.GetInstance().AddPost(post);
696 private PostClass CreatePostsFromStatusData(TwitterStatus status)
698 return CreatePostsFromStatusData(status, false);
701 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
703 var post = new PostClass();
704 TwitterEntities entities;
707 post.StatusId = status.Id;
708 if (status.RetweetedStatus != null)
710 var retweeted = status.RetweetedStatus;
712 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
715 post.RetweetedId = retweeted.Id;
717 post.TextFromApi = retweeted.FullText;
718 entities = retweeted.MergedEntities;
719 sourceHtml = retweeted.Source;
721 post.InReplyToStatusId = retweeted.InReplyToStatusId;
722 post.InReplyToUser = retweeted.InReplyToScreenName;
723 post.InReplyToUserId = status.InReplyToUserId;
732 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
733 post.IsFav = tc.Contains(retweeted.Id);
736 if (retweeted.Coordinates != null)
737 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
740 var user = retweeted.User;
743 post.UserId = user.Id;
744 post.ScreenName = user.ScreenName;
745 post.Nickname = user.Name.Trim();
746 post.ImageUrl = user.ProfileImageUrlHttps;
747 post.IsProtect = user.Protected;
752 post.ScreenName = "?????";
753 post.Nickname = "Unknown User";
757 if (status.User != null)
759 post.RetweetedBy = status.User.ScreenName;
760 post.RetweetedByUserId = status.User.Id;
761 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
765 post.RetweetedBy = "?????";
766 post.RetweetedByUserId = 0L;
771 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
773 post.TextFromApi = status.FullText;
774 entities = status.MergedEntities;
775 sourceHtml = status.Source;
776 post.InReplyToStatusId = status.InReplyToStatusId;
777 post.InReplyToUser = status.InReplyToScreenName;
778 post.InReplyToUserId = status.InReplyToUserId;
787 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
788 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
791 if (status.Coordinates != null)
792 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
795 var user = status.User;
798 post.UserId = user.Id;
799 post.ScreenName = user.ScreenName;
800 post.Nickname = user.Name.Trim();
801 post.ImageUrl = user.ProfileImageUrlHttps;
802 post.IsProtect = user.Protected;
803 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
808 post.ScreenName = "?????";
809 post.Nickname = "Unknown User";
813 string textFromApi = post.TextFromApi;
814 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
815 post.TextFromApi = textFromApi;
816 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
817 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
818 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
819 post.AccessibleText = this.CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus);
820 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
821 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
823 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
824 .Where(x => x != post.StatusId && x != post.RetweetedId)
825 .Distinct().ToArray();
827 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
828 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
831 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
832 if (post.Text == post.TextFromApi)
833 post.Text = post.TextFromApi;
834 if (post.AccessibleText == post.TextFromApi)
835 post.AccessibleText = post.TextFromApi;
837 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
838 post.ScreenName = string.Intern(post.ScreenName);
839 post.Nickname = string.Intern(post.Nickname);
840 post.ImageUrl = string.Intern(post.ImageUrl);
841 post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
844 var source = ParseSource(sourceHtml);
845 post.Source = string.Intern(source.Item1);
846 post.SourceUri = source.Item2;
848 post.IsReply = post.ReplyToList.Contains(_uname);
849 post.IsExcludeReply = false;
857 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
865 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
867 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
869 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
871 return GetQuoteTweetStatusIds(urls);
874 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
876 foreach (var url in urls)
878 var match = Twitter.StatusUrlRegex.Match(url);
881 if (long.TryParse(match.Groups["StatusId"].Value, out var statusId))
882 yield return statusId;
887 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
889 long? minimumId = null;
891 foreach (var status in items)
893 if (minimumId == null || minimumId.Value > status.Id)
894 minimumId = status.Id;
901 if (TabInformations.GetInstance().ContainsKey(status.Id)) continue;
905 if (tab.Contains(status.Id)) continue;
910 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
911 status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
913 var post = CreatePostsFromStatusData(status);
916 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
918 if (tab != null && tab.IsInnerStorageTabType)
919 tab.AddPostQueue(post);
921 TabInformations.GetInstance().AddPost(post);
927 private long? CreatePostsFromSearchJson(TwitterSearchResult items, PublicSearchTabModel tab, bool read, bool more)
929 long? minimumId = null;
931 foreach (var status in items.Statuses)
933 if (minimumId == null || minimumId.Value > status.Id)
934 minimumId = status.Id;
936 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
940 if (tab.Contains(status.Id)) continue;
943 var post = CreatePostsFromStatusData(status);
946 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
948 tab.AddPostQueue(post);
954 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
956 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
957 long? minimumId = null;
959 foreach (var status in items)
961 if (minimumId == null || minimumId.Value > status.Id)
962 minimumId = status.Id;
967 if (favTab.Contains(status.Id)) continue;
970 var post = CreatePostsFromStatusData(status, true);
974 TabInformations.GetInstance().AddPost(post);
980 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
982 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
984 TwitterStatus[] statuses;
987 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingManager.Common.IsListsIncludeRts)
988 .ConfigureAwait(false);
992 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Common.IsListsIncludeRts)
993 .ConfigureAwait(false);
996 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
998 if (minimumId != null && minimumId.Value < tab.OldestId)
999 tab.OldestId = minimumId.Value;
1003 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1005 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1006 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1008 if (!posts.ContainsKey(startStatusId))
1009 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1011 var nextPost = posts[startStatusId];
1012 while (nextPost.InReplyToStatusId != null)
1014 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1016 nextPost = posts[nextPost.InReplyToStatusId.Value];
1022 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
1024 var targetPost = tab.TargetPost;
1025 var relPosts = new Dictionary<Int64, PostClass>();
1026 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1029 var p = TabInformations.GetInstance()[targetPost.StatusId];
1030 if (p != null && p.InReplyToStatusId != null)
1036 p = await this.GetStatusApi(read, targetPost.StatusId)
1037 .ConfigureAwait(false);
1041 relPosts.Add(targetPost.StatusId, targetPost);
1043 Exception lastException = null;
1045 // in_reply_to_status_id を使用してリプライチェインを辿る
1046 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1048 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1050 var inReplyToId = nextPost.InReplyToStatusId.Value;
1052 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1053 if (inReplyToPost == null)
1057 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1058 .ConfigureAwait(false);
1060 catch (WebApiException ex)
1067 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1069 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1072 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1073 var text = targetPost.Text;
1074 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1075 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1076 foreach (var _match in ma)
1078 if (Int64.TryParse(_match.Groups["StatusId"].Value, out var _statusId))
1080 if (relPosts.ContainsKey(_statusId))
1083 var p = TabInformations.GetInstance()[_statusId];
1088 p = await this.GetStatusApi(read, _statusId)
1089 .ConfigureAwait(false);
1091 catch (WebApiException ex)
1099 relPosts.Add(p.StatusId, p);
1103 relPosts.Values.ToList().ForEach(p =>
1105 if (p.IsMe && !read && this._readOwnPost)
1110 tab.AddPostQueue(p);
1113 if (lastException != null)
1114 throw new WebApiException(lastException.Message, lastException);
1117 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1119 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1122 long? sinceId = null;
1125 maxId = tab.OldestId - 1;
1129 sinceId = tab.SinceId;
1132 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1133 .ConfigureAwait(false);
1135 if (!TabInformations.GetInstance().ContainsTab(tab))
1138 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, more);
1140 if (minimumId != null && minimumId.Value < tab.OldestId)
1141 tab.OldestId = minimumId.Value;
1144 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1146 foreach (var message in item)
1148 var post = new PostClass();
1151 post.StatusId = message.Id;
1152 if (gType != MyCommon.WORKERTYPE.UserStream)
1154 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1156 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1160 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1167 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1171 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1173 var textFromApi = message.Text;
1175 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1176 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1177 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1178 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1179 post.AccessibleText = this.CreateAccessibleText(textFromApi, message.Entities, quoteStatus: null);
1180 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1181 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1184 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1186 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1187 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1192 if (gType == MyCommon.WORKERTYPE.UserStream)
1194 if (this.Api.CurrentUserId == message.Recipient.Id)
1196 user = message.Sender;
1202 user = message.Recipient;
1209 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1211 user = message.Sender;
1217 user = message.Recipient;
1223 post.UserId = user.Id;
1224 post.ScreenName = user.ScreenName;
1225 post.Nickname = user.Name.Trim();
1226 post.ImageUrl = user.ProfileImageUrlHttps;
1227 post.IsProtect = user.Protected;
1229 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1230 if (post.Text == post.TextFromApi)
1231 post.Text = post.TextFromApi;
1232 if (post.AccessibleText == post.TextFromApi)
1233 post.AccessibleText = post.TextFromApi;
1235 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1236 post.ScreenName = string.Intern(post.ScreenName);
1237 post.Nickname = string.Intern(post.Nickname);
1238 post.ImageUrl = string.Intern(post.ImageUrl);
1242 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1243 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1248 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1249 post.IsReply = false;
1250 post.IsExcludeReply = false;
1253 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1254 dmTab.AddPostQueue(post);
1258 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1260 this.CheckAccountState();
1261 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1263 var count = GetApiResultCount(gType, more, false);
1265 TwitterDirectMessage[] messages;
1266 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1270 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1271 .ConfigureAwait(false);
1275 messages = await this.Api.DirectMessagesRecv(count)
1276 .ConfigureAwait(false);
1283 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1284 .ConfigureAwait(false);
1288 messages = await this.Api.DirectMessagesSent(count)
1289 .ConfigureAwait(false);
1293 CreateDirectMessagesFromJson(messages, gType, read);
1296 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1298 this.CheckAccountState();
1300 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1302 TwitterStatus[] statuses;
1305 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1306 .ConfigureAwait(false);
1310 statuses = await this.Api.FavoritesList(count)
1311 .ConfigureAwait(false);
1314 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1316 if (minimumId != null && minimumId.Value < tab.OldestId)
1317 tab.OldestId = minimumId.Value;
1320 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1322 if (entities != null)
1324 if (entities.Urls != null)
1326 foreach (var m in entities.Urls)
1328 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1331 if (entities.Media != null)
1333 foreach (var m in entities.Media)
1335 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1342 private string CreateAccessibleText(string text, TwitterEntities entities, TwitterStatus quoteStatus)
1344 if (entities == null)
1347 if (entities.Urls != null)
1349 foreach (var entity in entities.Urls)
1351 if (quoteStatus != null)
1353 var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1354 if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quoteStatus.IdStr)
1356 var quoteText = this.CreateAccessibleText(quoteStatus.FullText, quoteStatus.MergedEntities, quoteStatus: null);
1357 text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quoteStatus.User.ScreenName, quoteText));
1360 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1362 text = text.Replace(entity.Url, entity.DisplayUrl);
1367 if (entities.Media != null)
1369 foreach (var entity in entities.Media)
1371 if (!string.IsNullOrEmpty(entity.AltText))
1373 text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1375 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1377 text = text.Replace(entity.Url, entity.DisplayUrl);
1388 /// <exception cref="WebApiException"/>
1389 public async Task RefreshFollowerIds()
1391 if (MyCommon._endingFlag) return;
1394 var newFollowerIds = new HashSet<long>();
1397 var ret = await this.Api.FollowersIds(cursor)
1398 .ConfigureAwait(false);
1400 if (ret.Ids == null)
1401 throw new WebApiException("ret.ids == null");
1403 newFollowerIds.UnionWith(ret.Ids);
1404 cursor = ret.NextCursor;
1405 } while (cursor != 0);
1407 this.followerId = newFollowerIds;
1408 TabInformations.GetInstance().RefreshOwl(this.followerId);
1410 this._GetFollowerResult = true;
1413 public bool GetFollowersSuccess
1417 return _GetFollowerResult;
1422 /// RT 非表示ユーザーを更新します
1424 /// <exception cref="WebApiException"/>
1425 public async Task RefreshNoRetweetIds()
1427 if (MyCommon._endingFlag) return;
1429 this.noRTId = await this.Api.NoRetweetIds()
1430 .ConfigureAwait(false);
1432 this._GetNoRetweetResult = true;
1435 public bool GetNoRetweetSuccess
1439 return _GetNoRetweetResult;
1444 /// t.co の文字列長などの設定情報を更新します
1446 /// <exception cref="WebApiException"/>
1447 public async Task RefreshConfiguration()
1449 this.Configuration = await this.Api.Configuration()
1450 .ConfigureAwait(false);
1453 public async Task GetListsApi()
1455 this.CheckAccountState();
1457 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1458 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1459 .ConfigureAwait(false);
1461 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1462 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1463 .ConfigureAwait(false);
1465 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1466 .Select(x => new ListElement(x, this))
1470 public async Task DeleteList(long listId)
1472 await this.Api.ListsDestroy(listId)
1474 .ConfigureAwait(false);
1476 var tabinfo = TabInformations.GetInstance();
1478 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1479 .Where(x => x.Id != listId)
1483 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1485 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1486 .ConfigureAwait(false);
1488 var list = await response.LoadJsonAsync()
1489 .ConfigureAwait(false);
1491 return new ListElement(list, this);
1494 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1496 this.CheckAccountState();
1498 var users = await this.Api.ListsMembers(listId, cursor)
1499 .ConfigureAwait(false);
1501 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1503 return users.NextCursor;
1506 public async Task CreateListApi(string listName, bool isPrivate, string description)
1508 this.CheckAccountState();
1510 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1511 .ConfigureAwait(false);
1513 var list = await response.LoadJsonAsync()
1514 .ConfigureAwait(false);
1516 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1519 public async Task<bool> ContainsUserAtList(long listId, string user)
1521 this.CheckAccountState();
1525 await this.Api.ListsMembersShow(listId, user)
1526 .ConfigureAwait(false);
1530 catch (TwitterApiException ex)
1531 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1537 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1539 if (entities != null)
1541 if (entities.Hashtags != null)
1545 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1548 if (entities.UserMentions != null)
1550 foreach (var ent in entities.UserMentions)
1552 var screenName = ent.ScreenName.ToLowerInvariant();
1553 if (!AtList.Contains(screenName))
1554 AtList.Add(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 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1598 if (string.IsNullOrEmpty(sourceHtml))
1599 return Tuple.Create<string, Uri>("", null);
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 Tuple.Create(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.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1716 return this.GetTextLengthRemainInternal(postText, isDm: false);
1719 private int GetTextLengthRemainInternal(string postText, bool isDm)
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;
1745 return this.Configuration.DmTextCharacterLimit - textLength;
1747 return 140 - textLength;
1751 #region "UserStream"
1752 private string trackWord_ = "";
1753 public string TrackWord
1764 private bool allAtReply_ = false;
1765 public bool AllAtReply
1773 allAtReply_ = value;
1777 public event EventHandler NewPostFromStream;
1778 public event EventHandler UserStreamStarted;
1779 public event EventHandler UserStreamStopped;
1780 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1781 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1782 private DateTime _lastUserstreamDataReceived;
1783 private TwitterUserstream userStream;
1785 public class FormattedEvent
1787 public MyCommon.EVENTTYPE Eventtype { get; set; }
1788 public DateTime CreatedAt { get; set; }
1789 public string Event { get; set; }
1790 public string Username { get; set; }
1791 public string Target { get; set; }
1792 public Int64 Id { get; set; }
1793 public bool IsMe { get; set; }
1796 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1797 public List<FormattedEvent> StoredEvent
1801 return storedEvent_;
1805 storedEvent_ = value;
1809 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1811 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1812 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1813 ["follow"] = MyCommon.EVENTTYPE.Follow,
1814 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1815 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1816 ["block"] = MyCommon.EVENTTYPE.Block,
1817 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1818 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1819 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1820 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1821 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1822 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1823 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1824 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1825 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1826 ["mute"] = MyCommon.EVENTTYPE.Mute,
1827 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1828 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1831 public bool IsUserstreamDataReceived
1835 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
1839 private void userStream_StatusArrived(string line)
1841 this._lastUserstreamDataReceived = DateTime.Now;
1842 if (string.IsNullOrEmpty(line)) return;
1844 if (line.First() != '{' || line.Last() != '}')
1846 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
1854 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
1856 var xElm = XElement.Load(jsonReader);
1857 if (xElm.Element("friends") != null)
1859 Debug.WriteLine("friends");
1862 else if (xElm.Element("delete") != null)
1864 Debug.WriteLine("delete");
1867 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
1870 long.TryParse(idElm.Value, out id);
1872 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1874 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
1877 long.TryParse(idElm.Value, out id);
1879 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1883 MyCommon.TraceOut("delete:" + line);
1886 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
1888 var sEvt = this.StoredEvent[i];
1889 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
1891 this.StoredEvent.RemoveAt(i);
1896 else if (xElm.Element("limit") != null)
1898 Debug.WriteLine(line);
1901 else if (xElm.Element("event") != null)
1903 Debug.WriteLine("event: " + xElm.Element("event").Value);
1904 CreateEventFromJson(line);
1907 else if (xElm.Element("direct_message") != null)
1909 Debug.WriteLine("direct_message");
1912 else if (xElm.Element("retweeted_status") != null)
1914 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
1915 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
1917 // 自分に関係しないリツイートの場合は無視する
1918 var selfUserId = this.UserId.ToString();
1919 if (sourceUserId == selfUserId || targetUserId == selfUserId)
1921 // 公式 RT をイベントとしても扱う
1922 var evt = CreateEventFromRetweet(xElm);
1925 this.StoredEvent.Insert(0, evt);
1927 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
1931 // 従来通り公式 RT の表示も行うため return しない
1933 else if (xElm.Element("scrub_geo") != null)
1937 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
1938 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
1942 MyCommon.TraceOut("scrub_geo:" + line);
1952 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
1953 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
1955 catch (SerializationException ex)
1957 throw TwitterApiException.CreateFromException(ex, line);
1964 var status = TwitterStatusCompat.ParseJson(line);
1965 this.CreatePostsFromJson(new[] { status.Normalize() }, MyCommon.WORKERTYPE.UserStream, null, false);
1967 catch (SerializationException ex)
1969 throw TwitterApiException.CreateFromException(ex, line);
1973 catch (WebApiException ex)
1975 MyCommon.TraceOut(ex);
1978 catch(NullReferenceException)
1980 MyCommon.TraceOut("NullRef StatusArrived: " + line);
1983 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
1987 /// UserStreamsから受信した公式RTをイベントに変換します
1989 private FormattedEvent CreateEventFromRetweet(XElement xElm)
1991 return new FormattedEvent
1993 Eventtype = MyCommon.EVENTTYPE.Retweet,
1995 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
1996 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
1997 Username = xElm.XPathSelectElement("/user/screen_name").Value,
1998 Target = string.Format("@{0}:{1}", new[]
2000 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2001 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2003 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2007 private void CreateEventFromJson(string content)
2009 TwitterStreamEvent eventData = null;
2012 eventData = TwitterStreamEvent.ParseJson(content);
2014 catch(SerializationException ex)
2016 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2020 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2023 var evt = new FormattedEvent();
2024 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2025 evt.Event = eventData.Event;
2026 evt.Username = eventData.Source.ScreenName;
2027 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2029 eventTable.TryGetValue(eventData.Event, out var eventType);
2030 evt.Eventtype = eventType;
2032 TwitterStreamEvent<TwitterStatusCompat> tweetEvent;
2033 TwitterStatus tweet;
2035 switch (eventData.Event)
2037 case "access_revoked":
2038 case "access_unrevoked":
2040 case "user_suspend":
2043 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2045 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2049 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2054 evt.Target = "@" + eventData.Target.ScreenName;
2056 case "favorited_retweet":
2057 case "retweeted_retweet":
2061 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2062 tweet = tweetEvent.TargetObject.Normalize();
2063 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2066 if (SettingManager.Common.IsRemoveSameEvent)
2068 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2072 var tabinfo = TabInformations.GetInstance();
2074 var statusId = tweet.Id;
2075 if (!tabinfo.Posts.TryGetValue(statusId, out var post))
2078 if (eventData.Event == "favorite")
2080 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2081 favTab.AddPostQueue(post);
2083 if (tweetEvent.Source.Id == this.UserId)
2087 else if (tweetEvent.Target.Id == this.UserId)
2089 post.FavoritedCount++;
2091 if (SettingManager.Common.FavEventUnread)
2092 tabinfo.SetReadAllTab(post.StatusId, read: false);
2097 if (tweetEvent.Source.Id == this.UserId)
2101 else if (tweetEvent.Target.Id == this.UserId)
2103 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2107 case "quoted_tweet":
2108 if (evt.IsMe) return;
2110 tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2111 tweet = tweetEvent.TargetObject.Normalize();
2112 evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2115 if (SettingManager.Common.IsRemoveSameEvent)
2117 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2121 case "list_member_added":
2122 case "list_member_removed":
2123 case "list_created":
2124 case "list_destroyed":
2125 case "list_updated":
2126 case "list_user_subscribed":
2127 case "list_user_unsubscribed":
2128 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2129 evt.Target = listEvent.TargetObject.FullName;
2132 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2136 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2145 evt.Target = "@" + eventData.Target.ScreenName;
2146 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2148 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2152 evt.Target = "@" + eventData.Target.ScreenName;
2153 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2155 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2160 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2163 this.StoredEvent.Insert(0, evt);
2165 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2168 private void userStream_Started()
2170 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2173 private void userStream_Stopped()
2175 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2178 public bool UserStreamActive
2179 => this.userStream != null && this.userStream.IsStreamActive;
2181 public void StartUserStream()
2183 var newStream = new TwitterUserstream(this.Api);
2185 newStream.StatusArrived += userStream_StatusArrived;
2186 newStream.Started += userStream_Started;
2187 newStream.Stopped += userStream_Stopped;
2189 newStream.Start(this.AllAtReply, this.TrackWord);
2191 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2192 oldStream?.Dispose();
2195 public void StopUserStream()
2197 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2198 oldStream?.Dispose();
2201 public void ReconnectUserStream()
2203 if (this.userStream != null)
2205 this.StartUserStream();
2209 private class TwitterUserstream : IDisposable
2211 public bool AllAtReplies { get; private set; }
2212 public string TrackWords { get; private set; }
2214 public bool IsStreamActive { get; private set; }
2216 public event Action<string> StatusArrived;
2217 public event Action Stopped;
2218 public event Action Started;
2220 private TwitterApi twitterApi;
2222 private Task streamTask;
2223 private CancellationTokenSource streamCts;
2225 public TwitterUserstream(TwitterApi twitterApi)
2227 this.twitterApi = twitterApi;
2230 public void Start(bool allAtReplies, string trackwords)
2232 this.AllAtReplies = allAtReplies;
2233 this.TrackWords = trackwords;
2235 var cts = new CancellationTokenSource();
2237 this.streamCts = cts;
2238 this.streamTask = Task.Run(async () =>
2242 await this.UserStreamLoop(cts.Token)
2243 .ConfigureAwait(false);
2245 catch (OperationCanceledException) { }
2251 this.streamCts?.Cancel();
2253 // streamTask の完了を待たずに IsStreamActive を false にセットする
2254 this.IsStreamActive = false;
2255 this.Stopped?.Invoke();
2258 private async Task UserStreamLoop(CancellationToken cancellationToken)
2260 TimeSpan sleep = TimeSpan.Zero;
2263 if (sleep != TimeSpan.Zero)
2265 await Task.Delay(sleep, cancellationToken)
2266 .ConfigureAwait(false);
2267 sleep = TimeSpan.Zero;
2270 if (!MyCommon.IsNetworkAvailable())
2272 sleep = TimeSpan.FromSeconds(30);
2276 this.IsStreamActive = true;
2277 this.Started?.Invoke();
2281 var replies = this.AllAtReplies ? "all" : null;
2283 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2284 .ConfigureAwait(false))
2285 using (var reader = new StreamReader(stream))
2287 while (!reader.EndOfStream)
2289 var line = await reader.ReadLineAsync()
2290 .ConfigureAwait(false);
2292 cancellationToken.ThrowIfCancellationRequested();
2294 this.StatusArrived?.Invoke(line);
2298 // キャンセルされていないのにストリームが終了した場合
2299 sleep = TimeSpan.FromSeconds(30);
2301 catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2302 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2303 catch (OperationCanceledException)
2305 if (cancellationToken.IsCancellationRequested)
2308 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2309 sleep = TimeSpan.FromSeconds(30);
2311 catch (Exception ex)
2313 MyCommon.ExceptionOut(ex);
2314 sleep = TimeSpan.FromSeconds(30);
2318 this.IsStreamActive = false;
2319 this.Stopped?.Invoke();
2324 private bool disposed = false;
2326 public void Dispose()
2331 this.disposed = true;
2335 this.Started = null;
2336 this.Stopped = null;
2337 this.StatusArrived = null;
2342 #region "IDisposable Support"
2343 private bool disposedValue; // 重複する呼び出しを検出するには
2346 protected virtual void Dispose(bool disposing)
2348 if (!this.disposedValue)
2352 this.StopUserStream();
2355 this.disposedValue = true;
2358 //protected Overrides void Finalize()
2360 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2362 // MyBase.Finalize()
2365 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2366 public void Dispose()
2368 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2370 GC.SuppressFinalize(this);
2375 public class PostDeletedEventArgs : EventArgs
2377 public long StatusId { get; }
2379 public PostDeletedEventArgs(long statusId)
2381 this.StatusId = statusId;
2385 public class UserStreamEventReceivedEventArgs : EventArgs
2387 public Twitter.FormattedEvent EventData { get; }
2389 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2391 this.EventData = eventData;