OSDN Git Service

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