OSDN Git Service

graphqlエンドポイントを使用した検索タイムラインの取得に対応
[opentween/open-tween.git] / OpenTween / Twitter.cs
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.
10 //
11 // This file is part of OpenTween.
12 //
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)
16 // any later version.
17 //
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
21 // for more details.
22 //
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.
27
28 #nullable enable
29
30 using System;
31 using System.Collections.Generic;
32 using System.Diagnostics;
33 using System.IO;
34 using System.Linq;
35 using System.Net;
36 using System.Net.Http;
37 using System.Reflection;
38 using System.Runtime.CompilerServices;
39 using System.Text;
40 using System.Text.RegularExpressions;
41 using System.Threading;
42 using System.Threading.Tasks;
43 using System.Windows.Forms;
44 using OpenTween.Api;
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;
51
52 namespace OpenTween
53 {
54     public class Twitter : IDisposable
55     {
56         #region Regexp from twitter-text-js
57
58         // The code in this region code block incorporates works covered by
59         // the following copyright and permission notices:
60         //
61         //   Copyright 2011 Twitter, Inc.
62         //
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:
66         //
67         //   http://www.apache.org/licenses/LICENSE-2.0
68         //
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.
74
75         // Hashtag用正規表現
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})";
84         // URL正規表現
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]+";
98
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 = "(?:" +
103             "(?:" +
104                 $"{UrlValidGeneralPathChars}*" +
105                 $"(?:{UrlBalanceParens}{UrlValidGeneralPathChars}*)*" +
106                 UrlValidPathEndingChars +
107                 $")|(?:@{UrlValidGeneralPathChars}+/)" +
108             ")";
109
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}*)?" +
116                                     Qry +
117                                     ")";
118
119         #endregion
120
121         /// <summary>
122         /// Twitter API のステータスページのURL
123         /// </summary>
124         public const string ServiceAvailabilityStatusUrl = "https://api.twitterstat.us/";
125
126         /// <summary>
127         /// ツイートへのパーマリンクURLを判定する正規表現
128         /// </summary>
129         public static readonly Regex StatusUrlRegex = new(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
130
131         /// <summary>
132         /// attachment_url に指定可能な URL を判定する正規表現
133         /// </summary>
134         public static readonly Regex AttachmentUrlRegex = new(
135             @"https?://(
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]+(&.+)?
139 )$",
140             RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
141
142         /// <summary>
143         /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
144         /// </summary>
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);
153
154         /// <summary>
155         /// DM送信かどうかを判定する正規表現
156         /// </summary>
157         public static readonly Regex DMSendTextRegex = new(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
158
159         public TwitterApi Api { get; }
160
161         public TwitterConfiguration Configuration { get; private set; }
162
163         public TwitterTextConfiguration TextConfiguration { get; private set; }
164
165         public bool GetFollowersSuccess { get; private set; } = false;
166
167         public bool GetNoRetweetSuccess { get; private set; } = false;
168
169         private delegate void GetIconImageDelegate(PostClass post);
170
171         private readonly object lockObj = new();
172         private ISet<long> followerId = new HashSet<long>();
173         private long[] noRTId = Array.Empty<long>();
174
175         private readonly TwitterPostFactory postFactory;
176
177         private string? previousStatusId = null;
178
179         public Twitter(TwitterApi api)
180         {
181             this.postFactory = new(TabInformations.GetInstance());
182
183             this.Api = api;
184             this.Configuration = TwitterConfiguration.DefaultConfiguration();
185             this.TextConfiguration = TwitterTextConfiguration.DefaultConfiguration();
186         }
187
188         public TwitterApiAccessLevel AccessLevel
189             => MyCommon.TwitterApiInfo.AccessLevel;
190
191         protected void ResetApiStatus()
192             => MyCommon.TwitterApiInfo.Reset();
193
194         public void ClearAuthInfo()
195         {
196             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
197             this.ResetApiStatus();
198         }
199
200         public void VerifyCredentials()
201         {
202             try
203             {
204                 this.VerifyCredentialsAsync().Wait();
205             }
206             catch (AggregateException ex) when (ex.InnerException is WebApiException)
207             {
208                 throw new WebApiException(ex.InnerException.Message, ex);
209             }
210         }
211
212         public async Task VerifyCredentialsAsync()
213         {
214             var user = await this.Api.AccountVerifyCredentials()
215                 .ConfigureAwait(false);
216
217             this.UpdateUserStats(user);
218         }
219
220         public void Initialize(string token, string tokenSecret, string username, long userId)
221         {
222             // OAuth認証
223             if (MyCommon.IsNullOrEmpty(token) || MyCommon.IsNullOrEmpty(tokenSecret) || MyCommon.IsNullOrEmpty(username))
224             {
225                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
226             }
227             this.ResetApiStatus();
228             this.Api.Initialize(token, tokenSecret, userId, username);
229         }
230
231         public void Initialize(TwitterAppToken appToken, string token, string tokenSecret, string username, long userId)
232         {
233             // OAuth認証
234             if (MyCommon.IsNullOrEmpty(token) || MyCommon.IsNullOrEmpty(tokenSecret) || MyCommon.IsNullOrEmpty(username))
235             {
236                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
237             }
238             this.ResetApiStatus();
239             this.Api.Initialize(appToken, token, tokenSecret, userId, username);
240         }
241
242         public async Task<PostClass?> PostStatus(PostStatusParams param)
243         {
244             this.CheckAccountState();
245
246             if (Twitter.DMSendTextRegex.IsMatch(param.Text))
247             {
248                 var mediaId = param.MediaIds != null && param.MediaIds.Any() ? param.MediaIds[0] : (long?)null;
249
250                 await this.SendDirectMessage(param.Text, mediaId)
251                     .ConfigureAwait(false);
252                 return null;
253             }
254
255             TwitterStatus status;
256
257             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
258             {
259                 var request = new CreateTweetRequest
260                 {
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,
266                 };
267
268                 status = await request.Send(this.Api.Connection)
269                     .ConfigureAwait(false);
270             }
271             else
272             {
273                 var response = await this.Api.StatusesUpdate(
274                         param.Text,
275                         param.InReplyToStatusId?.ToTwitterStatusId(),
276                         param.MediaIds,
277                         param.AutoPopulateReplyMetadata,
278                         param.ExcludeReplyUserIds,
279                         param.AttachmentUrl
280                     )
281                     .ConfigureAwait(false);
282
283                 status = await response.LoadJsonAsync()
284                     .ConfigureAwait(false);
285             }
286
287             this.UpdateUserStats(status.User);
288
289             if (status.IdStr == this.previousStatusId)
290                 throw new WebApiException("OK:Delaying?");
291
292             this.previousStatusId = status.IdStr;
293
294             // 投稿したものを返す
295             var post = this.CreatePostsFromStatusData(status);
296             if (this.ReadOwnPost) post.IsRead = true;
297             return post;
298         }
299
300         public async Task DeleteTweet(TwitterStatusId tweetId)
301         {
302             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
303             {
304                 var request = new DeleteTweetRequest
305                 {
306                     TweetId = tweetId,
307                 };
308                 await request.Send(this.Api.Connection);
309             }
310             else
311             {
312                 await this.Api.StatusesDestroy(tweetId)
313                     .IgnoreResponse();
314             }
315         }
316
317         public async Task<long> UploadMedia(IMediaItem item, string? mediaCategory = null)
318         {
319             this.CheckAccountState();
320
321             var mediaType = item.Extension switch
322             {
323                 ".png" => "image/png",
324                 ".jpg" => "image/jpeg",
325                 ".jpeg" => "image/jpeg",
326                 ".gif" => "image/gif",
327                 _ => "application/octet-stream",
328             };
329
330             var initResponse = await this.Api.MediaUploadInit(item.Size, mediaType, mediaCategory)
331                 .ConfigureAwait(false);
332
333             var initMedia = await initResponse.LoadJsonAsync()
334                 .ConfigureAwait(false);
335
336             var mediaId = initMedia.MediaId;
337
338             await this.Api.MediaUploadAppend(mediaId, 0, item)
339                 .ConfigureAwait(false);
340
341             var response = await this.Api.MediaUploadFinalize(mediaId)
342                 .ConfigureAwait(false);
343
344             var media = await response.LoadJsonAsync()
345                 .ConfigureAwait(false);
346
347             while (media.ProcessingInfo is TwitterUploadMediaResult.MediaProcessingInfo processingInfo)
348             {
349                 switch (processingInfo.State)
350                 {
351                     case "pending":
352                         break;
353                     case "in_progress":
354                         break;
355                     case "succeeded":
356                         goto succeeded;
357                     case "failed":
358                         throw new WebApiException($"Err:Upload failed ({processingInfo.Error?.Name})");
359                     default:
360                         throw new WebApiException($"Err:Invalid state ({processingInfo.State})");
361                 }
362
363                 await Task.Delay(TimeSpan.FromSeconds(processingInfo.CheckAfterSecs ?? 5))
364                     .ConfigureAwait(false);
365
366                 media = await this.Api.MediaUploadStatus(mediaId)
367                     .ConfigureAwait(false);
368             }
369
370             succeeded:
371             return media.MediaId;
372         }
373
374         public async Task SendDirectMessage(string postStr, long? mediaId = null)
375         {
376             this.CheckAccountState();
377             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
378
379             var mc = Twitter.DMSendTextRegex.Match(postStr);
380
381             var body = mc.Groups["body"].Value;
382             var recipientName = mc.Groups["id"].Value;
383
384             var recipient = await this.Api.UsersShow(recipientName)
385                 .ConfigureAwait(false);
386
387             var response = await this.Api.DirectMessagesEventsNew(recipient.Id, body, mediaId)
388                 .ConfigureAwait(false);
389
390             var messageEventSingle = await response.LoadJsonAsync()
391                 .ConfigureAwait(false);
392
393             await this.CreateDirectMessagesEventFromJson(messageEventSingle, read: true)
394                 .ConfigureAwait(false);
395         }
396
397         public async Task<PostClass?> PostRetweet(PostId id, bool read)
398         {
399             this.CheckAccountState();
400
401             // データ部分の生成
402             var post = TabInformations.GetInstance()[id];
403             if (post == null)
404                 throw new WebApiException("Err:Target isn't found.");
405
406             var target = post.RetweetedId ?? id;  // 再RTの場合は元発言をRT
407
408             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
409             {
410                 var request = new CreateRetweetRequest
411                 {
412                     TweetId = target.ToTwitterStatusId(),
413                 };
414                 await request.Send(this.Api.Connection).ConfigureAwait(false);
415                 return null;
416             }
417
418             var response = await this.Api.StatusesRetweet(target.ToTwitterStatusId())
419                 .ConfigureAwait(false);
420
421             var status = await response.LoadJsonAsync()
422                 .ConfigureAwait(false);
423
424             // 二重取得回避
425             lock (this.lockObj)
426             {
427                 var statusId = new TwitterStatusId(status.IdStr);
428                 if (TabInformations.GetInstance().ContainsKey(statusId))
429                     return null;
430             }
431
432             // Retweet判定
433             if (status.RetweetedStatus == null)
434                 throw new WebApiException("Invalid Json!");
435
436             // Retweetしたものを返す
437             return this.CreatePostsFromStatusData(status) with
438             {
439                 IsMe = true,
440                 IsRead = this.ReadOwnPost ? true : read,
441                 IsOwl = false,
442             };
443         }
444
445         public async Task DeleteRetweet(PostClass post)
446         {
447             if (post.RetweetedId == null)
448                 throw new ArgumentException("post is not retweeted status", nameof(post));
449
450             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
451             {
452                 var request = new DeleteRetweetRequest
453                 {
454                     SourceTweetId = post.RetweetedId.ToTwitterStatusId(),
455                 };
456                 await request.Send(this.Api.Connection).ConfigureAwait(false);
457             }
458             else
459             {
460                 await this.Api.StatusesDestroy(post.StatusId.ToTwitterStatusId())
461                     .IgnoreResponse();
462             }
463         }
464
465         public string Username
466             => this.Api.CurrentScreenName;
467
468         public long UserId
469             => this.Api.CurrentUserId;
470
471         public static MyCommon.ACCOUNT_STATE AccountState { get; set; } = MyCommon.ACCOUNT_STATE.Valid;
472
473         public bool RestrictFavCheck { get; set; }
474
475         public bool ReadOwnPost { get; set; }
476
477         public int FollowersCount { get; private set; }
478
479         public int FriendsCount { get; private set; }
480
481         public int StatusesCount { get; private set; }
482
483         public string Location { get; private set; } = "";
484
485         public string Bio { get; private set; } = "";
486
487         /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
488         private void UpdateUserStats(TwitterUser self)
489         {
490             this.FollowersCount = self.FollowersCount;
491             this.FriendsCount = self.FriendsCount;
492             this.StatusesCount = self.StatusesCount;
493             this.Location = self.Location ?? "";
494             this.Bio = self.Description ?? "";
495         }
496
497         /// <summary>
498         /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
499         /// </summary>
500         public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
501             => count >= 20 && count <= GetMaxApiResultCount(type);
502
503         /// <summary>
504         /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
505         /// </summary>
506         public static bool VerifyMoreApiResultCount(int count)
507             => count >= 20 && count <= 200;
508
509         /// <summary>
510         /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
511         /// </summary>
512         public static bool VerifyFirstApiResultCount(int count)
513             => count >= 20 && count <= 200;
514
515         /// <summary>
516         /// WORKERTYPEに応じた取得可能な最大件数を取得する
517         /// </summary>
518         public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
519         {
520             // 参照: REST APIs - 各endpointのcountパラメータ
521             // https://dev.twitter.com/rest/public
522             return type switch
523             {
524                 MyCommon.WORKERTYPE.Timeline => 100,
525                 MyCommon.WORKERTYPE.Reply => 200,
526                 MyCommon.WORKERTYPE.UserTimeline => 200,
527                 MyCommon.WORKERTYPE.Favorites => 200,
528                 MyCommon.WORKERTYPE.List => 200, // 不明
529                 MyCommon.WORKERTYPE.PublicSearch => 100,
530                 _ => throw new InvalidOperationException("Invalid type: " + type),
531             };
532         }
533
534         /// <summary>
535         /// WORKERTYPEに応じた取得件数を取得する
536         /// </summary>
537         public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
538         {
539             if (SettingManager.Instance.Common.UseAdditionalCount)
540             {
541                 switch (type)
542                 {
543                     case MyCommon.WORKERTYPE.Favorites:
544                         if (SettingManager.Instance.Common.FavoritesCountApi != 0)
545                             return SettingManager.Instance.Common.FavoritesCountApi;
546                         break;
547                     case MyCommon.WORKERTYPE.List:
548                         if (SettingManager.Instance.Common.ListCountApi != 0)
549                             return SettingManager.Instance.Common.ListCountApi;
550                         break;
551                     case MyCommon.WORKERTYPE.PublicSearch:
552                         if (SettingManager.Instance.Common.SearchCountApi != 0)
553                             return SettingManager.Instance.Common.SearchCountApi;
554                         break;
555                     case MyCommon.WORKERTYPE.UserTimeline:
556                         if (SettingManager.Instance.Common.UserTimelineCountApi != 0)
557                             return SettingManager.Instance.Common.UserTimelineCountApi;
558                         break;
559                 }
560                 if (more && SettingManager.Instance.Common.MoreCountApi != 0)
561                 {
562                     return Math.Min(SettingManager.Instance.Common.MoreCountApi, GetMaxApiResultCount(type));
563                 }
564                 if (startup && SettingManager.Instance.Common.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
565                 {
566                     return Math.Min(SettingManager.Instance.Common.FirstCountApi, GetMaxApiResultCount(type));
567                 }
568             }
569
570             // 上記に当てはまらない場合の共通処理
571             var count = SettingManager.Instance.Common.CountApi;
572
573             if (type == MyCommon.WORKERTYPE.Reply)
574                 count = SettingManager.Instance.Common.CountApiReply;
575
576             return Math.Min(count, GetMaxApiResultCount(type));
577         }
578
579         public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
580         {
581             this.CheckAccountState();
582
583             var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
584
585             TwitterStatus[] statuses;
586             if (SettingManager.Instance.Common.EnableTwitterV2Api)
587             {
588                 var request = new GetTimelineRequest(this.UserId)
589                 {
590                     MaxResults = count,
591                     UntilId = more ? tab.OldestId.ToString() : null,
592                 };
593
594                 var response = await request.Send(this.Api.Connection)
595                     .ConfigureAwait(false);
596
597                 if (response.Data == null || response.Data.Length == 0)
598                     return;
599
600                 var tweetIds = response.Data.Select(x => x.Id).ToList();
601
602                 statuses = await this.Api.StatusesLookup(tweetIds)
603                     .ConfigureAwait(false);
604             }
605             else
606             {
607                 var maxId = more ? tab.OldestId : (long?)null;
608
609                 statuses = await this.Api.StatusesHomeTimeline(count, maxId)
610                     .ConfigureAwait(false);
611             }
612
613             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
614             if (minimumId != null)
615                 tab.OldestId = minimumId.Value;
616         }
617
618         public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
619         {
620             this.CheckAccountState();
621
622             var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
623
624             TwitterStatus[] statuses;
625             if (more)
626             {
627                 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
628                     .ConfigureAwait(false);
629             }
630             else
631             {
632                 statuses = await this.Api.StatusesMentionsTimeline(count)
633                     .ConfigureAwait(false);
634             }
635
636             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
637             if (minimumId != null)
638                 tab.OldestId = minimumId.Value;
639         }
640
641         public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
642         {
643             this.CheckAccountState();
644
645             var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
646
647             // Cookie を使用する場合のみ 99 件を超えて取得するとエラーが返る
648             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
649                 count = Math.Min(count, 99);
650
651             TwitterStatus[] statuses;
652             if (MyCommon.IsNullOrEmpty(userName))
653             {
654                 var target = tab.ScreenName;
655                 if (MyCommon.IsNullOrEmpty(target)) return;
656                 userName = target;
657                 statuses = await this.Api.StatusesUserTimeline(userName, count)
658                     .ConfigureAwait(false);
659             }
660             else
661             {
662                 if (more)
663                 {
664                     statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
665                         .ConfigureAwait(false);
666                 }
667                 else
668                 {
669                     statuses = await this.Api.StatusesUserTimeline(userName, count)
670                         .ConfigureAwait(false);
671                 }
672             }
673
674             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
675
676             if (minimumId != null)
677                 tab.OldestId = minimumId.Value;
678         }
679
680         public async Task<PostClass> GetStatusApi(bool read, TwitterStatusId id)
681         {
682             this.CheckAccountState();
683
684             TwitterStatus status;
685             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
686             {
687                 var request = new TweetDetailRequest
688                 {
689                     FocalTweetId = id,
690                 };
691                 var tweets = await request.Send(this.Api.Connection).ConfigureAwait(false);
692                 status = tweets.Select(x => x.ToTwitterStatus())
693                     .Where(x => x.IdStr == id.Id)
694                     .FirstOrDefault() ?? throw new WebApiException("Empty result set");
695             }
696             else
697             {
698                 status = await this.Api.StatusesShow(id)
699                     .ConfigureAwait(false);
700             }
701
702             var item = this.CreatePostsFromStatusData(status);
703
704             item.IsRead = read;
705             if (item.IsMe && !read && this.ReadOwnPost) item.IsRead = true;
706
707             return item;
708         }
709
710         public async Task GetStatusApi(bool read, TwitterStatusId id, TabModel tab)
711         {
712             var post = await this.GetStatusApi(read, id)
713                 .ConfigureAwait(false);
714
715             // 非同期アイコン取得&StatusDictionaryに追加
716             if (tab != null && tab.IsInnerStorageTabType)
717                 tab.AddPostQueue(post);
718             else
719                 TabInformations.GetInstance().AddPost(post);
720         }
721
722         private PostClass CreatePostsFromStatusData(TwitterStatus status)
723             => this.CreatePostsFromStatusData(status, favTweet: false);
724
725         private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
726             => this.postFactory.CreateFromStatus(status, this.UserId, this.followerId, favTweet);
727
728         private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel? tab, bool read)
729         {
730             long? minimumId = null;
731
732             foreach (var status in items)
733             {
734                 if (minimumId == null || minimumId.Value > status.Id)
735                     minimumId = status.Id;
736
737                 // 二重取得回避
738                 lock (this.lockObj)
739                 {
740                     var id = new TwitterStatusId(status.IdStr);
741                     if (tab == null)
742                     {
743                         if (TabInformations.GetInstance().ContainsKey(id)) continue;
744                     }
745                     else
746                     {
747                         if (tab.Contains(id)) continue;
748                     }
749                 }
750
751                 // RT禁止ユーザーによるもの
752                 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
753                     status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
754
755                 var post = this.CreatePostsFromStatusData(status);
756
757                 post.IsRead = read;
758                 if (post.IsMe && !read && this.ReadOwnPost) post.IsRead = true;
759
760                 if (tab != null && tab.IsInnerStorageTabType)
761                     tab.AddPostQueue(post);
762                 else
763                     TabInformations.GetInstance().AddPost(post);
764             }
765
766             return minimumId;
767         }
768
769         private long? CreatePostsFromSearchJson(TwitterStatus[] statuses, PublicSearchTabModel tab, bool read, bool more)
770         {
771             long? minimumId = null;
772
773             foreach (var status in statuses)
774             {
775                 if (minimumId == null || minimumId.Value > status.Id)
776                     minimumId = status.Id;
777
778                 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
779                 // 二重取得回避
780                 lock (this.lockObj)
781                 {
782                     if (tab.Contains(new TwitterStatusId(status.IdStr)))
783                         continue;
784                 }
785
786                 var post = this.CreatePostsFromStatusData(status);
787
788                 post.IsRead = read;
789                 if ((post.IsMe && !read) && this.ReadOwnPost) post.IsRead = true;
790
791                 tab.AddPostQueue(post);
792             }
793
794             return minimumId;
795         }
796
797         private long? CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
798         {
799             var favTab = TabInformations.GetInstance().FavoriteTab;
800             long? minimumId = null;
801
802             foreach (var status in items)
803             {
804                 if (minimumId == null || minimumId.Value > status.Id)
805                     minimumId = status.Id;
806
807                 // 二重取得回避
808                 lock (this.lockObj)
809                 {
810                     if (favTab.Contains(new TwitterStatusId(status.IdStr)))
811                         continue;
812                 }
813
814                 var post = this.CreatePostsFromStatusData(status, true);
815
816                 post.IsRead = read;
817
818                 TabInformations.GetInstance().AddPost(post);
819             }
820
821             return minimumId;
822         }
823
824         public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
825         {
826             var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
827
828             TwitterStatus[] statuses;
829             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
830             {
831                 var request = new ListLatestTweetsTimelineRequest(tab.ListInfo.Id.ToString())
832                 {
833                     Count = count,
834                     Cursor = more ? tab.CursorBottom : null,
835                 };
836                 var response = await request.Send(this.Api.Connection)
837                     .ConfigureAwait(false);
838
839                 var convertedStatuses = response.Tweets.Select(x => x.ToTwitterStatus());
840                 if (!SettingManager.Instance.Common.IsListsIncludeRts)
841                     convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null);
842
843                 statuses = convertedStatuses.ToArray();
844                 tab.CursorBottom = response.CursorBottom;
845             }
846             else if (more)
847             {
848                 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
849                     .ConfigureAwait(false);
850             }
851             else
852             {
853                 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingManager.Instance.Common.IsListsIncludeRts)
854                     .ConfigureAwait(false);
855             }
856
857             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
858
859             if (minimumId != null)
860                 tab.OldestId = minimumId.Value;
861         }
862
863         /// <summary>
864         /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
865         /// </summary>
866         /// <returns>posts の中から検索されたリプライチェインの末端</returns>
867         internal static PostClass FindTopOfReplyChain(IDictionary<PostId, PostClass> posts, PostId startStatusId)
868         {
869             if (!posts.ContainsKey(startStatusId))
870                 throw new ArgumentException("startStatusId (" + startStatusId.Id + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
871
872             var nextPost = posts[startStatusId];
873             while (nextPost.InReplyToStatusId != null)
874             {
875                 if (!posts.ContainsKey(nextPost.InReplyToStatusId))
876                     break;
877                 nextPost = posts[nextPost.InReplyToStatusId];
878             }
879
880             return nextPost;
881         }
882
883         public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
884         {
885             var targetPost = tab.TargetPost;
886
887             if (targetPost.RetweetedId != null)
888             {
889                 var originalPost = targetPost with
890                 {
891                     StatusId = targetPost.RetweetedId,
892                     RetweetedId = null,
893                     RetweetedBy = null,
894                 };
895                 targetPost = originalPost;
896             }
897
898             var relPosts = new Dictionary<PostId, PostClass>();
899             if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
900             {
901                 // 検索結果対応
902                 var p = TabInformations.GetInstance()[targetPost.StatusId];
903                 if (p != null && p.InReplyToStatusId != null)
904                 {
905                     targetPost = p;
906                 }
907                 else
908                 {
909                     p = await this.GetStatusApi(read, targetPost.StatusId.ToTwitterStatusId())
910                         .ConfigureAwait(false);
911                     targetPost = p;
912                 }
913             }
914             relPosts.Add(targetPost.StatusId, targetPost);
915
916             Exception? lastException = null;
917
918             // in_reply_to_status_id を使用してリプライチェインを辿る
919             var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
920             var loopCount = 1;
921             while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
922             {
923                 var inReplyToId = nextPost.InReplyToStatusId;
924
925                 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
926                 if (inReplyToPost == null)
927                 {
928                     try
929                     {
930                         inReplyToPost = await this.GetStatusApi(read, inReplyToId.ToTwitterStatusId())
931                             .ConfigureAwait(false);
932                     }
933                     catch (WebApiException ex)
934                     {
935                         lastException = ex;
936                         break;
937                     }
938                 }
939
940                 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
941
942                 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
943             }
944
945             // MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
946             var text = targetPost.Text;
947             var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
948                 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
949             foreach (var match in ma)
950             {
951                 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
952                 if (!relPosts.ContainsKey(statusId))
953                 {
954                     var p = TabInformations.GetInstance()[statusId];
955                     if (p == null)
956                     {
957                         try
958                         {
959                             p = await this.GetStatusApi(read, statusId)
960                                 .ConfigureAwait(false);
961                         }
962                         catch (WebApiException ex)
963                         {
964                             lastException = ex;
965                             break;
966                         }
967                     }
968
969                     if (p != null)
970                         relPosts.Add(p.StatusId, p);
971                 }
972             }
973
974             try
975             {
976                 var firstPost = nextPost;
977                 var posts = await this.GetConversationPosts(firstPost, targetPost)
978                     .ConfigureAwait(false);
979
980                 foreach (var post in posts.OrderBy(x => x.StatusId))
981                 {
982                     if (relPosts.ContainsKey(post.StatusId))
983                         continue;
984
985                     // リプライチェーンが繋がらないツイートは除外
986                     if (post.InReplyToStatusId == null || !relPosts.ContainsKey(post.InReplyToStatusId))
987                         continue;
988
989                     relPosts.Add(post.StatusId, post);
990                 }
991             }
992             catch (WebException ex)
993             {
994                 lastException = ex;
995             }
996
997             relPosts.Values.ToList().ForEach(p =>
998             {
999                 var post = p with { };
1000                 if (post.IsMe && !read && this.ReadOwnPost)
1001                     post.IsRead = true;
1002                 else
1003                     post.IsRead = read;
1004
1005                 tab.AddPostQueue(post);
1006             });
1007
1008             if (lastException != null)
1009                 throw new WebApiException(lastException.Message, lastException);
1010         }
1011
1012         private async Task<PostClass[]> GetConversationPosts(PostClass firstPost, PostClass targetPost)
1013         {
1014             var conversationId = firstPost.StatusId;
1015             var query = $"conversation_id:{conversationId.Id}";
1016
1017             if (targetPost.InReplyToUser != null && targetPost.InReplyToUser != targetPost.ScreenName)
1018                 query += $" (from:{targetPost.ScreenName} to:{targetPost.InReplyToUser}) OR (from:{targetPost.InReplyToUser} to:{targetPost.ScreenName})";
1019             else
1020                 query += $" from:{targetPost.ScreenName} to:{targetPost.ScreenName}";
1021
1022             var statuses = await this.Api.SearchTweets(query, count: 100)
1023                 .ConfigureAwait(false);
1024
1025             return statuses.Statuses.Select(x => this.CreatePostsFromStatusData(x)).ToArray();
1026         }
1027
1028         public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1029         {
1030             var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1031
1032             TwitterStatus[] statuses;
1033             if (this.Api.AppToken.AuthType == APIAuthType.TwitterComCookie)
1034             {
1035                 var request = new SearchTimelineRequest(tab.SearchWords)
1036                 {
1037                     Count = count,
1038                     Cursor = more ? tab.CursorBottom : null,
1039                 };
1040                 var response = await request.Send(this.Api.Connection)
1041                     .ConfigureAwait(false);
1042
1043                 var convertedStatuses = response.Tweets.Select(x => x.ToTwitterStatus());
1044                 if (!SettingManager.Instance.Common.IsListsIncludeRts)
1045                     convertedStatuses = convertedStatuses.Where(x => x.RetweetedStatus == null);
1046
1047                 statuses = convertedStatuses.ToArray();
1048                 tab.CursorBottom = response.CursorBottom;
1049             }
1050             else
1051             {
1052                 long? maxId = null;
1053                 long? sinceId = null;
1054                 if (more)
1055                 {
1056                     maxId = tab.OldestId - 1;
1057                 }
1058                 else
1059                 {
1060                     sinceId = tab.SinceId;
1061                 }
1062
1063                 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1064                     .ConfigureAwait(false);
1065
1066                 statuses = searchResult.Statuses;
1067             }
1068
1069             if (!TabInformations.GetInstance().ContainsTab(tab))
1070                 return;
1071
1072             var minimumId = this.CreatePostsFromSearchJson(statuses, tab, read, more);
1073
1074             if (minimumId != null)
1075                 tab.OldestId = minimumId.Value;
1076         }
1077
1078         public async Task GetDirectMessageEvents(bool read, DirectMessagesTabModel dmTab, bool backward)
1079         {
1080             this.CheckAccountState();
1081             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1082
1083             var count = 50;
1084
1085             TwitterMessageEventList eventList;
1086             if (backward)
1087             {
1088                 eventList = await this.Api.DirectMessagesEventsList(count, dmTab.NextCursor)
1089                     .ConfigureAwait(false);
1090             }
1091             else
1092             {
1093                 eventList = await this.Api.DirectMessagesEventsList(count)
1094                     .ConfigureAwait(false);
1095             }
1096
1097             dmTab.NextCursor = eventList.NextCursor;
1098
1099             await this.CreateDirectMessagesEventFromJson(eventList, read)
1100                 .ConfigureAwait(false);
1101         }
1102
1103         private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventSingle eventSingle, bool read)
1104         {
1105             var eventList = new TwitterMessageEventList
1106             {
1107                 Apps = new Dictionary<string, TwitterMessageEventList.App>(),
1108                 Events = new[] { eventSingle.Event },
1109             };
1110
1111             await this.CreateDirectMessagesEventFromJson(eventList, read)
1112                 .ConfigureAwait(false);
1113         }
1114
1115         private async Task CreateDirectMessagesEventFromJson(TwitterMessageEventList eventList, bool read)
1116         {
1117             var events = eventList.Events
1118                 .Where(x => x.Type == "message_create")
1119                 .ToArray();
1120
1121             if (events.Length == 0)
1122                 return;
1123
1124             var userIds = Enumerable.Concat(
1125                 events.Select(x => x.MessageCreate.SenderId),
1126                 events.Select(x => x.MessageCreate.Target.RecipientId)
1127             ).Distinct().ToArray();
1128
1129             var users = (await this.Api.UsersLookup(userIds).ConfigureAwait(false))
1130                 .ToDictionary(x => x.IdStr);
1131
1132             var apps = eventList.Apps ?? new Dictionary<string, TwitterMessageEventList.App>();
1133
1134             this.CreateDirectMessagesEventFromJson(events, users, apps, read);
1135         }
1136
1137         private void CreateDirectMessagesEventFromJson(
1138             IEnumerable<TwitterMessageEvent> events,
1139             IReadOnlyDictionary<string, TwitterUser> users,
1140             IReadOnlyDictionary<string, TwitterMessageEventList.App> apps,
1141             bool read)
1142         {
1143             var dmTab = TabInformations.GetInstance().DirectMessageTab;
1144
1145             foreach (var eventItem in events)
1146             {
1147                 var post = this.postFactory.CreateFromDirectMessageEvent(eventItem, users, apps, this.UserId);
1148
1149                 post.IsRead = read;
1150                 if (post.IsMe && !read && this.ReadOwnPost)
1151                     post.IsRead = true;
1152
1153                 dmTab.AddPostQueue(post);
1154             }
1155         }
1156
1157         public async Task GetFavoritesApi(bool read, FavoritesTabModel tab, bool backward)
1158         {
1159             this.CheckAccountState();
1160
1161             var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, backward, false);
1162
1163             TwitterStatus[] statuses;
1164             if (backward)
1165             {
1166                 statuses = await this.Api.FavoritesList(count, maxId: tab.OldestId)
1167                     .ConfigureAwait(false);
1168             }
1169             else
1170             {
1171                 statuses = await this.Api.FavoritesList(count)
1172                     .ConfigureAwait(false);
1173             }
1174
1175             var minimumId = this.CreateFavoritePostsFromJson(statuses, read);
1176
1177             if (minimumId != null)
1178                 tab.OldestId = minimumId.Value;
1179         }
1180
1181         /// <summary>
1182         /// フォロワーIDを更新します
1183         /// </summary>
1184         /// <exception cref="WebApiException"/>
1185         public async Task RefreshFollowerIds()
1186         {
1187             if (MyCommon.EndingFlag) return;
1188
1189             var cursor = -1L;
1190             var newFollowerIds = Enumerable.Empty<long>();
1191             do
1192             {
1193                 var ret = await this.Api.FollowersIds(cursor)
1194                     .ConfigureAwait(false);
1195
1196                 if (ret.Ids == null)
1197                     throw new WebApiException("ret.ids == null");
1198
1199                 newFollowerIds = newFollowerIds.Concat(ret.Ids);
1200                 cursor = ret.NextCursor;
1201             }
1202             while (cursor != 0);
1203
1204             this.followerId = newFollowerIds.ToHashSet();
1205             TabInformations.GetInstance().RefreshOwl(this.followerId);
1206
1207             this.GetFollowersSuccess = true;
1208         }
1209
1210         /// <summary>
1211         /// RT 非表示ユーザーを更新します
1212         /// </summary>
1213         /// <exception cref="WebApiException"/>
1214         public async Task RefreshNoRetweetIds()
1215         {
1216             if (MyCommon.EndingFlag) return;
1217
1218             this.noRTId = await this.Api.NoRetweetIds()
1219                 .ConfigureAwait(false);
1220
1221             this.GetNoRetweetSuccess = true;
1222         }
1223
1224         /// <summary>
1225         /// t.co の文字列長などの設定情報を更新します
1226         /// </summary>
1227         /// <exception cref="WebApiException"/>
1228         public async Task RefreshConfiguration()
1229         {
1230             this.Configuration = await this.Api.Configuration()
1231                 .ConfigureAwait(false);
1232
1233             // TextConfiguration 相当の JSON を得る API が存在しないため、TransformedURLLength のみ help/configuration.json に合わせて更新する
1234             this.TextConfiguration.TransformedURLLength = this.Configuration.ShortUrlLengthHttps;
1235         }
1236
1237         public async Task GetListsApi()
1238         {
1239             this.CheckAccountState();
1240
1241             var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1242                 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1243                     .ConfigureAwait(false);
1244
1245             var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1246                 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1247                     .ConfigureAwait(false);
1248
1249             TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1250                 .Select(x => new ListElement(x, this))
1251                 .ToList();
1252         }
1253
1254         public async Task DeleteList(long listId)
1255         {
1256             await this.Api.ListsDestroy(listId)
1257                 .IgnoreResponse()
1258                 .ConfigureAwait(false);
1259
1260             var tabinfo = TabInformations.GetInstance();
1261
1262             tabinfo.SubscribableLists = tabinfo.SubscribableLists
1263                 .Where(x => x.Id != listId)
1264                 .ToList();
1265         }
1266
1267         public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1268         {
1269             var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1270                 .ConfigureAwait(false);
1271
1272             var list = await response.LoadJsonAsync()
1273                 .ConfigureAwait(false);
1274
1275             return new ListElement(list, this);
1276         }
1277
1278         public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1279         {
1280             this.CheckAccountState();
1281
1282             var users = await this.Api.ListsMembers(listId, cursor)
1283                 .ConfigureAwait(false);
1284
1285             Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1286
1287             return users.NextCursor;
1288         }
1289
1290         public async Task CreateListApi(string listName, bool isPrivate, string description)
1291         {
1292             this.CheckAccountState();
1293
1294             var response = await this.Api.ListsCreate(listName, description, isPrivate)
1295                 .ConfigureAwait(false);
1296
1297             var list = await response.LoadJsonAsync()
1298                 .ConfigureAwait(false);
1299
1300             TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1301         }
1302
1303         public async Task<bool> ContainsUserAtList(long listId, string user)
1304         {
1305             this.CheckAccountState();
1306
1307             try
1308             {
1309                 await this.Api.ListsMembersShow(listId, user)
1310                     .ConfigureAwait(false);
1311
1312                 return true;
1313             }
1314             catch (TwitterApiException ex)
1315                 when (ex.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1316             {
1317                 return false;
1318             }
1319         }
1320
1321         public async Task<TwitterApiStatus?> GetInfoApi()
1322         {
1323             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1324
1325             if (MyCommon.EndingFlag) return null;
1326
1327             var limits = await this.Api.ApplicationRateLimitStatus()
1328                 .ConfigureAwait(false);
1329
1330             MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1331
1332             return MyCommon.TwitterApiInfo;
1333         }
1334
1335         /// <summary>
1336         /// ブロック中のユーザーを更新します
1337         /// </summary>
1338         /// <exception cref="WebApiException"/>
1339         public async Task RefreshBlockIds()
1340         {
1341             if (MyCommon.EndingFlag) return;
1342
1343             var cursor = -1L;
1344             var newBlockIds = Enumerable.Empty<long>();
1345             do
1346             {
1347                 var ret = await this.Api.BlocksIds(cursor)
1348                     .ConfigureAwait(false);
1349
1350                 newBlockIds = newBlockIds.Concat(ret.Ids);
1351                 cursor = ret.NextCursor;
1352             }
1353             while (cursor != 0);
1354
1355             var blockIdsSet = newBlockIds.ToHashSet();
1356             blockIdsSet.Remove(this.UserId); // 元のソースにあったので一応残しておく
1357
1358             TabInformations.GetInstance().BlockIds = blockIdsSet;
1359         }
1360
1361         /// <summary>
1362         /// ミュート中のユーザーIDを更新します
1363         /// </summary>
1364         /// <exception cref="WebApiException"/>
1365         public async Task RefreshMuteUserIdsAsync()
1366         {
1367             if (MyCommon.EndingFlag) return;
1368
1369             var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1370                 .ConfigureAwait(false);
1371
1372             TabInformations.GetInstance().MuteUserIds = ids.ToHashSet();
1373         }
1374
1375         public string[] GetHashList()
1376             => this.postFactory.GetReceivedHashtags();
1377
1378         public string AccessToken
1379             => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1380
1381         public string AccessTokenSecret
1382             => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1383
1384         private void CheckAccountState()
1385         {
1386             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1387                 throw new WebApiException("Auth error. Check your account");
1388         }
1389
1390         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1391         {
1392             if (!this.AccessLevel.HasFlag(accessLevelFlags))
1393                 throw new WebApiException("Auth Err:try to re-authorization.");
1394         }
1395
1396         public int GetTextLengthRemain(string postText)
1397         {
1398             var matchDm = Twitter.DMSendTextRegex.Match(postText);
1399             if (matchDm.Success)
1400                 return this.GetTextLengthRemainDM(matchDm.Groups["body"].Value);
1401
1402             return this.GetTextLengthRemainWeighted(postText);
1403         }
1404
1405         private int GetTextLengthRemainDM(string postText)
1406         {
1407             var textLength = 0;
1408
1409             var pos = 0;
1410             while (pos < postText.Length)
1411             {
1412                 textLength++;
1413
1414                 if (char.IsSurrogatePair(postText, pos))
1415                     pos += 2; // サロゲートペアの場合は2文字分進める
1416                 else
1417                     pos++;
1418             }
1419
1420             var urls = TweetExtractor.ExtractUrls(postText);
1421             foreach (var url in urls)
1422             {
1423                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1424                     ? this.Configuration.ShortUrlLengthHttps
1425                     : this.Configuration.ShortUrlLength;
1426
1427                 textLength += shortUrlLength - url.Length;
1428             }
1429
1430             return this.Configuration.DmTextCharacterLimit - textLength;
1431         }
1432
1433         private int GetTextLengthRemainWeighted(string postText)
1434         {
1435             var config = this.TextConfiguration;
1436             var totalWeight = 0;
1437
1438             int GetWeightFromCodepoint(int codepoint)
1439             {
1440                 foreach (var weightRange in config.Ranges)
1441                 {
1442                     if (codepoint >= weightRange.Start && codepoint <= weightRange.End)
1443                         return weightRange.Weight;
1444                 }
1445
1446                 return config.DefaultWeight;
1447             }
1448
1449             var urls = TweetExtractor.ExtractUrlEntities(postText).ToArray();
1450             var emojis = config.EmojiParsingEnabled
1451                 ? TweetExtractor.ExtractEmojiEntities(postText).ToArray()
1452                 : Array.Empty<TwitterEntityEmoji>();
1453
1454             var codepoints = postText.ToCodepoints().ToArray();
1455             var index = 0;
1456             while (index < codepoints.Length)
1457             {
1458                 var urlEntity = urls.FirstOrDefault(x => x.Indices[0] == index);
1459                 if (urlEntity != null)
1460                 {
1461                     totalWeight += config.TransformedURLLength * config.Scale;
1462                     index = urlEntity.Indices[1];
1463                     continue;
1464                 }
1465
1466                 var emojiEntity = emojis.FirstOrDefault(x => x.Indices[0] == index);
1467                 if (emojiEntity != null)
1468                 {
1469                     totalWeight += GetWeightFromCodepoint(codepoints[index]);
1470                     index = emojiEntity.Indices[1];
1471                     continue;
1472                 }
1473
1474                 var codepoint = codepoints[index];
1475                 totalWeight += GetWeightFromCodepoint(codepoint);
1476
1477                 index++;
1478             }
1479
1480             var remainWeight = config.MaxWeightedTweetLength * config.Scale - totalWeight;
1481
1482             return remainWeight / config.Scale;
1483         }
1484
1485         /// <summary>
1486         /// プロフィール画像のサイズを指定したURLを生成
1487         /// </summary>
1488         /// <remarks>
1489         /// https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/user-profile-images-and-banners を参照
1490         /// </remarks>
1491         public static string CreateProfileImageUrl(string normalUrl, string size)
1492         {
1493             return size switch
1494             {
1495                 "original" => normalUrl.Replace("_normal.", "."),
1496                 "normal" => normalUrl,
1497                 "bigger" or "mini" => normalUrl.Replace("_normal.", $"_{size}."),
1498                 _ => throw new ArgumentException($"Invalid size: ${size}", nameof(size)),
1499             };
1500         }
1501
1502         public static string DecideProfileImageSize(int sizePx)
1503         {
1504             return sizePx switch
1505             {
1506                 <= 24 => "mini",
1507                 <= 48 => "normal",
1508                 <= 73 => "bigger",
1509                 _ => "original",
1510             };
1511         }
1512
1513         public bool IsDisposed { get; private set; } = false;
1514
1515         protected virtual void Dispose(bool disposing)
1516         {
1517             if (this.IsDisposed)
1518                 return;
1519
1520             if (disposing)
1521             {
1522                 this.Api.Dispose();
1523             }
1524
1525             this.IsDisposed = true;
1526         }
1527
1528         public void Dispose()
1529         {
1530             this.Dispose(true);
1531             GC.SuppressFinalize(this);
1532         }
1533     }
1534 }