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 using 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 using 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 using 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 using 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 using 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 async Task PostFavAdd(TwitterStatusId statusId)
479 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
481 var request = new FavoriteTweetRequest
486 await request.Send(this.Api.Connection)
487 .ConfigureAwait(false);
493 await this.Api.FavoritesCreate(statusId)
495 .ConfigureAwait(false);
497 catch (TwitterApiException ex)
498 when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
500 // エラーコード 139 のみの場合は成功と見なす
505 public async Task PostFavRemove(TwitterStatusId statusId)
507 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
509 var request = new UnfavoriteTweetRequest
514 await request.Send(this.Api.Connection)
515 .ConfigureAwait(false);
519 await this.Api.FavoritesDestroy(statusId)
521 .ConfigureAwait(false);
525 public string Username
526 => this.Api.CurrentScreenName;
529 => this.Api.CurrentUserId;
531 public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
533 public bool RestrictFavCheck { get; set; }
535 public bool ReadOwnPost { get; set; }
537 public int FollowersCount { get; private set; }
539 public int FriendsCount { get; private set; }
541 public int StatusesCount { get; private set; }
543 public string Location { get; private set; } = "";
545 public string Bio { get; private set; } = "";
547 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
548 private void UpdateUserStats(TwitterUser self)
550 this.FollowersCount = self.FollowersCount;
551 this.FriendsCount = self.FriendsCount;
552 this.StatusesCount = self.StatusesCount;
553 this.Location = self.Location ?? "";
554 this.Bio = self.Description ?? "";
558 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
560 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
561 => count >= 20 && count <= GetMaxApiResultCount(type);
564 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
566 public static bool VerifyMoreApiResultCount(int count)
567 => count >= 20 && count <= 200;
570 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
572 public static bool VerifyFirstApiResultCount(int count)
573 => count >= 20 && count <= 200;
576 /// WORKERTYPEに応じた取得可能な最大件数を取得する
578 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
580 // 参照: REST APIs - 各endpointのcountパラメータ
581 // https://dev.twitter.com/rest/public
584 MyCommon.WORKERTYPE.Timeline => 100,
585 MyCommon.WORKERTYPE.Reply => 200,
586 MyCommon.WORKERTYPE.UserTimeline => 200,
587 MyCommon.WORKERTYPE.Favorites => 200,
588 MyCommon.WORKERTYPE.List => 200, // 不明
589 MyCommon.WORKERTYPE.PublicSearch => 100,
590 _ => throw new InvalidOperationException("Invalid type: " + type),
595 /// WORKERTYPEに応じた取得件数を取得する
597 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
599 if (SettingManager.Instance.Common.UseAdditionalCount)
603 case MyCommon.WORKERTYPE.Favorites:
604 if (SettingManager.Instance.Common.FavoritesCountApi != 0)
605 return SettingManager.Instance.Common.FavoritesCountApi;
607 case MyCommon.WORKERTYPE.List:
608 if (SettingManager.Instance.Common.ListCountApi != 0)
609 return SettingManager.Instance.Common.ListCountApi;
611 case MyCommon.WORKERTYPE.PublicSearch:
612 if (SettingManager.Instance.Common.SearchCountApi != 0)
613 return SettingManager.Instance.Common.SearchCountApi;
615 case MyCommon.WORKERTYPE.UserTimeline:
616 if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
617 return SettingManager.Instance.Common.UserTimelineCountApi;
620 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
622 return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
624 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
626 return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
631 var count = SettingManager.Instance.Common.CountApi;
633 if (type == MyCommon.WORKERTYPE.Reply)
634 count = SettingManager.Instance.Common.CountApiReply;
636 return Math.Min(count, GetMaxApiResultCount(type));
639 public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
641 this.CheckAccountState();
643 var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
645 TwitterStatus[] statuses;
646 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
648 var request = new HomeLatestTimelineRequest
651 Cursor = more ? tab.CursorBottom : tab.CursorTop,
653 var response = await request.Send(this.Api.Connection)
654 .ConfigureAwait(false);
656 statuses = response.ToTwitterStatuses();
658 tab.CursorBottom = response.CursorBottom;
661 tab.CursorTop = response.CursorTop;
663 else if (SettingManager.Instance.Common.EnableTwitterV2Api)
665 var request = new GetTimelineRequest(this.UserId)
668 UntilId = more ? tab.OldestId as TwitterStatusId : null,
671 var response = await request.Send(this.Api.Connection)
672 .ConfigureAwait(false);
674 if (response.Data == null || response.Data.Length == 0)
677 var tweetIds = response.Data.Select(x => x.Id).ToList();
679 statuses = await this.Api.StatusesLookup(tweetIds)
680 .ConfigureAwait(false);
684 var maxId = more ? tab.OldestId : null;
686 statuses = await this.Api.StatusesHomeTimeline(count, maxId as TwitterStatusId)
687 .ConfigureAwait(false);
690 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
691 if (minimumId != null)
692 tab.OldestId = minimumId;
695 public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
697 this.CheckAccountState();
699 var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
701 TwitterStatus[] statuses;
702 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
704 var request = new NotificationsMentionsRequest
706 Count = Math.Min(count, 50),
707 Cursor = more ? tab.CursorBottom : tab.CursorTop,
709 var response = await request.Send(this.Api.Connection)
710 .ConfigureAwait(false);
712 statuses = response.Statuses;
714 tab.CursorBottom = response.CursorBottom;
717 tab.CursorTop = response.CursorTop;
723 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId as TwitterStatusId)
724 .ConfigureAwait(false);
728 statuses = await this.Api.StatusesMentionsTimeline(count)
729 .ConfigureAwait(false);
733 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
734 if (minimumId != null)
735 tab.OldestId = minimumId;
738 public async Task GetUserTimelineApi(bool read, UserTimelineTabModel tab, bool more)
740 this.CheckAccountState();
742 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
744 TwitterStatus[] statuses;
745 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
747 var userId = tab.UserId;
748 if (MyCommon.IsNullOrEmpty(userId))
750 var user = await this.GetUserInfo(tab.ScreenName)
751 .ConfigureAwait(false);
754 tab.UserId = user.IdStr;
757 var request = new UserTweetsAndRepliesRequest(userId)
760 Cursor = more ? tab.CursorBottom : tab.CursorTop,
762 var response = await request.Send(this.Api.Connection)
763 .ConfigureAwait(false);
765 statuses = response.ToTwitterStatuses()
766 .Where(x => x.User.IdStr == userId) // リプライツリーに含まれる他ユーザーのツイートを除外
769 tab.CursorBottom = response.CursorBottom;
772 tab.CursorTop = response.CursorTop;
778 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count, maxId: tab.OldestId as TwitterStatusId)
779 .ConfigureAwait(false);
783 statuses = await this.Api.StatusesUserTimeline(tab.ScreenName, count)
784 .ConfigureAwait(false);
788 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
790 if (minimumId != null)
791 tab.OldestId = minimumId;
794 public async Task<PostClass> GetStatusApi(bool read, TwitterStatusId id)
796 this.CheckAccountState();
798 TwitterStatus status;
799 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
801 var request = new TweetDetailRequest
805 var tweets = await request.Send(this.Api.Connection).ConfigureAwait(false);
806 status = tweets.Select(x => x.ToTwitterStatus())
807 .Where(x => x.IdStr == id.Id)
808 .FirstOrDefault() ?? throw new WebApiException("Empty result set");
812 status = await this.Api.StatusesShow(id)
813 .ConfigureAwait(false);
816 var item = this.CreatePostsFromStatusData(status);
819 if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
824 public async Task GetStatusApi(bool read, TwitterStatusId id, TabModel tab)
826 var post = await this.GetStatusApi(read, id)
827 .ConfigureAwait(false);
829 // 非同期アイコン取得&StatusDictionaryに追加
830 if (tab != null && tab.IsInnerStorageTabType)
831 tab.AddPostQueue(post);
833 TabInformations.GetInstance().AddPost(post);
836 private PostClass CreatePostsFromStatusData(TwitterStatus status)
837 => this.CreatePostsFromStatusData(status, favTweet: false);
839 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
841 var post = this.postFactory.CreateFromStatus(status, this.UserId, this.followerId, favTweet);
842 _ = this.urlExpander.Expand(post);
847 private PostId? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
849 PostId? minimumId = null;
851 var posts = items.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
853 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
855 foreach (var post in posts)
857 if (!post.IsPromoted)
859 if (minimumId == null || minimumId > post.StatusId)
860 minimumId = post.StatusId;
866 var id = post.StatusId;
869 if (TabInformations.GetInstance().ContainsKey(id)) continue;
873 if (tab.Contains(id)) continue;
878 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
879 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
882 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
884 if (tab != null && tab.IsInnerStorageTabType)
885 tab.AddPostQueue(post);
887 TabInformations.GetInstance().AddPost(post);
893 private PostId? CreatePostsFromSearchJson(TwitterStatus[] statuses, PublicSearchTabModel tab, bool read, bool more)
895 PostId? minimumId = null;
897 var posts = statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
899 TwitterPostFactory.AdjustSortKeyForPromotedPost(posts);
901 foreach (var post in posts)
903 if (!post.IsPromoted)
905 if (minimumId == null || minimumId > post.StatusId)
906 minimumId = post.StatusId;
908 if (!more && (tab.SinceId == null || post.StatusId > tab.SinceId))
909 tab.SinceId = post.StatusId;
915 if (tab.Contains(post.StatusId))
920 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
922 tab.AddPostQueue(post);
928 private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
930 var favTab = TabInformations.GetInstance().FavoriteTab;
931 long? minimumId = null;
933 foreach (var status in items)
935 if (minimumId == null || minimumId.Value > status.Id)
936 minimumId = status.Id;
941 if (favTab.Contains(new TwitterStatusId(status.IdStr)))
945 var post = this.CreatePostsFromStatusData(status, true);
949 TabInformations.GetInstance().AddPost(post);
955 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
957 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
959 TwitterStatus[] statuses;
960 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
962 var request = new ListLatestTweetsTimelineRequest(tab.ListInfo.Id.ToString())
965 Cursor = more ? tab.CursorBottom : tab.CursorTop,
967 var response = await request.Send(this.Api.Connection)
968 .ConfigureAwait(false);
970 var convertedStatuses = response.ToTwitterStatuses();
972 if (!SettingManager.Instance.Common.IsListsIncludeRts)
973 convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null).ToArray();
975 statuses = convertedStatuses.ToArray();
976 tab.CursorBottom = response.CursorBottom;
979 tab.CursorTop = response.CursorTop;
983 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId as TwitterStatusId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
984 .ConfigureAwait(false);
988 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
989 .ConfigureAwait(false);
992 var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
994 if (minimumId != null)
995 tab.OldestId = minimumId;
999 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1001 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1002 internal static PostClass FindTopOfReplyChain(IDictionary<PostId, PostClass> posts, PostId startStatusId)
1004 if (!posts.ContainsKey(startStatusId))
1005 throw new ArgumentException("startStatusId (" + startStatusId.Id + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1007 var nextPost = posts[startStatusId];
1008 while (nextPost.InReplyToStatusId != null)
1010 if (!posts.ContainsKey(nextPost.InReplyToStatusId))
1012 nextPost = posts[nextPost.InReplyToStatusId];
1018 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
1020 var targetPost = tab.TargetPost;
1022 if (targetPost.RetweetedId != null)
1024 var originalPost = targetPost with
1026 StatusId = targetPost.RetweetedId,
1030 targetPost = originalPost;
1033 var relPosts = new Dictionary<PostId, PostClass>();
1034 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1037 var p = TabInformations.GetInstance()[targetPost.StatusId];
1038 if (p != null && p.InReplyToStatusId != null)
1044 p = await this.GetStatusApi(read, targetPost.StatusId.ToTwitterStatusId())
1045 .ConfigureAwait(false);
1049 relPosts.Add(targetPost.StatusId, targetPost);
1051 Exception? lastException = null;
1053 // in_reply_to_status_id を使用してリプライチェインを辿る
1054 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1056 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1058 var inReplyToId = nextPost.InReplyToStatusId;
1060 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1061 if (inReplyToPost == null)
1065 inReplyToPost = await this.GetStatusApi(read, inReplyToId.ToTwitterStatusId())
1066 .ConfigureAwait(false);
1068 catch (WebApiException ex)
1075 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1077 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1080 // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1081 var text = targetPost.Text;
1082 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1083 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1084 foreach (var match in ma)
1086 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
1087 if (!relPosts.ContainsKey(statusId))
1089 var p = TabInformations.GetInstance()[statusId];
1094 p = await this.GetStatusApi(read, statusId)
1095 .ConfigureAwait(false);
1097 catch (WebApiException ex)
1105 relPosts.Add(p.StatusId, p);
1111 var firstPost = nextPost;
1112 var posts = await this.GetConversationPosts(firstPost, targetPost)
1113 .ConfigureAwait(false);
1115 foreach (var post in posts.OrderBy(x => x.StatusId))
1117 if (relPosts.ContainsKey(post.StatusId))
1120 // リプライチェーンが繋がらないツイートは除外
1121 if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId))
1124 relPosts.Add(post.StatusId, post);
1127 catch (WebException ex)
1132 relPosts.Values.ToList().ForEach(p =>
1134 var post = p with { };
1135 if (post.IsMe && !read && this.ReadOwnPost)
1140 tab.AddPostQueue(post);
1143 if (lastException != null)
1144 throw new WebApiException(lastException.Message, lastException);
1147 private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1149 var conversationId = firstPost.StatusId;
1150 var query = $"conversation_id:{conversationId.Id}";
1152 if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1153 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1155 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1157 TwitterStatus[] statuses;
1158 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
1160 var request = new SearchTimelineRequest(query);
1161 var response = await request.Send(this.Api.Connection)
1162 .ConfigureAwait(false);
1164 statuses = response.ToTwitterStatuses();
1168 var response = await this.Api.SearchTweets(query, count: 100)
1169 .ConfigureAwait(false);
1171 statuses = response.Statuses;
1174 return statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1177 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1179 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1181 TwitterStatus[] statuses;
1182 if (this.Api.AuthType == APIAuthType.TwitterComCookie)
1184 var query = tab.SearchWords;
1186 if (!MyCommon.IsNullOrEmpty(tab.SearchLang))
1187 query = $"({query}) lang:{tab.SearchLang}";
1189 var request = new SearchTimelineRequest(query)
1192 Cursor = more ? tab.CursorBottom : tab.CursorTop,
1194 var response = await request.Send(this.Api.Connection)
1195 .ConfigureAwait(false);
1197 statuses = response.ToTwitterStatuses();
1199 tab.CursorBottom = response.CursorBottom;
1202 tab.CursorTop = response.CursorTop;
1206 TwitterStatusId? maxId = null;
1207 TwitterStatusId? sinceId = null;
1210 maxId = tab.OldestId as TwitterStatusId;
1214 sinceId = tab.SinceId as TwitterStatusId;
1217 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1218 .ConfigureAwait(false);
1220 statuses = searchResult.Statuses;
1223 if (!TabInformations.GetInstance().ContainsTab(tab))
1226 var minimumId = this.CreatePostsFromSearchJson(statuses, tab, read, more);
1228 if (minimumId != null)
1229 tab.OldestId = minimumId;
1232 public async Task GetDirectMessageEvents(bool read, DirectMessagesTabModel dmTab, bool backward)
1234 this.CheckAccountState();
1235 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1239 TwitterMessageEventList eventList;
1242 eventList = await this.Api.DirectMessagesEventsList(count, dmTab.NextCursor)
1243 .ConfigureAwait(false);
1247 eventList = await this.Api.DirectMessagesEventsList(count)
1248 .ConfigureAwait(false);
1251 dmTab.NextCursor = eventList.NextCursor;
1253 await this.CreateDirectMessagesEventFromJson(eventList, read)
1254 .ConfigureAwait(false);
1257 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1259 var eventList = new TwitterMessageEventList
1261 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1262 Events = new[] { eventSingle.Event },
1265 await this.CreateDirectMessagesEventFromJson(eventList, read)
1266 .ConfigureAwait(false);
1269 private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1271 var events = eventList.Events
1272 .Where(x => x.Type == "message_create")
1275 if (events.Length == 0)
1278 var userIds = Enumerable.Concat(
1279 events.Select(x => x.MessageCreate.SenderId),
1280 events.Select(x => x.MessageCreate.Target.RecipientId)
1281 ).Distinct().ToArray();
1283 var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1284 .ToDictionary(x => x.IdStr);
1286 var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1288 this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1291 private void CreateDirectMessagesEventFromJson(
1292 IEnumerable<TwitterMessageEvent> events,
1293 IReadOnlyDictionary<string, TwitterUser> users,
1294 IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1297 var dmTab = TabInformations.GetInstance().DirectMessageTab;
1299 foreach (var eventItem in events)
1301 var post = this.postFactory.CreateFromDirectMessageEvent(eventItem, users, apps, this.UserId);
1302 _ = this.urlExpander.Expand(post);
1305 if (post.IsMe && !read && this.ReadOwnPost)
1308 dmTab.AddPostQueue(post);
1312 public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1314 this.CheckAccountState();
1316 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1318 TwitterStatus[] statuses;
1321 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1322 .ConfigureAwait(false);
1326 statuses = await this.Api.FavoritesList(count)
1327 .ConfigureAwait(false);
1330 var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1332 if (minimumId != null)
1333 tab.OldestId = minimumId.Value;
1339 /// <exception cref="WebApiException"/>
1340 public async Task RefreshFollowerIds()
1342 if (MyCommon.EndingFlag) return;
1345 var newFollowerIds = Enumerable.Empty<long>();
1348 var ret = await this.Api.FollowersIds(cursor)
1349 .ConfigureAwait(false);
1351 if (ret.Ids == null)
1352 throw new WebApiException("ret.ids == null");
1354 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1355 cursor = ret.NextCursor;
1357 while (cursor != 0);
1359 this.followerId = newFollowerIds.ToHashSet();
1360 TabInformations.GetInstance().RefreshOwl(this.followerId);
1362 this.GetFollowersSuccess = true;
1366 /// RT 非表示ユーザーを更新します
1368 /// <exception cref="WebApiException"/>
1369 public async Task RefreshNoRetweetIds()
1371 if (MyCommon.EndingFlag) return;
1373 this.noRTId = await this.Api.NoRetweetIds()
1374 .ConfigureAwait(false);
1376 this.GetNoRetweetSuccess = true;
1380 /// t.co の文字列長などの設定情報を更新します
1382 /// <exception cref="WebApiException"/>
1383 public async Task RefreshConfiguration()
1385 this.Configuration = await this.Api.Configuration()
1386 .ConfigureAwait(false);
1388 // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1389 this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1392 public async Task GetListsApi()
1394 this.CheckAccountState();
1396 var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1397 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1398 .ConfigureAwait(false);
1400 var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1401 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1402 .ConfigureAwait(false);
1404 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1405 .Select(x => new ListElement(x, this))
1409 public async Task DeleteList(long listId)
1411 await this.Api.ListsDestroy(listId)
1413 .ConfigureAwait(false);
1415 var tabinfo = TabInformations.GetInstance();
1417 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1418 .Where(x => x.Id != listId)
1422 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1424 using var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1425 .ConfigureAwait(false);
1427 var list = await response.LoadJsonAsync()
1428 .ConfigureAwait(false);
1430 return new ListElement(list, this);
1433 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1435 this.CheckAccountState();
1437 var users = await this.Api.ListsMembers(listId, cursor)
1438 .ConfigureAwait(false);
1440 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1442 return users.NextCursor;
1445 public async Task CreateListApi(string listName, bool isPrivate, string description)
1447 this.CheckAccountState();
1449 using var response = await this.Api.ListsCreate(listName, description, isPrivate)
1450 .ConfigureAwait(false);
1452 var list = await response.LoadJsonAsync()
1453 .ConfigureAwait(false);
1455 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1458 public async Task<bool> ContainsUserAtList(long listId, string user)
1460 this.CheckAccountState();
1464 await this.Api.ListsMembersShow(listId, user)
1465 .ConfigureAwait(false);
1469 catch (TwitterApiException ex)
1470 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1476 public async Task<TwitterApiStatus?> GetInfoApi()
1478 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1480 if (MyCommon.EndingFlag) return null;
1482 var limits = await this.Api.ApplicationRateLimitStatus()
1483 .ConfigureAwait(false);
1485 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1487 return MyCommon.TwitterApiInfo;
1491 /// ブロック中のユーザーを更新します
1493 /// <exception cref="WebApiException"/>
1494 public async Task RefreshBlockIds()
1496 if (MyCommon.EndingFlag) return;
1499 var newBlockIds = Enumerable.Empty<long>();
1502 var ret = await this.Api.BlocksIds(cursor)
1503 .ConfigureAwait(false);
1505 newBlockIds = newBlockIds.Concat(ret.Ids);
1506 cursor = ret.NextCursor;
1508 while (cursor != 0);
1510 var blockIdsSet = newBlockIds.ToHashSet();
1511 blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1513 TabInformations.GetInstance().BlockIds = blockIdsSet;
1517 /// ミュート中のユーザーIDを更新します
1519 /// <exception cref="WebApiException"/>
1520 public async Task RefreshMuteUserIdsAsync()
1522 if (MyCommon.EndingFlag) return;
1524 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1525 .ConfigureAwait(false);
1527 TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1530 public string[] GetHashList()
1531 => this.postFactory.GetReceivedHashtags();
1533 private void CheckAccountState()
1535 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1536 throw new WebApiException("Auth error. Check your account");
1539 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1541 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1542 throw new WebApiException("Auth Err:try to re-authorization.");
1545 public int GetTextLengthRemain(string postText)
1547 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1548 if (matchDm.Success)
1549 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1551 return this.GetTextLengthRemainWeighted(postText);
1554 private int GetTextLengthRemainDM(string postText)
1559 while (pos < postText.Length)
1563 if (char.IsSurrogatePair(postText, pos))
1564 pos += 2; // サロゲートペアの場合は2文字分進める
1569 var urls = TweetExtractor.ExtractUrls(postText);
1570 foreach (var url in urls)
1572 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1573 ? this.Configuration.ShortUrlLengthHttps
1574 : this.Configuration.ShortUrlLength;
1576 textLength += shortUrlLength - url.Length;
1579 return this.Configuration.DmTextCharacterLimit - textLength;
1582 private int GetTextLengthRemainWeighted(string postText)
1584 var config = this.TextConfiguration;
1585 var totalWeight = 0;
1587 int GetWeightFromCodepoint(int codepoint)
1589 foreach (var weightRange in config.Ranges)
1591 if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1592 return weightRange.Weight;
1595 return config.DefaultWeight;
1598 var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1599 var emojis = config.EmojiParsingEnabled
1600 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1601 : Array.Empty<TwitterEntityEmoji>();
1603 var codepoints = postText.ToCodepoints().ToArray();
1605 while (index < codepoints.Length)
1607 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1608 if (urlEntity != null)
1610 totalWeight += config.TransformedURLLength * config.Scale;
1611 index = urlEntity.Indices[1];
1615 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1616 if (emojiEntity != null)
1618 totalWeight += GetWeightFromCodepoint(codepoints[index]);
1619 index = emojiEntity.Indices[1];
1623 var codepoint = codepoints[index];
1624 totalWeight += GetWeightFromCodepoint(codepoint);
1629 var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1631 return remainWeight / config.Scale;
1635 /// プロフィール画像のサイズを指定したURLを生成
1638 /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1640 public static string CreateProfileImageUrl(string normalUrl, string size)
1644 "original" => normalUrl.Replace("_normal.", "."),
1645 "normal" => normalUrl,
1646 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1647 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1651 public static string DecideProfileImageSize(int sizePx)
1653 return sizePx switch
1662 public bool IsDisposed { get; private set; } = false;
1664 protected virtual void Dispose(bool disposing)
1666 if (this.IsDisposed)
1674 this.IsDisposed = true;
1677 public void Dispose()
1680 GC.SuppressFinalize(this);