OSDN Git Service

ふぁぼイベントに含まれるツイートでExtended Tweetを考慮する
[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 using System.Diagnostics;
29 using System.IO;
30 using System.Linq;
31 using System.Net;
32 using System.Net.Http;
33 using System.Runtime.CompilerServices;
34 using System.Runtime.Serialization;
35 using System.Runtime.Serialization.Json;
36 using System.Text;
37 using System.Text.RegularExpressions;
38 using System.Threading;
39 using System.Threading.Tasks;
40 using System.Web;
41 using System.Xml;
42 using System.Xml.Linq;
43 using System.Xml.XPath;
44 using System;
45 using System.Reflection;
46 using System.Collections.Generic;
47 using System.Drawing;
48 using System.Windows.Forms;
49 using OpenTween.Api;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.Models;
53
54 namespace OpenTween
55 {
56     public class Twitter : IDisposable
57     {
58         #region Regexp from twitter-text-js
59
60         // The code in this region code block incorporates works covered by
61         // the following copyright and permission notices:
62         //
63         //   Copyright 2011 Twitter, Inc.
64         //
65         //   Licensed under the Apache License, Version 2.0 (the "License"); you
66         //   may not use this work except in compliance with the License. You
67         //   may obtain a copy of the License in the LICENSE file, or at:
68         //
69         //   http://www.apache.org/licenses/LICENSE-2.0
70         //
71         //   Unless required by applicable law or agreed to in writing, software
72         //   distributed under the License is distributed on an "AS IS" BASIS,
73         //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
74         //   implied. See the License for the specific language governing
75         //   permissions and limitations under the License.
76
77         //Hashtag用正規表現
78         private const string LATIN_ACCENTS = @"\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0100-\u024f\u0253\u0254\u0256\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff";
79         private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
80         //private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u3096\u3400-\u4DBF\u4E00-\u9FFF\u20000-\u2A6DF\u2A700-\u2B73F\u2B740-\u2B81F\u2F800-\u2FA1F";
81         private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
82         private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
83         private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84         private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
85         private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
86         public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
87         //URL正規表現
88         private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
89         public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
90         private const string url_invalid_domain_chars = @"\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$\u2000-\u200a\u0009-\u000d\u0020\u0085\u00a0\u1680\u180e\u2028\u2029\u202f\u205f\u3000\ufffe\ufeff\uffff\u202a-\u202e";
91         private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
92         private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
93         private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
94         private const string url_valid_GTLD = @"(?:(?: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]|$))";
95         private const string url_valid_CCTLD = @"(?:(?: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]|$))";
96         private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
97         private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
98         public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
99         public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
100         private const string url_valid_port_number = @"[0-9]+";
101
102         private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
103         private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
104         private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
105         private const string pth = "(?:" +
106             "(?:" +
107                 url_valid_general_path_chars + "*" +
108                 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
109                 url_valid_path_ending_chars +
110                 ")|(?:@" + url_valid_general_path_chars + "+/)" +
111             ")";
112         private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
113         public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
114                                     "(?<url>(?<protocol>https?://)?" +
115                                     "(?<domain>" + url_valid_domain + ")" +
116                                     "(?::" + url_valid_port_number + ")?" +
117                                     "(?<path>/" + pth + "*)?" +
118                                     qry +
119                                     ")";
120
121         #endregion
122
123         /// <summary>
124         /// Twitter API のステータスページのURL
125         /// </summary>
126         public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
127
128         /// <summary>
129         /// ツイートへのパーマリンクURLを判定する正規表現
130         /// </summary>
131         public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
132
133         /// <summary>
134         /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
135         /// </summary>
136         public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
137   favstar\.fm/users/[a-zA-Z0-9_]+/status/       # Favstar
138 | favstar\.fm/t/                                # Favstar (short)
139 | aclog\.koba789\.com/i/                        # aclog
140 | frtrt\.net/solo_status\.php\?status=          # RtRT
141 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
142
143         /// <summary>
144         /// DM送信かどうかを判定する正規表現
145         /// </summary>
146         public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
147
148         public TwitterApi Api { get; }
149         public TwitterConfiguration Configuration { get; private set; }
150
151         delegate void GetIconImageDelegate(PostClass post);
152         private readonly object LockObj = new object();
153         private ISet<long> followerId = new HashSet<long>();
154         private bool _GetFollowerResult = false;
155         private long[] noRTId = new long[0];
156         private bool _GetNoRetweetResult = false;
157
158         //プロパティからアクセスされる共通情報
159         private string _uname;
160
161         private bool _readOwnPost;
162         private List<string> _hashList = new List<string>();
163
164         //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
165         private long minDirectmessage = long.MaxValue;
166         private long minDirectmessageSent = long.MaxValue;
167
168         private long previousStatusId = -1L;
169
170         //private FavoriteQueue favQueue;
171
172         //private List<PostClass> _deletemessages = new List<PostClass>();
173
174         public Twitter() : this(new TwitterApi())
175         {
176         }
177
178         public Twitter(TwitterApi api)
179         {
180             this.Api = api;
181             this.Configuration = TwitterConfiguration.DefaultConfiguration();
182         }
183
184         public TwitterApiAccessLevel AccessLevel
185         {
186             get
187             {
188                 return MyCommon.TwitterApiInfo.AccessLevel;
189             }
190         }
191
192         protected void ResetApiStatus()
193         {
194             MyCommon.TwitterApiInfo.Reset();
195         }
196
197         public void ClearAuthInfo()
198         {
199             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
200             this.ResetApiStatus();
201         }
202
203         [Obsolete]
204         public void VerifyCredentials()
205         {
206             try
207             {
208                 this.VerifyCredentialsAsync().Wait();
209             }
210             catch (AggregateException ex) when (ex.InnerException is WebApiException)
211             {
212                 throw new WebApiException(ex.InnerException.Message, ex);
213             }
214         }
215
216         public async Task VerifyCredentialsAsync()
217         {
218             var user = await this.Api.AccountVerifyCredentials()
219                 .ConfigureAwait(false);
220
221             this.UpdateUserStats(user);
222         }
223
224         public void Initialize(string token, string tokenSecret, string username, long userId)
225         {
226             //OAuth認証
227             if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
228             {
229                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
230             }
231             this.ResetApiStatus();
232             this.Api.Initialize(token, tokenSecret, userId, username);
233             _uname = username.ToLowerInvariant();
234             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
235         }
236
237         public string PreProcessUrl(string orgData)
238         {
239             int posl1;
240             var posl2 = 0;
241             //var IDNConveter = new IdnMapping();
242             var href = "<a href=\"";
243
244             while (true)
245             {
246                 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
247                 {
248                     var urlStr = "";
249                     // IDN展開
250                     posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
251                     posl1 += href.Length;
252                     posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
253                     urlStr = orgData.Substring(posl1, posl2 - posl1);
254
255                     if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
256                         && !urlStr.StartsWith("https://", StringComparison.Ordinal)
257                         && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
258                     {
259                         continue;
260                     }
261
262                     var replacedUrl = MyCommon.IDNEncode(urlStr);
263                     if (replacedUrl == null) continue;
264                     if (replacedUrl == urlStr) continue;
265
266                     orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
267                     posl2 = 0;
268                 }
269                 else
270                 {
271                     break;
272                 }
273             }
274             return orgData;
275         }
276
277         public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
278         {
279             this.CheckAccountState();
280
281             if (mediaIds == null &&
282                 Twitter.DMSendTextRegex.IsMatch(postStr))
283             {
284                 await this.SendDirectMessage(postStr)
285                     .ConfigureAwait(false);
286                 return;
287             }
288
289             var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
290                 .ConfigureAwait(false);
291
292             var status = await response.LoadJsonAsync()
293                 .ConfigureAwait(false);
294
295             this.UpdateUserStats(status.User);
296
297             if (status.Id == this.previousStatusId)
298                 throw new WebApiException("OK:Delaying?");
299
300             this.previousStatusId = status.Id;
301         }
302
303         public async Task<long> UploadMedia(IMediaItem item)
304         {
305             this.CheckAccountState();
306
307             var response = await this.Api.MediaUpload(item)
308                 .ConfigureAwait(false);
309
310             var media = await response.LoadJsonAsync()
311                 .ConfigureAwait(false);
312
313             return media.MediaId;
314         }
315
316         public async Task SendDirectMessage(string postStr)
317         {
318             this.CheckAccountState();
319             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
320
321             var mc = Twitter.DMSendTextRegex.Match(postStr);
322
323             var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
324                 .ConfigureAwait(false);
325
326             var dm = await response.LoadJsonAsync()
327                 .ConfigureAwait(false);
328
329             this.UpdateUserStats(dm.Sender);
330         }
331
332         public async Task PostRetweet(long id, bool read)
333         {
334             this.CheckAccountState();
335
336             //データ部分の生成
337             var post = TabInformations.GetInstance()[id];
338             if (post == null)
339                 throw new WebApiException("Err:Target isn't found.");
340
341             var target = post.RetweetedId ?? id;  //再RTの場合は元発言をRT
342
343             var response = await this.Api.StatusesRetweet(target)
344                 .ConfigureAwait(false);
345
346             var status = await response.LoadJsonAsync()
347                 .ConfigureAwait(false);
348
349             //二重取得回避
350             lock (LockObj)
351             {
352                 if (TabInformations.GetInstance().ContainsKey(status.Id))
353                     return;
354             }
355
356             //Retweet判定
357             if (status.RetweetedStatus == null)
358                 throw new WebApiException("Invalid Json!");
359
360             //ReTweetしたものをTLに追加
361             post = CreatePostsFromStatusData(status);
362             
363             //ユーザー情報
364             post.IsMe = true;
365
366             post.IsRead = read;
367             post.IsOwl = false;
368             if (_readOwnPost) post.IsRead = true;
369             post.IsDm = false;
370
371             TabInformations.GetInstance().AddPost(post);
372         }
373
374         public string Username
375             => this.Api.CurrentScreenName;
376
377         public long UserId
378             => this.Api.CurrentUserId;
379
380         private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
381         public static MyCommon.ACCOUNT_STATE AccountState
382         {
383             get
384             {
385                 return _accountState;
386             }
387             set
388             {
389                 _accountState = value;
390             }
391         }
392
393         public bool RestrictFavCheck { get; set; }
394
395         public bool ReadOwnPost
396         {
397             get
398             {
399                 return _readOwnPost;
400             }
401             set
402             {
403                 _readOwnPost = value;
404             }
405         }
406
407         public int FollowersCount { get; private set; }
408         public int FriendsCount { get; private set; }
409         public int StatusesCount { get; private set; }
410         public string Location { get; private set; } = "";
411         public string Bio { get; private set; } = "";
412
413         /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
414         private void UpdateUserStats(TwitterUser self)
415         {
416             this.FollowersCount = self.FollowersCount;
417             this.FriendsCount = self.FriendsCount;
418             this.StatusesCount = self.StatusesCount;
419             this.Location = self.Location;
420             this.Bio = self.Description;
421         }
422
423         /// <summary>
424         /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
425         /// </summary>
426         public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
427         {
428             return count >= 20 && count <= GetMaxApiResultCount(type);
429         }
430
431         /// <summary>
432         /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
433         /// </summary>
434         public static bool VerifyMoreApiResultCount(int count)
435         {
436             return count >= 20 && count <= 200;
437         }
438
439         /// <summary>
440         /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
441         /// </summary>
442         public static bool VerifyFirstApiResultCount(int count)
443         {
444             return count >= 20 && count <= 200;
445         }
446
447         /// <summary>
448         /// WORKERTYPEに応じた取得可能な最大件数を取得する
449         /// </summary>
450         public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
451         {
452             // 参照: REST APIs - 各endpointのcountパラメータ
453             // https://dev.twitter.com/rest/public
454             switch (type)
455             {
456                 case MyCommon.WORKERTYPE.Timeline:
457                 case MyCommon.WORKERTYPE.Reply:
458                 case MyCommon.WORKERTYPE.UserTimeline:
459                 case MyCommon.WORKERTYPE.Favorites:
460                 case MyCommon.WORKERTYPE.DirectMessegeRcv:
461                 case MyCommon.WORKERTYPE.DirectMessegeSnt:
462                 case MyCommon.WORKERTYPE.List:  // 不明
463                     return 200;
464
465                 case MyCommon.WORKERTYPE.PublicSearch:
466                     return 100;
467
468                 default:
469                     throw new InvalidOperationException("Invalid type: " + type);
470             }
471         }
472
473         /// <summary>
474         /// WORKERTYPEに応じた取得件数を取得する
475         /// </summary>
476         public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
477         {
478             if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
479                 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
480             {
481                 return 20;
482             }
483
484             if (SettingCommon.Instance.UseAdditionalCount)
485             {
486                 switch (type)
487                 {
488                     case MyCommon.WORKERTYPE.Favorites:
489                         if (SettingCommon.Instance.FavoritesCountApi != 0)
490                             return SettingCommon.Instance.FavoritesCountApi;
491                         break;
492                     case MyCommon.WORKERTYPE.List:
493                         if (SettingCommon.Instance.ListCountApi != 0)
494                             return SettingCommon.Instance.ListCountApi;
495                         break;
496                     case MyCommon.WORKERTYPE.PublicSearch:
497                         if (SettingCommon.Instance.SearchCountApi != 0)
498                             return SettingCommon.Instance.SearchCountApi;
499                         break;
500                     case MyCommon.WORKERTYPE.UserTimeline:
501                         if (SettingCommon.Instance.UserTimelineCountApi != 0)
502                             return SettingCommon.Instance.UserTimelineCountApi;
503                         break;
504                 }
505                 if (more && SettingCommon.Instance.MoreCountApi != 0)
506                 {
507                     return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
508                 }
509                 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
510                 {
511                     return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
512                 }
513             }
514
515             // 上記に当てはまらない場合の共通処理
516             var count = SettingCommon.Instance.CountApi;
517
518             if (type == MyCommon.WORKERTYPE.Reply)
519                 count = SettingCommon.Instance.CountApiReply;
520
521             return Math.Min(count, GetMaxApiResultCount(type));
522         }
523
524         public async Task GetHomeTimelineApi(bool read, HomeTabModel tab, bool more, bool startup)
525         {
526             this.CheckAccountState();
527
528             var count = GetApiResultCount(MyCommon.WORKERTYPE.Timeline, more, startup);
529
530             TwitterStatus[] statuses;
531             if (more)
532             {
533                 statuses = await this.Api.StatusesHomeTimeline(count, maxId: tab.OldestId)
534                     .ConfigureAwait(false);
535             }
536             else
537             {
538                 statuses = await this.Api.StatusesHomeTimeline(count)
539                     .ConfigureAwait(false);
540             }
541
542             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Timeline, tab, read);
543             if (minimumId != null)
544                 tab.OldestId = minimumId.Value;
545         }
546
547         public async Task GetMentionsTimelineApi(bool read, MentionsTabModel tab, bool more, bool startup)
548         {
549             this.CheckAccountState();
550
551             var count = GetApiResultCount(MyCommon.WORKERTYPE.Reply, more, startup);
552
553             TwitterStatus[] statuses;
554             if (more)
555             {
556                 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: tab.OldestId)
557                     .ConfigureAwait(false);
558             }
559             else
560             {
561                 statuses = await this.Api.StatusesMentionsTimeline(count)
562                     .ConfigureAwait(false);
563             }
564
565             var minimumId = this.CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.Reply, tab, read);
566             if (minimumId != null)
567                 tab.OldestId = minimumId.Value;
568         }
569
570         public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
571         {
572             this.CheckAccountState();
573
574             var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
575
576             TwitterStatus[] statuses;
577             if (string.IsNullOrEmpty(userName))
578             {
579                 var target = tab.ScreenName;
580                 if (string.IsNullOrEmpty(target)) return;
581                 userName = target;
582                 statuses = await this.Api.StatusesUserTimeline(userName, count)
583                     .ConfigureAwait(false);
584             }
585             else
586             {
587                 if (more)
588                 {
589                     statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
590                         .ConfigureAwait(false);
591                 }
592                 else
593                 {
594                     statuses = await this.Api.StatusesUserTimeline(userName, count)
595                         .ConfigureAwait(false);
596                 }
597             }
598
599             var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
600
601             if (minimumId != null)
602                 tab.OldestId = minimumId.Value;
603         }
604
605         public async Task<PostClass> GetStatusApi(bool read, long id)
606         {
607             this.CheckAccountState();
608
609             var status = await this.Api.StatusesShow(id)
610                 .ConfigureAwait(false);
611
612             var item = CreatePostsFromStatusData(status);
613
614             item.IsRead = read;
615             if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
616
617             return item;
618         }
619
620         public async Task GetStatusApi(bool read, long id, TabModel tab)
621         {
622             var post = await this.GetStatusApi(read, id)
623                 .ConfigureAwait(false);
624
625             //非同期アイコン取得&StatusDictionaryに追加
626             if (tab != null && tab.IsInnerStorageTabType)
627                 tab.AddPostQueue(post);
628             else
629                 TabInformations.GetInstance().AddPost(post);
630         }
631
632         private PostClass CreatePostsFromStatusData(TwitterStatus status)
633         {
634             return CreatePostsFromStatusData(status, false);
635         }
636
637         private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
638         {
639             var post = new PostClass();
640             TwitterEntities entities;
641             string sourceHtml;
642
643             post.StatusId = status.Id;
644             if (status.RetweetedStatus != null)
645             {
646                 var retweeted = status.RetweetedStatus;
647
648                 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
649
650                 //Id
651                 post.RetweetedId = retweeted.Id;
652                 //本文
653                 post.TextFromApi = retweeted.FullText;
654                 entities = retweeted.MergedEntities;
655                 sourceHtml = retweeted.Source;
656                 //Reply先
657                 post.InReplyToStatusId = retweeted.InReplyToStatusId;
658                 post.InReplyToUser = retweeted.InReplyToScreenName;
659                 post.InReplyToUserId = status.InReplyToUserId;
660
661                 if (favTweet)
662                 {
663                     post.IsFav = true;
664                 }
665                 else
666                 {
667                     //幻覚fav対策
668                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
669                     post.IsFav = tc.Contains(retweeted.Id);
670                 }
671
672                 if (retweeted.Coordinates != null)
673                     post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
674
675                 //以下、ユーザー情報
676                 var user = retweeted.User;
677                 if (user != null)
678                 {
679                     post.UserId = user.Id;
680                     post.ScreenName = user.ScreenName;
681                     post.Nickname = user.Name.Trim();
682                     post.ImageUrl = user.ProfileImageUrlHttps;
683                     post.IsProtect = user.Protected;
684                 }
685                 else
686                 {
687                     post.UserId = 0L;
688                     post.ScreenName = "?????";
689                     post.Nickname = "Unknown User";
690                 }
691
692                 //Retweetした人
693                 if (status.User != null)
694                 {
695                     post.RetweetedBy = status.User.ScreenName;
696                     post.RetweetedByUserId = status.User.Id;
697                     post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
698                 }
699                 else
700                 {
701                     post.RetweetedBy = "?????";
702                     post.RetweetedByUserId = 0L;
703                 }
704             }
705             else
706             {
707                 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
708                 //本文
709                 post.TextFromApi = status.FullText;
710                 entities = status.MergedEntities;
711                 sourceHtml = status.Source;
712                 post.InReplyToStatusId = status.InReplyToStatusId;
713                 post.InReplyToUser = status.InReplyToScreenName;
714                 post.InReplyToUserId = status.InReplyToUserId;
715
716                 if (favTweet)
717                 {
718                     post.IsFav = true;
719                 }
720                 else
721                 {
722                     //幻覚fav対策
723                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
724                     post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
725                 }
726
727                 if (status.Coordinates != null)
728                     post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
729
730                 //以下、ユーザー情報
731                 var user = status.User;
732                 if (user != null)
733                 {
734                     post.UserId = user.Id;
735                     post.ScreenName = user.ScreenName;
736                     post.Nickname = user.Name.Trim();
737                     post.ImageUrl = user.ProfileImageUrlHttps;
738                     post.IsProtect = user.Protected;
739                     post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
740                 }
741                 else
742                 {
743                     post.UserId = 0L;
744                     post.ScreenName = "?????";
745                     post.Nickname = "Unknown User";
746                 }
747             }
748             //HTMLに整形
749             string textFromApi = post.TextFromApi;
750             post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
751             post.TextFromApi = textFromApi;
752             post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
753             post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
754             post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
755             post.AccessibleText = this.CreateAccessibleText(textFromApi, entities, (status.RetweetedStatus ?? status).QuotedStatus);
756             post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
757             post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
758
759             post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
760                 .Where(x => x != post.StatusId && x != post.RetweetedId)
761                 .Distinct().ToArray();
762
763             post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
764                 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
765                 .ToArray();
766
767             // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
768             if (post.Text == post.TextFromApi)
769                 post.Text = post.TextFromApi;
770             if (post.AccessibleText == post.TextFromApi)
771                 post.AccessibleText = post.TextFromApi;
772
773             // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
774             post.ScreenName = string.Intern(post.ScreenName);
775             post.Nickname = string.Intern(post.Nickname);
776             post.ImageUrl = string.Intern(post.ImageUrl);
777             post.RetweetedBy = post.RetweetedBy != null ? string.Intern(post.RetweetedBy) : null;
778
779             //Source整形
780             var source = ParseSource(sourceHtml);
781             post.Source = string.Intern(source.Item1);
782             post.SourceUri = source.Item2;
783
784             post.IsReply = post.ReplyToList.Contains(_uname);
785             post.IsExcludeReply = false;
786
787             if (post.IsMe)
788             {
789                 post.IsOwl = false;
790             }
791             else
792             {
793                 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
794             }
795
796             post.IsDm = false;
797             return post;
798         }
799
800         /// <summary>
801         /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
802         /// </summary>
803         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
804         {
805             var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
806
807             return GetQuoteTweetStatusIds(urls);
808         }
809
810         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
811         {
812             foreach (var url in urls)
813             {
814                 var match = Twitter.StatusUrlRegex.Match(url);
815                 if (match.Success)
816                 {
817                     long statusId;
818                     if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
819                         yield return statusId;
820                 }
821             }
822         }
823
824         private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
825         {
826             long? minimumId = null;
827
828             foreach (var status in items)
829             {
830                 if (minimumId == null || minimumId.Value > status.Id)
831                     minimumId = status.Id;
832
833                 //二重取得回避
834                 lock (LockObj)
835                 {
836                     if (tab == null)
837                     {
838                         if (TabInformations.GetInstance().ContainsKey(status.Id)) continue;
839                     }
840                     else
841                     {
842                         if (tab.Contains(status.Id)) continue;
843                     }
844                 }
845
846                 //RT禁止ユーザーによるもの
847                 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
848                     status.RetweetedStatus != null && this.noRTId.Contains(status.User.Id)) continue;
849
850                 var post = CreatePostsFromStatusData(status);
851
852                 post.IsRead = read;
853                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
854
855                 if (tab != null && tab.IsInnerStorageTabType)
856                     tab.AddPostQueue(post);
857                 else
858                     TabInformations.GetInstance().AddPost(post);
859             }
860
861             return minimumId;
862         }
863
864         private long? CreatePostsFromSearchJson(TwitterSearchResult items, PublicSearchTabModel tab, bool read, bool more)
865         {
866             long? minimumId = null;
867
868             foreach (var status in items.Statuses)
869             {
870                 if (minimumId == null || minimumId.Value > status.Id)
871                     minimumId = status.Id;
872
873                 if (!more && status.Id > tab.SinceId) tab.SinceId = status.Id;
874                 //二重取得回避
875                 lock (LockObj)
876                 {
877                     if (tab.Contains(status.Id)) continue;
878                 }
879
880                 var post = CreatePostsFromStatusData(status);
881
882                 post.IsRead = read;
883                 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
884
885                 tab.AddPostQueue(post);
886             }
887
888             return minimumId;
889         }
890
891         private void CreateFavoritePostsFromJson(TwitterStatus[] items, bool read)
892         {
893             var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
894
895             foreach (var status in items)
896             {
897                 //二重取得回避
898                 lock (LockObj)
899                 {
900                     if (favTab.Contains(status.Id)) continue;
901                 }
902
903                 var post = CreatePostsFromStatusData(status, true);
904
905                 post.IsRead = read;
906
907                 TabInformations.GetInstance().AddPost(post);
908             }
909         }
910
911         public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
912         {
913             var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
914
915             TwitterStatus[] statuses;
916             if (more)
917             {
918                 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
919                     .ConfigureAwait(false);
920             }
921             else
922             {
923                 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
924                     .ConfigureAwait(false);
925             }
926
927             var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
928
929             if (minimumId != null)
930                 tab.OldestId = minimumId.Value;
931         }
932
933         /// <summary>
934         /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
935         /// </summary>
936         /// <returns>posts の中から検索されたリプライチェインの末端</returns>
937         internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
938         {
939             if (!posts.ContainsKey(startStatusId))
940                 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
941
942             var nextPost = posts[startStatusId];
943             while (nextPost.InReplyToStatusId != null)
944             {
945                 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
946                     break;
947                 nextPost = posts[nextPost.InReplyToStatusId.Value];
948             }
949
950             return nextPost;
951         }
952
953         public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
954         {
955             var targetPost = tab.TargetPost;
956             var relPosts = new Dictionary<Int64, PostClass>();
957             if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
958             {
959                 //検索結果対応
960                 var p = TabInformations.GetInstance()[targetPost.StatusId];
961                 if (p != null && p.InReplyToStatusId != null)
962                 {
963                     targetPost = p;
964                 }
965                 else
966                 {
967                     p = await this.GetStatusApi(read, targetPost.StatusId)
968                         .ConfigureAwait(false);
969                     targetPost = p;
970                 }
971             }
972             relPosts.Add(targetPost.StatusId, targetPost);
973
974             Exception lastException = null;
975
976             // in_reply_to_status_id を使用してリプライチェインを辿る
977             var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
978             var loopCount = 1;
979             while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
980             {
981                 var inReplyToId = nextPost.InReplyToStatusId.Value;
982
983                 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
984                 if (inReplyToPost == null)
985                 {
986                     try
987                     {
988                         inReplyToPost = await this.GetStatusApi(read, inReplyToId)
989                             .ConfigureAwait(false);
990                     }
991                     catch (WebApiException ex)
992                     {
993                         lastException = ex;
994                         break;
995                     }
996                 }
997
998                 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
999
1000                 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1001             }
1002
1003             //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1004             var text = targetPost.Text;
1005             var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1006                 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1007             foreach (var _match in ma)
1008             {
1009                 Int64 _statusId;
1010                 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1011                 {
1012                     if (relPosts.ContainsKey(_statusId))
1013                         continue;
1014
1015                     var p = TabInformations.GetInstance()[_statusId];
1016                     if (p == null)
1017                     {
1018                         try
1019                         {
1020                             p = await this.GetStatusApi(read, _statusId)
1021                                 .ConfigureAwait(false);
1022                         }
1023                         catch (WebApiException ex)
1024                         {
1025                             lastException = ex;
1026                             break;
1027                         }
1028                     }
1029
1030                     if (p != null)
1031                         relPosts.Add(p.StatusId, p);
1032                 }
1033             }
1034
1035             relPosts.Values.ToList().ForEach(p =>
1036             {
1037                 if (p.IsMe && !read && this._readOwnPost)
1038                     p.IsRead = true;
1039                 else
1040                     p.IsRead = read;
1041
1042                 tab.AddPostQueue(p);
1043             });
1044
1045             if (lastException != null)
1046                 throw new WebApiException(lastException.Message, lastException);
1047         }
1048
1049         public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1050         {
1051             var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1052
1053             long? maxId = null;
1054             long? sinceId = null;
1055             if (more)
1056             {
1057                 maxId = tab.OldestId - 1;
1058             }
1059             else
1060             {
1061                 sinceId = tab.SinceId;
1062             }
1063
1064             var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1065                 .ConfigureAwait(false);
1066
1067             if (!TabInformations.GetInstance().ContainsTab(tab))
1068                 return;
1069
1070             var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, more);
1071
1072             if (minimumId != null)
1073                 tab.OldestId = minimumId.Value;
1074         }
1075
1076         private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1077         {
1078             foreach (var message in item)
1079             {
1080                 var post = new PostClass();
1081                 try
1082                 {
1083                     post.StatusId = message.Id;
1084                     if (gType != MyCommon.WORKERTYPE.UserStream)
1085                     {
1086                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1087                         {
1088                             if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1089                         }
1090                         else
1091                         {
1092                             if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1093                         }
1094                     }
1095
1096                     //二重取得回避
1097                     lock (LockObj)
1098                     {
1099                         if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1100                     }
1101                     //sender_id
1102                     //recipient_id
1103                     post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1104                     //本文
1105                     var textFromApi = message.Text;
1106                     //HTMLに整形
1107                     post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1108                     post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1109                     post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1110                     post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1111                     post.AccessibleText = this.CreateAccessibleText(textFromApi, message.Entities, quoteStatus: null);
1112                     post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText);
1113                     post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661");
1114                     post.IsFav = false;
1115
1116                     post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1117
1118                     post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1119                         .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1120                         .ToArray();
1121
1122                     //以下、ユーザー情報
1123                     TwitterUser user;
1124                     if (gType == MyCommon.WORKERTYPE.UserStream)
1125                     {
1126                         if (this.Api.CurrentUserId == message.Recipient.Id)
1127                         {
1128                             user = message.Sender;
1129                             post.IsMe = false;
1130                             post.IsOwl = true;
1131                         }
1132                         else
1133                         {
1134                             user = message.Recipient;
1135                             post.IsMe = true;
1136                             post.IsOwl = false;
1137                         }
1138                     }
1139                     else
1140                     {
1141                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1142                         {
1143                             user = message.Sender;
1144                             post.IsMe = false;
1145                             post.IsOwl = true;
1146                         }
1147                         else
1148                         {
1149                             user = message.Recipient;
1150                             post.IsMe = true;
1151                             post.IsOwl = false;
1152                         }
1153                     }
1154
1155                     post.UserId = user.Id;
1156                     post.ScreenName = user.ScreenName;
1157                     post.Nickname = user.Name.Trim();
1158                     post.ImageUrl = user.ProfileImageUrlHttps;
1159                     post.IsProtect = user.Protected;
1160
1161                     // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる)
1162                     if (post.Text == post.TextFromApi)
1163                         post.Text = post.TextFromApi;
1164                     if (post.AccessibleText == post.TextFromApi)
1165                         post.AccessibleText = post.TextFromApi;
1166
1167                     // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す
1168                     post.ScreenName = string.Intern(post.ScreenName);
1169                     post.Nickname = string.Intern(post.Nickname);
1170                     post.ImageUrl = string.Intern(post.ImageUrl);
1171                 }
1172                 catch(Exception ex)
1173                 {
1174                     MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1175                     MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1176                     continue;
1177                 }
1178
1179                 post.IsRead = read;
1180                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1181                 post.IsReply = false;
1182                 post.IsExcludeReply = false;
1183                 post.IsDm = true;
1184
1185                 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1186                 dmTab.AddPostQueue(post);
1187             }
1188         }
1189
1190         public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1191         {
1192             this.CheckAccountState();
1193             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1194
1195             var count = GetApiResultCount(gType, more, false);
1196
1197             TwitterDirectMessage[] messages;
1198             if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1199             {
1200                 if (more)
1201                 {
1202                     messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1203                         .ConfigureAwait(false);
1204                 }
1205                 else
1206                 {
1207                     messages = await this.Api.DirectMessagesRecv(count)
1208                         .ConfigureAwait(false);
1209                 }
1210             }
1211             else
1212             {
1213                 if (more)
1214                 {
1215                     messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1216                         .ConfigureAwait(false);
1217                 }
1218                 else
1219                 {
1220                     messages = await this.Api.DirectMessagesSent(count)
1221                         .ConfigureAwait(false);
1222                 }
1223             }
1224
1225             CreateDirectMessagesFromJson(messages, gType, read);
1226         }
1227
1228         public async Task GetFavoritesApi(bool read, bool more)
1229         {
1230             this.CheckAccountState();
1231
1232             var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1233
1234             var statuses = await this.Api.FavoritesList(count)
1235                 .ConfigureAwait(false);
1236
1237             CreateFavoritePostsFromJson(statuses, read);
1238         }
1239
1240         private string ReplaceTextFromApi(string text, TwitterEntities entities)
1241         {
1242             if (entities != null)
1243             {
1244                 if (entities.Urls != null)
1245                 {
1246                     foreach (var m in entities.Urls)
1247                     {
1248                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1249                     }
1250                 }
1251                 if (entities.Media != null)
1252                 {
1253                     foreach (var m in entities.Media)
1254                     {
1255                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1256                     }
1257                 }
1258             }
1259             return text;
1260         }
1261
1262         private string CreateAccessibleText(string text, TwitterEntities entities, TwitterStatus quoteStatus)
1263         {
1264             if (entities == null)
1265                 return text;
1266
1267             if (entities.Urls != null)
1268             {
1269                 foreach (var entity in entities.Urls)
1270                 {
1271                     if (quoteStatus != null)
1272                     {
1273                         var matchStatusUrl = Twitter.StatusUrlRegex.Match(entity.ExpandedUrl);
1274                         if (matchStatusUrl.Success && matchStatusUrl.Groups["StatusId"].Value == quoteStatus.IdStr)
1275                         {
1276                             var quoteText = this.CreateAccessibleText(quoteStatus.FullText, quoteStatus.MergedEntities, quoteStatus: null);
1277                             text = text.Replace(entity.Url, string.Format(Properties.Resources.QuoteStatus_AccessibleText, quoteStatus.User.ScreenName, quoteText));
1278                         }
1279                     }
1280                     else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1281                     {
1282                         text = text.Replace(entity.Url, entity.DisplayUrl);
1283                     }
1284                 }
1285             }
1286
1287             if (entities.Media != null)
1288             {
1289                 foreach (var entity in entities.Media)
1290                 {
1291                     if (!string.IsNullOrEmpty(entity.AltText))
1292                     {
1293                         text = text.Replace(entity.Url, string.Format(Properties.Resources.ImageAltText, entity.AltText));
1294                     }
1295                     else if (!string.IsNullOrEmpty(entity.DisplayUrl))
1296                     {
1297                         text = text.Replace(entity.Url, entity.DisplayUrl);
1298                     }
1299                 }
1300             }
1301
1302             return text;
1303         }
1304
1305         /// <summary>
1306         /// フォロワーIDを更新します
1307         /// </summary>
1308         /// <exception cref="WebApiException"/>
1309         public async Task RefreshFollowerIds()
1310         {
1311             if (MyCommon._endingFlag) return;
1312
1313             var cursor = -1L;
1314             var newFollowerIds = new HashSet<long>();
1315             do
1316             {
1317                 var ret = await this.Api.FollowersIds(cursor)
1318                     .ConfigureAwait(false);
1319
1320                 if (ret.Ids == null)
1321                     throw new WebApiException("ret.ids == null");
1322
1323                 newFollowerIds.UnionWith(ret.Ids);
1324                 cursor = ret.NextCursor;
1325             } while (cursor != 0);
1326
1327             this.followerId = newFollowerIds;
1328             TabInformations.GetInstance().RefreshOwl(this.followerId);
1329
1330             this._GetFollowerResult = true;
1331         }
1332
1333         public bool GetFollowersSuccess
1334         {
1335             get
1336             {
1337                 return _GetFollowerResult;
1338             }
1339         }
1340
1341         /// <summary>
1342         /// RT 非表示ユーザーを更新します
1343         /// </summary>
1344         /// <exception cref="WebApiException"/>
1345         public async Task RefreshNoRetweetIds()
1346         {
1347             if (MyCommon._endingFlag) return;
1348
1349             this.noRTId = await this.Api.NoRetweetIds()
1350                 .ConfigureAwait(false);
1351
1352             this._GetNoRetweetResult = true;
1353         }
1354
1355         public bool GetNoRetweetSuccess
1356         {
1357             get
1358             {
1359                 return _GetNoRetweetResult;
1360             }
1361         }
1362
1363         /// <summary>
1364         /// t.co の文字列長などの設定情報を更新します
1365         /// </summary>
1366         /// <exception cref="WebApiException"/>
1367         public async Task RefreshConfiguration()
1368         {
1369             this.Configuration = await this.Api.Configuration()
1370                 .ConfigureAwait(false);
1371         }
1372
1373         public async Task GetListsApi()
1374         {
1375             this.CheckAccountState();
1376
1377             var ownedLists = await TwitterLists.GetAllItemsAsync(x =>
1378                 this.Api.ListsOwnerships(this.Username, cursor: x, count: 1000))
1379                     .ConfigureAwait(false);
1380
1381             var subscribedLists = await TwitterLists.GetAllItemsAsync(x =>
1382                 this.Api.ListsSubscriptions(this.Username, cursor: x, count: 1000))
1383                     .ConfigureAwait(false);
1384
1385             TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1386                 .Select(x => new ListElement(x, this))
1387                 .ToList();
1388         }
1389
1390         public async Task DeleteList(long listId)
1391         {
1392             await this.Api.ListsDestroy(listId)
1393                 .IgnoreResponse()
1394                 .ConfigureAwait(false);
1395
1396             var tabinfo = TabInformations.GetInstance();
1397
1398             tabinfo.SubscribableLists = tabinfo.SubscribableLists
1399                 .Where(x => x.Id != listId)
1400                 .ToList();
1401         }
1402
1403         public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1404         {
1405             var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1406                 .ConfigureAwait(false);
1407
1408             var list = await response.LoadJsonAsync()
1409                 .ConfigureAwait(false);
1410
1411             return new ListElement(list, this);
1412         }
1413
1414         public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1415         {
1416             this.CheckAccountState();
1417
1418             var users = await this.Api.ListsMembers(listId, cursor)
1419                 .ConfigureAwait(false);
1420
1421             Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1422
1423             return users.NextCursor;
1424         }
1425
1426         public async Task CreateListApi(string listName, bool isPrivate, string description)
1427         {
1428             this.CheckAccountState();
1429
1430             var response = await this.Api.ListsCreate(listName, description, isPrivate)
1431                 .ConfigureAwait(false);
1432
1433             var list = await response.LoadJsonAsync()
1434                 .ConfigureAwait(false);
1435
1436             TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1437         }
1438
1439         public async Task<bool> ContainsUserAtList(long listId, string user)
1440         {
1441             this.CheckAccountState();
1442
1443             try
1444             {
1445                 await this.Api.ListsMembersShow(listId, user)
1446                     .ConfigureAwait(false);
1447
1448                 return true;
1449             }
1450             catch (TwitterApiException ex)
1451                 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1452             {
1453                 return false;
1454             }
1455         }
1456
1457         public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1458         {
1459             if (entities != null)
1460             {
1461                 if (entities.Hashtags != null)
1462                 {
1463                     lock (this.LockObj)
1464                     {
1465                         this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1466                     }
1467                 }
1468                 if (entities.UserMentions != null)
1469                 {
1470                     foreach (var ent in entities.UserMentions)
1471                     {
1472                         var screenName = ent.ScreenName.ToLowerInvariant();
1473                         if (!AtList.Contains(screenName))
1474                             AtList.Add(screenName);
1475                     }
1476                 }
1477                 if (entities.Media != null)
1478                 {
1479                     if (media != null)
1480                     {
1481                         foreach (var ent in entities.Media)
1482                         {
1483                             if (!media.Any(x => x.Url == ent.MediaUrl))
1484                             {
1485                                 if (ent.VideoInfo != null &&
1486                                     ent.Type == "animated_gif" || ent.Type == "video")
1487                                 {
1488                                     //var videoUrl = ent.VideoInfo.Variants
1489                                     //    .Where(v => v.ContentType == "video/mp4")
1490                                     //    .OrderByDescending(v => v.Bitrate)
1491                                     //    .Select(v => v.Url).FirstOrDefault();
1492                                     media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1493                                 }
1494                                 else
1495                                     media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1496                             }
1497                         }
1498                     }
1499                 }
1500             }
1501
1502             // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1503             text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1504
1505             text = Regex.Replace(text, "(^|[^a-zA-Z0-9_/&##@@>=.~])(sm|nm)([0-9]{1,10})", "$1<a href=\"http://www.nicovideo.jp/watch/$2$3\">$2$3</a>");
1506             text = PreProcessUrl(text); //IDN置換
1507
1508             return text;
1509         }
1510
1511         private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1512
1513         /// <summary>
1514         /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1515         /// </summary>
1516         public static Tuple<string, Uri> ParseSource(string sourceHtml)
1517         {
1518             if (string.IsNullOrEmpty(sourceHtml))
1519                 return Tuple.Create<string, Uri>("", null);
1520
1521             string sourceText;
1522             Uri sourceUri;
1523
1524             // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1525
1526             var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1527             if (match.Success)
1528             {
1529                 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1530                 try
1531                 {
1532                     var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1533                     sourceUri = new Uri(SourceUriBase, uriStr);
1534                 }
1535                 catch (UriFormatException)
1536                 {
1537                     sourceUri = null;
1538                 }
1539             }
1540             else
1541             {
1542                 sourceText = WebUtility.HtmlDecode(sourceHtml);
1543                 sourceUri = null;
1544             }
1545
1546             return Tuple.Create(sourceText, sourceUri);
1547         }
1548
1549         public async Task<TwitterApiStatus> GetInfoApi()
1550         {
1551             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1552
1553             if (MyCommon._endingFlag) return null;
1554
1555             var limits = await this.Api.ApplicationRateLimitStatus()
1556                 .ConfigureAwait(false);
1557
1558             MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1559
1560             return MyCommon.TwitterApiInfo;
1561         }
1562
1563         /// <summary>
1564         /// ブロック中のユーザーを更新します
1565         /// </summary>
1566         /// <exception cref="WebApiException"/>
1567         public async Task RefreshBlockIds()
1568         {
1569             if (MyCommon._endingFlag) return;
1570
1571             var cursor = -1L;
1572             var newBlockIds = new HashSet<long>();
1573             do
1574             {
1575                 var ret = await this.Api.BlocksIds(cursor)
1576                     .ConfigureAwait(false);
1577
1578                 newBlockIds.UnionWith(ret.Ids);
1579                 cursor = ret.NextCursor;
1580             } while (cursor != 0);
1581
1582             newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1583
1584             TabInformations.GetInstance().BlockIds = newBlockIds;
1585         }
1586
1587         /// <summary>
1588         /// ミュート中のユーザーIDを更新します
1589         /// </summary>
1590         /// <exception cref="WebApiException"/>
1591         public async Task RefreshMuteUserIdsAsync()
1592         {
1593             if (MyCommon._endingFlag) return;
1594
1595             var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1596                 .ConfigureAwait(false);
1597
1598             TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1599         }
1600
1601         public string[] GetHashList()
1602         {
1603             string[] hashArray;
1604             lock (LockObj)
1605             {
1606                 hashArray = _hashList.ToArray();
1607                 _hashList.Clear();
1608             }
1609             return hashArray;
1610         }
1611
1612         public string AccessToken
1613             => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1614
1615         public string AccessTokenSecret
1616             => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1617
1618         private void CheckAccountState()
1619         {
1620             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1621                 throw new WebApiException("Auth error. Check your account");
1622         }
1623
1624         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1625         {
1626             if (!this.AccessLevel.HasFlag(accessLevelFlags))
1627                 throw new WebApiException("Auth Err:try to re-authorization.");
1628         }
1629
1630         public int GetTextLengthRemain(string postText)
1631         {
1632             var matchDm = Twitter.DMSendTextRegex.Match(postText);
1633             if (matchDm.Success)
1634                 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1635
1636             return this.GetTextLengthRemainInternal(postText, isDm: false);
1637         }
1638
1639         private int GetTextLengthRemainInternal(string postText, bool isDm)
1640         {
1641             var textLength = 0;
1642
1643             var pos = 0;
1644             while (pos < postText.Length)
1645             {
1646                 textLength++;
1647
1648                 if (char.IsSurrogatePair(postText, pos))
1649                     pos += 2; // サロゲートペアの場合は2文字分進める
1650                 else
1651                     pos++;
1652             }
1653
1654             var urls = TweetExtractor.ExtractUrls(postText);
1655             foreach (var url in urls)
1656             {
1657                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1658                     ? this.Configuration.ShortUrlLengthHttps
1659                     : this.Configuration.ShortUrlLength;
1660
1661                 textLength += shortUrlLength - url.Length;
1662             }
1663
1664             if (isDm)
1665                 return this.Configuration.DmTextCharacterLimit - textLength;
1666             else
1667                 return 140 - textLength;
1668         }
1669
1670
1671 #region "UserStream"
1672         private string trackWord_ = "";
1673         public string TrackWord
1674         {
1675             get
1676             {
1677                 return trackWord_;
1678             }
1679             set
1680             {
1681                 trackWord_ = value;
1682             }
1683         }
1684         private bool allAtReply_ = false;
1685         public bool AllAtReply
1686         {
1687             get
1688             {
1689                 return allAtReply_;
1690             }
1691             set
1692             {
1693                 allAtReply_ = value;
1694             }
1695         }
1696
1697         public event EventHandler NewPostFromStream;
1698         public event EventHandler UserStreamStarted;
1699         public event EventHandler UserStreamStopped;
1700         public event EventHandler<PostDeletedEventArgs> PostDeleted;
1701         public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1702         private DateTime _lastUserstreamDataReceived;
1703         private TwitterUserstream userStream;
1704
1705         public class FormattedEvent
1706         {
1707             public MyCommon.EVENTTYPE Eventtype { get; set; }
1708             public DateTime CreatedAt { get; set; }
1709             public string Event { get; set; }
1710             public string Username { get; set; }
1711             public string Target { get; set; }
1712             public Int64 Id { get; set; }
1713             public bool IsMe { get; set; }
1714         }
1715
1716         public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1717         public List<FormattedEvent> StoredEvent
1718         {
1719             get
1720             {
1721                 return storedEvent_;
1722             }
1723             set
1724             {
1725                 storedEvent_ = value;
1726             }
1727         }
1728
1729         private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1730         {
1731             ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1732             ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1733             ["follow"] = MyCommon.EVENTTYPE.Follow,
1734             ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1735             ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1736             ["block"] = MyCommon.EVENTTYPE.Block,
1737             ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1738             ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1739             ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1740             ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1741             ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1742             ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1743             ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1744             ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1745             ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1746             ["mute"] = MyCommon.EVENTTYPE.Mute,
1747             ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1748             ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1749         };
1750
1751         public bool IsUserstreamDataReceived
1752         {
1753             get
1754             {
1755                 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
1756             }
1757         }
1758
1759         private void userStream_StatusArrived(string line)
1760         {
1761             this._lastUserstreamDataReceived = DateTime.Now;
1762             if (string.IsNullOrEmpty(line)) return;
1763
1764             if (line.First() != '{' || line.Last() != '}')
1765             {
1766                 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
1767                 return;
1768             }
1769
1770             var isDm = false;
1771
1772             try
1773             {
1774                 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
1775                 {
1776                     var xElm = XElement.Load(jsonReader);
1777                     if (xElm.Element("friends") != null)
1778                     {
1779                         Debug.WriteLine("friends");
1780                         return;
1781                     }
1782                     else if (xElm.Element("delete") != null)
1783                     {
1784                         Debug.WriteLine("delete");
1785                         Int64 id;
1786                         XElement idElm;
1787                         if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
1788                         {
1789                             id = 0;
1790                             long.TryParse(idElm.Value, out id);
1791
1792                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1793                         }
1794                         else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
1795                         {
1796                             id = 0;
1797                             long.TryParse(idElm.Value, out id);
1798
1799                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
1800                         }
1801                         else
1802                         {
1803                             MyCommon.TraceOut("delete:" + line);
1804                             return;
1805                         }
1806                         for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
1807                         {
1808                             var sEvt = this.StoredEvent[i];
1809                             if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
1810                             {
1811                                 this.StoredEvent.RemoveAt(i);
1812                             }
1813                         }
1814                         return;
1815                     }
1816                     else if (xElm.Element("limit") != null)
1817                     {
1818                         Debug.WriteLine(line);
1819                         return;
1820                     }
1821                     else if (xElm.Element("event") != null)
1822                     {
1823                         Debug.WriteLine("event: " + xElm.Element("event").Value);
1824                         CreateEventFromJson(line);
1825                         return;
1826                     }
1827                     else if (xElm.Element("direct_message") != null)
1828                     {
1829                         Debug.WriteLine("direct_message");
1830                         isDm = true;
1831                     }
1832                     else if (xElm.Element("retweeted_status") != null)
1833                     {
1834                         var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
1835                         var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
1836
1837                         // 自分に関係しないリツイートの場合は無視する
1838                         var selfUserId = this.UserId.ToString();
1839                         if (sourceUserId == selfUserId || targetUserId == selfUserId)
1840                         {
1841                             // 公式 RT をイベントとしても扱う
1842                             var evt = CreateEventFromRetweet(xElm);
1843                             if (evt != null)
1844                             {
1845                                 this.StoredEvent.Insert(0, evt);
1846
1847                                 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
1848                             }
1849                         }
1850
1851                         // 従来通り公式 RT の表示も行うため return しない
1852                     }
1853                     else if (xElm.Element("scrub_geo") != null)
1854                     {
1855                         try
1856                         {
1857                             TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
1858                                                                         long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
1859                         }
1860                         catch(Exception)
1861                         {
1862                             MyCommon.TraceOut("scrub_geo:" + line);
1863                         }
1864                         return;
1865                     }
1866                 }
1867
1868                 if (isDm)
1869                 {
1870                     try
1871                     {
1872                         var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
1873                         this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
1874                     }
1875                     catch (SerializationException ex)
1876                     {
1877                         throw TwitterApiException.CreateFromException(ex, line);
1878                     }
1879                 }
1880                 else
1881                 {
1882                     try
1883                     {
1884                         var status = TwitterStatusCompat.ParseJson(line);
1885                         this.CreatePostsFromJson(new[] { status.Normalize() }, MyCommon.WORKERTYPE.UserStream, null, false);
1886                     }
1887                     catch (SerializationException ex)
1888                     {
1889                         throw TwitterApiException.CreateFromException(ex, line);
1890                     }
1891                 }
1892             }
1893             catch (WebApiException ex)
1894             {
1895                 MyCommon.TraceOut(ex);
1896                 return;
1897             }
1898             catch(NullReferenceException)
1899             {
1900                 MyCommon.TraceOut("NullRef StatusArrived: " + line);
1901             }
1902
1903             this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
1904         }
1905
1906         /// <summary>
1907         /// UserStreamsから受信した公式RTをイベントに変換します
1908         /// </summary>
1909         private FormattedEvent CreateEventFromRetweet(XElement xElm)
1910         {
1911             return new FormattedEvent
1912             {
1913                 Eventtype = MyCommon.EVENTTYPE.Retweet,
1914                 Event = "retweet",
1915                 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
1916                 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
1917                 Username = xElm.XPathSelectElement("/user/screen_name").Value,
1918                 Target = string.Format("@{0}:{1}", new[]
1919                 {
1920                     xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
1921                     WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
1922                 }),
1923                 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
1924             };
1925         }
1926
1927         private void CreateEventFromJson(string content)
1928         {
1929             TwitterStreamEvent eventData = null;
1930             try
1931             {
1932                 eventData = TwitterStreamEvent.ParseJson(content);
1933             }
1934             catch(SerializationException ex)
1935             {
1936                 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
1937             }
1938             catch(Exception ex)
1939             {
1940                 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
1941             }
1942
1943             var evt = new FormattedEvent();
1944             evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
1945             evt.Event = eventData.Event;
1946             evt.Username = eventData.Source.ScreenName;
1947             evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
1948
1949             MyCommon.EVENTTYPE eventType;
1950             eventTable.TryGetValue(eventData.Event, out eventType);
1951             evt.Eventtype = eventType;
1952
1953             TwitterStreamEvent<TwitterStatusCompat> tweetEvent;
1954             TwitterStatus tweet;
1955
1956             switch (eventData.Event)
1957             {
1958                 case "access_revoked":
1959                 case "access_unrevoked":
1960                 case "user_delete":
1961                 case "user_suspend":
1962                     return;
1963                 case "follow":
1964                     if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
1965                     {
1966                         if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
1967                     }
1968                     else
1969                     {
1970                         return;    //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
1971                     }
1972                     evt.Target = "";
1973                     break;
1974                 case "unfollow":
1975                     evt.Target = "@" + eventData.Target.ScreenName;
1976                     break;
1977                 case "favorited_retweet":
1978                 case "retweeted_retweet":
1979                     return;
1980                 case "favorite":
1981                 case "unfavorite":
1982                     tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
1983                     tweet = tweetEvent.TargetObject.Normalize();
1984                     evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
1985                     evt.Id = tweet.Id;
1986
1987                     if (SettingCommon.Instance.IsRemoveSameEvent)
1988                     {
1989                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
1990                             return;
1991                     }
1992
1993                     var tabinfo = TabInformations.GetInstance();
1994
1995                     PostClass post;
1996                     var statusId = tweet.Id;
1997                     if (!tabinfo.Posts.TryGetValue(statusId, out post))
1998                         break;
1999
2000                     if (eventData.Event == "favorite")
2001                     {
2002                         var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2003                         favTab.AddPostQueue(post);
2004
2005                         if (tweetEvent.Source.Id == this.UserId)
2006                         {
2007                             post.IsFav = true;
2008                         }
2009                         else if (tweetEvent.Target.Id == this.UserId)
2010                         {
2011                             post.FavoritedCount++;
2012
2013                             if (SettingCommon.Instance.FavEventUnread)
2014                                 tabinfo.SetReadAllTab(post.StatusId, read: false);
2015                         }
2016                     }
2017                     else // unfavorite
2018                     {
2019                         if (tweetEvent.Source.Id == this.UserId)
2020                         {
2021                             post.IsFav = false;
2022                         }
2023                         else if (tweetEvent.Target.Id == this.UserId)
2024                         {
2025                             post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2026                         }
2027                     }
2028                     break;
2029                 case "quoted_tweet":
2030                     if (evt.IsMe) return;
2031
2032                     tweetEvent = TwitterStreamEvent<TwitterStatusCompat>.ParseJson(content);
2033                     tweet = tweetEvent.TargetObject.Normalize();
2034                     evt.Target = "@" + tweet.User.ScreenName + ":" + WebUtility.HtmlDecode(tweet.FullText);
2035                     evt.Id = tweet.Id;
2036
2037                     if (SettingCommon.Instance.IsRemoveSameEvent)
2038                     {
2039                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2040                             return;
2041                     }
2042                     break;
2043                 case "list_member_added":
2044                 case "list_member_removed":
2045                 case "list_created":
2046                 case "list_destroyed":
2047                 case "list_updated":
2048                 case "list_user_subscribed":
2049                 case "list_user_unsubscribed":
2050                     var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2051                     evt.Target = listEvent.TargetObject.FullName;
2052                     break;
2053                 case "block":
2054                     if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2055                     evt.Target = "";
2056                     break;
2057                 case "unblock":
2058                     if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2059                     evt.Target = "";
2060                     break;
2061                 case "user_update":
2062                     evt.Target = "";
2063                     break;
2064                 
2065                 // Mute / Unmute
2066                 case "mute":
2067                     evt.Target = "@" + eventData.Target.ScreenName;
2068                     if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2069                     {
2070                         TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2071                     }
2072                     break;
2073                 case "unmute":
2074                     evt.Target = "@" + eventData.Target.ScreenName;
2075                     if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2076                     {
2077                         TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2078                     }
2079                     break;
2080
2081                 default:
2082                     MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2083                     break;
2084             }
2085             this.StoredEvent.Insert(0, evt);
2086
2087             this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2088         }
2089
2090         private void userStream_Started()
2091         {
2092             this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2093         }
2094
2095         private void userStream_Stopped()
2096         {
2097             this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2098         }
2099
2100         public bool UserStreamActive
2101             => this.userStream != null && this.userStream.IsStreamActive;
2102
2103         public void StartUserStream()
2104         {
2105             var newStream = new TwitterUserstream(this.Api);
2106
2107             newStream.StatusArrived += userStream_StatusArrived;
2108             newStream.Started += userStream_Started;
2109             newStream.Stopped += userStream_Stopped;
2110
2111             newStream.Start(this.AllAtReply, this.TrackWord);
2112
2113             var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2114             oldStream?.Dispose();
2115         }
2116
2117         public void StopUserStream()
2118         {
2119             var oldStream = Interlocked.Exchange(ref this.userStream, null);
2120             oldStream?.Dispose();
2121         }
2122
2123         public void ReconnectUserStream()
2124         {
2125             if (this.userStream != null)
2126             {
2127                 this.StartUserStream();
2128             }
2129         }
2130
2131         private class TwitterUserstream : IDisposable
2132         {
2133             public bool AllAtReplies { get; private set; }
2134             public string TrackWords { get; private set; }
2135
2136             public bool IsStreamActive { get; private set; }
2137
2138             public event Action<string> StatusArrived;
2139             public event Action Stopped;
2140             public event Action Started;
2141
2142             private TwitterApi twitterApi;
2143
2144             private Task streamTask;
2145             private CancellationTokenSource streamCts;
2146
2147             public TwitterUserstream(TwitterApi twitterApi)
2148             {
2149                 this.twitterApi = twitterApi;
2150             }
2151
2152             public void Start(bool allAtReplies, string trackwords)
2153             {
2154                 this.AllAtReplies = allAtReplies;
2155                 this.TrackWords = trackwords;
2156
2157                 var cts = new CancellationTokenSource();
2158
2159                 this.streamCts = cts;
2160                 this.streamTask = Task.Run(async () =>
2161                 {
2162                     try
2163                     {
2164                         await this.UserStreamLoop(cts.Token)
2165                             .ConfigureAwait(false);
2166                     }
2167                     catch (OperationCanceledException) { }
2168                 });
2169             }
2170
2171             public void Stop()
2172             {
2173                 this.streamCts?.Cancel();
2174
2175                 // streamTask の完了を待たずに IsStreamActive を false にセットする
2176                 this.IsStreamActive = false;
2177                 this.Stopped?.Invoke();
2178             }
2179
2180             private async Task UserStreamLoop(CancellationToken cancellationToken)
2181             {
2182                 TimeSpan sleep = TimeSpan.Zero;
2183                 for (;;)
2184                 {
2185                     if (sleep != TimeSpan.Zero)
2186                     {
2187                         await Task.Delay(sleep, cancellationToken)
2188                             .ConfigureAwait(false);
2189                         sleep = TimeSpan.Zero;
2190                     }
2191
2192                     if (!MyCommon.IsNetworkAvailable())
2193                     {
2194                         sleep = TimeSpan.FromSeconds(30);
2195                         continue;
2196                     }
2197
2198                     this.IsStreamActive = true;
2199                     this.Started?.Invoke();
2200
2201                     try
2202                     {
2203                         var replies = this.AllAtReplies ? "all" : null;
2204
2205                         using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2206                             .ConfigureAwait(false))
2207                         using (var reader = new StreamReader(stream))
2208                         {
2209                             while (!reader.EndOfStream)
2210                             {
2211                                 var line = await reader.ReadLineAsync()
2212                                     .ConfigureAwait(false);
2213
2214                                 cancellationToken.ThrowIfCancellationRequested();
2215
2216                                 this.StatusArrived?.Invoke(line);
2217                             }
2218                         }
2219
2220                         // キャンセルされていないのにストリームが終了した場合
2221                         sleep = TimeSpan.FromSeconds(30);
2222                     }
2223                     catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2224                     catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2225                     catch (OperationCanceledException)
2226                     {
2227                         if (cancellationToken.IsCancellationRequested)
2228                             throw;
2229
2230                         // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2231                         sleep = TimeSpan.FromSeconds(30);
2232                     }
2233                     catch (Exception ex)
2234                     {
2235                         MyCommon.ExceptionOut(ex);
2236                         sleep = TimeSpan.FromSeconds(30);
2237                     }
2238                     finally
2239                     {
2240                         this.IsStreamActive = false;
2241                         this.Stopped?.Invoke();
2242                     }
2243                 }
2244             }
2245
2246             private bool disposed = false;
2247
2248             public void Dispose()
2249             {
2250                 if (this.disposed)
2251                     return;
2252
2253                 this.disposed = true;
2254
2255                 this.Stop();
2256
2257                 this.Started = null;
2258                 this.Stopped = null;
2259                 this.StatusArrived = null;
2260             }
2261         }
2262 #endregion
2263
2264 #region "IDisposable Support"
2265         private bool disposedValue; // 重複する呼び出しを検出するには
2266
2267         // IDisposable
2268         protected virtual void Dispose(bool disposing)
2269         {
2270             if (!this.disposedValue)
2271             {
2272                 if (disposing)
2273                 {
2274                     this.StopUserStream();
2275                 }
2276             }
2277             this.disposedValue = true;
2278         }
2279
2280         //protected Overrides void Finalize()
2281         //{
2282         //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2283         //    Dispose(false)
2284         //    MyBase.Finalize()
2285         //}
2286
2287         // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2288         public void Dispose()
2289         {
2290             // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2291             Dispose(true);
2292             GC.SuppressFinalize(this);
2293         }
2294 #endregion
2295     }
2296
2297     public class PostDeletedEventArgs : EventArgs
2298     {
2299         public long StatusId { get; }
2300
2301         public PostDeletedEventArgs(long statusId)
2302         {
2303             this.StatusId = statusId;
2304         }
2305     }
2306
2307     public class UserStreamEventReceivedEventArgs : EventArgs
2308     {
2309         public Twitter.FormattedEvent EventData { get; }
2310
2311         public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2312         {
2313             this.EventData = eventData;
2314         }
2315     }
2316 }