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.
31 using System.Collections.Generic;
32 using System.Diagnostics;
33 using System.Globalization;
37 using System.Net.Http;
38 using System.Reflection;
39 using System.Runtime.CompilerServices;
41 using System.Text.RegularExpressions;
42 using System.Threading;
43 using System.Threading.Tasks;
44 using System.Windows.Forms;
46 using OpenTween.Api.DataModel;
47 using OpenTween.Api.TwitterV2;
48 using OpenTween.Connection;
49 using OpenTween.Models;
50 using OpenTween.Setting;
54 public class Twitter : IDisposable
56 #region Regexp from twitter-text-js
58 // The code in this region code block incorporates works covered by
59 // the following copyright and permission notices:
61 // Copyright 2011 Twitter, Inc.
63 // Licensed under the Apache License, Version 2.0 (the "License"); you
64 // may not use this work except in compliance with the License. You
65 // may obtain a copy of the License in the LICENSE file, or at:
67 // http://www.apache.org/licenses/LICENSE-2.0
69 // Unless required by applicable law or agreed to in writing, software
70 // distributed under the License is distributed on an "AS IS" BASIS,
71 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
72 // implied. See the License for the specific language governing
73 // permissions and limitations under the License.
76 private const string LatinAccents = @"\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0100-\u024f\u0253\u0254\u0256\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff";
77 private const string NonLatinHashtagChars = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
78 private const string CJHashtagCharacters = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
79 private const string HashtagBoundary = @"^|$|\s|「|」|。|\.|!";
80 private const string HashtagAlpha = $"[A-Za-z_{LatinAccents}{NonLatinHashtagChars}{CJHashtagCharacters}]";
81 private const string HashtagAlphanumeric = $"[A-Za-z0-9_{LatinAccents}{NonLatinHashtagChars}{CJHashtagCharacters}]";
82 private const string HashtagTerminator = $"[^A-Za-z0-9_{LatinAccents}{NonLatinHashtagChars}{CJHashtagCharacters}]";
83 public const string Hashtag = $"({HashtagBoundary})(#|#)({HashtagAlphanumeric}*{HashtagAlpha}{HashtagAlphanumeric}*)(?={HashtagTerminator}|{HashtagBoundary})";
85 private const string UrlValidPrecedingChars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
86 public const string UrlInvalidWithoutProtocolPrecedingChars = @"[-_./]$";
87 private const string UrlInvalidDomainChars = @"\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$\u2000-\u200a\u0009-\u000d\u0020\u0085\u00a0\u1680\u180e\u2028\u2029\u202f\u205f\u3000\ufffe\ufeff\uffff\u202a-\u202e";
88 private const string UrlValidDomainChars = $@"[^{UrlInvalidDomainChars}]";
89 private const string UrlValidSubdomain = $@"(?:(?:{UrlValidDomainChars}(?:[_-]|{UrlValidDomainChars})*)?{UrlValidDomainChars}\.)";
90 private const string UrlValidDomainName = $@"(?:(?:{UrlValidDomainChars}(?:-|{UrlValidDomainChars})*)?{UrlValidDomainChars}\.)";
91 private const string UrlValidGTLD = @"(?:(?: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]|$))";
92 private const string UrlValidCCTLD = @"(?:(?: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]|$))";
93 private const string UrlValidPunycode = @"(?:xn--[0-9a-z]+)";
94 private const string UrlValidDomain = $@"(?<domain>{UrlValidSubdomain}*{UrlValidDomainName}(?:{UrlValidGTLD}|{UrlValidCCTLD})|{UrlValidPunycode})";
95 public const string UrlValidAsciiDomain = $@"(?:(?:[a-z0-9{LatinAccents}]+)\.)+(?:{UrlValidGTLD}|{UrlValidCCTLD}|{UrlValidPunycode})";
96 public const string UrlInvalidShortDomain = $"^{UrlValidDomainName}{UrlValidCCTLD}$";
97 private const string UrlValidPortNumber = @"[0-9]+";
99 private const string UrlValidGeneralPathChars = $@"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&{LatinAccents}]";
100 private const string UrlBalanceParens = $@"(?:\({UrlValidGeneralPathChars}+\))";
101 private const string UrlValidPathEndingChars = $@"(?:[+\-a-z0-9=_#/{LatinAccents}]|{UrlBalanceParens})";
102 private const string Pth = "(?:" +
104 $"{UrlValidGeneralPathChars}*" +
105 $"(?:{UrlBalanceParens}{UrlValidGeneralPathChars}*)*" +
106 UrlValidPathEndingChars +
107 $")|(?:@{UrlValidGeneralPathChars}+/)" +
110 private const string Qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
111 public const string RgUrl = $@"(?<before>{UrlValidPrecedingChars})" +
112 "(?<url>(?<protocol>https?://)?" +
113 $"(?<domain>{UrlValidDomain})" +
114 $"(?::{UrlValidPortNumber})?" +
115 $"(?<path>/{Pth}*)?" +
122 /// Twitter API のステータスページのURL
124 public const string ServiceAvailabilityStatusUrl = "https://api.twitterstat.us/";
127 /// ツイートへのパーマリンクURLを判定する正規表現
129 public static readonly Regex StatusUrlRegex = new(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
132 /// attachment_url に指定可能な URL を判定する正規表現
134 public static readonly Regex AttachmentUrlRegex = new(
136 twitter\.com/[0-9A-Za-z_]+/status/[0-9]+
137 | mobile\.twitter\.com/[0-9A-Za-z_]+/status/[0-9]+
138 | twitter\.com/messages/compose\?recipient_id=[0-9]+(&.+)?
140 RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
143 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
145 public static readonly Regex ThirdPartyStatusUrlRegex = new(
146 @"https?://(?:[^.]+\.)?(?:
147 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
148 | favstar\.fm/t/ # Favstar (short)
149 | aclog\.koba789\.com/i/ # aclog
150 | frtrt\.net/solo_status\.php\?status= # RtRT
151 )(?<StatusId>[0-9]+)",
152 RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
155 /// DM送信かどうかを判定する正規表現
157 public static readonly Regex DMSendTextRegex = new(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
159 public TwitterApi Api { get; }
161 public TwitterConfiguration Configuration { get; private set; }
163 public TwitterTextConfiguration TextConfiguration { get; private set; }
165 public bool GetFollowersSuccess { get; private set; } = false;
167 public bool GetNoRetweetSuccess { get; private set; } = false;
169 private delegate void GetIconImageDelegate(PostClass post);
171 private readonly object lockObj = new();
172 private ISet<long> followerId = new HashSet<long>();
173 private long[] noRTId = Array.Empty<long>();
175 // プロパティからアクセスされる共通情報
176 private readonly List<string> hashList = new();
178 private string? nextCursorDirectMessage = null;
180 private long previousStatusId = -1L;
182 public Twitter(TwitterApi api)
185 this.Configuration = TwitterConfiguration.DefaultConfiguration();
186 this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
189 public TwitterApiAccessLevel AccessLevel
190 => MyCommon.TwitterApiInfo.AccessLevel;
192 protected void ResetApiStatus()
193 => MyCommon.TwitterApiInfo.Reset();
195 public void ClearAuthInfo()
197 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
198 this.ResetApiStatus();
201 public void VerifyCredentials()
205 this.VerifyCredentialsAsync().Wait();
207 catch (AggregateException ex) when (ex.InnerException is WebApiException)
209 throw new WebApiException(ex.InnerException.Message, ex);
213 public async Task VerifyCredentialsAsync()
215 var user = await this.Api.AccountVerifyCredentials()
216 .ConfigureAwait(false);
218 this.UpdateUserStats(user);
221 public void Initialize(string token, string tokenSecret, string username, long userId)
224 if (MyCommon.IsNullOrEmpty(token) || MyCommon.IsNullOrEmpty(tokenSecret) || MyCommon.IsNullOrEmpty(username))
226 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
228 this.ResetApiStatus();
229 this.Api.Initialize(token, tokenSecret, userId, username);
232 internal static string PreProcessUrl(string orgData)
236 var href = "<a href=\"";
240 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
243 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
244 posl1 += href.Length;
245 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
246 var urlStr = orgData.Substring(posl1, posl2 - posl1);
248 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
249 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
250 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
255 var replacedUrl = MyCommon.IDNEncode(urlStr);
256 if (replacedUrl == null) continue;
257 if (replacedUrl == urlStr) continue;
259 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
270 public async Task<PostClass?> PostStatus(PostStatusParams param)
272 this.CheckAccountState();
274 if (Twitter.DMSendTextRegex.IsMatch(param.Text))
276 var mediaId = param.MediaIds != null && param.MediaIds.Any() ? param.MediaIds[0] : (long?)null;
278 await this.SendDirectMessage(param.Text, mediaId)
279 .ConfigureAwait(false);
283 var response = await this.Api.StatusesUpdate(
285 param.InReplyToStatusId,
287 param.AutoPopulateReplyMetadata,
288 param.ExcludeReplyUserIds,
291 .ConfigureAwait(false);
293 var status = await response.LoadJsonAsync()
294 .ConfigureAwait(false);
296 this.UpdateUserStats(status.User);
298 if (status.Id == this.previousStatusId)
299 throw new WebApiException("OK:Delaying?");
301 this.previousStatusId = status.Id;
304 var post = this.CreatePostsFromStatusData(status);
305 if (this.ReadOwnPost) post.IsRead = true;
309 public async Task<long> UploadMedia(IMediaItem item, string? mediaCategory = null)
311 this.CheckAccountState();
313 var mediaType = item.Extension switch
315 ".png" => "image/png",
316 ".jpg" => "image/jpeg",
317 ".jpeg" => "image/jpeg",
318 ".gif" => "image/gif",
319 _ => "application/octet-stream",
322 var initResponse = await this.Api.MediaUploadInit(item.Size, mediaType, mediaCategory)
323 .ConfigureAwait(false);
325 var initMedia = await initResponse.LoadJsonAsync()
326 .ConfigureAwait(false);
328 var mediaId = initMedia.MediaId;
330 await this.Api.MediaUploadAppend(mediaId, 0, item)
331 .ConfigureAwait(false);
333 var response = await this.Api.MediaUploadFinalize(mediaId)
334 .ConfigureAwait(false);
336 var media = await response.LoadJsonAsync()
337 .ConfigureAwait(false);
339 while (media.ProcessingInfo is TwitterUploadMediaResult.MediaProcessingInfo processingInfo)
341 switch (processingInfo.State)
350 throw new WebApiException($"Err:Upload failed ({processingInfo.Error?.Name})");
352 throw new WebApiException($"Err:Invalid state ({processingInfo.State})");
355 await Task.Delay(TimeSpan.FromSeconds(processingInfo.CheckAfterSecs ?? 5))
356 .ConfigureAwait(false);
358 media = await this.Api.MediaUploadStatus(mediaId)
359 .ConfigureAwait(false);
363 return media.MediaId;
366 public async Task SendDirectMessage(string postStr, long? mediaId = null)
368 this.CheckAccountState();
369 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
371 var mc = Twitter.DMSendTextRegex.Match(postStr);
373 var body = mc.Groups["body"].Value;
374 var recipientName = mc.Groups["id"].Value;
376 var recipient = await this.Api.UsersShow(recipientName)
377 .ConfigureAwait(false);
379 var response = await this.Api.DirectMessagesEventsNew(recipient.Id, body, mediaId)
380 .ConfigureAwait(false);
382 var messageEventSingle = await response.LoadJsonAsync()
383 .ConfigureAwait(false);
385 await this.CreateDirectMessagesEventFromJson(messageEventSingle, read: true)
386 .ConfigureAwait(false);
389 public async Task<PostClass?> PostRetweet(long id, bool read)
391 this.CheckAccountState();
394 var post = TabInformations.GetInstance()[id];
396 throw new WebApiException("Err:Target isn't found.");
398 var target = post.RetweetedId ?? id; // 再RTの場合は元発言をRT
400 var response = await this.Api.StatusesRetweet(target)
401 .ConfigureAwait(false);
403 var status = await response.LoadJsonAsync()
404 .ConfigureAwait(false);
409 if (TabInformations.GetInstance().ContainsKey(status.Id))
414 if (status.RetweetedStatus == null)
415 throw new WebApiException("Invalid Json!");
418 post = this.CreatePostsFromStatusData(status);
425 if (this.ReadOwnPost) post.IsRead = true;
431 public string Username
432 => this.Api.CurrentScreenName;
435 => this.Api.CurrentUserId;
437 public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
439 public bool RestrictFavCheck { get; set; }
441 public bool ReadOwnPost { get; set; }
443 public int FollowersCount { get; private set; }
445 public int FriendsCount { get; private set; }
447 public int StatusesCount { get; private set; }
449 public string Location { get; private set; } = "";
451 public string Bio { get; private set; } = "";
453 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
454 private void UpdateUserStats(TwitterUser self)
456 this.FollowersCount = self.FollowersCount;
457 this.FriendsCount = self.FriendsCount;
458 this.StatusesCount = self.StatusesCount;
459 this.Location = self.Location ?? "";
460 this.Bio = self.Description ?? "";
464 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
466 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
467 => count >= 20 && count <= GetMaxApiResultCount(type);
470 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
472 public static bool VerifyMoreApiResultCount(int count)
473 => count >= 20 && count <= 200;
476 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
478 public static bool VerifyFirstApiResultCount(int count)
479 => count >= 20 && count <= 200;
482 /// WORKERTYPEに応じた取得可能な最大件数を取得する
484 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
486 // 参照: REST APIs - 各endpointのcountパラメータ
487 // https://dev.twitter.com/rest/public
490 MyCommon.WORKERTYPE.Timeline => 200,
491 MyCommon.WORKERTYPE.Reply => 200,
492 MyCommon.WORKERTYPE.UserTimeline => 200,
493 MyCommon.WORKERTYPE.Favorites => 200,
494 MyCommon.WORKERTYPE.List => 200, // 不明
495 MyCommon.WORKERTYPE.PublicSearch => 100,
496 _ => throw new InvalidOperationException("Invalid type: " + type),
501 /// WORKERTYPEに応じた取得件数を取得する
503 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
505 if (SettingManager.Instance.Common.UseAdditionalCount)
509 case MyCommon.WORKERTYPE.Favorites:
510 if (SettingManager.Instance.Common.FavoritesCountApi != 0)
511 return SettingManager.Instance.Common.FavoritesCountApi;
513 case MyCommon.WORKERTYPE.List:
514 if (SettingManager.Instance.Common.ListCountApi != 0)
515 return SettingManager.Instance.Common.ListCountApi;
517 case MyCommon.WORKERTYPE.PublicSearch:
518 if (SettingManager.Instance.Common.SearchCountApi != 0)
519 return SettingManager.Instance.Common.SearchCountApi;
521 case MyCommon.WORKERTYPE.UserTimeline:
522 if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
523 return SettingManager.Instance.Common.UserTimelineCountApi;
526 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
528 return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
530 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
532 return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
537 var count = SettingManager.Instance.Common.CountApi;
539 if (type == MyCommon.WORKERTYPE.Reply)
540 count = SettingManager.Instance.Common.CountApiReply;
542 return Math.Min(count, GetMaxApiResultCount(type));
545 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
547 this.CheckAccountState();
549 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
551 var request = new GetTimelineRequest(this.UserId)
554 UntilId = more ? tab.OldestId.ToString() : null,
557 var response = await request.Send(this.Api.Connection)
558 .ConfigureAwait(false);
560 var tweetIds = response.Data.Select(x => x.Id).ToList();
562 var statuses = await this.Api.StatusesLookup(tweetIds)
563 .ConfigureAwait(false);
565 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
566 if (minimumId != null)
567 tab.OldestId = minimumId.Value;
570 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
572 this.CheckAccountState();
574 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
576 TwitterStatus[] statuses;
579 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
580 .ConfigureAwait(false);
584 statuses = await this.Api.StatusesMentionsTimeline(count)
585 .ConfigureAwait(false);
588 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
589 if (minimumId != null)
590 tab.OldestId = minimumId.Value;
593 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
595 this.CheckAccountState();
597 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
599 TwitterStatus[] statuses;
600 if (MyCommon.IsNullOrEmpty(userName))
602 var target = tab.ScreenName;
603 if (MyCommon.IsNullOrEmpty(target)) return;
605 statuses = await this.Api.StatusesUserTimeline(userName, count)
606 .ConfigureAwait(false);
612 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
613 .ConfigureAwait(false);
617 statuses = await this.Api.StatusesUserTimeline(userName, count)
618 .ConfigureAwait(false);
622 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
624 if (minimumId != null)
625 tab.OldestId = minimumId.Value;
628 public async Task<PostClass> GetStatusApi(bool read, long id)
630 this.CheckAccountState();
632 var status = await this.Api.StatusesShow(id)
633 .ConfigureAwait(false);
635 var item = this.CreatePostsFromStatusData(status);
638 if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
643 public async Task GetStatusApi(bool read, long id, TabModel tab)
645 var post = await this.GetStatusApi(read, id)
646 .ConfigureAwait(false);
648 // 非同期アイコン取得&StatusDictionaryに追加
649 if (tab != null && tab.IsInnerStorageTabType)
650 tab.AddPostQueue(post);
652 TabInformations.GetInstance().AddPost(post);
655 private PostClass CreatePostsFromStatusData(TwitterStatus status)
656 => this.CreatePostsFromStatusData(status, false);
658 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
660 var post = new PostClass();
661 TwitterEntities entities;
664 post.StatusId = status.Id;
665 if (status.RetweetedStatus != null)
667 var retweeted = status.RetweetedStatus;
669 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
672 post.RetweetedId = retweeted.Id;
674 post.TextFromApi = retweeted.FullText;
675 entities = retweeted.MergedEntities;
676 sourceHtml = retweeted.Source;
678 post.InReplyToStatusId = retweeted.InReplyToStatusId;
679 post.InReplyToUser = retweeted.InReplyToScreenName;
680 post.InReplyToUserId = status.InReplyToUserId;
689 var tc = TabInformations.GetInstance().FavoriteTab;
690 post.IsFav = tc.Contains(retweeted.Id);
693 if (retweeted.Coordinates != null)
694 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
697 var user = retweeted.User;
700 post.UserId = user.Id;
701 post.ScreenName = user.ScreenName;
702 post.Nickname = user.Name.Trim();
703 post.ImageUrl = user.ProfileImageUrlHttps;
704 post.IsProtect = user.Protected;
709 post.ScreenName = "?????";
710 post.Nickname = "Unknown User";
714 if (status.User != null)
716 post.RetweetedBy = status.User.ScreenName;
717 post.RetweetedByUserId = status.User.Id;
718 post.IsMe = post.RetweetedByUserId == this.UserId;
722 post.RetweetedBy = "?????";
723 post.RetweetedByUserId = 0L;
728 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
730 post.TextFromApi = status.FullText;
731 entities = status.MergedEntities;
732 sourceHtml = status.Source;
733 post.InReplyToStatusId = status.InReplyToStatusId;
734 post.InReplyToUser = status.InReplyToScreenName;
735 post.InReplyToUserId = status.InReplyToUserId;
744 var tc = TabInformations.GetInstance().FavoriteTab;
745 post.IsFav = tc.Posts.TryGetValue(post.StatusId, out var tabinfoPost) && tabinfoPost.IsFav;
748 if (status.Coordinates != null)
749 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
752 var user = status.User;
755 post.UserId = user.Id;
756 post.ScreenName = user.ScreenName;
757 post.Nickname = user.Name.Trim();
758 post.ImageUrl = user.ProfileImageUrlHttps;
759 post.IsProtect = user.Protected;
760 post.IsMe = post.UserId == this.UserId;
765 post.ScreenName = "?????";
766 post.Nickname = "Unknown User";
770 var textFromApi = post.TextFromApi;
772 var quotedStatusLink = (status.RetweetedStatus ?? status).QuotedStatusPermalink;
774 if (quotedStatusLink != null && entities.Urls.Any(x => x.ExpandedUrl == quotedStatusLink.Expanded))
775 quotedStatusLink = null; // 移行期は entities.urls と quoted_status_permalink の両方に含まれる場合がある
777 post.Text = CreateHtmlAnchor(textFromApi, entities, quotedStatusLink);
778 post.TextFromApi = textFromApi;
779 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities, quotedStatusLink);
780 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
781 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
782 post.AccessibleText = CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus, quotedStatusLink);
783 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
784 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
786 this.ExtractEntities(entities, post.ReplyToList, post.Media);
788 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities, quotedStatusLink)
789 .Where(x => x != post.StatusId && x != post.RetweetedId)
790 .Distinct().ToArray();
792 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
793 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
796 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
797 if (post.Text == post.TextFromApi)
798 post.Text = post.TextFromApi;
799 if (post.AccessibleText == post.TextFromApi)
800 post.AccessibleText = post.TextFromApi;
802 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
803 post.ScreenName = string.Intern(post.ScreenName);
804 post.Nickname = string.Intern(post.Nickname);
805 post.ImageUrl = string.Intern(post.ImageUrl);
806 post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
809 var (sourceText, sourceUri) = ParseSource(sourceHtml);
810 post.Source = string.Intern(sourceText);
811 post.SourceUri = sourceUri;
813 post.IsReply = post.RetweetedId == null && post.ReplyToList.Any(x => x.UserId == this.UserId);
814 post.IsExcludeReply = false;
822 if (this.followerId.Count > 0) post.IsOwl = !this.followerId.Contains(post.UserId);
830 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
832 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity>? entities, TwitterQuotedStatusPermalink? quotedStatusLink)
834 entities ??= Enumerable.Empty<TwitterEntity>();
836 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
838 if (quotedStatusLink != null)
839 urls = urls.Append(quotedStatusLink.Expanded);
841 return GetQuoteTweetStatusIds(urls);
844 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
846 foreach (var url in urls)
848 var match = Twitter.StatusUrlRegex.Match(url);
851 if (long.TryParse(match.Groups["StatusId"].Value, out var statusId))
852 yield return statusId;
857 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
859 long? minimumId = null;
861 foreach (var status in items)
863 if (minimumId == null || minimumId.Value > status.Id)
864 minimumId = status.Id;
871 if (TabInformations.GetInstance().ContainsKey(status.Id)) continue;
875 if (tab.Contains(status.Id)) continue;
880 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
881 status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
883 var post = this.CreatePostsFromStatusData(status);
886 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
888 if (tab != null && tab.IsInnerStorageTabType)
889 tab.AddPostQueue(post);
891 TabInformations.GetInstance().AddPost(post);
897 private long? CreatePostsFromSearchJson(TwitterSearchResult items, PublicSearchTabModel tab, bool read, bool more)
899 long? minimumId = null;
901 foreach (var status in items.Statuses)
903 if (minimumId == null || minimumId.Value > status.Id)
904 minimumId = status.Id;
906 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
910 if (tab.Contains(status.Id)) continue;
913 var post = this.CreatePostsFromStatusData(status);
916 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
918 tab.AddPostQueue(post);
924 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
926 var favTab = TabInformations.GetInstance().FavoriteTab;
927 long? minimumId = null;
929 foreach (var status in items)
931 if (minimumId == null || minimumId.Value > status.Id)
932 minimumId = status.Id;
937 if (favTab.Contains(status.Id)) continue;
940 var post = this.CreatePostsFromStatusData(status, true);
944 TabInformations.GetInstance().AddPost(post);
950 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
952 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
954 TwitterStatus[] statuses;
957 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
958 .ConfigureAwait(false);
962 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
963 .ConfigureAwait(false);
966 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
968 if (minimumId != null)
969 tab.OldestId = minimumId.Value;
973 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
975 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
976 internal static PostClass FindTopOfReplyChain(IDictionary<long, PostClass> posts, long startStatusId)
978 if (!posts.ContainsKey(startStatusId))
979 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
981 var nextPost = posts[startStatusId];
982 while (nextPost.InReplyToStatusId != null)
984 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
986 nextPost = posts[nextPost.InReplyToStatusId.Value];
992 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
994 var targetPost = tab.TargetPost;
996 if (targetPost.RetweetedId != null)
998 var originalPost = targetPost.Clone();
999 originalPost.StatusId = targetPost.RetweetedId.Value;
1000 originalPost.RetweetedId = null;
1001 originalPost.RetweetedBy = null;
1002 targetPost = originalPost;
1005 var relPosts = new Dictionary<long, PostClass>();
1006 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1009 var p = TabInformations.GetInstance()[targetPost.StatusId];
1010 if (p != null && p.InReplyToStatusId != null)
1016 p = await this.GetStatusApi(read, targetPost.StatusId)
1017 .ConfigureAwait(false);
1021 relPosts.Add(targetPost.StatusId, targetPost);
1023 Exception? lastException = null;
1025 // in_reply_to_status_id を使用してリプライチェインを辿る
1026 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1028 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1030 var inReplyToId = nextPost.InReplyToStatusId.Value;
1032 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1033 if (inReplyToPost == null)
1037 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1038 .ConfigureAwait(false);
1040 catch (WebApiException ex)
1047 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1049 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1052 // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1053 var text = targetPost.Text;
1054 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1055 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1056 foreach (var match in ma)
1058 if (long.TryParse(match.Groups["StatusId"].Value, out var statusId))
1060 if (relPosts.ContainsKey(statusId))
1063 var p = TabInformations.GetInstance()[statusId];
1068 p = await this.GetStatusApi(read, statusId)
1069 .ConfigureAwait(false);
1071 catch (WebApiException ex)
1079 relPosts.Add(p.StatusId, p);
1085 var firstPost = nextPost;
1086 var posts = await this.GetConversationPosts(firstPost, targetPost)
1087 .ConfigureAwait(false);
1089 foreach (var post in posts.OrderBy(x => x.StatusId))
1091 if (relPosts.ContainsKey(post.StatusId))
1094 // リプライチェーンが繋がらないツイートは除外
1095 if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId.Value))
1098 relPosts.Add(post.StatusId, post);
1101 catch (WebException ex)
1106 relPosts.Values.ToList().ForEach(p =>
1108 var post = p.Clone();
1109 if (post.IsMe && !read && this.ReadOwnPost)
1114 tab.AddPostQueue(post);
1117 if (lastException != null)
1118 throw new WebApiException(lastException.Message, lastException);
1121 private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1123 var conversationId = firstPost.StatusId;
1124 var query = $"conversation_id:{conversationId}";
1126 if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1127 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1129 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1131 var statuses = await this.Api.SearchTweets(query, count: 100)
1132 .ConfigureAwait(false);
1134 return statuses.Statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1137 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1139 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1142 long? sinceId = null;
1145 maxId = tab.OldestId - 1;
1149 sinceId = tab.SinceId;
1152 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1153 .ConfigureAwait(false);
1155 if (!TabInformations.GetInstance().ContainsTab(tab))
1158 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, more);
1160 if (minimumId != null)
1161 tab.OldestId = minimumId.Value;
1164 public async Task GetDirectMessageEvents(bool read, bool backward)
1166 this.CheckAccountState();
1167 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1171 TwitterMessageEventList eventList;
1174 eventList = await this.Api.DirectMessagesEventsList(count, this.nextCursorDirectMessage)
1175 .ConfigureAwait(false);
1179 eventList = await this.Api.DirectMessagesEventsList(count)
1180 .ConfigureAwait(false);
1183 this.nextCursorDirectMessage = eventList.NextCursor;
1185 await this.CreateDirectMessagesEventFromJson(eventList, read)
1186 .ConfigureAwait(false);
1189 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1191 var eventList = new TwitterMessageEventList
1193 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1194 Events = new[] { eventSingle.Event },
1197 await this.CreateDirectMessagesEventFromJson(eventList, read)
1198 .ConfigureAwait(false);
1201 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1203 var events = eventList.Events
1204 .Where(x => x.Type == "message_create")
1207 if (events.Length == 0)
1210 var userIds = Enumerable.Concat(
1211 events.Select(x => x.MessageCreate.SenderId),
1212 events.Select(x => x.MessageCreate.Target.RecipientId)
1213 ).Distinct().ToArray();
1215 var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1216 .ToDictionary(x => x.IdStr);
1218 var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1220 this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1223 private void CreateDirectMessagesEventFromJson(
1224 IEnumerable<TwitterMessageEvent> events,
1225 IReadOnlyDictionary<string, TwitterUser> users,
1226 IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1229 foreach (var eventItem in events)
1231 var post = new PostClass();
1232 post.StatusId = long.Parse(eventItem.Id);
1234 var timestamp = long.Parse(eventItem.CreatedTimestamp);
1235 post.CreatedAt = DateTimeUtc.UnixEpoch + TimeSpan.FromTicks(timestamp * TimeSpan.TicksPerMillisecond);
1237 var textFromApi = eventItem.MessageCreate.MessageData.Text;
1239 var entities = eventItem.MessageCreate.MessageData.Entities;
1240 var mediaEntity = eventItem.MessageCreate.MessageData.Attachment?.Media;
1242 if (mediaEntity != null)
1243 entities.Media = new[] { mediaEntity };
1246 post.Text = CreateHtmlAnchor(textFromApi, entities, quotedStatusLink: null);
1247 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, entities, quotedStatusLink: null);
1248 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1249 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1250 post.AccessibleText = CreateAccessibleText(textFromApi, entities, quotedStatus: null, quotedStatusLink: null);
1251 post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1252 post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1255 this.ExtractEntities(entities, post.ReplyToList, post.Media);
1257 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities, quotedStatusLink: null)
1258 .Distinct().ToArray();
1260 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1261 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1266 if (eventItem.MessageCreate.SenderId != this.Api.CurrentUserId.ToString(CultureInfo.InvariantCulture))
1268 userId = eventItem.MessageCreate.SenderId;
1274 userId = eventItem.MessageCreate.Target.RecipientId;
1279 if (!users.TryGetValue(userId, out var user))
1282 post.UserId = user.Id;
1283 post.ScreenName = user.ScreenName;
1284 post.Nickname = user.Name.Trim();
1285 post.ImageUrl = user.ProfileImageUrlHttps;
1286 post.IsProtect = user.Protected;
1288 // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1289 if (post.Text == post.TextFromApi)
1290 post.Text = post.TextFromApi;
1291 if (post.AccessibleText == post.TextFromApi)
1292 post.AccessibleText = post.TextFromApi;
1294 // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1295 post.ScreenName = string.Intern(post.ScreenName);
1296 post.Nickname = string.Intern(post.Nickname);
1297 post.ImageUrl = string.Intern(post.ImageUrl);
1299 var appId = eventItem.MessageCreate.SourceAppId;
1300 if (appId != null && apps.TryGetValue(appId, out var app))
1302 post.Source = string.Intern(app.Name);
1306 post.SourceUri = new Uri(SourceUriBase, app.Url);
1308 catch (UriFormatException)
1314 if (post.IsMe && !read && this.ReadOwnPost)
1316 post.IsReply = false;
1317 post.IsExcludeReply = false;
1320 var dmTab = TabInformations.GetInstance().DirectMessageTab;
1321 dmTab.AddPostQueue(post);
1325 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1327 this.CheckAccountState();
1329 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1331 TwitterStatus[] statuses;
1334 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1335 .ConfigureAwait(false);
1339 statuses = await this.Api.FavoritesList(count)
1340 .ConfigureAwait(false);
1343 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1345 if (minimumId != null)
1346 tab.OldestId = minimumId.Value;
1349 private string ReplaceTextFromApi(string text, TwitterEntities? entities, TwitterQuotedStatusPermalink? quotedStatusLink)
1351 if (entities != null)
1353 if (entities.Urls != null)
1355 foreach (var m in entities.Urls)
1357 if (!MyCommon.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1360 if (entities.Media != null)
1362 foreach (var m in entities.Media)
1364 if (!MyCommon.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1369 if (quotedStatusLink != null)
1370 text += " " + quotedStatusLink.Display;
1375 internal static string CreateAccessibleText(string text, TwitterEntities? entities, TwitterStatus? quotedStatus, TwitterQuotedStatusPermalink? quotedStatusLink)
1377 if (entities == null)
1380 if (entities.Urls != null)
1382 foreach (var entity in entities.Urls)
1384 if (quotedStatus != null)
1386 var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1387 if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quotedStatus.IdStr)
1389 var quotedText = CreateAccessibleText(quotedStatus.FullText, quotedStatus.MergedEntities, quotedStatus: null, quotedStatusLink: null);
1390 text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quotedStatus.User.ScreenName, quotedText));
1395 if (!MyCommon.IsNullOrEmpty(entity.DisplayUrl))
1396 text = text.Replace(entity.Url, entity.DisplayUrl);
1400 if (entities.Media != null)
1402 foreach (var entity in entities.Media)
1404 if (!MyCommon.IsNullOrEmpty(entity.AltText))
1406 text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1408 else if (!MyCommon.IsNullOrEmpty(entity.DisplayUrl))
1410 text = text.Replace(entity.Url, entity.DisplayUrl);
1415 if (quotedStatus != null && quotedStatusLink != null)
1417 var quoteText = CreateAccessibleText(quotedStatus.FullText, quotedStatus.MergedEntities, quotedStatus: null, quotedStatusLink: null);
1418 text += " " + string.Format(Properties.Resources.QuoteStatus_AccessibleText, quotedStatus.User.ScreenName, quoteText);
1427 /// <exception cref="WebApiException"/>
1428 public async Task RefreshFollowerIds()
1430 if (MyCommon.EndingFlag) return;
1433 var newFollowerIds = Enumerable.Empty<long>();
1436 var ret = await this.Api.FollowersIds(cursor)
1437 .ConfigureAwait(false);
1439 if (ret.Ids == null)
1440 throw new WebApiException("ret.ids == null");
1442 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1443 cursor = ret.NextCursor;
1445 while (cursor != 0);
1447 this.followerId = newFollowerIds.ToHashSet();
1448 TabInformations.GetInstance().RefreshOwl(this.followerId);
1450 this.GetFollowersSuccess = true;
1454 /// RT 非表示ユーザーを更新します
1456 /// <exception cref="WebApiException"/>
1457 public async Task RefreshNoRetweetIds()
1459 if (MyCommon.EndingFlag) return;
1461 this.noRTId = await this.Api.NoRetweetIds()
1462 .ConfigureAwait(false);
1464 this.GetNoRetweetSuccess = true;
1468 /// t.co の文字列長などの設定情報を更新します
1470 /// <exception cref="WebApiException"/>
1471 public async Task RefreshConfiguration()
1473 this.Configuration = await this.Api.Configuration()
1474 .ConfigureAwait(false);
1476 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1477 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1480 public async Task GetListsApi()
1482 this.CheckAccountState();
1484 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1485 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1486 .ConfigureAwait(false);
1488 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1489 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1490 .ConfigureAwait(false);
1492 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1493 .Select(x => new ListElement(x, this))
1497 public async Task DeleteList(long listId)
1499 await this.Api.ListsDestroy(listId)
1501 .ConfigureAwait(false);
1503 var tabinfo = TabInformations.GetInstance();
1505 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1506 .Where(x => x.Id != listId)
1510 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1512 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1513 .ConfigureAwait(false);
1515 var list = await response.LoadJsonAsync()
1516 .ConfigureAwait(false);
1518 return new ListElement(list, this);
1521 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1523 this.CheckAccountState();
1525 var users = await this.Api.ListsMembers(listId, cursor)
1526 .ConfigureAwait(false);
1528 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1530 return users.NextCursor;
1533 public async Task CreateListApi(string listName, bool isPrivate, string description)
1535 this.CheckAccountState();
1537 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1538 .ConfigureAwait(false);
1540 var list = await response.LoadJsonAsync()
1541 .ConfigureAwait(false);
1543 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1546 public async Task<bool> ContainsUserAtList(long listId, string user)
1548 this.CheckAccountState();
1552 await this.Api.ListsMembersShow(listId, user)
1553 .ConfigureAwait(false);
1557 catch (TwitterApiException ex)
1558 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1564 private void ExtractEntities(TwitterEntities? entities, List<(long UserId, string ScreenName)> atList, List<MediaInfo> media)
1566 if (entities != null)
1568 if (entities.Hashtags != null)
1572 this.hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1575 if (entities.UserMentions != null)
1577 foreach (var ent in entities.UserMentions)
1579 atList.Add((ent.Id, ent.ScreenName));
1582 if (entities.Media != null)
1586 foreach (var ent in entities.Media)
1588 if (!media.Any(x => x.Url == ent.MediaUrlHttps))
1590 if (ent.VideoInfo != null &&
1591 ent.Type == "animated_gif" || ent.Type == "video")
1593 media.Add(new MediaInfo(ent.MediaUrlHttps, ent.AltText, ent.ExpandedUrl));
1597 media.Add(new MediaInfo(ent.MediaUrlHttps, ent.AltText, videoUrl: null));
1606 internal static string CreateHtmlAnchor(string text, TwitterEntities? entities, TwitterQuotedStatusPermalink? quotedStatusLink)
1608 var mergedEntities = entities.Concat(TweetExtractor.ExtractEmojiEntities(text));
1610 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1611 text = TweetFormatter.AutoLinkHtml(text, mergedEntities, keepTco: true);
1613 text = Regex.Replace(text, "(^|[^a-zA-Z0-9_/&##@@>=.~])(sm|nm)([0-9]{1,10})", "$1<a href=\"https://www.nicovideo.jp/watch/$2$3\">$2$3</a>");
1614 text = PreProcessUrl(text); // IDN置換
1616 if (quotedStatusLink != null)
1618 text += string.Format(" <a href=\"{0}\" title=\"{0}\">{1}</a>",
1619 WebUtility.HtmlEncode(quotedStatusLink.Url),
1620 WebUtility.HtmlEncode(quotedStatusLink.Display));
1626 private static readonly Uri SourceUriBase = new("https://twitter.com/");
1629 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1631 internal static (string SourceText, Uri? SourceUri) ParseSource(string? sourceHtml)
1633 if (MyCommon.IsNullOrEmpty(sourceHtml))
1639 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1641 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1644 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1647 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1648 sourceUri = new Uri(SourceUriBase, uriStr);
1650 catch (UriFormatException)
1657 sourceText = WebUtility.HtmlDecode(sourceHtml);
1661 return (sourceText, sourceUri);
1664 public async Task<TwitterApiStatus?> GetInfoApi()
1666 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1668 if (MyCommon.EndingFlag) return null;
1670 var limits = await this.Api.ApplicationRateLimitStatus()
1671 .ConfigureAwait(false);
1673 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1675 return MyCommon.TwitterApiInfo;
1679 /// ブロック中のユーザーを更新します
1681 /// <exception cref="WebApiException"/>
1682 public async Task RefreshBlockIds()
1684 if (MyCommon.EndingFlag) return;
1687 var newBlockIds = Enumerable.Empty<long>();
1690 var ret = await this.Api.BlocksIds(cursor)
1691 .ConfigureAwait(false);
1693 newBlockIds = newBlockIds.Concat(ret.Ids);
1694 cursor = ret.NextCursor;
1696 while (cursor != 0);
1698 var blockIdsSet = newBlockIds.ToHashSet();
1699 blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1701 TabInformations.GetInstance().BlockIds = blockIdsSet;
1705 /// ミュート中のユーザーIDを更新します
1707 /// <exception cref="WebApiException"/>
1708 public async Task RefreshMuteUserIdsAsync()
1710 if (MyCommon.EndingFlag) return;
1712 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1713 .ConfigureAwait(false);
1715 TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1718 public string[] GetHashList()
1723 hashArray = this.hashList.ToArray();
1724 this.hashList.Clear();
1729 public string AccessToken
1730 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1732 public string AccessTokenSecret
1733 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1735 private void CheckAccountState()
1737 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1738 throw new WebApiException("Auth error. Check your account");
1741 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1743 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1744 throw new WebApiException("Auth Err:try to re-authorization.");
1747 public int GetTextLengthRemain(string postText)
1749 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1750 if (matchDm.Success)
1751 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1753 return this.GetTextLengthRemainWeighted(postText);
1756 private int GetTextLengthRemainDM(string postText)
1761 while (pos < postText.Length)
1765 if (char.IsSurrogatePair(postText, pos))
1766 pos += 2; // サロゲートペアの場合は2文字分進める
1771 var urls = TweetExtractor.ExtractUrls(postText);
1772 foreach (var url in urls)
1774 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1775 ? this.Configuration.ShortUrlLengthHttps
1776 : this.Configuration.ShortUrlLength;
1778 textLength += shortUrlLength - url.Length;
1781 return this.Configuration.DmTextCharacterLimit - textLength;
1784 private int GetTextLengthRemainWeighted(string postText)
1786 var config = this.TextConfiguration;
1787 var totalWeight = 0;
1789 int GetWeightFromCodepoint(int codepoint)
1791 foreach (var weightRange in config.Ranges)
1793 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1794 return weightRange.Weight;
1797 return config.DefaultWeight;
1800 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1801 var emojis = config.EmojiParsingEnabled
1802 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1803 : Array.Empty<TwitterEntityEmoji>();
1805 var codepoints = postText.ToCodepoints().ToArray();
1807 while (index < codepoints.Length)
1809 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1810 if (urlEntity != null)
1812 totalWeight += config.TransformedURLLength * config.Scale;
1813 index = urlEntity.Indices[1];
1817 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1818 if (emojiEntity != null)
1820 totalWeight += GetWeightFromCodepoint(codepoints[index]);
1821 index = emojiEntity.Indices[1];
1825 var codepoint = codepoints[index];
1826 totalWeight += GetWeightFromCodepoint(codepoint);
1831 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1833 return remainWeight / config.Scale;
1837 /// プロフィール画像のサイズを指定したURLを生成
1840 /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1842 public static string CreateProfileImageUrl(string normalUrl, string size)
1846 "original" => normalUrl.Replace("_normal.", "."),
1847 "normal" => normalUrl,
1848 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1849 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1853 public static string DecideProfileImageSize(int sizePx)
1855 return sizePx switch
1864 public bool IsDisposed { get; private set; } = false;
1866 protected virtual void Dispose(bool disposing)
1868 if (this.IsDisposed)
1876 this.IsDisposed = true;
1879 public void Dispose()
1882 GC.SuppressFinalize(this);