OSDN Git Service

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