OSDN Git Service

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