OSDN Git Service

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