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;
176 private readonly PostUrlExpander urlExpander;
178 private string? previousStatusId = null;
180 public Twitter(TwitterApi api)
182 this.postFactory = new(TabInformations.GetInstance());
183 this.urlExpander = new(ShortUrl.Instance);
186 this.Configuration = TwitterConfiguration.DefaultConfiguration();
187 this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
190 public TwitterApiAccessLevel AccessLevel
191 => MyCommon.TwitterApiInfo.AccessLevel;
193 protected void ResetApiStatus()
194 => MyCommon.TwitterApiInfo.Reset();
196 public void ClearAuthInfo()
198 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
199 this.ResetApiStatus();
202 public void VerifyCredentials()
206 this.VerifyCredentialsAsync().Wait();
208 catch (AggregateException ex) when (ex.InnerException is WebApiException)
210 throw new WebApiException(ex.InnerException.Message, ex);
214 public async Task VerifyCredentialsAsync()
216 var user = await this.Api.AccountVerifyCredentials()
217 .ConfigureAwait(false);
219 this.UpdateUserStats(user);
222 public void Initialize(ITwitterCredential credential, string username, long userId)
225 if (credential is TwitterCredentialNone)
226 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
228 this.ResetApiStatus();
229 this.Api.Initialize(credential, userId, username);
232 public async Task<PostClass?> PostStatus(PostStatusParams param)
234 this.CheckAccountState();
236 if (Twitter.DMSendTextRegex.IsMatch(param.Text))
238 var mediaId = param.MediaIds != null && param.MediaIds.Any() ? param.MediaIds[0] : (long?)null;
240 await this.SendDirectMessage(param.Text, mediaId)
241 .ConfigureAwait(false);
245 TwitterStatus status;
247 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
249 var request = new CreateTweetRequest
251 TweetText = param.Text,
252 InReplyToTweetId = param.InReplyToStatusId?.ToTwitterStatusId(),
253 ExcludeReplyUserIds = param.ExcludeReplyUserIds.Select(x => x.ToString()).ToArray(),
254 MediaIds = param.MediaIds.Select(x => x.ToString()).ToArray(),
255 AttachmentUrl = param.AttachmentUrl,
258 status = await request.Send(this.Api.Connection)
259 .ConfigureAwait(false);
263 var response = await this.Api.StatusesUpdate(
265 param.InReplyToStatusId?.ToTwitterStatusId(),
267 param.AutoPopulateReplyMetadata,
268 param.ExcludeReplyUserIds,
271 .ConfigureAwait(false);
273 status = await response.LoadJsonAsync()
274 .ConfigureAwait(false);
277 this.UpdateUserStats(status.User);
279 if (status.IdStr == this.previousStatusId)
280 throw new WebApiException("OK:Delaying?");
282 this.previousStatusId = status.IdStr;
285 var post = this.CreatePostsFromStatusData(status);
286 if (this.ReadOwnPost) post.IsRead = true;
290 public async Task DeleteTweet(TwitterStatusId tweetId)
292 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
294 var request = new DeleteTweetRequest
298 await request.Send(this.Api.Connection);
302 await this.Api.StatusesDestroy(tweetId)
307 public async Task<long> UploadMedia(IMediaItem item, string? mediaCategory = null)
309 this.CheckAccountState();
311 var mediaType = item.Extension switch
313 ".png" => "image/png",
314 ".jpg" => "image/jpeg",
315 ".jpeg" => "image/jpeg",
316 ".gif" => "image/gif",
317 _ => "application/octet-stream",
320 var initResponse = await this.Api.MediaUploadInit(item.Size, mediaType, mediaCategory)
321 .ConfigureAwait(false);
323 var initMedia = await initResponse.LoadJsonAsync()
324 .ConfigureAwait(false);
326 var mediaId = initMedia.MediaId;
328 await this.Api.MediaUploadAppend(mediaId, 0, item)
329 .ConfigureAwait(false);
331 var response = await this.Api.MediaUploadFinalize(mediaId)
332 .ConfigureAwait(false);
334 var media = await response.LoadJsonAsync()
335 .ConfigureAwait(false);
337 while (media.ProcessingInfo is TwitterUploadMediaResult.MediaProcessingInfo processingInfo)
339 switch (processingInfo.State)
348 throw new WebApiException($"Err:Upload failed ({processingInfo.Error?.Name})");
350 throw new WebApiException($"Err:Invalid state ({processingInfo.State})");
353 await Task.Delay(TimeSpan.FromSeconds(processingInfo.CheckAfterSecs ?? 5))
354 .ConfigureAwait(false);
356 media = await this.Api.MediaUploadStatus(mediaId)
357 .ConfigureAwait(false);
361 return media.MediaId;
364 public async Task SendDirectMessage(string postStr, long? mediaId = null)
366 this.CheckAccountState();
367 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
369 var mc = Twitter.DMSendTextRegex.Match(postStr);
371 var body = mc.Groups["body"].Value;
372 var recipientName = mc.Groups["id"].Value;
374 var recipient = await this.GetUserInfo(recipientName)
375 .ConfigureAwait(false);
377 var response = await this.Api.DirectMessagesEventsNew(recipient.Id, body, mediaId)
378 .ConfigureAwait(false);
380 var messageEventSingle = await response.LoadJsonAsync()
381 .ConfigureAwait(false);
383 await this.CreateDirectMessagesEventFromJson(messageEventSingle, read: true)
384 .ConfigureAwait(false);
387 public async Task<PostClass?> PostRetweet(PostId id, bool read)
389 this.CheckAccountState();
392 var post = TabInformations.GetInstance()[id];
394 throw new WebApiException("Err:Target isn't found.");
396 var target = post.RetweetedId ?? id; // 再RTの場合は元発言をRT
398 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
400 var request = new CreateRetweetRequest
402 TweetId = target.ToTwitterStatusId(),
404 await request.Send(this.Api.Connection).ConfigureAwait(false);
408 var response = await this.Api.StatusesRetweet(target.ToTwitterStatusId())
409 .ConfigureAwait(false);
411 var status = await response.LoadJsonAsync()
412 .ConfigureAwait(false);
417 var statusId = new TwitterStatusId(status.IdStr);
418 if (TabInformations.GetInstance().ContainsKey(statusId))
423 if (status.RetweetedStatus == null)
424 throw new WebApiException("Invalid Json!");
427 return this.CreatePostsFromStatusData(status) with
430 IsRead = this.ReadOwnPost ? true : read,
435 public async Task DeleteRetweet(PostClass post)
437 if (post.RetweetedId == null)
438 throw new ArgumentException("post is not retweeted status", nameof(post));
440 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
442 var request = new DeleteRetweetRequest
444 SourceTweetId = post.RetweetedId.ToTwitterStatusId(),
446 await request.Send(this.Api.Connection).ConfigureAwait(false);
450 await this.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
455 public async Task<TwitterUser> GetUserInfo(string screenName)
457 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
459 var request = new UserByScreenNameRequest
461 ScreenName = screenName,
463 var response = await request.Send(this.Api.Connection)
464 .ConfigureAwait(false);
466 return response.ToTwitterUser();
470 var user = await this.Api.UsersShow(screenName)
471 .ConfigureAwait(false);
477 public string Username
478 => this.Api.CurrentScreenName;
481 => this.Api.CurrentUserId;
483 public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
485 public bool RestrictFavCheck { get; set; }
487 public bool ReadOwnPost { get; set; }
489 public int FollowersCount { get; private set; }
491 public int FriendsCount { get; private set; }
493 public int StatusesCount { get; private set; }
495 public string Location { get; private set; } = "";
497 public string Bio { get; private set; } = "";
499 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
500 private void UpdateUserStats(TwitterUser self)
502 this.FollowersCount = self.FollowersCount;
503 this.FriendsCount = self.FriendsCount;
504 this.StatusesCount = self.StatusesCount;
505 this.Location = self.Location ?? "";
506 this.Bio = self.Description ?? "";
510 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
512 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
513 => count >= 20 && count <= GetMaxApiResultCount(type);
516 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
518 public static bool VerifyMoreApiResultCount(int count)
519 => count >= 20 && count <= 200;
522 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
524 public static bool VerifyFirstApiResultCount(int count)
525 => count >= 20 && count <= 200;
528 /// WORKERTYPEに応じた取得可能な最大件数を取得する
530 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
532 // 参照: REST APIs - 各endpointのcountパラメータ
533 // https://dev.twitter.com/rest/public
536 MyCommon.WORKERTYPE.Timeline => 100,
537 MyCommon.WORKERTYPE.Reply => 200,
538 MyCommon.WORKERTYPE.UserTimeline => 200,
539 MyCommon.WORKERTYPE.Favorites => 200,
540 MyCommon.WORKERTYPE.List => 200, // 不明
541 MyCommon.WORKERTYPE.PublicSearch => 100,
542 _ => throw new InvalidOperationException("Invalid type: " + type),
547 /// WORKERTYPEに応じた取得件数を取得する
549 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
551 if (SettingManager.Instance.Common.UseAdditionalCount)
555 case MyCommon.WORKERTYPE.Favorites:
556 if (SettingManager.Instance.Common.FavoritesCountApi != 0)
557 return SettingManager.Instance.Common.FavoritesCountApi;
559 case MyCommon.WORKERTYPE.List:
560 if (SettingManager.Instance.Common.ListCountApi != 0)
561 return SettingManager.Instance.Common.ListCountApi;
563 case MyCommon.WORKERTYPE.PublicSearch:
564 if (SettingManager.Instance.Common.SearchCountApi != 0)
565 return SettingManager.Instance.Common.SearchCountApi;
567 case MyCommon.WORKERTYPE.UserTimeline:
568 if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
569 return SettingManager.Instance.Common.UserTimelineCountApi;
572 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
574 return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
576 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
578 return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
583 var count = SettingManager.Instance.Common.CountApi;
585 if (type == MyCommon.WORKERTYPE.Reply)
586 count = SettingManager.Instance.Common.CountApiReply;
588 return Math.Min(count, GetMaxApiResultCount(type));
591 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
593 this.CheckAccountState();
595 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
597 TwitterStatus[] statuses;
598 if (SettingManager.Instance.Common.EnableTwitterV2Api)
600 var request = new GetTimelineRequest(this.UserId)
603 UntilId = more ? tab.OldestId as TwitterStatusId : null,
606 var response = await request.Send(this.Api.Connection)
607 .ConfigureAwait(false);
609 if (response.Data == null || response.Data.Length == 0)
612 var tweetIds = response.Data.Select(x => x.Id).ToList();
614 statuses = await this.Api.StatusesLookup(tweetIds)
615 .ConfigureAwait(false);
619 var maxId = more ? tab.OldestId : null;
621 statuses = await this.Api.StatusesHomeTimeline(count, maxId as TwitterStatusId)
622 .ConfigureAwait(false);
625 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
626 if (minimumId != null)
627 tab.OldestId = minimumId;
630 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
632 this.CheckAccountState();
634 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
636 TwitterStatus[] statuses;
639 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId as TwitterStatusId)
640 .ConfigureAwait(false);
644 statuses = await this.Api.StatusesMentionsTimeline(count)
645 .ConfigureAwait(false);
648 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
649 if (minimumId != null)
650 tab.OldestId = minimumId;
653 public async Task GetUserTimelineApi(bool read, UserTimelineTabModel tab, bool more)
655 this.CheckAccountState();
657 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
659 TwitterStatus[] statuses;
660 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
662 var userId = tab.UserId;
663 if (MyCommon.IsNullOrEmpty(userId))
665 var user = await this.GetUserInfo(tab.ScreenName)
666 .ConfigureAwait(false);
669 tab.UserId = user.IdStr;
672 var request = new UserTweetsAndRepliesRequest(userId)
675 Cursor = more ? tab.CursorBottom : tab.CursorTop,
677 var response = await request.Send(this.Api.Connection)
678 .ConfigureAwait(false);
680 statuses = response.Tweets
681 .Where(x => !x.IsTombstone)
682 .Select(x => x.ToTwitterStatus())
683 .Where(x => x.User.IdStr == userId) // リプライツリーに含まれる他ユーザーのツイートを除外
686 tab.CursorBottom = response.CursorBottom;
689 tab.CursorTop = response.CursorTop;
695 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count, maxId: tab.OldestId as TwitterStatusId)
696 .ConfigureAwait(false);
700 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count)
701 .ConfigureAwait(false);
705 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
707 if (minimumId != null)
708 tab.OldestId = minimumId;
711 public async Task<PostClass> GetStatusApi(bool read, TwitterStatusId id)
713 this.CheckAccountState();
715 TwitterStatus status;
716 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
718 var request = new TweetDetailRequest
722 var tweets = await request.Send(this.Api.Connection).ConfigureAwait(false);
723 status = tweets.Select(x => x.ToTwitterStatus())
724 .Where(x => x.IdStr == id.Id)
725 .FirstOrDefault() ?? throw new WebApiException("Empty result set");
729 status = await this.Api.StatusesShow(id)
730 .ConfigureAwait(false);
733 var item = this.CreatePostsFromStatusData(status);
736 if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
741 public async Task GetStatusApi(bool read, TwitterStatusId id, TabModel tab)
743 var post = await this.GetStatusApi(read, id)
744 .ConfigureAwait(false);
746 // 非同期アイコン取得&StatusDictionaryに追加
747 if (tab != null && tab.IsInnerStorageTabType)
748 tab.AddPostQueue(post);
750 TabInformations.GetInstance().AddPost(post);
753 private PostClass CreatePostsFromStatusData(TwitterStatus status)
754 => this.CreatePostsFromStatusData(status, favTweet: false);
756 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
758 var post = this.postFactory.CreateFromStatus(status, this.UserId, this.followerId, favTweet);
759 _ = this.urlExpander.Expand(post);
764 private PostId? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
766 PostId? minimumId = null;
768 var posts = items.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
770 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
772 foreach (var post in posts)
774 if (!post.IsPromoted)
776 if (minimumId == null || minimumId > post.StatusId)
777 minimumId = post.StatusId;
783 var id = post.StatusId;
786 if (TabInformations.GetInstance().ContainsKey(id)) continue;
790 if (tab.Contains(id)) continue;
795 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
796 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
799 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
801 if (tab != null && tab.IsInnerStorageTabType)
802 tab.AddPostQueue(post);
804 TabInformations.GetInstance().AddPost(post);
810 private PostId? CreatePostsFromSearchJson(TwitterStatus[] statuses, PublicSearchTabModel tab, bool read, bool more)
812 PostId? minimumId = null;
814 var posts = statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
816 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
818 foreach (var post in posts)
820 if (!post.IsPromoted)
822 if (minimumId == null || minimumId > post.StatusId)
823 minimumId = post.StatusId;
825 if (!more && (tab.SinceId == null || post.StatusId > tab.SinceId))
826 tab.SinceId = post.StatusId;
832 if (tab.Contains(post.StatusId))
837 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
839 tab.AddPostQueue(post);
845 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
847 var favTab = TabInformations.GetInstance().FavoriteTab;
848 long? minimumId = null;
850 foreach (var status in items)
852 if (minimumId == null || minimumId.Value > status.Id)
853 minimumId = status.Id;
858 if (favTab.Contains(new TwitterStatusId(status.IdStr)))
862 var post = this.CreatePostsFromStatusData(status, true);
866 TabInformations.GetInstance().AddPost(post);
872 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
874 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
876 TwitterStatus[] statuses;
877 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
879 var request = new ListLatestTweetsTimelineRequest(tab.ListInfo.Id.ToString())
882 Cursor = more ? tab.CursorBottom : tab.CursorTop,
884 var response = await request.Send(this.Api.Connection)
885 .ConfigureAwait(false);
887 var convertedStatuses = response.Tweets
888 .Where(x => !x.IsTombstone)
889 .Select(x => x.ToTwitterStatus());
891 if (!SettingManager.Instance.Common.IsListsIncludeRts)
892 convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null);
894 statuses = convertedStatuses.ToArray();
895 tab.CursorBottom = response.CursorBottom;
898 tab.CursorTop = response.CursorTop;
902 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId as TwitterStatusId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
903 .ConfigureAwait(false);
907 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
908 .ConfigureAwait(false);
911 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
913 if (minimumId != null)
914 tab.OldestId = minimumId;
918 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
920 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
921 internal static PostClass FindTopOfReplyChain(IDictionary<PostId, PostClass> posts, PostId startStatusId)
923 if (!posts.ContainsKey(startStatusId))
924 throw new ArgumentException("startStatusId (" + startStatusId.Id + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
926 var nextPost = posts[startStatusId];
927 while (nextPost.InReplyToStatusId != null)
929 if (!posts.ContainsKey(nextPost.InReplyToStatusId))
931 nextPost = posts[nextPost.InReplyToStatusId];
937 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
939 var targetPost = tab.TargetPost;
941 if (targetPost.RetweetedId != null)
943 var originalPost = targetPost with
945 StatusId = targetPost.RetweetedId,
949 targetPost = originalPost;
952 var relPosts = new Dictionary<PostId, PostClass>();
953 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
956 var p = TabInformations.GetInstance()[targetPost.StatusId];
957 if (p != null && p.InReplyToStatusId != null)
963 p = await this.GetStatusApi(read, targetPost.StatusId.ToTwitterStatusId())
964 .ConfigureAwait(false);
968 relPosts.Add(targetPost.StatusId, targetPost);
970 Exception? lastException = null;
972 // in_reply_to_status_id を使用してリプライチェインを辿る
973 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
975 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
977 var inReplyToId = nextPost.InReplyToStatusId;
979 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
980 if (inReplyToPost == null)
984 inReplyToPost = await this.GetStatusApi(read, inReplyToId.ToTwitterStatusId())
985 .ConfigureAwait(false);
987 catch (WebApiException ex)
994 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
996 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
999 // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1000 var text = targetPost.Text;
1001 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1002 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1003 foreach (var match in ma)
1005 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
1006 if (!relPosts.ContainsKey(statusId))
1008 var p = TabInformations.GetInstance()[statusId];
1013 p = await this.GetStatusApi(read, statusId)
1014 .ConfigureAwait(false);
1016 catch (WebApiException ex)
1024 relPosts.Add(p.StatusId, p);
1030 var firstPost = nextPost;
1031 var posts = await this.GetConversationPosts(firstPost, targetPost)
1032 .ConfigureAwait(false);
1034 foreach (var post in posts.OrderBy(x => x.StatusId))
1036 if (relPosts.ContainsKey(post.StatusId))
1039 // リプライチェーンが繋がらないツイートは除外
1040 if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId))
1043 relPosts.Add(post.StatusId, post);
1046 catch (WebException ex)
1051 relPosts.Values.ToList().ForEach(p =>
1053 var post = p with { };
1054 if (post.IsMe && !read && this.ReadOwnPost)
1059 tab.AddPostQueue(post);
1062 if (lastException != null)
1063 throw new WebApiException(lastException.Message, lastException);
1066 private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1068 var conversationId = firstPost.StatusId;
1069 var query = $"conversation_id:{conversationId.Id}";
1071 if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1072 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1074 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1076 var statuses = await this.Api.SearchTweets(query, count: 100)
1077 .ConfigureAwait(false);
1079 return statuses.Statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1082 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1084 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1086 TwitterStatus[] statuses;
1087 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
1089 var request = new SearchTimelineRequest(tab.SearchWords)
1092 Cursor = more ? tab.CursorBottom : tab.CursorTop,
1094 var response = await request.Send(this.Api.Connection)
1095 .ConfigureAwait(false);
1097 statuses = response.Tweets
1098 .Where(x => !x.IsTombstone)
1099 .Select(x => x.ToTwitterStatus())
1102 tab.CursorBottom = response.CursorBottom;
1105 tab.CursorTop = response.CursorTop;
1109 TwitterStatusId? maxId = null;
1110 TwitterStatusId? sinceId = null;
1113 maxId = tab.OldestId as TwitterStatusId;
1117 sinceId = tab.SinceId as TwitterStatusId;
1120 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1121 .ConfigureAwait(false);
1123 statuses = searchResult.Statuses;
1126 if (!TabInformations.GetInstance().ContainsTab(tab))
1129 var minimumId = this.CreatePostsFromSearchJson(statuses, tab, read, more);
1131 if (minimumId != null)
1132 tab.OldestId = minimumId;
1135 public async Task GetDirectMessageEvents(bool read, DirectMessagesTabModel dmTab, bool backward)
1137 this.CheckAccountState();
1138 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1142 TwitterMessageEventList eventList;
1145 eventList = await this.Api.DirectMessagesEventsList(count, dmTab.NextCursor)
1146 .ConfigureAwait(false);
1150 eventList = await this.Api.DirectMessagesEventsList(count)
1151 .ConfigureAwait(false);
1154 dmTab.NextCursor = eventList.NextCursor;
1156 await this.CreateDirectMessagesEventFromJson(eventList, read)
1157 .ConfigureAwait(false);
1160 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1162 var eventList = new TwitterMessageEventList
1164 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1165 Events = new[] { eventSingle.Event },
1168 await this.CreateDirectMessagesEventFromJson(eventList, read)
1169 .ConfigureAwait(false);
1172 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1174 var events = eventList.Events
1175 .Where(x => x.Type == "message_create")
1178 if (events.Length == 0)
1181 var userIds = Enumerable.Concat(
1182 events.Select(x => x.MessageCreate.SenderId),
1183 events.Select(x => x.MessageCreate.Target.RecipientId)
1184 ).Distinct().ToArray();
1186 var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1187 .ToDictionary(x => x.IdStr);
1189 var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1191 this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1194 private void CreateDirectMessagesEventFromJson(
1195 IEnumerable<TwitterMessageEvent> events,
1196 IReadOnlyDictionary<string, TwitterUser> users,
1197 IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1200 var dmTab = TabInformations.GetInstance().DirectMessageTab;
1202 foreach (var eventItem in events)
1204 var post = this.postFactory.CreateFromDirectMessageEvent(eventItem, users, apps, this.UserId);
1205 _ = this.urlExpander.Expand(post);
1208 if (post.IsMe && !read && this.ReadOwnPost)
1211 dmTab.AddPostQueue(post);
1215 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1217 this.CheckAccountState();
1219 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1221 TwitterStatus[] statuses;
1224 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1225 .ConfigureAwait(false);
1229 statuses = await this.Api.FavoritesList(count)
1230 .ConfigureAwait(false);
1233 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1235 if (minimumId != null)
1236 tab.OldestId = minimumId.Value;
1242 /// <exception cref="WebApiException"/>
1243 public async Task RefreshFollowerIds()
1245 if (MyCommon.EndingFlag) return;
1248 var newFollowerIds = Enumerable.Empty<long>();
1251 var ret = await this.Api.FollowersIds(cursor)
1252 .ConfigureAwait(false);
1254 if (ret.Ids == null)
1255 throw new WebApiException("ret.ids == null");
1257 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1258 cursor = ret.NextCursor;
1260 while (cursor != 0);
1262 this.followerId = newFollowerIds.ToHashSet();
1263 TabInformations.GetInstance().RefreshOwl(this.followerId);
1265 this.GetFollowersSuccess = true;
1269 /// RT 非表示ユーザーを更新します
1271 /// <exception cref="WebApiException"/>
1272 public async Task RefreshNoRetweetIds()
1274 if (MyCommon.EndingFlag) return;
1276 this.noRTId = await this.Api.NoRetweetIds()
1277 .ConfigureAwait(false);
1279 this.GetNoRetweetSuccess = true;
1283 /// t.co の文字列長などの設定情報を更新します
1285 /// <exception cref="WebApiException"/>
1286 public async Task RefreshConfiguration()
1288 this.Configuration = await this.Api.Configuration()
1289 .ConfigureAwait(false);
1291 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1292 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1295 public async Task GetListsApi()
1297 this.CheckAccountState();
1299 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1300 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1301 .ConfigureAwait(false);
1303 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1304 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1305 .ConfigureAwait(false);
1307 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1308 .Select(x => new ListElement(x, this))
1312 public async Task DeleteList(long listId)
1314 await this.Api.ListsDestroy(listId)
1316 .ConfigureAwait(false);
1318 var tabinfo = TabInformations.GetInstance();
1320 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1321 .Where(x => x.Id != listId)
1325 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1327 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1328 .ConfigureAwait(false);
1330 var list = await response.LoadJsonAsync()
1331 .ConfigureAwait(false);
1333 return new ListElement(list, this);
1336 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1338 this.CheckAccountState();
1340 var users = await this.Api.ListsMembers(listId, cursor)
1341 .ConfigureAwait(false);
1343 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1345 return users.NextCursor;
1348 public async Task CreateListApi(string listName, bool isPrivate, string description)
1350 this.CheckAccountState();
1352 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1353 .ConfigureAwait(false);
1355 var list = await response.LoadJsonAsync()
1356 .ConfigureAwait(false);
1358 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1361 public async Task<bool> ContainsUserAtList(long listId, string user)
1363 this.CheckAccountState();
1367 await this.Api.ListsMembersShow(listId, user)
1368 .ConfigureAwait(false);
1372 catch (TwitterApiException ex)
1373 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1379 public async Task<TwitterApiStatus?> GetInfoApi()
1381 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1383 if (MyCommon.EndingFlag) return null;
1385 var limits = await this.Api.ApplicationRateLimitStatus()
1386 .ConfigureAwait(false);
1388 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1390 return MyCommon.TwitterApiInfo;
1394 /// ブロック中のユーザーを更新します
1396 /// <exception cref="WebApiException"/>
1397 public async Task RefreshBlockIds()
1399 if (MyCommon.EndingFlag) return;
1402 var newBlockIds = Enumerable.Empty<long>();
1405 var ret = await this.Api.BlocksIds(cursor)
1406 .ConfigureAwait(false);
1408 newBlockIds = newBlockIds.Concat(ret.Ids);
1409 cursor = ret.NextCursor;
1411 while (cursor != 0);
1413 var blockIdsSet = newBlockIds.ToHashSet();
1414 blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1416 TabInformations.GetInstance().BlockIds = blockIdsSet;
1420 /// ミュート中のユーザーIDを更新します
1422 /// <exception cref="WebApiException"/>
1423 public async Task RefreshMuteUserIdsAsync()
1425 if (MyCommon.EndingFlag) return;
1427 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1428 .ConfigureAwait(false);
1430 TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1433 public string[] GetHashList()
1434 => this.postFactory.GetReceivedHashtags();
1436 private void CheckAccountState()
1438 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1439 throw new WebApiException("Auth error. Check your account");
1442 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1444 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1445 throw new WebApiException("Auth Err:try to re-authorization.");
1448 public int GetTextLengthRemain(string postText)
1450 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1451 if (matchDm.Success)
1452 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1454 return this.GetTextLengthRemainWeighted(postText);
1457 private int GetTextLengthRemainDM(string postText)
1462 while (pos < postText.Length)
1466 if (char.IsSurrogatePair(postText, pos))
1467 pos += 2; // サロゲートペアの場合は2文字分進める
1472 var urls = TweetExtractor.ExtractUrls(postText);
1473 foreach (var url in urls)
1475 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1476 ? this.Configuration.ShortUrlLengthHttps
1477 : this.Configuration.ShortUrlLength;
1479 textLength += shortUrlLength - url.Length;
1482 return this.Configuration.DmTextCharacterLimit - textLength;
1485 private int GetTextLengthRemainWeighted(string postText)
1487 var config = this.TextConfiguration;
1488 var totalWeight = 0;
1490 int GetWeightFromCodepoint(int codepoint)
1492 foreach (var weightRange in config.Ranges)
1494 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1495 return weightRange.Weight;
1498 return config.DefaultWeight;
1501 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1502 var emojis = config.EmojiParsingEnabled
1503 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1504 : Array.Empty<TwitterEntityEmoji>();
1506 var codepoints = postText.ToCodepoints().ToArray();
1508 while (index < codepoints.Length)
1510 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1511 if (urlEntity != null)
1513 totalWeight += config.TransformedURLLength * config.Scale;
1514 index = urlEntity.Indices[1];
1518 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1519 if (emojiEntity != null)
1521 totalWeight += GetWeightFromCodepoint(codepoints[index]);
1522 index = emojiEntity.Indices[1];
1526 var codepoint = codepoints[index];
1527 totalWeight += GetWeightFromCodepoint(codepoint);
1532 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1534 return remainWeight / config.Scale;
1538 /// プロフィール画像のサイズを指定したURLを生成
1541 /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1543 public static string CreateProfileImageUrl(string normalUrl, string size)
1547 "original" => normalUrl.Replace("_normal.", "."),
1548 "normal" => normalUrl,
1549 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1550 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1554 public static string DecideProfileImageSize(int sizePx)
1556 return sizePx switch
1565 public bool IsDisposed { get; private set; } = false;
1567 protected virtual void Dispose(bool disposing)
1569 if (this.IsDisposed)
1577 this.IsDisposed = true;
1580 public void Dispose()
1583 GC.SuppressFinalize(this);