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;
36 using System.Net.Http;
37 using System.Reflection;
38 using System.Runtime.CompilerServices;
40 using System.Text.RegularExpressions;
41 using System.Threading;
42 using System.Threading.Tasks;
43 using System.Windows.Forms;
45 using OpenTween.Api.DataModel;
46 using OpenTween.Api.GraphQL;
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 private readonly TwitterPostFactory postFactory;
177 private string? previousStatusId = null;
179 public Twitter(TwitterApi api)
181 this.postFactory = new(TabInformations.GetInstance());
184 this.Configuration = TwitterConfiguration.DefaultConfiguration();
185 this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
188 public TwitterApiAccessLevel AccessLevel
189 => MyCommon.TwitterApiInfo.AccessLevel;
191 protected void ResetApiStatus()
192 => MyCommon.TwitterApiInfo.Reset();
194 public void ClearAuthInfo()
196 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
197 this.ResetApiStatus();
200 public void VerifyCredentials()
204 this.VerifyCredentialsAsync().Wait();
206 catch (AggregateException ex) when (ex.InnerException is WebApiException)
208 throw new WebApiException(ex.InnerException.Message, ex);
212 public async Task VerifyCredentialsAsync()
214 var user = await this.Api.AccountVerifyCredentials()
215 .ConfigureAwait(false);
217 this.UpdateUserStats(user);
220 public void Initialize(string token, string tokenSecret, string username, long userId)
223 if (MyCommon.IsNullOrEmpty(token) || MyCommon.IsNullOrEmpty(tokenSecret) || MyCommon.IsNullOrEmpty(username))
225 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
227 this.ResetApiStatus();
228 this.Api.Initialize(token, tokenSecret, userId, username);
231 public void Initialize(ITwitterCredential credential, string username, long userId)
234 if (credential is TwitterCredentialNone)
235 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
237 this.ResetApiStatus();
238 this.Api.Initialize(credential, userId, username);
241 public async Task<PostClass?> PostStatus(PostStatusParams param)
243 this.CheckAccountState();
245 if (Twitter.DMSendTextRegex.IsMatch(param.Text))
247 var mediaId = param.MediaIds != null && param.MediaIds.Any() ? param.MediaIds[0] : (long?)null;
249 await this.SendDirectMessage(param.Text, mediaId)
250 .ConfigureAwait(false);
254 TwitterStatus status;
256 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
258 var request = new CreateTweetRequest
260 TweetText = param.Text,
261 InReplyToTweetId = param.InReplyToStatusId?.ToTwitterStatusId(),
262 ExcludeReplyUserIds = param.ExcludeReplyUserIds.Select(x => x.ToString()).ToArray(),
263 MediaIds = param.MediaIds.Select(x => x.ToString()).ToArray(),
264 AttachmentUrl = param.AttachmentUrl,
267 status = await request.Send(this.Api.Connection)
268 .ConfigureAwait(false);
272 var response = await this.Api.StatusesUpdate(
274 param.InReplyToStatusId?.ToTwitterStatusId(),
276 param.AutoPopulateReplyMetadata,
277 param.ExcludeReplyUserIds,
280 .ConfigureAwait(false);
282 status = await response.LoadJsonAsync()
283 .ConfigureAwait(false);
286 this.UpdateUserStats(status.User);
288 if (status.IdStr == this.previousStatusId)
289 throw new WebApiException("OK:Delaying?");
291 this.previousStatusId = status.IdStr;
294 var post = this.CreatePostsFromStatusData(status);
295 if (this.ReadOwnPost) post.IsRead = true;
299 public async Task DeleteTweet(TwitterStatusId tweetId)
301 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
303 var request = new DeleteTweetRequest
307 await request.Send(this.Api.Connection);
311 await this.Api.StatusesDestroy(tweetId)
316 public async Task<long> UploadMedia(IMediaItem item, string? mediaCategory = null)
318 this.CheckAccountState();
320 var mediaType = item.Extension switch
322 ".png" => "image/png",
323 ".jpg" => "image/jpeg",
324 ".jpeg" => "image/jpeg",
325 ".gif" => "image/gif",
326 _ => "application/octet-stream",
329 var initResponse = await this.Api.MediaUploadInit(item.Size, mediaType, mediaCategory)
330 .ConfigureAwait(false);
332 var initMedia = await initResponse.LoadJsonAsync()
333 .ConfigureAwait(false);
335 var mediaId = initMedia.MediaId;
337 await this.Api.MediaUploadAppend(mediaId, 0, item)
338 .ConfigureAwait(false);
340 var response = await this.Api.MediaUploadFinalize(mediaId)
341 .ConfigureAwait(false);
343 var media = await response.LoadJsonAsync()
344 .ConfigureAwait(false);
346 while (media.ProcessingInfo is TwitterUploadMediaResult.MediaProcessingInfo processingInfo)
348 switch (processingInfo.State)
357 throw new WebApiException($"Err:Upload failed ({processingInfo.Error?.Name})");
359 throw new WebApiException($"Err:Invalid state ({processingInfo.State})");
362 await Task.Delay(TimeSpan.FromSeconds(processingInfo.CheckAfterSecs ?? 5))
363 .ConfigureAwait(false);
365 media = await this.Api.MediaUploadStatus(mediaId)
366 .ConfigureAwait(false);
370 return media.MediaId;
373 public async Task SendDirectMessage(string postStr, long? mediaId = null)
375 this.CheckAccountState();
376 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
378 var mc = Twitter.DMSendTextRegex.Match(postStr);
380 var body = mc.Groups["body"].Value;
381 var recipientName = mc.Groups["id"].Value;
383 var recipient = await this.GetUserInfo(recipientName)
384 .ConfigureAwait(false);
386 var response = await this.Api.DirectMessagesEventsNew(recipient.Id, body, mediaId)
387 .ConfigureAwait(false);
389 var messageEventSingle = await response.LoadJsonAsync()
390 .ConfigureAwait(false);
392 await this.CreateDirectMessagesEventFromJson(messageEventSingle, read: true)
393 .ConfigureAwait(false);
396 public async Task<PostClass?> PostRetweet(PostId id, bool read)
398 this.CheckAccountState();
401 var post = TabInformations.GetInstance()[id];
403 throw new WebApiException("Err:Target isn't found.");
405 var target = post.RetweetedId ?? id; // 再RTの場合は元発言をRT
407 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
409 var request = new CreateRetweetRequest
411 TweetId = target.ToTwitterStatusId(),
413 await request.Send(this.Api.Connection).ConfigureAwait(false);
417 var response = await this.Api.StatusesRetweet(target.ToTwitterStatusId())
418 .ConfigureAwait(false);
420 var status = await response.LoadJsonAsync()
421 .ConfigureAwait(false);
426 var statusId = new TwitterStatusId(status.IdStr);
427 if (TabInformations.GetInstance().ContainsKey(statusId))
432 if (status.RetweetedStatus == null)
433 throw new WebApiException("Invalid Json!");
436 return this.CreatePostsFromStatusData(status) with
439 IsRead = this.ReadOwnPost ? true : read,
444 public async Task DeleteRetweet(PostClass post)
446 if (post.RetweetedId == null)
447 throw new ArgumentException("post is not retweeted status", nameof(post));
449 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
451 var request = new DeleteRetweetRequest
453 SourceTweetId = post.RetweetedId.ToTwitterStatusId(),
455 await request.Send(this.Api.Connection).ConfigureAwait(false);
459 await this.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
464 public async Task<TwitterUser> GetUserInfo(string screenName)
466 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
468 var request = new UserByScreenNameRequest
470 ScreenName = screenName,
472 var response = await request.Send(this.Api.Connection)
473 .ConfigureAwait(false);
475 return response.ToTwitterUser();
479 var user = await this.Api.UsersShow(screenName)
480 .ConfigureAwait(false);
486 public string Username
487 => this.Api.CurrentScreenName;
490 => this.Api.CurrentUserId;
492 public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
494 public bool RestrictFavCheck { get; set; }
496 public bool ReadOwnPost { get; set; }
498 public int FollowersCount { get; private set; }
500 public int FriendsCount { get; private set; }
502 public int StatusesCount { get; private set; }
504 public string Location { get; private set; } = "";
506 public string Bio { get; private set; } = "";
508 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
509 private void UpdateUserStats(TwitterUser self)
511 this.FollowersCount = self.FollowersCount;
512 this.FriendsCount = self.FriendsCount;
513 this.StatusesCount = self.StatusesCount;
514 this.Location = self.Location ?? "";
515 this.Bio = self.Description ?? "";
519 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
521 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
522 => count >= 20 && count <= GetMaxApiResultCount(type);
525 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
527 public static bool VerifyMoreApiResultCount(int count)
528 => count >= 20 && count <= 200;
531 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
533 public static bool VerifyFirstApiResultCount(int count)
534 => count >= 20 && count <= 200;
537 /// WORKERTYPEに応じた取得可能な最大件数を取得する
539 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
541 // 参照: REST APIs - 各endpointのcountパラメータ
542 // https://dev.twitter.com/rest/public
545 MyCommon.WORKERTYPE.Timeline => 100,
546 MyCommon.WORKERTYPE.Reply => 200,
547 MyCommon.WORKERTYPE.UserTimeline => 200,
548 MyCommon.WORKERTYPE.Favorites => 200,
549 MyCommon.WORKERTYPE.List => 200, // 不明
550 MyCommon.WORKERTYPE.PublicSearch => 100,
551 _ => throw new InvalidOperationException("Invalid type: " + type),
556 /// WORKERTYPEに応じた取得件数を取得する
558 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
560 if (SettingManager.Instance.Common.UseAdditionalCount)
564 case MyCommon.WORKERTYPE.Favorites:
565 if (SettingManager.Instance.Common.FavoritesCountApi != 0)
566 return SettingManager.Instance.Common.FavoritesCountApi;
568 case MyCommon.WORKERTYPE.List:
569 if (SettingManager.Instance.Common.ListCountApi != 0)
570 return SettingManager.Instance.Common.ListCountApi;
572 case MyCommon.WORKERTYPE.PublicSearch:
573 if (SettingManager.Instance.Common.SearchCountApi != 0)
574 return SettingManager.Instance.Common.SearchCountApi;
576 case MyCommon.WORKERTYPE.UserTimeline:
577 if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
578 return SettingManager.Instance.Common.UserTimelineCountApi;
581 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
583 return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
585 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
587 return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
592 var count = SettingManager.Instance.Common.CountApi;
594 if (type == MyCommon.WORKERTYPE.Reply)
595 count = SettingManager.Instance.Common.CountApiReply;
597 return Math.Min(count, GetMaxApiResultCount(type));
600 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
602 this.CheckAccountState();
604 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
606 TwitterStatus[] statuses;
607 if (SettingManager.Instance.Common.EnableTwitterV2Api)
609 var request = new GetTimelineRequest(this.UserId)
612 UntilId = more ? tab.OldestId as TwitterStatusId : null,
615 var response = await request.Send(this.Api.Connection)
616 .ConfigureAwait(false);
618 if (response.Data == null || response.Data.Length == 0)
621 var tweetIds = response.Data.Select(x => x.Id).ToList();
623 statuses = await this.Api.StatusesLookup(tweetIds)
624 .ConfigureAwait(false);
628 var maxId = more ? tab.OldestId : null;
630 statuses = await this.Api.StatusesHomeTimeline(count, maxId as TwitterStatusId)
631 .ConfigureAwait(false);
634 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
635 if (minimumId != null)
636 tab.OldestId = minimumId;
639 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
641 this.CheckAccountState();
643 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
645 TwitterStatus[] statuses;
648 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId as TwitterStatusId)
649 .ConfigureAwait(false);
653 statuses = await this.Api.StatusesMentionsTimeline(count)
654 .ConfigureAwait(false);
657 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
658 if (minimumId != null)
659 tab.OldestId = minimumId;
662 public async Task GetUserTimelineApi(bool read, UserTimelineTabModel tab, bool more)
664 this.CheckAccountState();
666 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
668 TwitterStatus[] statuses;
669 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
671 var userId = tab.UserId;
672 if (MyCommon.IsNullOrEmpty(userId))
674 var user = await this.GetUserInfo(tab.ScreenName)
675 .ConfigureAwait(false);
678 tab.UserId = user.IdStr;
681 var request = new UserTweetsAndRepliesRequest(userId)
684 Cursor = more ? tab.CursorBottom : tab.CursorTop,
686 var response = await request.Send(this.Api.Connection)
687 .ConfigureAwait(false);
689 statuses = response.Tweets
690 .Where(x => !x.IsTombstone)
691 .Select(x => x.ToTwitterStatus())
692 .Where(x => x.User.IdStr == userId) // リプライツリーに含まれる他ユーザーのツイートを除外
695 tab.CursorBottom = response.CursorBottom;
698 tab.CursorTop = response.CursorTop;
704 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count, maxId: tab.OldestId as TwitterStatusId)
705 .ConfigureAwait(false);
709 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count)
710 .ConfigureAwait(false);
714 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
716 if (minimumId != null)
717 tab.OldestId = minimumId;
720 public async Task<PostClass> GetStatusApi(bool read, TwitterStatusId id)
722 this.CheckAccountState();
724 TwitterStatus status;
725 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
727 var request = new TweetDetailRequest
731 var tweets = await request.Send(this.Api.Connection).ConfigureAwait(false);
732 status = tweets.Select(x => x.ToTwitterStatus())
733 .Where(x => x.IdStr == id.Id)
734 .FirstOrDefault() ?? throw new WebApiException("Empty result set");
738 status = await this.Api.StatusesShow(id)
739 .ConfigureAwait(false);
742 var item = this.CreatePostsFromStatusData(status);
745 if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
750 public async Task GetStatusApi(bool read, TwitterStatusId id, TabModel tab)
752 var post = await this.GetStatusApi(read, id)
753 .ConfigureAwait(false);
755 // 非同期アイコン取得&StatusDictionaryに追加
756 if (tab != null && tab.IsInnerStorageTabType)
757 tab.AddPostQueue(post);
759 TabInformations.GetInstance().AddPost(post);
762 private PostClass CreatePostsFromStatusData(TwitterStatus status)
763 => this.CreatePostsFromStatusData(status, favTweet: false);
765 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
766 => this.postFactory.CreateFromStatus(status, this.UserId, this.followerId, favTweet);
768 private PostId? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
770 PostId? minimumId = null;
772 var posts = items.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
774 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
776 foreach (var post in posts)
778 if (!post.IsPromoted)
780 if (minimumId == null || minimumId > post.StatusId)
781 minimumId = post.StatusId;
787 var id = post.StatusId;
790 if (TabInformations.GetInstance().ContainsKey(id)) continue;
794 if (tab.Contains(id)) continue;
799 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
800 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
803 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
805 if (tab != null && tab.IsInnerStorageTabType)
806 tab.AddPostQueue(post);
808 TabInformations.GetInstance().AddPost(post);
814 private PostId? CreatePostsFromSearchJson(TwitterStatus[] statuses, PublicSearchTabModel tab, bool read, bool more)
816 PostId? minimumId = null;
818 var posts = statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
820 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
822 foreach (var post in posts)
824 if (!post.IsPromoted)
826 if (minimumId == null || minimumId > post.StatusId)
827 minimumId = post.StatusId;
829 if (!more && (tab.SinceId == null || post.StatusId > tab.SinceId))
830 tab.SinceId = post.StatusId;
836 if (tab.Contains(post.StatusId))
841 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
843 tab.AddPostQueue(post);
849 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
851 var favTab = TabInformations.GetInstance().FavoriteTab;
852 long? minimumId = null;
854 foreach (var status in items)
856 if (minimumId == null || minimumId.Value > status.Id)
857 minimumId = status.Id;
862 if (favTab.Contains(new TwitterStatusId(status.IdStr)))
866 var post = this.CreatePostsFromStatusData(status, true);
870 TabInformations.GetInstance().AddPost(post);
876 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
878 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
880 TwitterStatus[] statuses;
881 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
883 var request = new ListLatestTweetsTimelineRequest(tab.ListInfo.Id.ToString())
886 Cursor = more ? tab.CursorBottom : tab.CursorTop,
888 var response = await request.Send(this.Api.Connection)
889 .ConfigureAwait(false);
891 var convertedStatuses = response.Tweets
892 .Where(x => !x.IsTombstone)
893 .Select(x => x.ToTwitterStatus());
895 if (!SettingManager.Instance.Common.IsListsIncludeRts)
896 convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null);
898 statuses = convertedStatuses.ToArray();
899 tab.CursorBottom = response.CursorBottom;
902 tab.CursorTop = response.CursorTop;
906 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId as TwitterStatusId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
907 .ConfigureAwait(false);
911 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
912 .ConfigureAwait(false);
915 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
917 if (minimumId != null)
918 tab.OldestId = minimumId;
922 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
924 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
925 internal static PostClass FindTopOfReplyChain(IDictionary<PostId, PostClass> posts, PostId startStatusId)
927 if (!posts.ContainsKey(startStatusId))
928 throw new ArgumentException("startStatusId (" + startStatusId.Id + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
930 var nextPost = posts[startStatusId];
931 while (nextPost.InReplyToStatusId != null)
933 if (!posts.ContainsKey(nextPost.InReplyToStatusId))
935 nextPost = posts[nextPost.InReplyToStatusId];
941 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
943 var targetPost = tab.TargetPost;
945 if (targetPost.RetweetedId != null)
947 var originalPost = targetPost with
949 StatusId = targetPost.RetweetedId,
953 targetPost = originalPost;
956 var relPosts = new Dictionary<PostId, PostClass>();
957 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
960 var p = TabInformations.GetInstance()[targetPost.StatusId];
961 if (p != null && p.InReplyToStatusId != null)
967 p = await this.GetStatusApi(read, targetPost.StatusId.ToTwitterStatusId())
968 .ConfigureAwait(false);
972 relPosts.Add(targetPost.StatusId, targetPost);
974 Exception? lastException = null;
976 // in_reply_to_status_id を使用してリプライチェインを辿る
977 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
979 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
981 var inReplyToId = nextPost.InReplyToStatusId;
983 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
984 if (inReplyToPost == null)
988 inReplyToPost = await this.GetStatusApi(read, inReplyToId.ToTwitterStatusId())
989 .ConfigureAwait(false);
991 catch (WebApiException ex)
998 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1000 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1003 // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1004 var text = targetPost.Text;
1005 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1006 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1007 foreach (var match in ma)
1009 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
1010 if (!relPosts.ContainsKey(statusId))
1012 var p = TabInformations.GetInstance()[statusId];
1017 p = await this.GetStatusApi(read, statusId)
1018 .ConfigureAwait(false);
1020 catch (WebApiException ex)
1028 relPosts.Add(p.StatusId, p);
1034 var firstPost = nextPost;
1035 var posts = await this.GetConversationPosts(firstPost, targetPost)
1036 .ConfigureAwait(false);
1038 foreach (var post in posts.OrderBy(x => x.StatusId))
1040 if (relPosts.ContainsKey(post.StatusId))
1043 // リプライチェーンが繋がらないツイートは除外
1044 if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId))
1047 relPosts.Add(post.StatusId, post);
1050 catch (WebException ex)
1055 relPosts.Values.ToList().ForEach(p =>
1057 var post = p with { };
1058 if (post.IsMe && !read && this.ReadOwnPost)
1063 tab.AddPostQueue(post);
1066 if (lastException != null)
1067 throw new WebApiException(lastException.Message, lastException);
1070 private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1072 var conversationId = firstPost.StatusId;
1073 var query = $"conversation_id:{conversationId.Id}";
1075 if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1076 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1078 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1080 var statuses = await this.Api.SearchTweets(query, count: 100)
1081 .ConfigureAwait(false);
1083 return statuses.Statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1086 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1088 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1090 TwitterStatus[] statuses;
1091 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
1093 var request = new SearchTimelineRequest(tab.SearchWords)
1096 Cursor = more ? tab.CursorBottom : tab.CursorTop,
1098 var response = await request.Send(this.Api.Connection)
1099 .ConfigureAwait(false);
1101 statuses = response.Tweets
1102 .Where(x => !x.IsTombstone)
1103 .Select(x => x.ToTwitterStatus())
1106 tab.CursorBottom = response.CursorBottom;
1109 tab.CursorTop = response.CursorTop;
1113 TwitterStatusId? maxId = null;
1114 TwitterStatusId? sinceId = null;
1117 maxId = tab.OldestId as TwitterStatusId;
1121 sinceId = tab.SinceId as TwitterStatusId;
1124 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1125 .ConfigureAwait(false);
1127 statuses = searchResult.Statuses;
1130 if (!TabInformations.GetInstance().ContainsTab(tab))
1133 var minimumId = this.CreatePostsFromSearchJson(statuses, tab, read, more);
1135 if (minimumId != null)
1136 tab.OldestId = minimumId;
1139 public async Task GetDirectMessageEvents(bool read, DirectMessagesTabModel dmTab, bool backward)
1141 this.CheckAccountState();
1142 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1146 TwitterMessageEventList eventList;
1149 eventList = await this.Api.DirectMessagesEventsList(count, dmTab.NextCursor)
1150 .ConfigureAwait(false);
1154 eventList = await this.Api.DirectMessagesEventsList(count)
1155 .ConfigureAwait(false);
1158 dmTab.NextCursor = eventList.NextCursor;
1160 await this.CreateDirectMessagesEventFromJson(eventList, read)
1161 .ConfigureAwait(false);
1164 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1166 var eventList = new TwitterMessageEventList
1168 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1169 Events = new[] { eventSingle.Event },
1172 await this.CreateDirectMessagesEventFromJson(eventList, read)
1173 .ConfigureAwait(false);
1176 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1178 var events = eventList.Events
1179 .Where(x => x.Type == "message_create")
1182 if (events.Length == 0)
1185 var userIds = Enumerable.Concat(
1186 events.Select(x => x.MessageCreate.SenderId),
1187 events.Select(x => x.MessageCreate.Target.RecipientId)
1188 ).Distinct().ToArray();
1190 var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1191 .ToDictionary(x => x.IdStr);
1193 var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1195 this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1198 private void CreateDirectMessagesEventFromJson(
1199 IEnumerable<TwitterMessageEvent> events,
1200 IReadOnlyDictionary<string, TwitterUser> users,
1201 IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1204 var dmTab = TabInformations.GetInstance().DirectMessageTab;
1206 foreach (var eventItem in events)
1208 var post = this.postFactory.CreateFromDirectMessageEvent(eventItem, users, apps, this.UserId);
1211 if (post.IsMe && !read && this.ReadOwnPost)
1214 dmTab.AddPostQueue(post);
1218 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1220 this.CheckAccountState();
1222 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1224 TwitterStatus[] statuses;
1227 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1228 .ConfigureAwait(false);
1232 statuses = await this.Api.FavoritesList(count)
1233 .ConfigureAwait(false);
1236 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1238 if (minimumId != null)
1239 tab.OldestId = minimumId.Value;
1245 /// <exception cref="WebApiException"/>
1246 public async Task RefreshFollowerIds()
1248 if (MyCommon.EndingFlag) return;
1251 var newFollowerIds = Enumerable.Empty<long>();
1254 var ret = await this.Api.FollowersIds(cursor)
1255 .ConfigureAwait(false);
1257 if (ret.Ids == null)
1258 throw new WebApiException("ret.ids == null");
1260 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1261 cursor = ret.NextCursor;
1263 while (cursor != 0);
1265 this.followerId = newFollowerIds.ToHashSet();
1266 TabInformations.GetInstance().RefreshOwl(this.followerId);
1268 this.GetFollowersSuccess = true;
1272 /// RT 非表示ユーザーを更新します
1274 /// <exception cref="WebApiException"/>
1275 public async Task RefreshNoRetweetIds()
1277 if (MyCommon.EndingFlag) return;
1279 this.noRTId = await this.Api.NoRetweetIds()
1280 .ConfigureAwait(false);
1282 this.GetNoRetweetSuccess = true;
1286 /// t.co の文字列長などの設定情報を更新します
1288 /// <exception cref="WebApiException"/>
1289 public async Task RefreshConfiguration()
1291 this.Configuration = await this.Api.Configuration()
1292 .ConfigureAwait(false);
1294 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1295 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1298 public async Task GetListsApi()
1300 this.CheckAccountState();
1302 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1303 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1304 .ConfigureAwait(false);
1306 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1307 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1308 .ConfigureAwait(false);
1310 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1311 .Select(x => new ListElement(x, this))
1315 public async Task DeleteList(long listId)
1317 await this.Api.ListsDestroy(listId)
1319 .ConfigureAwait(false);
1321 var tabinfo = TabInformations.GetInstance();
1323 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1324 .Where(x => x.Id != listId)
1328 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1330 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1331 .ConfigureAwait(false);
1333 var list = await response.LoadJsonAsync()
1334 .ConfigureAwait(false);
1336 return new ListElement(list, this);
1339 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1341 this.CheckAccountState();
1343 var users = await this.Api.ListsMembers(listId, cursor)
1344 .ConfigureAwait(false);
1346 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1348 return users.NextCursor;
1351 public async Task CreateListApi(string listName, bool isPrivate, string description)
1353 this.CheckAccountState();
1355 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1356 .ConfigureAwait(false);
1358 var list = await response.LoadJsonAsync()
1359 .ConfigureAwait(false);
1361 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1364 public async Task<bool> ContainsUserAtList(long listId, string user)
1366 this.CheckAccountState();
1370 await this.Api.ListsMembersShow(listId, user)
1371 .ConfigureAwait(false);
1375 catch (TwitterApiException ex)
1376 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1382 public async Task<TwitterApiStatus?> GetInfoApi()
1384 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1386 if (MyCommon.EndingFlag) return null;
1388 var limits = await this.Api.ApplicationRateLimitStatus()
1389 .ConfigureAwait(false);
1391 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1393 return MyCommon.TwitterApiInfo;
1397 /// ブロック中のユーザーを更新します
1399 /// <exception cref="WebApiException"/>
1400 public async Task RefreshBlockIds()
1402 if (MyCommon.EndingFlag) return;
1405 var newBlockIds = Enumerable.Empty<long>();
1408 var ret = await this.Api.BlocksIds(cursor)
1409 .ConfigureAwait(false);
1411 newBlockIds = newBlockIds.Concat(ret.Ids);
1412 cursor = ret.NextCursor;
1414 while (cursor != 0);
1416 var blockIdsSet = newBlockIds.ToHashSet();
1417 blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1419 TabInformations.GetInstance().BlockIds = blockIdsSet;
1423 /// ミュート中のユーザーIDを更新します
1425 /// <exception cref="WebApiException"/>
1426 public async Task RefreshMuteUserIdsAsync()
1428 if (MyCommon.EndingFlag) return;
1430 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1431 .ConfigureAwait(false);
1433 TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1436 public string[] GetHashList()
1437 => this.postFactory.GetReceivedHashtags();
1439 private void CheckAccountState()
1441 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1442 throw new WebApiException("Auth error. Check your account");
1445 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1447 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1448 throw new WebApiException("Auth Err:try to re-authorization.");
1451 public int GetTextLengthRemain(string postText)
1453 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1454 if (matchDm.Success)
1455 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1457 return this.GetTextLengthRemainWeighted(postText);
1460 private int GetTextLengthRemainDM(string postText)
1465 while (pos < postText.Length)
1469 if (char.IsSurrogatePair(postText, pos))
1470 pos += 2; // サロゲートペアの場合は2文字分進める
1475 var urls = TweetExtractor.ExtractUrls(postText);
1476 foreach (var url in urls)
1478 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1479 ? this.Configuration.ShortUrlLengthHttps
1480 : this.Configuration.ShortUrlLength;
1482 textLength += shortUrlLength - url.Length;
1485 return this.Configuration.DmTextCharacterLimit - textLength;
1488 private int GetTextLengthRemainWeighted(string postText)
1490 var config = this.TextConfiguration;
1491 var totalWeight = 0;
1493 int GetWeightFromCodepoint(int codepoint)
1495 foreach (var weightRange in config.Ranges)
1497 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1498 return weightRange.Weight;
1501 return config.DefaultWeight;
1504 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1505 var emojis = config.EmojiParsingEnabled
1506 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1507 : Array.Empty<TwitterEntityEmoji>();
1509 var codepoints = postText.ToCodepoints().ToArray();
1511 while (index < codepoints.Length)
1513 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1514 if (urlEntity != null)
1516 totalWeight += config.TransformedURLLength * config.Scale;
1517 index = urlEntity.Indices[1];
1521 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1522 if (emojiEntity != null)
1524 totalWeight += GetWeightFromCodepoint(codepoints[index]);
1525 index = emojiEntity.Indices[1];
1529 var codepoint = codepoints[index];
1530 totalWeight += GetWeightFromCodepoint(codepoint);
1535 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1537 return remainWeight / config.Scale;
1541 /// プロフィール画像のサイズを指定したURLを生成
1544 /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1546 public static string CreateProfileImageUrl(string normalUrl, string size)
1550 "original" => normalUrl.Replace("_normal.", "."),
1551 "normal" => normalUrl,
1552 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1553 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1557 public static string DecideProfileImageSize(int sizePx)
1559 return sizePx switch
1568 public bool IsDisposed { get; private set; } = false;
1570 protected virtual void Dispose(bool disposing)
1572 if (this.IsDisposed)
1580 this.IsDisposed = true;
1583 public void Dispose()
1586 GC.SuppressFinalize(this);