OSDN Git Service

Twitter.Initialize内でTwitterApi.Initializeメソッドを呼び出す
[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 void GetListsApi()
1718         {
1719             this.CheckAccountState();
1720
1721             HttpStatusCode res;
1722             IEnumerable<ListElement> lists;
1723             var content = "";
1724
1725             try
1726             {
1727                 res = twCon.GetLists(this.Username, ref content);
1728             }
1729             catch (Exception ex)
1730             {
1731                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1732             }
1733
1734             this.CheckStatusCode(res, content);
1735
1736             try
1737             {
1738                 lists = TwitterList.ParseJsonArray(content)
1739                     .Select(x => new ListElement(x, this));
1740             }
1741             catch (SerializationException ex)
1742             {
1743                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1744                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1745             }
1746             catch (Exception ex)
1747             {
1748                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1749                 throw new WebApiException("Err:Invalid Json!", content, ex);
1750             }
1751
1752             try
1753             {
1754                 res = twCon.GetListsSubscriptions(this.Username, ref content);
1755             }
1756             catch (Exception ex)
1757             {
1758                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1759             }
1760
1761             this.CheckStatusCode(res, content);
1762
1763             try
1764             {
1765                 lists = lists.Concat(TwitterList.ParseJsonArray(content)
1766                     .Select(x => new ListElement(x, this)));
1767             }
1768             catch (SerializationException ex)
1769             {
1770                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1771                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1772             }
1773             catch (Exception ex)
1774             {
1775                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1776                 throw new WebApiException("Err:Invalid Json!", content, ex);
1777             }
1778
1779             TabInformations.GetInstance().SubscribableLists = lists.ToList();
1780         }
1781
1782         public void DeleteList(string list_id)
1783         {
1784             HttpStatusCode res;
1785             var content = "";
1786
1787             try
1788             {
1789                 res = twCon.DeleteListID(this.Username, list_id, ref content);
1790             }
1791             catch(Exception ex)
1792             {
1793                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1794             }
1795
1796             this.CheckStatusCode(res, content);
1797         }
1798
1799         public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
1800         {
1801             HttpStatusCode res;
1802             var content = "";
1803
1804             try
1805             {
1806                 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
1807             }
1808             catch(Exception ex)
1809             {
1810                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1811             }
1812
1813             this.CheckStatusCode(res, content);
1814
1815             try
1816             {
1817                 var le = TwitterList.ParseJson(content);
1818                 return  new ListElement(le, this);
1819             }
1820             catch(SerializationException ex)
1821             {
1822                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1823                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1824             }
1825             catch(Exception ex)
1826             {
1827                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1828                 throw new WebApiException("Err:Invalid Json!", content, ex);
1829             }
1830         }
1831
1832         public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
1833         {
1834             this.CheckAccountState();
1835
1836             HttpStatusCode res;
1837             var content = "";
1838             try
1839             {
1840                 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
1841             }
1842             catch(Exception ex)
1843             {
1844                 throw new WebApiException("Err:" + ex.Message);
1845             }
1846
1847             this.CheckStatusCode(res, content);
1848
1849             try
1850             {
1851                 var users = TwitterUsers.ParseJson(content);
1852                 Array.ForEach<TwitterUser>(
1853                     users.Users,
1854                     u => lists.Add(new UserInfo(u)));
1855
1856                 return users.NextCursor;
1857             }
1858             catch(SerializationException ex)
1859             {
1860                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1861                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1862             }
1863             catch(Exception ex)
1864             {
1865                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1866                 throw new WebApiException("Err:Invalid Json!", content, ex);
1867             }
1868         }
1869
1870         public void CreateListApi(string listName, bool isPrivate, string description)
1871         {
1872             this.CheckAccountState();
1873
1874             HttpStatusCode res;
1875             var content = "";
1876             try
1877             {
1878                 res = twCon.CreateLists(listName, isPrivate, description, ref content);
1879             }
1880             catch(Exception ex)
1881             {
1882                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1883             }
1884
1885             this.CheckStatusCode(res, content);
1886
1887             try
1888             {
1889                 var le = TwitterList.ParseJson(content);
1890                 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
1891             }
1892             catch(SerializationException ex)
1893             {
1894                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1895                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1896             }
1897             catch(Exception ex)
1898             {
1899                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1900                 throw new WebApiException("Err:Invalid Json!", content, ex);
1901             }
1902         }
1903
1904         public bool ContainsUserAtList(string listId, string user)
1905         {
1906             this.CheckAccountState();
1907
1908             HttpStatusCode res;
1909             var content = "";
1910
1911             try
1912             {
1913                 res = this.twCon.ShowListMember(listId, user, ref content);
1914             }
1915             catch(Exception ex)
1916             {
1917                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1918             }
1919
1920             if (res == HttpStatusCode.NotFound)
1921             {
1922                 return false;
1923             }
1924
1925             this.CheckStatusCode(res, content);
1926
1927             try
1928             {
1929                 TwitterUser.ParseJson(content);
1930                 return true;
1931             }
1932             catch(Exception)
1933             {
1934                 return false;
1935             }
1936         }
1937
1938         public void AddUserToList(string listId, string user)
1939         {
1940             HttpStatusCode res;
1941             var content = "";
1942
1943             try
1944             {
1945                 res = twCon.CreateListMembers(listId, user, ref content);
1946             }
1947             catch(Exception ex)
1948             {
1949                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1950             }
1951
1952             this.CheckStatusCode(res, content);
1953         }
1954
1955         public void RemoveUserToList(string listId, string user)
1956         {
1957             HttpStatusCode res;
1958             var content = "";
1959
1960             try
1961             {
1962                 res = twCon.DeleteListMembers(listId, user, ref content);
1963             }
1964             catch(Exception ex)
1965             {
1966                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1967             }
1968
1969             this.CheckStatusCode(res, content);
1970         }
1971
1972         public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1973         {
1974             if (entities != null)
1975             {
1976                 if (entities.Hashtags != null)
1977                 {
1978                     lock (this.LockObj)
1979                     {
1980                         this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1981                     }
1982                 }
1983                 if (entities.UserMentions != null)
1984                 {
1985                     foreach (var ent in entities.UserMentions)
1986                     {
1987                         var screenName = ent.ScreenName.ToLowerInvariant();
1988                         if (!AtList.Contains(screenName))
1989                             AtList.Add(screenName);
1990                     }
1991                 }
1992                 if (entities.Media != null)
1993                 {
1994                     if (media != null)
1995                     {
1996                         foreach (var ent in entities.Media)
1997                         {
1998                             if (!media.Any(x => x.Url == ent.MediaUrl))
1999                             {
2000                                 if (ent.VideoInfo != null &&
2001                                     ent.Type == "animated_gif" || ent.Type == "video")
2002                                 {
2003                                     //var videoUrl = ent.VideoInfo.Variants
2004                                     //    .Where(v => v.ContentType == "video/mp4")
2005                                     //    .OrderByDescending(v => v.Bitrate)
2006                                     //    .Select(v => v.Url).FirstOrDefault();
2007                                     media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
2008                                 }
2009                                 else
2010                                     media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
2011                             }
2012                         }
2013                     }
2014                 }
2015             }
2016
2017             // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2018             text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2019
2020             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>");
2021             text = PreProcessUrl(text); //IDN置換
2022
2023             return text;
2024         }
2025
2026         private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
2027
2028         /// <summary>
2029         /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2030         /// </summary>
2031         public static Tuple<string, Uri> ParseSource(string sourceHtml)
2032         {
2033             if (string.IsNullOrEmpty(sourceHtml))
2034                 return Tuple.Create<string, Uri>("", null);
2035
2036             string sourceText;
2037             Uri sourceUri;
2038
2039             // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2040
2041             var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2042             if (match.Success)
2043             {
2044                 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2045                 try
2046                 {
2047                     var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2048                     sourceUri = new Uri(SourceUriBase, uriStr);
2049                 }
2050                 catch (UriFormatException)
2051                 {
2052                     sourceUri = null;
2053                 }
2054             }
2055             else
2056             {
2057                 sourceText = WebUtility.HtmlDecode(sourceHtml);
2058                 sourceUri = null;
2059             }
2060
2061             return Tuple.Create(sourceText, sourceUri);
2062         }
2063
2064         public TwitterApiStatus GetInfoApi()
2065         {
2066             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2067
2068             if (MyCommon._endingFlag) return null;
2069
2070             HttpStatusCode res;
2071             var content = "";
2072             try
2073             {
2074                 res = twCon.RateLimitStatus(ref content);
2075             }
2076             catch (Exception)
2077             {
2078                 this.ResetApiStatus();
2079                 return null;
2080             }
2081
2082             this.CheckStatusCode(res, content);
2083
2084             try
2085             {
2086                 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2087                 return MyCommon.TwitterApiInfo;
2088             }
2089             catch (Exception ex)
2090             {
2091                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2092                 MyCommon.TwitterApiInfo.Reset();
2093                 return null;
2094             }
2095         }
2096
2097         /// <summary>
2098         /// ブロック中のユーザーを更新します
2099         /// </summary>
2100         /// <exception cref="WebApiException"/>
2101         public async Task RefreshBlockIds()
2102         {
2103             if (MyCommon._endingFlag) return;
2104
2105             var cursor = -1L;
2106             var newBlockIds = new HashSet<long>();
2107             do
2108             {
2109                 var ret = await this.Api.BlocksIds(cursor)
2110                     .ConfigureAwait(false);
2111
2112                 newBlockIds.UnionWith(ret.Ids);
2113                 cursor = ret.NextCursor;
2114             } while (cursor != 0);
2115
2116             newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2117
2118             TabInformations.GetInstance().BlockIds = newBlockIds;
2119         }
2120
2121         /// <summary>
2122         /// ミュート中のユーザーIDを更新します
2123         /// </summary>
2124         /// <exception cref="WebApiException"/>
2125         public async Task RefreshMuteUserIdsAsync()
2126         {
2127             if (MyCommon._endingFlag) return;
2128
2129             var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
2130                 .ConfigureAwait(false);
2131
2132             TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2133         }
2134
2135         public string[] GetHashList()
2136         {
2137             string[] hashArray;
2138             lock (LockObj)
2139             {
2140                 hashArray = _hashList.ToArray();
2141                 _hashList.Clear();
2142             }
2143             return hashArray;
2144         }
2145
2146         public string AccessToken
2147         {
2148             get
2149             {
2150                 return twCon.AccessToken;
2151             }
2152         }
2153
2154         public string AccessTokenSecret
2155         {
2156             get
2157             {
2158                 return twCon.AccessTokenSecret;
2159             }
2160         }
2161
2162         private void CheckAccountState()
2163         {
2164             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2165                 throw new WebApiException("Auth error. Check your account");
2166         }
2167
2168         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2169         {
2170             if (!this.AccessLevel.HasFlag(accessLevelFlags))
2171                 throw new WebApiException("Auth Err:try to re-authorization.");
2172         }
2173
2174         private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2175             [CallerMemberName] string callerMethodName = "")
2176         {
2177             if (httpStatus == HttpStatusCode.OK)
2178             {
2179                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2180                 return;
2181             }
2182
2183             if (string.IsNullOrWhiteSpace(responseText))
2184             {
2185                 if (httpStatus == HttpStatusCode.Unauthorized)
2186                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2187
2188                 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2189             }
2190
2191             try
2192             {
2193                 var errors = TwitterError.ParseJson(responseText).Errors;
2194                 if (errors == null || !errors.Any())
2195                 {
2196                     throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2197                 }
2198
2199                 foreach (var error in errors)
2200                 {
2201                     if (error.Code == TwitterErrorCode.InvalidToken ||
2202                         error.Code == TwitterErrorCode.SuspendedAccount)
2203                     {
2204                         Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2205                     }
2206                 }
2207
2208                 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2209             }
2210             catch (SerializationException) { }
2211
2212             throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2213         }
2214
2215         public int GetTextLengthRemain(string postText)
2216         {
2217             var matchDm = Twitter.DMSendTextRegex.Match(postText);
2218             if (matchDm.Success)
2219                 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2220
2221             return this.GetTextLengthRemainInternal(postText, isDm: false);
2222         }
2223
2224         private int GetTextLengthRemainInternal(string postText, bool isDm)
2225         {
2226             var textLength = 0;
2227
2228             var pos = 0;
2229             while (pos < postText.Length)
2230             {
2231                 textLength++;
2232
2233                 if (char.IsSurrogatePair(postText, pos))
2234                     pos += 2; // サロゲートペアの場合は2文字分進める
2235                 else
2236                     pos++;
2237             }
2238
2239             var urls = TweetExtractor.ExtractUrls(postText);
2240             foreach (var url in urls)
2241             {
2242                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
2243                     ? this.Configuration.ShortUrlLengthHttps
2244                     : this.Configuration.ShortUrlLength;
2245
2246                 textLength += shortUrlLength - url.Length;
2247             }
2248
2249             if (isDm)
2250                 return this.Configuration.DmTextCharacterLimit - textLength;
2251             else
2252                 return 140 - textLength;
2253         }
2254
2255
2256 #region "UserStream"
2257         private string trackWord_ = "";
2258         public string TrackWord
2259         {
2260             get
2261             {
2262                 return trackWord_;
2263             }
2264             set
2265             {
2266                 trackWord_ = value;
2267             }
2268         }
2269         private bool allAtReply_ = false;
2270         public bool AllAtReply
2271         {
2272             get
2273             {
2274                 return allAtReply_;
2275             }
2276             set
2277             {
2278                 allAtReply_ = value;
2279             }
2280         }
2281
2282         public event EventHandler NewPostFromStream;
2283         public event EventHandler UserStreamStarted;
2284         public event EventHandler UserStreamStopped;
2285         public event EventHandler<PostDeletedEventArgs> PostDeleted;
2286         public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
2287         private DateTime _lastUserstreamDataReceived;
2288         private TwitterUserstream userStream;
2289
2290         public class FormattedEvent
2291         {
2292             public MyCommon.EVENTTYPE Eventtype { get; set; }
2293             public DateTime CreatedAt { get; set; }
2294             public string Event { get; set; }
2295             public string Username { get; set; }
2296             public string Target { get; set; }
2297             public Int64 Id { get; set; }
2298             public bool IsMe { get; set; }
2299         }
2300
2301         public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
2302         public List<FormattedEvent> StoredEvent
2303         {
2304             get
2305             {
2306                 return storedEvent_;
2307             }
2308             set
2309             {
2310                 storedEvent_ = value;
2311             }
2312         }
2313
2314         private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
2315         {
2316             ["favorite"] = MyCommon.EVENTTYPE.Favorite,
2317             ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
2318             ["follow"] = MyCommon.EVENTTYPE.Follow,
2319             ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
2320             ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
2321             ["block"] = MyCommon.EVENTTYPE.Block,
2322             ["unblock"] = MyCommon.EVENTTYPE.Unblock,
2323             ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
2324             ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2325             ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2326             ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2327             ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2328             ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2329             ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2330             ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2331             ["mute"] = MyCommon.EVENTTYPE.Mute,
2332             ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2333             ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2334         };
2335
2336         public bool IsUserstreamDataReceived
2337         {
2338             get
2339             {
2340                 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2341             }
2342         }
2343
2344         private void userStream_StatusArrived(string line)
2345         {
2346             this._lastUserstreamDataReceived = DateTime.Now;
2347             if (string.IsNullOrEmpty(line)) return;
2348
2349             if (line.First() != '{' || line.Last() != '}')
2350             {
2351                 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2352                 return;
2353             }
2354
2355             var isDm = false;
2356
2357             try
2358             {
2359                 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2360                 {
2361                     var xElm = XElement.Load(jsonReader);
2362                     if (xElm.Element("friends") != null)
2363                     {
2364                         Debug.WriteLine("friends");
2365                         return;
2366                     }
2367                     else if (xElm.Element("delete") != null)
2368                     {
2369                         Debug.WriteLine("delete");
2370                         Int64 id;
2371                         XElement idElm;
2372                         if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2373                         {
2374                             id = 0;
2375                             long.TryParse(idElm.Value, out id);
2376
2377                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2378                         }
2379                         else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2380                         {
2381                             id = 0;
2382                             long.TryParse(idElm.Value, out id);
2383
2384                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2385                         }
2386                         else
2387                         {
2388                             MyCommon.TraceOut("delete:" + line);
2389                             return;
2390                         }
2391                         for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2392                         {
2393                             var sEvt = this.StoredEvent[i];
2394                             if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2395                             {
2396                                 this.StoredEvent.RemoveAt(i);
2397                             }
2398                         }
2399                         return;
2400                     }
2401                     else if (xElm.Element("limit") != null)
2402                     {
2403                         Debug.WriteLine(line);
2404                         return;
2405                     }
2406                     else if (xElm.Element("event") != null)
2407                     {
2408                         Debug.WriteLine("event: " + xElm.Element("event").Value);
2409                         CreateEventFromJson(line);
2410                         return;
2411                     }
2412                     else if (xElm.Element("direct_message") != null)
2413                     {
2414                         Debug.WriteLine("direct_message");
2415                         isDm = true;
2416                     }
2417                     else if (xElm.Element("retweeted_status") != null)
2418                     {
2419                         var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2420                         var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2421
2422                         // 自分に関係しないリツイートの場合は無視する
2423                         var selfUserId = this.UserId.ToString();
2424                         if (sourceUserId == selfUserId || targetUserId == selfUserId)
2425                         {
2426                             // 公式 RT をイベントとしても扱う
2427                             var evt = CreateEventFromRetweet(xElm);
2428                             if (evt != null)
2429                             {
2430                                 this.StoredEvent.Insert(0, evt);
2431
2432                                 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2433                             }
2434                         }
2435
2436                         // 従来通り公式 RT の表示も行うため return しない
2437                     }
2438                     else if (xElm.Element("scrub_geo") != null)
2439                     {
2440                         try
2441                         {
2442                             TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2443                                                                         long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2444                         }
2445                         catch(Exception)
2446                         {
2447                             MyCommon.TraceOut("scrub_geo:" + line);
2448                         }
2449                         return;
2450                     }
2451                 }
2452
2453                 if (isDm)
2454                 {
2455                     try
2456                     {
2457                         var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2458                         this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2459                     }
2460                     catch (SerializationException ex)
2461                     {
2462                         throw TwitterApiException.CreateFromException(ex, line);
2463                     }
2464                 }
2465                 else
2466                 {
2467                     try
2468                     {
2469                         var status = TwitterStatus.ParseJson(line);
2470                         this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2471                     }
2472                     catch (SerializationException ex)
2473                     {
2474                         throw TwitterApiException.CreateFromException(ex, line);
2475                     }
2476                 }
2477             }
2478             catch (WebApiException ex)
2479             {
2480                 MyCommon.TraceOut(ex);
2481                 return;
2482             }
2483             catch(NullReferenceException)
2484             {
2485                 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2486             }
2487
2488             this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2489         }
2490
2491         /// <summary>
2492         /// UserStreamsから受信した公式RTをイベントに変換します
2493         /// </summary>
2494         private FormattedEvent CreateEventFromRetweet(XElement xElm)
2495         {
2496             return new FormattedEvent
2497             {
2498                 Eventtype = MyCommon.EVENTTYPE.Retweet,
2499                 Event = "retweet",
2500                 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2501                 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2502                 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2503                 Target = string.Format("@{0}:{1}", new[]
2504                 {
2505                     xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2506                     WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2507                 }),
2508                 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2509             };
2510         }
2511
2512         private void CreateEventFromJson(string content)
2513         {
2514             TwitterStreamEvent eventData = null;
2515             try
2516             {
2517                 eventData = TwitterStreamEvent.ParseJson(content);
2518             }
2519             catch(SerializationException ex)
2520             {
2521                 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2522             }
2523             catch(Exception ex)
2524             {
2525                 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2526             }
2527
2528             var evt = new FormattedEvent();
2529             evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2530             evt.Event = eventData.Event;
2531             evt.Username = eventData.Source.ScreenName;
2532             evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2533
2534             MyCommon.EVENTTYPE eventType;
2535             eventTable.TryGetValue(eventData.Event, out eventType);
2536             evt.Eventtype = eventType;
2537
2538             TwitterStreamEvent<TwitterStatus> tweetEvent;
2539
2540             switch (eventData.Event)
2541             {
2542                 case "access_revoked":
2543                 case "access_unrevoked":
2544                 case "user_delete":
2545                 case "user_suspend":
2546                     return;
2547                 case "follow":
2548                     if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2549                     {
2550                         if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2551                     }
2552                     else
2553                     {
2554                         return;    //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2555                     }
2556                     evt.Target = "";
2557                     break;
2558                 case "unfollow":
2559                     evt.Target = "@" + eventData.Target.ScreenName;
2560                     break;
2561                 case "favorited_retweet":
2562                 case "retweeted_retweet":
2563                     return;
2564                 case "favorite":
2565                 case "unfavorite":
2566                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2567                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2568                     evt.Id = tweetEvent.TargetObject.Id;
2569
2570                     if (SettingCommon.Instance.IsRemoveSameEvent)
2571                     {
2572                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2573                             return;
2574                     }
2575
2576                     var tabinfo = TabInformations.GetInstance();
2577
2578                     PostClass post;
2579                     var statusId = tweetEvent.TargetObject.Id;
2580                     if (!tabinfo.Posts.TryGetValue(statusId, out post))
2581                         break;
2582
2583                     if (eventData.Event == "favorite")
2584                     {
2585                         var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2586                         if (!favTab.Contains(post.StatusId))
2587                             favTab.AddPostImmediately(post.StatusId, post.IsRead);
2588
2589                         if (tweetEvent.Source.Id == this.UserId)
2590                         {
2591                             post.IsFav = true;
2592                         }
2593                         else if (tweetEvent.Target.Id == this.UserId)
2594                         {
2595                             post.FavoritedCount++;
2596
2597                             if (SettingCommon.Instance.FavEventUnread)
2598                                 tabinfo.SetReadAllTab(post.StatusId, read: false);
2599                         }
2600                     }
2601                     else // unfavorite
2602                     {
2603                         if (tweetEvent.Source.Id == this.UserId)
2604                         {
2605                             post.IsFav = false;
2606                         }
2607                         else if (tweetEvent.Target.Id == this.UserId)
2608                         {
2609                             post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2610                         }
2611                     }
2612                     break;
2613                 case "quoted_tweet":
2614                     if (evt.IsMe) return;
2615
2616                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2617                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2618                     evt.Id = tweetEvent.TargetObject.Id;
2619
2620                     if (SettingCommon.Instance.IsRemoveSameEvent)
2621                     {
2622                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2623                             return;
2624                     }
2625                     break;
2626                 case "list_member_added":
2627                 case "list_member_removed":
2628                 case "list_created":
2629                 case "list_destroyed":
2630                 case "list_updated":
2631                 case "list_user_subscribed":
2632                 case "list_user_unsubscribed":
2633                     var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2634                     evt.Target = listEvent.TargetObject.FullName;
2635                     break;
2636                 case "block":
2637                     if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2638                     evt.Target = "";
2639                     break;
2640                 case "unblock":
2641                     if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2642                     evt.Target = "";
2643                     break;
2644                 case "user_update":
2645                     evt.Target = "";
2646                     break;
2647                 
2648                 // Mute / Unmute
2649                 case "mute":
2650                     evt.Target = "@" + eventData.Target.ScreenName;
2651                     if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2652                     {
2653                         TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2654                     }
2655                     break;
2656                 case "unmute":
2657                     evt.Target = "@" + eventData.Target.ScreenName;
2658                     if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2659                     {
2660                         TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2661                     }
2662                     break;
2663
2664                 default:
2665                     MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2666                     break;
2667             }
2668             this.StoredEvent.Insert(0, evt);
2669
2670             this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2671         }
2672
2673         private void userStream_Started()
2674         {
2675             this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2676         }
2677
2678         private void userStream_Stopped()
2679         {
2680             this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2681         }
2682
2683         public bool UserStreamActive
2684             => this.userStream == null ? false : this.userStream.IsStreamActive;
2685
2686         public void StartUserStream()
2687         {
2688             var newStream = new TwitterUserstream(this.Api);
2689
2690             newStream.StatusArrived += userStream_StatusArrived;
2691             newStream.Started += userStream_Started;
2692             newStream.Stopped += userStream_Stopped;
2693
2694             newStream.Start(this.AllAtReply, this.TrackWord);
2695
2696             var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2697             oldStream?.Dispose();
2698         }
2699
2700         public void StopUserStream()
2701         {
2702             var oldStream = Interlocked.Exchange(ref this.userStream, null);
2703             oldStream?.Dispose();
2704         }
2705
2706         public void ReconnectUserStream()
2707         {
2708             this.StartUserStream();
2709         }
2710
2711         private class TwitterUserstream : IDisposable
2712         {
2713             public bool AllAtReplies { get; private set; }
2714             public string TrackWords { get; private set; }
2715
2716             public bool IsStreamActive { get; private set; }
2717
2718             public event Action<string> StatusArrived;
2719             public event Action Stopped;
2720             public event Action Started;
2721
2722             private TwitterApi twitterApi;
2723
2724             private Task streamTask;
2725             private CancellationTokenSource streamCts;
2726
2727             public TwitterUserstream(TwitterApi twitterApi)
2728             {
2729                 this.twitterApi = twitterApi;
2730             }
2731
2732             public void Start(bool allAtReplies, string trackwords)
2733             {
2734                 this.AllAtReplies = allAtReplies;
2735                 this.TrackWords = trackwords;
2736
2737                 var cts = new CancellationTokenSource();
2738
2739                 this.streamCts = cts;
2740                 this.streamTask = Task.Run(async () =>
2741                 {
2742                     try
2743                     {
2744                         await this.UserStreamLoop(cts.Token)
2745                             .ConfigureAwait(false);
2746                     }
2747                     catch (OperationCanceledException) { }
2748                 });
2749             }
2750
2751             public void Stop()
2752             {
2753                 this.streamCts?.Cancel();
2754
2755                 // streamTask の完了を待たずに IsStreamActive を false にセットする
2756                 this.IsStreamActive = false;
2757                 this.Stopped?.Invoke();
2758             }
2759
2760             private async Task UserStreamLoop(CancellationToken cancellationToken)
2761             {
2762                 TimeSpan? sleep = null;
2763                 for (;;)
2764                 {
2765                     if (sleep != null)
2766                     {
2767                         await Task.Delay(sleep.Value, cancellationToken)
2768                             .ConfigureAwait(false);
2769                         sleep = null;
2770                     }
2771
2772                     if (!MyCommon.IsNetworkAvailable())
2773                     {
2774                         sleep = TimeSpan.FromSeconds(30);
2775                         continue;
2776                     }
2777
2778                     this.IsStreamActive = true;
2779                     this.Started?.Invoke();
2780
2781                     try
2782                     {
2783                         var replies = this.AllAtReplies ? "all" : null;
2784
2785                         using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2786                             .ConfigureAwait(false))
2787                         using (var reader = new StreamReader(stream))
2788                         {
2789                             while (!reader.EndOfStream)
2790                             {
2791                                 var line = await reader.ReadLineAsync()
2792                                     .ConfigureAwait(false);
2793
2794                                 cancellationToken.ThrowIfCancellationRequested();
2795
2796                                 this.StatusArrived?.Invoke(line);
2797                             }
2798                         }
2799
2800                         // キャンセルされていないのにストリームが終了した場合
2801                         sleep = TimeSpan.FromSeconds(30);
2802                     }
2803                     catch (HttpRequestException) { sleep = TimeSpan.FromSeconds(30); }
2804                     catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2805                     catch (OperationCanceledException)
2806                     {
2807                         if (cancellationToken.IsCancellationRequested)
2808                             throw;
2809
2810                         // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2811                         sleep = TimeSpan.FromSeconds(30);
2812                     }
2813                     catch (Exception ex)
2814                     {
2815                         MyCommon.ExceptionOut(ex);
2816                         sleep = TimeSpan.FromSeconds(30);
2817                     }
2818                     finally
2819                     {
2820                         this.IsStreamActive = false;
2821                         this.Stopped?.Invoke();
2822                     }
2823                 }
2824             }
2825
2826             private bool disposed = false;
2827
2828             public void Dispose()
2829             {
2830                 if (this.disposed)
2831                     return;
2832
2833                 this.disposed = true;
2834
2835                 this.Stop();
2836
2837                 this.Started = null;
2838                 this.Stopped = null;
2839                 this.StatusArrived = null;
2840             }
2841         }
2842 #endregion
2843
2844 #region "IDisposable Support"
2845         private bool disposedValue; // 重複する呼び出しを検出するには
2846
2847         // IDisposable
2848         protected virtual void Dispose(bool disposing)
2849         {
2850             if (!this.disposedValue)
2851             {
2852                 if (disposing)
2853                 {
2854                     this.StopUserStream();
2855                 }
2856             }
2857             this.disposedValue = true;
2858         }
2859
2860         //protected Overrides void Finalize()
2861         //{
2862         //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2863         //    Dispose(false)
2864         //    MyBase.Finalize()
2865         //}
2866
2867         // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2868         public void Dispose()
2869         {
2870             // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2871             Dispose(true);
2872             GC.SuppressFinalize(this);
2873         }
2874 #endregion
2875     }
2876
2877     public class PostDeletedEventArgs : EventArgs
2878     {
2879         public long StatusId { get; }
2880
2881         public PostDeletedEventArgs(long statusId)
2882         {
2883             this.StatusId = statusId;
2884         }
2885     }
2886
2887     public class UserStreamEventReceivedEventArgs : EventArgs
2888     {
2889         public Twitter.FormattedEvent EventData { get; }
2890
2891         public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2892         {
2893             this.EventData = eventData;
2894         }
2895     }
2896 }