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(TwitterAppToken appToken, string token, string tokenSecret, string username, long userId)
234 if (MyCommon.IsNullOrEmpty(token) || MyCommon.IsNullOrEmpty(tokenSecret) || MyCommon.IsNullOrEmpty(username))
236 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
238 this.ResetApiStatus();
239 this.Api.Initialize(appToken, token, tokenSecret, userId, username);
242 public async Task<PostClass?> PostStatus(PostStatusParams param)
244 this.CheckAccountState();
246 if (Twitter.DMSendTextRegex.IsMatch(param.Text))
248 var mediaId = param.MediaIds != null && param.MediaIds.Any() ? param.MediaIds[0] : (long?)null;
250 await this.SendDirectMessage(param.Text, mediaId)
251 .ConfigureAwait(false);
255 TwitterStatus status;
257 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
259 var request = new CreateTweetRequest
261 TweetText = param.Text,
262 InReplyToTweetId = param.InReplyToStatusId?.ToTwitterStatusId(),
263 ExcludeReplyUserIds = param.ExcludeReplyUserIds.Select(x => x.ToString()).ToArray(),
264 MediaIds = param.MediaIds.Select(x => x.ToString()).ToArray(),
265 AttachmentUrl = param.AttachmentUrl,
268 status = await request.Send(this.Api.Connection)
269 .ConfigureAwait(false);
273 var response = await this.Api.StatusesUpdate(
275 param.InReplyToStatusId?.ToTwitterStatusId(),
277 param.AutoPopulateReplyMetadata,
278 param.ExcludeReplyUserIds,
281 .ConfigureAwait(false);
283 status = await response.LoadJsonAsync()
284 .ConfigureAwait(false);
287 this.UpdateUserStats(status.User);
289 if (status.IdStr == this.previousStatusId)
290 throw new WebApiException("OK:Delaying?");
292 this.previousStatusId = status.IdStr;
295 var post = this.CreatePostsFromStatusData(status);
296 if (this.ReadOwnPost) post.IsRead = true;
300 public async Task DeleteTweet(TwitterStatusId tweetId)
302 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
304 var request = new DeleteTweetRequest
308 await request.Send(this.Api.Connection);
312 await this.Api.StatusesDestroy(tweetId)
317 public async Task<long> UploadMedia(IMediaItem item, string? mediaCategory = null)
319 this.CheckAccountState();
321 var mediaType = item.Extension switch
323 ".png" => "image/png",
324 ".jpg" => "image/jpeg",
325 ".jpeg" => "image/jpeg",
326 ".gif" => "image/gif",
327 _ => "application/octet-stream",
330 var initResponse = await this.Api.MediaUploadInit(item.Size, mediaType, mediaCategory)
331 .ConfigureAwait(false);
333 var initMedia = await initResponse.LoadJsonAsync()
334 .ConfigureAwait(false);
336 var mediaId = initMedia.MediaId;
338 await this.Api.MediaUploadAppend(mediaId, 0, item)
339 .ConfigureAwait(false);
341 var response = await this.Api.MediaUploadFinalize(mediaId)
342 .ConfigureAwait(false);
344 var media = await response.LoadJsonAsync()
345 .ConfigureAwait(false);
347 while (media.ProcessingInfo is TwitterUploadMediaResult.MediaProcessingInfo processingInfo)
349 switch (processingInfo.State)
358 throw new WebApiException($"Err:Upload failed ({processingInfo.Error?.Name})");
360 throw new WebApiException($"Err:Invalid state ({processingInfo.State})");
363 await Task.Delay(TimeSpan.FromSeconds(processingInfo.CheckAfterSecs ?? 5))
364 .ConfigureAwait(false);
366 media = await this.Api.MediaUploadStatus(mediaId)
367 .ConfigureAwait(false);
371 return media.MediaId;
374 public async Task SendDirectMessage(string postStr, long? mediaId = null)
376 this.CheckAccountState();
377 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
379 var mc = Twitter.DMSendTextRegex.Match(postStr);
381 var body = mc.Groups["body"].Value;
382 var recipientName = mc.Groups["id"].Value;
384 var recipient = await this.GetUserInfo(recipientName)
385 .ConfigureAwait(false);
387 var response = await this.Api.DirectMessagesEventsNew(recipient.Id, body, mediaId)
388 .ConfigureAwait(false);
390 var messageEventSingle = await response.LoadJsonAsync()
391 .ConfigureAwait(false);
393 await this.CreateDirectMessagesEventFromJson(messageEventSingle, read: true)
394 .ConfigureAwait(false);
397 public async Task<PostClass?> PostRetweet(PostId id, bool read)
399 this.CheckAccountState();
402 var post = TabInformations.GetInstance()[id];
404 throw new WebApiException("Err:Target isn't found.");
406 var target = post.RetweetedId ?? id; // 再RTの場合は元発言をRT
408 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
410 var request = new CreateRetweetRequest
412 TweetId = target.ToTwitterStatusId(),
414 await request.Send(this.Api.Connection).ConfigureAwait(false);
418 var response = await this.Api.StatusesRetweet(target.ToTwitterStatusId())
419 .ConfigureAwait(false);
421 var status = await response.LoadJsonAsync()
422 .ConfigureAwait(false);
427 var statusId = new TwitterStatusId(status.IdStr);
428 if (TabInformations.GetInstance().ContainsKey(statusId))
433 if (status.RetweetedStatus == null)
434 throw new WebApiException("Invalid Json!");
437 return this.CreatePostsFromStatusData(status) with
440 IsRead = this.ReadOwnPost ? true : read,
445 public async Task DeleteRetweet(PostClass post)
447 if (post.RetweetedId == null)
448 throw new ArgumentException("post is not retweeted status", nameof(post));
450 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
452 var request = new DeleteRetweetRequest
454 SourceTweetId = post.RetweetedId.ToTwitterStatusId(),
456 await request.Send(this.Api.Connection).ConfigureAwait(false);
460 await this.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
465 public async Task<TwitterUser> GetUserInfo(string screenName)
467 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
469 var request = new UserByScreenNameRequest
471 ScreenName = screenName,
473 var response = await request.Send(this.Api.Connection)
474 .ConfigureAwait(false);
476 return response.ToTwitterUser();
480 var user = await this.Api.UsersShow(screenName)
481 .ConfigureAwait(false);
487 public string Username
488 => this.Api.CurrentScreenName;
491 => this.Api.CurrentUserId;
493 public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
495 public bool RestrictFavCheck { get; set; }
497 public bool ReadOwnPost { get; set; }
499 public int FollowersCount { get; private set; }
501 public int FriendsCount { get; private set; }
503 public int StatusesCount { get; private set; }
505 public string Location { get; private set; } = "";
507 public string Bio { get; private set; } = "";
509 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
510 private void UpdateUserStats(TwitterUser self)
512 this.FollowersCount = self.FollowersCount;
513 this.FriendsCount = self.FriendsCount;
514 this.StatusesCount = self.StatusesCount;
515 this.Location = self.Location ?? "";
516 this.Bio = self.Description ?? "";
520 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
522 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
523 => count >= 20 && count <= GetMaxApiResultCount(type);
526 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
528 public static bool VerifyMoreApiResultCount(int count)
529 => count >= 20 && count <= 200;
532 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
534 public static bool VerifyFirstApiResultCount(int count)
535 => count >= 20 && count <= 200;
538 /// WORKERTYPEに応じた取得可能な最大件数を取得する
540 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
542 // 参照: REST APIs - 各endpointのcountパラメータ
543 // https://dev.twitter.com/rest/public
546 MyCommon.WORKERTYPE.Timeline => 100,
547 MyCommon.WORKERTYPE.Reply => 200,
548 MyCommon.WORKERTYPE.UserTimeline => 200,
549 MyCommon.WORKERTYPE.Favorites => 200,
550 MyCommon.WORKERTYPE.List => 200, // 不明
551 MyCommon.WORKERTYPE.PublicSearch => 100,
552 _ => throw new InvalidOperationException("Invalid type: " + type),
557 /// WORKERTYPEに応じた取得件数を取得する
559 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
561 if (SettingManager.Instance.Common.UseAdditionalCount)
565 case MyCommon.WORKERTYPE.Favorites:
566 if (SettingManager.Instance.Common.FavoritesCountApi != 0)
567 return SettingManager.Instance.Common.FavoritesCountApi;
569 case MyCommon.WORKERTYPE.List:
570 if (SettingManager.Instance.Common.ListCountApi != 0)
571 return SettingManager.Instance.Common.ListCountApi;
573 case MyCommon.WORKERTYPE.PublicSearch:
574 if (SettingManager.Instance.Common.SearchCountApi != 0)
575 return SettingManager.Instance.Common.SearchCountApi;
577 case MyCommon.WORKERTYPE.UserTimeline:
578 if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
579 return SettingManager.Instance.Common.UserTimelineCountApi;
582 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
584 return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
586 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
588 return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
593 var count = SettingManager.Instance.Common.CountApi;
595 if (type == MyCommon.WORKERTYPE.Reply)
596 count = SettingManager.Instance.Common.CountApiReply;
598 return Math.Min(count, GetMaxApiResultCount(type));
601 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
603 this.CheckAccountState();
605 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
607 TwitterStatus[] statuses;
608 if (SettingManager.Instance.Common.EnableTwitterV2Api)
610 var request = new GetTimelineRequest(this.UserId)
613 UntilId = more ? tab.OldestId as TwitterStatusId : null,
616 var response = await request.Send(this.Api.Connection)
617 .ConfigureAwait(false);
619 if (response.Data == null || response.Data.Length == 0)
622 var tweetIds = response.Data.Select(x => x.Id).ToList();
624 statuses = await this.Api.StatusesLookup(tweetIds)
625 .ConfigureAwait(false);
629 var maxId = more ? tab.OldestId : null;
631 statuses = await this.Api.StatusesHomeTimeline(count, maxId as TwitterStatusId)
632 .ConfigureAwait(false);
635 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
636 if (minimumId != null)
637 tab.OldestId = minimumId;
640 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
642 this.CheckAccountState();
644 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
646 TwitterStatus[] statuses;
649 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId as TwitterStatusId)
650 .ConfigureAwait(false);
654 statuses = await this.Api.StatusesMentionsTimeline(count)
655 .ConfigureAwait(false);
658 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
659 if (minimumId != null)
660 tab.OldestId = minimumId;
663 public async Task GetUserTimelineApi(bool read, UserTimelineTabModel tab, bool more)
665 this.CheckAccountState();
667 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
669 // Cookie を使用する場合のみ 99 件を超えて取得するとエラーが返る
670 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
671 count = Math.Min(count, 99);
673 TwitterStatus[] statuses;
674 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
676 var userId = tab.UserId;
677 if (MyCommon.IsNullOrEmpty(userId))
679 var user = await this.GetUserInfo(tab.ScreenName)
680 .ConfigureAwait(false);
683 tab.UserId = user.IdStr;
686 var request = new UserTweetsRequest(userId)
689 Cursor = more ? tab.CursorBottom : null,
691 var response = await request.Send(this.Api.Connection)
692 .ConfigureAwait(false);
694 statuses = response.Tweets.Select(x => x.ToTwitterStatus()).ToArray();
695 tab.CursorBottom = response.CursorBottom;
701 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count, maxId: tab.OldestId as TwitterStatusId)
702 .ConfigureAwait(false);
706 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count)
707 .ConfigureAwait(false);
711 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
713 if (minimumId != null)
714 tab.OldestId = minimumId;
717 public async Task<PostClass> GetStatusApi(bool read, TwitterStatusId id)
719 this.CheckAccountState();
721 TwitterStatus status;
722 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
724 var request = new TweetDetailRequest
728 var tweets = await request.Send(this.Api.Connection).ConfigureAwait(false);
729 status = tweets.Select(x => x.ToTwitterStatus())
730 .Where(x => x.IdStr == id.Id)
731 .FirstOrDefault() ?? throw new WebApiException("Empty result set");
735 status = await this.Api.StatusesShow(id)
736 .ConfigureAwait(false);
739 var item = this.CreatePostsFromStatusData(status);
742 if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
747 public async Task GetStatusApi(bool read, TwitterStatusId id, TabModel tab)
749 var post = await this.GetStatusApi(read, id)
750 .ConfigureAwait(false);
752 // 非同期アイコン取得&StatusDictionaryに追加
753 if (tab != null && tab.IsInnerStorageTabType)
754 tab.AddPostQueue(post);
756 TabInformations.GetInstance().AddPost(post);
759 private PostClass CreatePostsFromStatusData(TwitterStatus status)
760 => this.CreatePostsFromStatusData(status, favTweet: false);
762 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
763 => this.postFactory.CreateFromStatus(status, this.UserId, this.followerId, favTweet);
765 private PostId? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
767 PostId? minimumId = null;
769 var posts = items.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
771 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
773 foreach (var post in posts)
775 if (!post.IsPromoted)
777 if (minimumId == null || minimumId > post.StatusId)
778 minimumId = post.StatusId;
784 var id = post.StatusId;
787 if (TabInformations.GetInstance().ContainsKey(id)) continue;
791 if (tab.Contains(id)) continue;
796 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
797 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
800 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
802 if (tab != null && tab.IsInnerStorageTabType)
803 tab.AddPostQueue(post);
805 TabInformations.GetInstance().AddPost(post);
811 private PostId? CreatePostsFromSearchJson(TwitterStatus[] statuses, PublicSearchTabModel tab, bool read, bool more)
813 PostId? minimumId = null;
815 var posts = statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
817 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
819 foreach (var post in posts)
821 if (!post.IsPromoted)
823 if (minimumId == null || minimumId > post.StatusId)
824 minimumId = post.StatusId;
826 if (!more && (tab.SinceId == null || post.StatusId > tab.SinceId))
827 tab.SinceId = post.StatusId;
833 if (tab.Contains(post.StatusId))
838 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
840 tab.AddPostQueue(post);
846 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
848 var favTab = TabInformations.GetInstance().FavoriteTab;
849 long? minimumId = null;
851 foreach (var status in items)
853 if (minimumId == null || minimumId.Value > status.Id)
854 minimumId = status.Id;
859 if (favTab.Contains(new TwitterStatusId(status.IdStr)))
863 var post = this.CreatePostsFromStatusData(status, true);
867 TabInformations.GetInstance().AddPost(post);
873 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
875 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
877 TwitterStatus[] statuses;
878 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
880 var request = new ListLatestTweetsTimelineRequest(tab.ListInfo.Id.ToString())
883 Cursor = more ? tab.CursorBottom : null,
885 var response = await request.Send(this.Api.Connection)
886 .ConfigureAwait(false);
888 var convertedStatuses = response.Tweets.Select(x => x.ToTwitterStatus());
889 if (!SettingManager.Instance.Common.IsListsIncludeRts)
890 convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null);
892 statuses = convertedStatuses.ToArray();
893 tab.CursorBottom = response.CursorBottom;
897 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId as TwitterStatusId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
898 .ConfigureAwait(false);
902 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
903 .ConfigureAwait(false);
906 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
908 if (minimumId != null)
909 tab.OldestId = minimumId;
913 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
915 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
916 internal static PostClass FindTopOfReplyChain(IDictionary<PostId, PostClass> posts, PostId startStatusId)
918 if (!posts.ContainsKey(startStatusId))
919 throw new ArgumentException("startStatusId (" + startStatusId.Id + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
921 var nextPost = posts[startStatusId];
922 while (nextPost.InReplyToStatusId != null)
924 if (!posts.ContainsKey(nextPost.InReplyToStatusId))
926 nextPost = posts[nextPost.InReplyToStatusId];
932 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
934 var targetPost = tab.TargetPost;
936 if (targetPost.RetweetedId != null)
938 var originalPost = targetPost with
940 StatusId = targetPost.RetweetedId,
944 targetPost = originalPost;
947 var relPosts = new Dictionary<PostId, PostClass>();
948 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
951 var p = TabInformations.GetInstance()[targetPost.StatusId];
952 if (p != null && p.InReplyToStatusId != null)
958 p = await this.GetStatusApi(read, targetPost.StatusId.ToTwitterStatusId())
959 .ConfigureAwait(false);
963 relPosts.Add(targetPost.StatusId, targetPost);
965 Exception? lastException = null;
967 // in_reply_to_status_id を使用してリプライチェインを辿る
968 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
970 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
972 var inReplyToId = nextPost.InReplyToStatusId;
974 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
975 if (inReplyToPost == null)
979 inReplyToPost = await this.GetStatusApi(read, inReplyToId.ToTwitterStatusId())
980 .ConfigureAwait(false);
982 catch (WebApiException ex)
989 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
991 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
994 // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
995 var text = targetPost.Text;
996 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
997 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
998 foreach (var match in ma)
1000 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
1001 if (!relPosts.ContainsKey(statusId))
1003 var p = TabInformations.GetInstance()[statusId];
1008 p = await this.GetStatusApi(read, statusId)
1009 .ConfigureAwait(false);
1011 catch (WebApiException ex)
1019 relPosts.Add(p.StatusId, p);
1025 var firstPost = nextPost;
1026 var posts = await this.GetConversationPosts(firstPost, targetPost)
1027 .ConfigureAwait(false);
1029 foreach (var post in posts.OrderBy(x => x.StatusId))
1031 if (relPosts.ContainsKey(post.StatusId))
1034 // リプライチェーンが繋がらないツイートは除外
1035 if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId))
1038 relPosts.Add(post.StatusId, post);
1041 catch (WebException ex)
1046 relPosts.Values.ToList().ForEach(p =>
1048 var post = p with { };
1049 if (post.IsMe && !read && this.ReadOwnPost)
1054 tab.AddPostQueue(post);
1057 if (lastException != null)
1058 throw new WebApiException(lastException.Message, lastException);
1061 private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1063 var conversationId = firstPost.StatusId;
1064 var query = $"conversation_id:{conversationId.Id}";
1066 if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1067 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1069 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1071 var statuses = await this.Api.SearchTweets(query, count: 100)
1072 .ConfigureAwait(false);
1074 return statuses.Statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1077 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1079 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1081 TwitterStatus[] statuses;
1082 if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
1084 var request = new SearchTimelineRequest(tab.SearchWords)
1087 Cursor = more ? tab.CursorBottom : null,
1089 var response = await request.Send(this.Api.Connection)
1090 .ConfigureAwait(false);
1092 statuses = response.Tweets.Select(x => x.ToTwitterStatus()).ToArray();
1093 tab.CursorBottom = response.CursorBottom;
1097 TwitterStatusId? maxId = null;
1098 TwitterStatusId? sinceId = null;
1101 maxId = tab.OldestId as TwitterStatusId;
1105 sinceId = tab.SinceId as TwitterStatusId;
1108 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1109 .ConfigureAwait(false);
1111 statuses = searchResult.Statuses;
1114 if (!TabInformations.GetInstance().ContainsTab(tab))
1117 var minimumId = this.CreatePostsFromSearchJson(statuses, tab, read, more);
1119 if (minimumId != null)
1120 tab.OldestId = minimumId;
1123 public async Task GetDirectMessageEvents(bool read, DirectMessagesTabModel dmTab, bool backward)
1125 this.CheckAccountState();
1126 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1130 TwitterMessageEventList eventList;
1133 eventList = await this.Api.DirectMessagesEventsList(count, dmTab.NextCursor)
1134 .ConfigureAwait(false);
1138 eventList = await this.Api.DirectMessagesEventsList(count)
1139 .ConfigureAwait(false);
1142 dmTab.NextCursor = eventList.NextCursor;
1144 await this.CreateDirectMessagesEventFromJson(eventList, read)
1145 .ConfigureAwait(false);
1148 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1150 var eventList = new TwitterMessageEventList
1152 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1153 Events = new[] { eventSingle.Event },
1156 await this.CreateDirectMessagesEventFromJson(eventList, read)
1157 .ConfigureAwait(false);
1160 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1162 var events = eventList.Events
1163 .Where(x => x.Type == "message_create")
1166 if (events.Length == 0)
1169 var userIds = Enumerable.Concat(
1170 events.Select(x => x.MessageCreate.SenderId),
1171 events.Select(x => x.MessageCreate.Target.RecipientId)
1172 ).Distinct().ToArray();
1174 var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1175 .ToDictionary(x => x.IdStr);
1177 var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1179 this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1182 private void CreateDirectMessagesEventFromJson(
1183 IEnumerable<TwitterMessageEvent> events,
1184 IReadOnlyDictionary<string, TwitterUser> users,
1185 IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1188 var dmTab = TabInformations.GetInstance().DirectMessageTab;
1190 foreach (var eventItem in events)
1192 var post = this.postFactory.CreateFromDirectMessageEvent(eventItem, users, apps, this.UserId);
1195 if (post.IsMe && !read && this.ReadOwnPost)
1198 dmTab.AddPostQueue(post);
1202 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1204 this.CheckAccountState();
1206 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1208 TwitterStatus[] statuses;
1211 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1212 .ConfigureAwait(false);
1216 statuses = await this.Api.FavoritesList(count)
1217 .ConfigureAwait(false);
1220 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1222 if (minimumId != null)
1223 tab.OldestId = minimumId.Value;
1229 /// <exception cref="WebApiException"/>
1230 public async Task RefreshFollowerIds()
1232 if (MyCommon.EndingFlag) return;
1235 var newFollowerIds = Enumerable.Empty<long>();
1238 var ret = await this.Api.FollowersIds(cursor)
1239 .ConfigureAwait(false);
1241 if (ret.Ids == null)
1242 throw new WebApiException("ret.ids == null");
1244 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1245 cursor = ret.NextCursor;
1247 while (cursor != 0);
1249 this.followerId = newFollowerIds.ToHashSet();
1250 TabInformations.GetInstance().RefreshOwl(this.followerId);
1252 this.GetFollowersSuccess = true;
1256 /// RT 非表示ユーザーを更新します
1258 /// <exception cref="WebApiException"/>
1259 public async Task RefreshNoRetweetIds()
1261 if (MyCommon.EndingFlag) return;
1263 this.noRTId = await this.Api.NoRetweetIds()
1264 .ConfigureAwait(false);
1266 this.GetNoRetweetSuccess = true;
1270 /// t.co の文字列長などの設定情報を更新します
1272 /// <exception cref="WebApiException"/>
1273 public async Task RefreshConfiguration()
1275 this.Configuration = await this.Api.Configuration()
1276 .ConfigureAwait(false);
1278 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1279 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1282 public async Task GetListsApi()
1284 this.CheckAccountState();
1286 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1287 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1288 .ConfigureAwait(false);
1290 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1291 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1292 .ConfigureAwait(false);
1294 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1295 .Select(x => new ListElement(x, this))
1299 public async Task DeleteList(long listId)
1301 await this.Api.ListsDestroy(listId)
1303 .ConfigureAwait(false);
1305 var tabinfo = TabInformations.GetInstance();
1307 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1308 .Where(x => x.Id != listId)
1312 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1314 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1315 .ConfigureAwait(false);
1317 var list = await response.LoadJsonAsync()
1318 .ConfigureAwait(false);
1320 return new ListElement(list, this);
1323 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1325 this.CheckAccountState();
1327 var users = await this.Api.ListsMembers(listId, cursor)
1328 .ConfigureAwait(false);
1330 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1332 return users.NextCursor;
1335 public async Task CreateListApi(string listName, bool isPrivate, string description)
1337 this.CheckAccountState();
1339 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1340 .ConfigureAwait(false);
1342 var list = await response.LoadJsonAsync()
1343 .ConfigureAwait(false);
1345 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1348 public async Task<bool> ContainsUserAtList(long listId, string user)
1350 this.CheckAccountState();
1354 await this.Api.ListsMembersShow(listId, user)
1355 .ConfigureAwait(false);
1359 catch (TwitterApiException ex)
1360 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1366 public async Task<TwitterApiStatus?> GetInfoApi()
1368 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1370 if (MyCommon.EndingFlag) return null;
1372 var limits = await this.Api.ApplicationRateLimitStatus()
1373 .ConfigureAwait(false);
1375 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1377 return MyCommon.TwitterApiInfo;
1381 /// ブロック中のユーザーを更新します
1383 /// <exception cref="WebApiException"/>
1384 public async Task RefreshBlockIds()
1386 if (MyCommon.EndingFlag) return;
1389 var newBlockIds = Enumerable.Empty<long>();
1392 var ret = await this.Api.BlocksIds(cursor)
1393 .ConfigureAwait(false);
1395 newBlockIds = newBlockIds.Concat(ret.Ids);
1396 cursor = ret.NextCursor;
1398 while (cursor != 0);
1400 var blockIdsSet = newBlockIds.ToHashSet();
1401 blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1403 TabInformations.GetInstance().BlockIds = blockIdsSet;
1407 /// ミュート中のユーザーIDを更新します
1409 /// <exception cref="WebApiException"/>
1410 public async Task RefreshMuteUserIdsAsync()
1412 if (MyCommon.EndingFlag) return;
1414 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1415 .ConfigureAwait(false);
1417 TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1420 public string[] GetHashList()
1421 => this.postFactory.GetReceivedHashtags();
1423 public string AccessToken
1424 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1426 public string AccessTokenSecret
1427 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1429 private void CheckAccountState()
1431 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1432 throw new WebApiException("Auth error. Check your account");
1435 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1437 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1438 throw new WebApiException("Auth Err:try to re-authorization.");
1441 public int GetTextLengthRemain(string postText)
1443 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1444 if (matchDm.Success)
1445 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1447 return this.GetTextLengthRemainWeighted(postText);
1450 private int GetTextLengthRemainDM(string postText)
1455 while (pos < postText.Length)
1459 if (char.IsSurrogatePair(postText, pos))
1460 pos += 2; // サロゲートペアの場合は2文字分進める
1465 var urls = TweetExtractor.ExtractUrls(postText);
1466 foreach (var url in urls)
1468 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1469 ? this.Configuration.ShortUrlLengthHttps
1470 : this.Configuration.ShortUrlLength;
1472 textLength += shortUrlLength - url.Length;
1475 return this.Configuration.DmTextCharacterLimit - textLength;
1478 private int GetTextLengthRemainWeighted(string postText)
1480 var config = this.TextConfiguration;
1481 var totalWeight = 0;
1483 int GetWeightFromCodepoint(int codepoint)
1485 foreach (var weightRange in config.Ranges)
1487 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1488 return weightRange.Weight;
1491 return config.DefaultWeight;
1494 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1495 var emojis = config.EmojiParsingEnabled
1496 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1497 : Array.Empty<TwitterEntityEmoji>();
1499 var codepoints = postText.ToCodepoints().ToArray();
1501 while (index < codepoints.Length)
1503 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1504 if (urlEntity != null)
1506 totalWeight += config.TransformedURLLength * config.Scale;
1507 index = urlEntity.Indices[1];
1511 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1512 if (emojiEntity != null)
1514 totalWeight += GetWeightFromCodepoint(codepoints[index]);
1515 index = emojiEntity.Indices[1];
1519 var codepoint = codepoints[index];
1520 totalWeight += GetWeightFromCodepoint(codepoint);
1525 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1527 return remainWeight / config.Scale;
1531 /// プロフィール画像のサイズを指定したURLを生成
1534 /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1536 public static string CreateProfileImageUrl(string normalUrl, string size)
1540 "original" => normalUrl.Replace("_normal.", "."),
1541 "normal" => normalUrl,
1542 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1543 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1547 public static string DecideProfileImageSize(int sizePx)
1549 return sizePx switch
1558 public bool IsDisposed { get; private set; } = false;
1560 protected virtual void Dispose(bool disposing)
1562 if (this.IsDisposed)
1570 this.IsDisposed = true;
1573 public void Dispose()
1576 GC.SuppressFinalize(this);