OSDN Git Service

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