OSDN Git Service

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