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;
56 public class Twitter : IDisposable
58 #region Regexp from twitter-text-js
60 // The code in this region code block incorporates works covered by
61 // the following copyright and permission notices:
63 // Copyright 2011 Twitter, Inc.
65 // Licensed under the Apache License, Version 2.0 (the "License"); you
66 // may not use this work except in compliance with the License. You
67 // may obtain a copy of the License in the LICENSE file, or at:
69 // http://www.apache.org/licenses/LICENSE-2.0
71 // Unless required by applicable law or agreed to in writing, software
72 // distributed under the License is distributed on an "AS IS" BASIS,
73 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
74 // implied. See the License for the specific language governing
75 // permissions and limitations under the License.
78 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";
79 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
80 //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";
81 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
82 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
83 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
85 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
86 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
88 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
89 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
90 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";
91 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
92 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
93 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
94 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]|$))";
95 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]|$))";
96 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
97 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
98 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
99 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
100 private const string url_valid_port_number = @"[0-9]+";
102 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
103 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
104 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
105 private const string pth = "(?:" +
107 url_valid_general_path_chars + "*" +
108 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
109 url_valid_path_ending_chars +
110 ")|(?:@" + url_valid_general_path_chars + "+/)" +
112 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
113 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
114 "(?<url>(?<protocol>https?://)?" +
115 "(?<domain>" + url_valid_domain + ")" +
116 "(?::" + url_valid_port_number + ")?" +
117 "(?<path>/" + pth + "*)?" +
124 /// Twitter API のステータスページのURL
126 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
129 /// ツイートへのパーマリンクURLを判定する正規表現
131 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
134 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
136 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
137 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
138 | favstar\.fm/t/ # Favstar (short)
139 | aclog\.koba789\.com/i/ # aclog
140 | frtrt\.net/solo_status\.php\?status= # RtRT
141 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
144 /// DM送信かどうかを判定する正規表現
146 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
148 public TwitterApi Api { get; }
149 public TwitterConfiguration Configuration { get; private set; }
151 delegate void GetIconImageDelegate(PostClass post);
152 private readonly object LockObj = new object();
153 private ISet<long> followerId = new HashSet<long>();
154 private bool _GetFollowerResult = false;
155 private long[] noRTId = new long[0];
156 private bool _GetNoRetweetResult = false;
159 private string _uname;
161 private bool _readOwnPost;
162 private List<string> _hashList = new List<string>();
164 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
165 private long minDirectmessage = long.MaxValue;
166 private long minDirectmessageSent = long.MaxValue;
168 private long previousStatusId = -1L;
170 //private FavoriteQueue favQueue;
172 //private List<PostClass> _deletemessages = new List<PostClass>();
174 public Twitter() : this(new TwitterApi())
178 public Twitter(TwitterApi api)
181 this.Configuration = TwitterConfiguration.DefaultConfiguration();
184 public TwitterApiAccessLevel AccessLevel
188 return MyCommon.TwitterApiInfo.AccessLevel;
192 protected void ResetApiStatus()
194 MyCommon.TwitterApiInfo.Reset();
197 public void ClearAuthInfo()
199 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
200 this.ResetApiStatus();
204 public void VerifyCredentials()
208 this.VerifyCredentialsAsync().Wait();
210 catch (AggregateException ex) when (ex.InnerException is WebApiException)
212 throw new WebApiException(ex.InnerException.Message, ex);
216 public async Task VerifyCredentialsAsync()
218 var user = await this.Api.AccountVerifyCredentials()
219 .ConfigureAwait(false);
221 this.UpdateUserStats(user);
224 public void Initialize(string token, string tokenSecret, string username, long userId)
227 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
229 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
231 this.ResetApiStatus();
232 this.Api.Initialize(token, tokenSecret, userId, username);
233 _uname = username.ToLowerInvariant();
234 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
237 public string PreProcessUrl(string orgData)
241 //var IDNConveter = new IdnMapping();
242 var href = "<a href=\"";
246 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
250 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
251 posl1 += href.Length;
252 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
253 urlStr = orgData.Substring(posl1, posl2 - posl1);
255 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
256 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
257 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
262 var replacedUrl = MyCommon.IDNEncode(urlStr);
263 if (replacedUrl == null) continue;
264 if (replacedUrl == urlStr) continue;
266 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
277 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
279 this.CheckAccountState();
281 if (mediaIds == null &&
282 Twitter.DMSendTextRegex.IsMatch(postStr))
284 await this.SendDirectMessage(postStr)
285 .ConfigureAwait(false);
289 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
290 .ConfigureAwait(false);
292 var status = await response.LoadJsonAsync()
293 .ConfigureAwait(false);
295 this.UpdateUserStats(status.User);
297 if (status.Id == this.previousStatusId)
298 throw new WebApiException("OK:Delaying?");
300 this.previousStatusId = status.Id;
303 public async Task<long> UploadMedia(IMediaItem item)
305 this.CheckAccountState();
307 var response = await this.Api.MediaUpload(item)
308 .ConfigureAwait(false);
310 var media = await response.LoadJsonAsync()
311 .ConfigureAwait(false);
313 return media.MediaId;
316 public async Task SendDirectMessage(string postStr)
318 this.CheckAccountState();
319 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
321 var mc = Twitter.DMSendTextRegex.Match(postStr);
323 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
324 .ConfigureAwait(false);
326 var dm = await response.LoadJsonAsync()
327 .ConfigureAwait(false);
329 this.UpdateUserStats(dm.Sender);
332 public async Task PostRetweet(long id, bool read)
334 this.CheckAccountState();
338 var post = TabInformations.GetInstance()[id];
341 throw new WebApiException("Err:Target isn't found.");
343 if (TabInformations.GetInstance()[id].RetweetedId != null)
345 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
348 var response = await this.Api.StatusesRetweet(target)
349 .ConfigureAwait(false);
351 var status = await response.LoadJsonAsync()
352 .ConfigureAwait(false);
355 post = CreatePostsFromStatusData(status);
357 throw new WebApiException("Invalid Json!");
362 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
366 if (post.RetweetedId == null)
367 throw new WebApiException("Invalid Json!");
373 if (_readOwnPost) post.IsRead = true;
376 TabInformations.GetInstance().AddPost(post);
379 public string Username
380 => this.Api.CurrentScreenName;
383 => this.Api.CurrentUserId;
385 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
386 public static MyCommon.ACCOUNT_STATE AccountState
390 return _accountState;
394 _accountState = value;
398 public bool RestrictFavCheck { get; set; }
400 public bool ReadOwnPost
408 _readOwnPost = value;
412 public int FollowersCount { get; private set; }
413 public int FriendsCount { get; private set; }
414 public int StatusesCount { get; private set; }
415 public string Location { get; private set; } = "";
416 public string Bio { get; private set; } = "";
418 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
419 private void UpdateUserStats(TwitterUser self)
421 this.FollowersCount = self.FollowersCount;
422 this.FriendsCount = self.FriendsCount;
423 this.StatusesCount = self.StatusesCount;
424 this.Location = self.Location;
425 this.Bio = self.Description;
429 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
431 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
433 return count >= 20 && count <= GetMaxApiResultCount(type);
437 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
439 public static bool VerifyMoreApiResultCount(int count)
441 return count >= 20 && count <= 200;
445 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
447 public static bool VerifyFirstApiResultCount(int count)
449 return count >= 20 && count <= 200;
453 /// WORKERTYPEに応じた取得可能な最大件数を取得する
455 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
457 // 参照: REST APIs - 各endpointのcountパラメータ
458 // https://dev.twitter.com/rest/public
461 case MyCommon.WORKERTYPE.Timeline:
462 case MyCommon.WORKERTYPE.Reply:
463 case MyCommon.WORKERTYPE.UserTimeline:
464 case MyCommon.WORKERTYPE.Favorites:
465 case MyCommon.WORKERTYPE.DirectMessegeRcv:
466 case MyCommon.WORKERTYPE.DirectMessegeSnt:
467 case MyCommon.WORKERTYPE.List: // 不明
470 case MyCommon.WORKERTYPE.PublicSearch:
474 throw new InvalidOperationException("Invalid type: " + type);
479 /// WORKERTYPEに応じた取得件数を取得する
481 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
483 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
484 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
489 if (SettingCommon.Instance.UseAdditionalCount)
493 case MyCommon.WORKERTYPE.Favorites:
494 if (SettingCommon.Instance.FavoritesCountApi != 0)
495 return SettingCommon.Instance.FavoritesCountApi;
497 case MyCommon.WORKERTYPE.List:
498 if (SettingCommon.Instance.ListCountApi != 0)
499 return SettingCommon.Instance.ListCountApi;
501 case MyCommon.WORKERTYPE.PublicSearch:
502 if (SettingCommon.Instance.SearchCountApi != 0)
503 return SettingCommon.Instance.SearchCountApi;
505 case MyCommon.WORKERTYPE.UserTimeline:
506 if (SettingCommon.Instance.UserTimelineCountApi != 0)
507 return SettingCommon.Instance.UserTimelineCountApi;
510 if (more && SettingCommon.Instance.MoreCountApi != 0)
512 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
514 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
516 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
521 var count = SettingCommon.Instance.CountApi;
523 if (type == MyCommon.WORKERTYPE.Reply)
524 count = SettingCommon.Instance.CountApiReply;
526 return Math.Min(count, GetMaxApiResultCount(type));
529 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
531 this.CheckAccountState();
533 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
535 TwitterStatus[] statuses;
538 statuses = await this.Api.StatusesHomeTimeline(count, maxId: tab.OldestId)
539 .ConfigureAwait(false);
543 statuses = await this.Api.StatusesHomeTimeline(count)
544 .ConfigureAwait(false);
547 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
548 if (minimumId != null)
549 tab.OldestId = minimumId.Value;
552 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
554 this.CheckAccountState();
556 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
558 TwitterStatus[] statuses;
561 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
562 .ConfigureAwait(false);
566 statuses = await this.Api.StatusesMentionsTimeline(count)
567 .ConfigureAwait(false);
570 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
571 if (minimumId != null)
572 tab.OldestId = minimumId.Value;
575 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
577 this.CheckAccountState();
579 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
581 TwitterStatus[] statuses;
582 if (string.IsNullOrEmpty(userName))
584 var target = tab.ScreenName;
585 if (string.IsNullOrEmpty(target)) return;
587 statuses = await this.Api.StatusesUserTimeline(userName, count)
588 .ConfigureAwait(false);
594 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
595 .ConfigureAwait(false);
599 statuses = await this.Api.StatusesUserTimeline(userName, count)
600 .ConfigureAwait(false);
604 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
606 if (minimumId != null)
607 tab.OldestId = minimumId.Value;
610 public async Task<PostClass> GetStatusApi(bool read, long id)
612 this.CheckAccountState();
614 var status = await this.Api.StatusesShow(id)
615 .ConfigureAwait(false);
617 var item = CreatePostsFromStatusData(status);
619 throw new WebApiException("Err:Can't create post");
622 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
627 public async Task GetStatusApi(bool read, long id, TabModel tab)
629 var post = await this.GetStatusApi(read, id)
630 .ConfigureAwait(false);
632 //非同期アイコン取得&StatusDictionaryに追加
633 if (tab != null && tab.IsInnerStorageTabType)
634 tab.AddPostQueue(post);
636 TabInformations.GetInstance().AddPost(post);
639 private PostClass CreatePostsFromStatusData(TwitterStatus status)
641 return CreatePostsFromStatusData(status, false);
644 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
646 var post = new PostClass();
647 TwitterEntities entities;
650 post.StatusId = status.Id;
651 if (status.RetweetedStatus != null)
653 var retweeted = status.RetweetedStatus;
655 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
658 post.RetweetedId = retweeted.Id;
660 post.TextFromApi = retweeted.Text;
661 entities = retweeted.MergedEntities;
662 sourceHtml = retweeted.Source;
664 post.InReplyToStatusId = retweeted.InReplyToStatusId;
665 post.InReplyToUser = retweeted.InReplyToScreenName;
666 post.InReplyToUserId = status.InReplyToUserId;
675 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
676 post.IsFav = tc.Contains(retweeted.Id);
679 if (retweeted.Coordinates != null)
680 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
683 var user = retweeted.User;
686 post.UserId = user.Id;
687 post.ScreenName = user.ScreenName;
688 post.Nickname = user.Name.Trim();
689 post.ImageUrl = user.ProfileImageUrlHttps;
690 post.IsProtect = user.Protected;
695 post.ScreenName = "?????";
696 post.Nickname = "Unknown User";
700 if (status.User != null)
702 post.RetweetedBy = status.User.ScreenName;
703 post.RetweetedByUserId = status.User.Id;
704 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
708 post.RetweetedBy = "?????";
709 post.RetweetedByUserId = 0L;
714 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
716 post.TextFromApi = status.Text;
717 entities = status.MergedEntities;
718 sourceHtml = status.Source;
719 post.InReplyToStatusId = status.InReplyToStatusId;
720 post.InReplyToUser = status.InReplyToScreenName;
721 post.InReplyToUserId = status.InReplyToUserId;
730 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
731 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
734 if (status.Coordinates != null)
735 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
738 var user = status.User;
741 post.UserId = user.Id;
742 post.ScreenName = user.ScreenName;
743 post.Nickname = user.Name.Trim();
744 post.ImageUrl = user.ProfileImageUrlHttps;
745 post.IsProtect = user.Protected;
746 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
751 post.ScreenName = "?????";
752 post.Nickname = "Unknown User";
756 string textFromApi = post.TextFromApi;
757 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
758 post.TextFromApi = textFromApi;
759 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
760 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
761 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
762 post.AccessibleText = this.CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus);
763 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
764 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
766 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
767 .Where(x => x != post.StatusId && x != post.RetweetedId)
768 .Distinct().ToArray();
770 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
771 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
774 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
775 if (post.Text == post.TextFromApi)
776 post.Text = post.TextFromApi;
777 if (post.AccessibleText == post.TextFromApi)
778 post.AccessibleText = post.TextFromApi;
780 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
781 post.ScreenName = string.Intern(post.ScreenName);
782 post.Nickname = string.Intern(post.Nickname);
783 post.ImageUrl = string.Intern(post.ImageUrl);
784 post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
787 var source = ParseSource(sourceHtml);
788 post.Source = string.Intern(source.Item1);
789 post.SourceUri = source.Item2;
791 post.IsReply = post.ReplyToList.Contains(_uname);
792 post.IsExcludeReply = false;
800 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
808 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
810 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
812 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
814 return GetQuoteTweetStatusIds(urls);
817 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
819 foreach (var url in urls)
821 var match = Twitter.StatusUrlRegex.Match(url);
825 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
826 yield return statusId;
831 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
833 long? minimumId = null;
835 foreach (var status in items)
837 PostClass post = null;
838 post = CreatePostsFromStatusData(status);
839 if (post == null) continue;
841 if (minimumId == null || minimumId.Value > post.StatusId)
842 minimumId = post.StatusId;
849 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
853 if (tab.Contains(post.StatusId)) continue;
858 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
859 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
862 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
864 //非同期アイコン取得&StatusDictionaryに追加
865 if (tab != null && tab.IsInnerStorageTabType)
866 tab.AddPostQueue(post);
868 TabInformations.GetInstance().AddPost(post);
874 private long? CreatePostsFromSearchJson(TwitterSearchResult items, TabModel tab, bool read, int count, bool more)
876 long? minimumId = null;
878 foreach (var result in items.Statuses)
880 var post = CreatePostsFromStatusData(result);
884 if (minimumId == null || minimumId.Value > post.StatusId)
885 minimumId = post.StatusId;
887 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
893 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
897 if (tab.Contains(post.StatusId)) continue;
902 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
904 //非同期アイコン取得&StatusDictionaryに追加
905 if (tab != null && tab.IsInnerStorageTabType)
906 tab.AddPostQueue(post);
908 TabInformations.GetInstance().AddPost(post);
914 private void CreateFavoritePostsFromJson(TwitterStatus[] item, bool read)
916 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
918 foreach (var status in item)
923 if (favTab.Contains(status.Id)) continue;
926 var post = CreatePostsFromStatusData(status, true);
927 if (post == null) continue;
931 TabInformations.GetInstance().AddPost(post);
935 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
937 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
939 TwitterStatus[] statuses;
942 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
943 .ConfigureAwait(false);
947 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
948 .ConfigureAwait(false);
951 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
953 if (minimumId != null)
954 tab.OldestId = minimumId.Value;
958 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
960 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
961 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
963 if (!posts.ContainsKey(startStatusId))
964 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
966 var nextPost = posts[startStatusId];
967 while (nextPost.InReplyToStatusId != null)
969 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
971 nextPost = posts[nextPost.InReplyToStatusId.Value];
977 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
979 var targetPost = tab.TargetPost;
980 var relPosts = new Dictionary<Int64, PostClass>();
981 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
984 var p = TabInformations.GetInstance()[targetPost.StatusId];
985 if (p != null && p.InReplyToStatusId != null)
991 p = await this.GetStatusApi(read, targetPost.StatusId)
992 .ConfigureAwait(false);
996 relPosts.Add(targetPost.StatusId, targetPost);
998 Exception lastException = null;
1000 // in_reply_to_status_id を使用してリプライチェインを辿る
1001 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1003 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1005 var inReplyToId = nextPost.InReplyToStatusId.Value;
1007 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1008 if (inReplyToPost == null)
1012 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1013 .ConfigureAwait(false);
1015 catch (WebApiException ex)
1022 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1024 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1027 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1028 var text = targetPost.Text;
1029 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1030 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1031 foreach (var _match in ma)
1034 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1036 if (relPosts.ContainsKey(_statusId))
1039 var p = TabInformations.GetInstance()[_statusId];
1044 p = await this.GetStatusApi(read, _statusId)
1045 .ConfigureAwait(false);
1047 catch (WebApiException ex)
1055 relPosts.Add(p.StatusId, p);
1059 relPosts.Values.ToList().ForEach(p =>
1061 if (p.IsMe && !read && this._readOwnPost)
1066 tab.AddPostQueue(p);
1069 if (lastException != null)
1070 throw new WebApiException(lastException.Message, lastException);
1073 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1075 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1078 long? sinceId = null;
1081 maxId = tab.OldestId - 1;
1085 sinceId = tab.SinceId;
1088 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1089 .ConfigureAwait(false);
1091 if (!TabInformations.GetInstance().ContainsTab(tab))
1094 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, count, more);
1096 if (minimumId != null)
1097 tab.OldestId = minimumId.Value;
1100 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1102 foreach (var message in item)
1104 var post = new PostClass();
1107 post.StatusId = message.Id;
1108 if (gType != MyCommon.WORKERTYPE.UserStream)
1110 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1112 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1116 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1123 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1127 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1129 var textFromApi = message.Text;
1131 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1132 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1133 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1134 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1135 post.AccessibleText = this.CreateAccessibleText(textFromApi, message.Entities, quoteStatus: null);
1136 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1137 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1140 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1142 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1143 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1148 if (gType == MyCommon.WORKERTYPE.UserStream)
1150 if (this.Api.CurrentUserId == message.Recipient.Id)
1152 user = message.Sender;
1158 user = message.Recipient;
1165 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1167 user = message.Sender;
1173 user = message.Recipient;
1179 post.UserId = user.Id;
1180 post.ScreenName = user.ScreenName;
1181 post.Nickname = user.Name.Trim();
1182 post.ImageUrl = user.ProfileImageUrlHttps;
1183 post.IsProtect = user.Protected;
1185 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1186 if (post.Text == post.TextFromApi)
1187 post.Text = post.TextFromApi;
1188 if (post.AccessibleText == post.TextFromApi)
1189 post.AccessibleText = post.TextFromApi;
1191 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1192 post.ScreenName = string.Intern(post.ScreenName);
1193 post.Nickname = string.Intern(post.Nickname);
1194 post.ImageUrl = string.Intern(post.ImageUrl);
1198 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1199 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1204 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1205 post.IsReply = false;
1206 post.IsExcludeReply = false;
1209 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1210 dmTab.AddPostQueue(post);
1214 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1216 this.CheckAccountState();
1217 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1219 var count = GetApiResultCount(gType, more, false);
1221 TwitterDirectMessage[] messages;
1222 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1226 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1227 .ConfigureAwait(false);
1231 messages = await this.Api.DirectMessagesRecv(count)
1232 .ConfigureAwait(false);
1239 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1240 .ConfigureAwait(false);
1244 messages = await this.Api.DirectMessagesSent(count)
1245 .ConfigureAwait(false);
1249 CreateDirectMessagesFromJson(messages, gType, read);
1252 public async Task GetFavoritesApi(bool read, bool more)
1254 this.CheckAccountState();
1256 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1258 var statuses = await this.Api.FavoritesList(count)
1259 .ConfigureAwait(false);
1261 CreateFavoritePostsFromJson(statuses, read);
1264 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1266 if (entities != null)
1268 if (entities.Urls != null)
1270 foreach (var m in entities.Urls)
1272 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1275 if (entities.Media != null)
1277 foreach (var m in entities.Media)
1279 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1286 private string CreateAccessibleText(string text, TwitterEntities entities, TwitterStatus quoteStatus)
1288 if (entities == null)
1291 if (entities.Urls != null)
1293 foreach (var entity in entities.Urls)
1295 if (quoteStatus != null)
1297 var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1298 if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quoteStatus.IdStr)
1300 var quoteText = this.CreateAccessibleText(quoteStatus.Text, quoteStatus.MergedEntities, quoteStatus: null);
1301 text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quoteStatus.User.ScreenName, quoteText));
1304 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1306 text = text.Replace(entity.Url, entity.DisplayUrl);
1311 if (entities.Media != null)
1313 foreach (var entity in entities.Media)
1315 if (!string.IsNullOrEmpty(entity.AltText))
1317 text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1319 else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1321 text = text.Replace(entity.Url, entity.DisplayUrl);
1332 /// <exception cref="WebApiException"/>
1333 public async Task RefreshFollowerIds()
1335 if (MyCommon._endingFlag) return;
1338 var newFollowerIds = new HashSet<long>();
1341 var ret = await this.Api.FollowersIds(cursor)
1342 .ConfigureAwait(false);
1344 if (ret.Ids == null)
1345 throw new WebApiException("ret.ids == null");
1347 newFollowerIds.UnionWith(ret.Ids);
1348 cursor = ret.NextCursor;
1349 } while (cursor != 0);
1351 this.followerId = newFollowerIds;
1352 TabInformations.GetInstance().RefreshOwl(this.followerId);
1354 this._GetFollowerResult = true;
1357 public bool GetFollowersSuccess
1361 return _GetFollowerResult;
1366 /// RT 非表示ユーザーを更新します
1368 /// <exception cref="WebApiException"/>
1369 public async Task RefreshNoRetweetIds()
1371 if (MyCommon._endingFlag) return;
1373 this.noRTId = await this.Api.NoRetweetIds()
1374 .ConfigureAwait(false);
1376 this._GetNoRetweetResult = true;
1379 public bool GetNoRetweetSuccess
1383 return _GetNoRetweetResult;
1388 /// t.co の文字列長などの設定情報を更新します
1390 /// <exception cref="WebApiException"/>
1391 public async Task RefreshConfiguration()
1393 this.Configuration = await this.Api.Configuration()
1394 .ConfigureAwait(false);
1397 public async Task GetListsApi()
1399 this.CheckAccountState();
1401 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1402 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1403 .ConfigureAwait(false);
1405 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1406 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1407 .ConfigureAwait(false);
1409 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1410 .Select(x => new ListElement(x, this))
1414 public async Task DeleteList(long listId)
1416 await this.Api.ListsDestroy(listId)
1418 .ConfigureAwait(false);
1420 var tabinfo = TabInformations.GetInstance();
1422 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1423 .Where(x => x.Id != listId)
1427 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1429 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1430 .ConfigureAwait(false);
1432 var list = await response.LoadJsonAsync()
1433 .ConfigureAwait(false);
1435 return new ListElement(list, this);
1438 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1440 this.CheckAccountState();
1442 var users = await this.Api.ListsMembers(listId, cursor)
1443 .ConfigureAwait(false);
1445 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1447 return users.NextCursor;
1450 public async Task CreateListApi(string listName, bool isPrivate, string description)
1452 this.CheckAccountState();
1454 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1455 .ConfigureAwait(false);
1457 var list = await response.LoadJsonAsync()
1458 .ConfigureAwait(false);
1460 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1463 public async Task<bool> ContainsUserAtList(long listId, string user)
1465 this.CheckAccountState();
1469 await this.Api.ListsMembersShow(listId, user)
1470 .ConfigureAwait(false);
1474 catch (TwitterApiException ex)
1475 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1481 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1483 if (entities != null)
1485 if (entities.Hashtags != null)
1489 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1492 if (entities.UserMentions != null)
1494 foreach (var ent in entities.UserMentions)
1496 var screenName = ent.ScreenName.ToLowerInvariant();
1497 if (!AtList.Contains(screenName))
1498 AtList.Add(screenName);
1501 if (entities.Media != null)
1505 foreach (var ent in entities.Media)
1507 if (!media.Any(x => x.Url == ent.MediaUrl))
1509 if (ent.VideoInfo != null &&
1510 ent.Type == "animated_gif" || ent.Type == "video")
1512 //var videoUrl = ent.VideoInfo.Variants
1513 // .Where(v => v.ContentType == "video/mp4")
1514 // .OrderByDescending(v => v.Bitrate)
1515 // .Select(v => v.Url).FirstOrDefault();
1516 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1519 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1526 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1527 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1529 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>");
1530 text = PreProcessUrl(text); //IDN置換
1535 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1538 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1540 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1542 if (string.IsNullOrEmpty(sourceHtml))
1543 return Tuple.Create<string, Uri>("", null);
1548 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1550 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1553 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1556 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1557 sourceUri = new Uri(SourceUriBase, uriStr);
1559 catch (UriFormatException)
1566 sourceText = WebUtility.HtmlDecode(sourceHtml);
1570 return Tuple.Create(sourceText, sourceUri);
1573 public async Task<TwitterApiStatus> GetInfoApi()
1575 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1577 if (MyCommon._endingFlag) return null;
1579 var limits = await this.Api.ApplicationRateLimitStatus()
1580 .ConfigureAwait(false);
1582 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1584 return MyCommon.TwitterApiInfo;
1588 /// ブロック中のユーザーを更新します
1590 /// <exception cref="WebApiException"/>
1591 public async Task RefreshBlockIds()
1593 if (MyCommon._endingFlag) return;
1596 var newBlockIds = new HashSet<long>();
1599 var ret = await this.Api.BlocksIds(cursor)
1600 .ConfigureAwait(false);
1602 newBlockIds.UnionWith(ret.Ids);
1603 cursor = ret.NextCursor;
1604 } while (cursor != 0);
1606 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1608 TabInformations.GetInstance().BlockIds = newBlockIds;
1612 /// ミュート中のユーザーIDを更新します
1614 /// <exception cref="WebApiException"/>
1615 public async Task RefreshMuteUserIdsAsync()
1617 if (MyCommon._endingFlag) return;
1619 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1620 .ConfigureAwait(false);
1622 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1625 public string[] GetHashList()
1630 hashArray = _hashList.ToArray();
1636 public string AccessToken
1637 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1639 public string AccessTokenSecret
1640 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1642 private void CheckAccountState()
1644 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1645 throw new WebApiException("Auth error. Check your account");
1648 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1650 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1651 throw new WebApiException("Auth Err:try to re-authorization.");
1654 public int GetTextLengthRemain(string postText)
1656 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1657 if (matchDm.Success)
1658 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1660 return this.GetTextLengthRemainInternal(postText, isDm: false);
1663 private int GetTextLengthRemainInternal(string postText, bool isDm)
1668 while (pos < postText.Length)
1672 if (char.IsSurrogatePair(postText, pos))
1673 pos += 2; // サロゲートペアの場合は2文字分進める
1678 var urls = TweetExtractor.ExtractUrls(postText);
1679 foreach (var url in urls)
1681 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1682 ? this.Configuration.ShortUrlLengthHttps
1683 : this.Configuration.ShortUrlLength;
1685 textLength += shortUrlLength - url.Length;
1689 return this.Configuration.DmTextCharacterLimit - textLength;
1691 return 140 - textLength;
1695 #region "UserStream"
1696 private string trackWord_ = "";
1697 public string TrackWord
1708 private bool allAtReply_ = false;
1709 public bool AllAtReply
1717 allAtReply_ = value;
1721 public event EventHandler NewPostFromStream;
1722 public event EventHandler UserStreamStarted;
1723 public event EventHandler UserStreamStopped;
1724 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1725 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1726 private DateTime _lastUserstreamDataReceived;
1727 private TwitterUserstream userStream;
1729 public class FormattedEvent
1731 public MyCommon.EVENTTYPE Eventtype { get; set; }
1732 public DateTime CreatedAt { get; set; }
1733 public string Event { get; set; }
1734 public string Username { get; set; }
1735 public string Target { get; set; }
1736 public Int64 Id { get; set; }
1737 public bool IsMe { get; set; }
1740 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1741 public List<FormattedEvent> StoredEvent
1745 return storedEvent_;
1749 storedEvent_ = value;
1753 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1755 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1756 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1757 ["follow"] = MyCommon.EVENTTYPE.Follow,
1758 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1759 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1760 ["block"] = MyCommon.EVENTTYPE.Block,
1761 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1762 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1763 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1764 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1765 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1766 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1767 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1768 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1769 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1770 ["mute"] = MyCommon.EVENTTYPE.Mute,
1771 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1772 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1775 public bool IsUserstreamDataReceived
1779 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
1783 private void userStream_StatusArrived(string line)
1785 this._lastUserstreamDataReceived = DateTime.Now;
1786 if (string.IsNullOrEmpty(line)) return;
1788 if (line.First() != '{' || line.Last() != '}')
1790 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
1798 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
1800 var xElm = XElement.Load(jsonReader);
1801 if (xElm.Element("friends") != null)
1803 Debug.WriteLine("friends");
1806 else if (xElm.Element("delete") != null)
1808 Debug.WriteLine("delete");
1811 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
1814 long.TryParse(idElm.Value, out id);
1816 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1818 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
1821 long.TryParse(idElm.Value, out id);
1823 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1827 MyCommon.TraceOut("delete:" + line);
1830 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
1832 var sEvt = this.StoredEvent[i];
1833 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
1835 this.StoredEvent.RemoveAt(i);
1840 else if (xElm.Element("limit") != null)
1842 Debug.WriteLine(line);
1845 else if (xElm.Element("event") != null)
1847 Debug.WriteLine("event: " + xElm.Element("event").Value);
1848 CreateEventFromJson(line);
1851 else if (xElm.Element("direct_message") != null)
1853 Debug.WriteLine("direct_message");
1856 else if (xElm.Element("retweeted_status") != null)
1858 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
1859 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
1861 // 自分に関係しないリツイートの場合は無視する
1862 var selfUserId = this.UserId.ToString();
1863 if (sourceUserId == selfUserId || targetUserId == selfUserId)
1865 // 公式 RT をイベントとしても扱う
1866 var evt = CreateEventFromRetweet(xElm);
1869 this.StoredEvent.Insert(0, evt);
1871 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
1875 // 従来通り公式 RT の表示も行うため return しない
1877 else if (xElm.Element("scrub_geo") != null)
1881 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
1882 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
1886 MyCommon.TraceOut("scrub_geo:" + line);
1896 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
1897 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
1899 catch (SerializationException ex)
1901 throw TwitterApiException.CreateFromException(ex, line);
1908 var status = TwitterStatus.ParseJson(line);
1909 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
1911 catch (SerializationException ex)
1913 throw TwitterApiException.CreateFromException(ex, line);
1917 catch (WebApiException ex)
1919 MyCommon.TraceOut(ex);
1922 catch(NullReferenceException)
1924 MyCommon.TraceOut("NullRef StatusArrived: " + line);
1927 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
1931 /// UserStreamsから受信した公式RTをイベントに変換します
1933 private FormattedEvent CreateEventFromRetweet(XElement xElm)
1935 return new FormattedEvent
1937 Eventtype = MyCommon.EVENTTYPE.Retweet,
1939 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
1940 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
1941 Username = xElm.XPathSelectElement("/user/screen_name").Value,
1942 Target = string.Format("@{0}:{1}", new[]
1944 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
1945 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
1947 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
1951 private void CreateEventFromJson(string content)
1953 TwitterStreamEvent eventData = null;
1956 eventData = TwitterStreamEvent.ParseJson(content);
1958 catch(SerializationException ex)
1960 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
1964 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
1967 var evt = new FormattedEvent();
1968 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
1969 evt.Event = eventData.Event;
1970 evt.Username = eventData.Source.ScreenName;
1971 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
1973 MyCommon.EVENTTYPE eventType;
1974 eventTable.TryGetValue(eventData.Event, out eventType);
1975 evt.Eventtype = eventType;
1977 TwitterStreamEvent<TwitterStatus> tweetEvent;
1979 switch (eventData.Event)
1981 case "access_revoked":
1982 case "access_unrevoked":
1984 case "user_suspend":
1987 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
1989 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
1993 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
1998 evt.Target = "@" + eventData.Target.ScreenName;
2000 case "favorited_retweet":
2001 case "retweeted_retweet":
2005 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2006 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2007 evt.Id = tweetEvent.TargetObject.Id;
2009 if (SettingCommon.Instance.IsRemoveSameEvent)
2011 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2015 var tabinfo = TabInformations.GetInstance();
2018 var statusId = tweetEvent.TargetObject.Id;
2019 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2022 if (eventData.Event == "favorite")
2024 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2025 if (!favTab.Contains(post.StatusId))
2026 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2028 if (tweetEvent.Source.Id == this.UserId)
2032 else if (tweetEvent.Target.Id == this.UserId)
2034 post.FavoritedCount++;
2036 if (SettingCommon.Instance.FavEventUnread)
2037 tabinfo.SetReadAllTab(post.StatusId, read: false);
2042 if (tweetEvent.Source.Id == this.UserId)
2046 else if (tweetEvent.Target.Id == this.UserId)
2048 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2052 case "quoted_tweet":
2053 if (evt.IsMe) return;
2055 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2056 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2057 evt.Id = tweetEvent.TargetObject.Id;
2059 if (SettingCommon.Instance.IsRemoveSameEvent)
2061 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2065 case "list_member_added":
2066 case "list_member_removed":
2067 case "list_created":
2068 case "list_destroyed":
2069 case "list_updated":
2070 case "list_user_subscribed":
2071 case "list_user_unsubscribed":
2072 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2073 evt.Target = listEvent.TargetObject.FullName;
2076 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2080 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2089 evt.Target = "@" + eventData.Target.ScreenName;
2090 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2092 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2096 evt.Target = "@" + eventData.Target.ScreenName;
2097 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2099 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2104 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2107 this.StoredEvent.Insert(0, evt);
2109 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2112 private void userStream_Started()
2114 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2117 private void userStream_Stopped()
2119 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2122 public bool UserStreamActive
2123 => this.userStream != null && this.userStream.IsStreamActive;
2125 public void StartUserStream()
2127 var newStream = new TwitterUserstream(this.Api);
2129 newStream.StatusArrived += userStream_StatusArrived;
2130 newStream.Started += userStream_Started;
2131 newStream.Stopped += userStream_Stopped;
2133 newStream.Start(this.AllAtReply, this.TrackWord);
2135 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2136 oldStream?.Dispose();
2139 public void StopUserStream()
2141 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2142 oldStream?.Dispose();
2145 public void ReconnectUserStream()
2147 if (this.userStream != null)
2149 this.StartUserStream();
2153 private class TwitterUserstream : IDisposable
2155 public bool AllAtReplies { get; private set; }
2156 public string TrackWords { get; private set; }
2158 public bool IsStreamActive { get; private set; }
2160 public event Action<string> StatusArrived;
2161 public event Action Stopped;
2162 public event Action Started;
2164 private TwitterApi twitterApi;
2166 private Task streamTask;
2167 private CancellationTokenSource streamCts;
2169 public TwitterUserstream(TwitterApi twitterApi)
2171 this.twitterApi = twitterApi;
2174 public void Start(bool allAtReplies, string trackwords)
2176 this.AllAtReplies = allAtReplies;
2177 this.TrackWords = trackwords;
2179 var cts = new CancellationTokenSource();
2181 this.streamCts = cts;
2182 this.streamTask = Task.Run(async () =>
2186 await this.UserStreamLoop(cts.Token)
2187 .ConfigureAwait(false);
2189 catch (OperationCanceledException) { }
2195 this.streamCts?.Cancel();
2197 // streamTask の完了を待たずに IsStreamActive を false にセットする
2198 this.IsStreamActive = false;
2199 this.Stopped?.Invoke();
2202 private async Task UserStreamLoop(CancellationToken cancellationToken)
2204 TimeSpan sleep = TimeSpan.Zero;
2207 if (sleep != TimeSpan.Zero)
2209 await Task.Delay(sleep, cancellationToken)
2210 .ConfigureAwait(false);
2211 sleep = TimeSpan.Zero;
2214 if (!MyCommon.IsNetworkAvailable())
2216 sleep = TimeSpan.FromSeconds(30);
2220 this.IsStreamActive = true;
2221 this.Started?.Invoke();
2225 var replies = this.AllAtReplies ? "all" : null;
2227 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2228 .ConfigureAwait(false))
2229 using (var reader = new StreamReader(stream))
2231 while (!reader.EndOfStream)
2233 var line = await reader.ReadLineAsync()
2234 .ConfigureAwait(false);
2236 cancellationToken.ThrowIfCancellationRequested();
2238 this.StatusArrived?.Invoke(line);
2242 // キャンセルされていないのにストリームが終了した場合
2243 sleep = TimeSpan.FromSeconds(30);
2245 catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2246 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2247 catch (OperationCanceledException)
2249 if (cancellationToken.IsCancellationRequested)
2252 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2253 sleep = TimeSpan.FromSeconds(30);
2255 catch (Exception ex)
2257 MyCommon.ExceptionOut(ex);
2258 sleep = TimeSpan.FromSeconds(30);
2262 this.IsStreamActive = false;
2263 this.Stopped?.Invoke();
2268 private bool disposed = false;
2270 public void Dispose()
2275 this.disposed = true;
2279 this.Started = null;
2280 this.Stopped = null;
2281 this.StatusArrived = null;
2286 #region "IDisposable Support"
2287 private bool disposedValue; // 重複する呼び出しを検出するには
2290 protected virtual void Dispose(bool disposing)
2292 if (!this.disposedValue)
2296 this.StopUserStream();
2299 this.disposedValue = true;
2302 //protected Overrides void Finalize()
2304 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2306 // MyBase.Finalize()
2309 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2310 public void Dispose()
2312 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2314 GC.SuppressFinalize(this);
2319 public class PostDeletedEventArgs : EventArgs
2321 public long StatusId { get; }
2323 public PostDeletedEventArgs(long statusId)
2325 this.StatusId = statusId;
2329 public class UserStreamEventReceivedEventArgs : EventArgs
2331 public Twitter.FormattedEvent EventData { get; }
2333 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2335 this.EventData = eventData;