OSDN Git Service

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